Escaping special characters when naming a table column without setting define off - sql

Before I posted my question, I read up various posts on this site about how to escape a special character when inserting a new field value or looking for a field name in the where clause. What I did not find was how to escape a special character when you want to name a table or column with one.
So, I want to name fieldA as this&that, e.g.
select fieldA this&that from tableA
I also want to use a substitution variable (&var) in the same query, so set define off wouldn't help.
I tried to use 'this' || chr(38) || 'that' with or without single quotes, but SQL Developer doesn't like either.
Any ideas?

You would need to quote the identifier, but this is a really bad idea; every reference to the column everywhere will also have to be quoted and match the case exactly. See this, and the documentation, which advises against using quoted identifiers.
It's an even worse idea with an ampersand because of its use for substitution variables, as you're seeing. To create the table and then use substitution variables in the same script you would need to turn off defines before the creation, and then turn them back on afterwards:
set define off
create table bad_idea("this&that" number);
set define on
But you still couldn't refer to the table name and a substitution variable in the same statement, unless you set define to something non-standard:
set define "^"
insert into bad_idea("this&that") values (^var);
But again everything that ever refers to that column will need to take that into account too, as well as the case and quoting.
I'd seriously reconsider and make it something like this_and_that, or omit the 'and' part completely if it isn't really adding anything (or your real column name is approaching the length limit).
If you only need it as a column alias you can do the same thing, and it would be slightly less painful, but still not ideal:
set define "^"
select fieldA "this&that" from tableA where fieldB = ^var;

Related

Column names using Oracle reserved word

Inside my database I have some tables that use a column with a reserved word name for example user, I have created it using " as "USER" but when I want to get it I have realized that I have to put it in capital letters, I have already investigated and I obtained that when placing " oracle respects it as case sensitive, they somehow know how to avoid this and obtain my column without the need for it to be written as defined, that is, case insensitive.
I am working Oracle with Firedac, on the Firedac side, do you know if something can be done so that this can be solved by having to put the column name as it is?
No.
You chose to have a column that conflicts with a reserved word, so you had to quote it when you declared it. You also need to quote this identifier everytime you use it - and a quoted identifier is case-sensitive by design.
I would strongly suggest avoiding having column names that conflict with SQL reserved word (or keywords). There is no benefit, and many drawbacks. You could just rename that column to usr, username, userid, or else. Declare the new name as a unquoted identifier, and you will never need to worry about this all afterwards.

How to add brackets in heading of a table column in database?

I want to create a database containing multiple tables using postgres 11 and i'm currently creating a table which contain brackets in the heading of the column (as shown as follows).
Table - supp_details
supp_id|supp_name | supp_weight(Kg)|
Can i add units to the heading and what is the proper way to do so with sql?
I'm a fresher to query writing, so please help me with this.
You could place the column name in quotes, e.g. use "supp_weight(Kg)", but it is best to avoid placing special characters or keywords as object names. Instead, I suggest using the following name:
supp_weight_kg
It is just a single string requiring no escaping, and makes it clear what the units are. A better option might be to just use supp_weight, and maybe just keep a note somewhere that the column uses kilograms as the unit by default.
You will need to use quoted identifiers but I strongly recommend not to do that:
create table supp_details
(
supp_id integer,
supp_name text,
"supp_weight(kg)" integer
);
Adding bracket symbols into your column names is possible but probably a bad idea. If you want to micromanage the name just for display purposes of the end result, you should probably do it in an alias, using the AS keyword.
SELECT supp_id, supp_name, supp_weight AS "supp_weight(Kg)" FROM ...
Or add the decorations on the client side before it displays the results.

Replace single quote to regular abbreviation

I have a table with a state column. Inside the state column I have a value like TX` I want to replace that ending character to make the State read TX. How would I do that please give examples
You already have answers for replacing the quote, but I wanted to provide methods for avoiding this problem in the first place.
As noted in #SeanLange's answer, you can use define your State field as a CHAR(2) , so you know that you'll never have a dummy character following a valid state code. You could also handle this in your client code, sanitizing the input before even sending to the database.
One could argue that it would even be a good idea to define a lookup table with a foreign key constraint, so users could only input valid values. You could also use this lookup table client-side (e.g. to provide a list of states).
Of course, you also have to consider internationalization: What about when/if you need to store locations outside of the United States, that may have > 2 characters?
You can escape a single quote by doubling it and including it in quotes. So:
select replace(state, '''', ''')
Of course, if the problem is just a bad third character, then LEFT(state, 2) might do the trick as well.
As a Sean Lang's comment said, you can do this in many different ways. For simplicity, you can just use LEFT(string, #) function for the whole typecasting as long as your raw values are all in the TX` format (**two letter abbrev and one ` , so three characters total for every value in that field.
If that is the case then just do:
SELECT CAST(LEFT(t.state_column, 2) As Varchar(2)) As state,
t.column_2,
t.column_3
/* and so on for all the columns you want */
FROM table t;
--
Further Reference:
- https://w3resource.com/PostgreSQL/left-function.php

To make entire column names in lower case in oracle

I am using oracle xe,while creating columns it is created in upper case.Is there any rule to make the entire database columns in lower case.
To answer to your specific question: No
(you cannot globally change all column headings to lowercase)
Nonquoted Identifiers:
Unless you use quotes when creating objects the default for storage is upper case and these are called nonquoted identifiers in documentation. This allows "case insensitive" use of those names. e.g. a field stored with the name DESCRIPTION can be used in lowercase or mixed case like dEscRipTion
Quoted Identifiers
If however you use "quoted identifiers" then you create case sensitive names and all references to them must be a precise match. So a field with the stored name of DesCripTion must always be used with exactly that mixed case and DescripTion would not work.
In short, don't mess with the defaults, you are way better off leaving them as "nonquoted identifiers"
see: Schema Object Naming Rules
use oracle "rename" syntax.
for example:
// existing column on TABLE1 is CITY_NAME
// new name is cityName
// you can rename table and/or columns
rename table SCHEMA1.TABLE1 to "NewTableName"
and
rename column SCHEMA1.TABLE1.CITY_NAME to "cityName"
the main thing to remember is to enclose the new name in quotes.
you have to modify your exiting views and cursors because they will break.

Table or column name cannot start with numeric?

I tried to create table named 15909434_user with syntax like below:
CREATE TABLE 15909434_user ( ... )
It would produced error of course. Then, after I tried to have a bit research with google, I found a good article here that describe:
When you create an object in PostgreSQL, you give that object a name. Every table has a name, every column has a name, and so on. PostgreSQL uses a single data type to define all object names: the name type.
A value of type name is a string of 63 or fewer characters. A name must start with a letter or an underscore; the rest of the string can contain letters, digits, and underscores.
...
If you find that you need to create an object that does not meet these rules, you can enclose the name in double quotes. Wrapping a name in quotes creates a quoted identifier. For example, you could create a table whose name is "3.14159"—the double quotes are required, but are not actually a part of the name (that is, they are not stored and do not count against the 63-character limit). ...
Okay, now I know how to solve this by use this syntax (putting double quote on table name):
CREATE TABLE "15909434_user" ( ... )
You can create table or column name such as "15909434_user" and also user_15909434, but cannot create table or column name begin with numeric without use of double quotes.
So then, I am curious about the reason behind that (except it is a convention). Why this convention applied? Is it to avoid something like syntax limitation or other reason?
Thanks in advance for your attention!
It comes from the original sql standards, which through several layers of indirection eventually get to an identifier start block, which is one of several things, but primarily it is "a simple latin letter". There are other things too that can be used, but if you want to see all the details, go to http://en.wikipedia.org/wiki/SQL-92 and follow the links to the actual standard ( page 85 )
Having non numeric identifier introducers makes writing a parser to decode sql for execution easier and quicker, but a quoted form is fine too.
Edit: Why is it easier for the parser?
The problem for a parser is more in the SELECT-list clause than the FROM clause. The select-list is the list of expressions that are selected from the tables, and this is very flexible, allowing simple column names and numeric expressions. Consider the following:
SELECT 2e2 + 3.4 FROM ...
If table names, and column names could start with numerics, is 2e2 a column name or a valid number (e format is typically permitted in numeric literals) and is 3.4 the table "3" and column "4" or is it the numeric value 3.4 ?
Having the rule that identifiers start with simple latin letters (and some other specific things) means that a parser that sees 2e2 can quickly discern this will be a numeric expression, same deal with 3.4
While it would be possible to devise a scheme to allow numeric leading characters, this might lead to even more obscure rules (opinion), so this rule is a nice solution. If you allowed digits first, then it would always need quoting, which is arguably not as 'clean'.
Disclaimer, I've simplified the above slightly, ignoring corelation names to keep it short. I'm not totally familiar with postgres, but have double checked the above answer against Oracle RDB documentation and sql spec
I'd imagine it's to do with the grammar.
SELECT 24*DAY_NUMBER as X from MY_TABLE
is fine, but ambiguous if 24 was allowed as a column name.
Adding quotes means you're explicitly referring to an identifier not a constant. So in order to use it, you'd always have to escape it anyway.