A CREATE statement with quoted fields in Oracle - sql

I have created a table in Oracle 10g using the following CREATE statement.
CREATE TABLE test ("id" NUMBER(35, 0) primary key, "description" VARCHAR2(250) not null);
The basic table structure looks like as follows.
--------------------------------------------------------------------------------
Column Name Data Type Nullable Default Primary Key
--------------------------------------------------------------------------------
id NUMBER(35, 0) No - 1
description VARCHAR2(250) No - -
It should precisely be noted that the column names in this CREATE statement are enclosed within double quotes just for having a fun :)
After issuing this DDL statement, I issued three DML statements to add this many rows as follows.
INSERT INTO test VALUES (1, 'aaa');
INSERT INTO test VALUES (2, 'bbb');
INSERT INTO test VALUES (3, 'ccc');
And finally, the following SELECT statement was executed to verify, if those rows were inserted.
SELECT * FROM test;
Oracle indeed displays three rows exactly as inserted on executing this query.
But when I issue the following SELECT query,
SELECT id, description FROM test;
Oracle complains,
ORA-00904: "DESCRIPTION": invalid identifier
The following (same) query also,
SELECT id FROM test;
fails with the error,
ORA-00904: "ID": invalid identifier
The same is true for the query,
SELECT description FROM test;
The only SELECT query with the meta character * works. Listing fields in the SELECT clause doesn't work. Capitalizing the column names in the SELECT clause also doesn't work.
What is the reason behind it?
Please don't just say, Don't do this. I'm interested in knowing the reason behind it.

OK, I won't say it, I'll just think it loudly.
The documentation clearly says that if you have quoted identifiers, you have to quote them everywhere (my italics for emphasis):
Every database object has a name. In a SQL statement, you represent the name of an object with a quoted identifier or a nonquoted identifier.
A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you must use the double quotation marks whenever you refer to that object.
A nonquoted identifier is not surrounded by any punctuation.
So you always have to do:
SELECT "id", "description" FROM test;
Which is a pain. But obviously I'm just thinking that too, not really saying it.

Related

Column isn't being found?

I am trying to display the username, last name, join date and country name for all the users who joined after the 13th January 2017 in ascending order. However each time I try to call any column, I get the error message "Column: Invalid Identifier".
SELECT Username, LastName, JoinDate, CountryName
FROM BR_USER, BR_COUNTRY
WHERE JoinDate = '01-JAN-17' AND JoinDate IS NOT NULL
ORDER BY JoinDate ASC;
Here is an image of how the BR_USER table is created.
Simple codes like:
SELECT UserId
FROM BR_USER;
Gives the same invalid identifier error, help
As the documentation explains:
Every database object has a name. In a SQL statement, you represent the name of an object with a quoted identifier or a nonquoted identifier.
A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you must use the double quotation marks whenever you refer to that object.
If you define a column name with double quotes, you are condemned to using the double quotes whenever your reference that column. Or table or anything else with a name.
Actually, I don't think the documentation is 100% correct. Oracle uppercases all identifiers for resolution. So, if you define a quoted identifier with all upper case, then it will work without quotes. So this works:
create table t (
"COL" int
);
select "COL", COL, col
from t;
Here is a db<>fiddle.
But who wants to remember such rules -- rules so arcane and complex that the documentation is even misleading.
Simple solution: Don't use double quotes.

Apache derby - SELECT * FROM tablename dont work

When i execute SELECT * FROM tablename generate that erorr :
java.sql.SQLSyntaxErrorException: Table/View 'tablename' does not exist.
but if i run that sql command
SELECT * FROM "tablename" the sql run without problems why.
This is an aspect of the SQL standard known as "delimited identifiers".
Table names, column names, and other objects are things that you can give names to in your database.
The SQL standard says that, if you aren't particular about the upper/lower case of your object names, you can just specify the names without quotation marks, and your database will process them in a case-insensitive manner (typically, by converting an unquoted object name into the all-upper-case version of that name).
CREATE TABLE mytable(c1 INT, c2 CHAR(10));
INSERT INTO MyTable (C1, C2) VALUES (42, 'Bryan');
SELECT c2 FROM MYTABLE;
Since you didn't specify any object names in quotation marks, all of these examples work fine, because mytable, MyTable, and MYTABLE are all the same, when they aren't in quotation marks.
But if you specify your object names in quotation marks, then you have to get things exactly right:
CREATE TABLE "MyCaseSensitiveTable" (c1 int, c2 char(10));
INSERT INTO MyCaseInsensitiveTable (c1, c2) values (64, 'a nice age');
In this case, your INSERT statement will be rejected, because "MyCaseSensitiveTable" is different than MyCaseSensitiveTable.
Delimited identifiers bring other advantages:
You can use otherwise-reserved keywords from the SQL language as table names, so you can create a table named "TABLE" if you want.
You can use various special characters in your database object names.
Personally, I try never to use delimited identifiers, because I think they make my programs hard to read. But they are a completely legitimate part of the SQL standard and they are widely used.
But, the bottom line is: if you're going to put your database object names in quotation marks, you have to put them in quotation marks all the time, and you have to give the name exactly the same each time, but if you don't use quotation marks for your database object names, they will be treated in a case-insensitive manner.

Oracle DB quote column names

When using regular tables, its fine to use the following Oracle SQL query:
SELECT max(some_primary_key) FROM MyTable
However, when using Database Objects (i.e. a table of an object), this yields to the following error:
ORA-00904: "SOME_PRIMARY_KEY": invalid identifier
When quoting the column name, like this:
SELECT max("some_primary_key") FROM MyTable
This works like expected. Why is it necessary to escape column names when working with Objects, but not with Tables?
It doesn't have to do with objects or tables, it has to do with how these objects/tables have been created.
If you do
create table "blabla" then you always need to address this table with "blabla", if you do create table blabla then you can address this table via BLABLA or blabla or bLabLa. Using " " makes the name case sensitive and that is the reason why most developers don't use " " because usually you don't want case sensitive names .
Database Object Naming Rules
Every database object has a name. In a SQL statement, you represent
the name of an object with a quoted identifier or a nonquoted
identifier.
A quoted identifier begins and ends with double quotation marks ("). If you name a schema object using a quoted identifier, then you
must use the double quotation marks whenever you refer to that object.
A nonquoted identifier is not surrounded by any punctuation.
You can use either quoted or nonquoted identifiers to name any
database object. However, database names, global database names, and
database link names are always case insensitive and are stored as
uppercase. If you specify such names as quoted identifiers, then the
quotation marks are silently ignored. Refer to CREATE USER for
additional rules for naming users and passwords.
To summarize this
When you do :
SELECT max(some_primary_key) FROM MyTable
Oracle assume that your column was declared like this :
CREATE TABLE MyTable (
some_primary_key INT,
...
)
Seing the resulting error, it's not the case. You obviously declared it like this :
CREATE TABLE MyTable (
"some_primary_key" INT,
...
)
And you should thus always refer to that column using double quotes and proper case, thus :
SELECT max("some_primary_key") FROM MyTable
The bible : Oracle Database Object Names and Qualifiers
[TL;DR] The simplest thing to do is to never use double quotes around object names and just let oracle manage the case-sensitivity in its default manner.
Oracle databases are, by default, case sensitive; however, they will also, by default, convert everything to upper-case so that the case sensitivity is abstracted from you, the user.
CREATE TABLE Test ( column_name NUMBER );
Then:
SELECT COUNT(column_name) FROM test;
SELECT COUNT(Column_Name) FROM Test;
SELECT COUNT(COLUMN_NAME) FROM TEST;
SELECT COUNT(CoLuMn_NaMe) FROM tEsT;
SELECT COUNT("COLUMN_NAME") FROM "TEST";
Will all give the same output and:
DESCRIBE test;
Outputs:
Name Null Type
----------- ---- ------
COLUMN_NAME NUMBER
(Note: Oracle's default behaviour is to convert the name to upper case.)
If you use double quotes then oracle will respect your use of case in the object's name (and you are then required to always use the same case):
CREATE TABLE "tEsT" ( "CoLuMn_NaMe" NUMBER );
(Note: Both the table and column name are surrounded in double quotes and now require you to use exactly the same case, and quotes, when you refer to them.)
Then you can only do (since you need to respect the case sensitivity):
SELECT COUNT("CoLuMn_NaMe") FROM "tEsT";
And
DESCRIBE "tEsT";
Outputs:
Name Null Type
----------- ---- ------
CoLuMn_NaMe NUMBER
(Note: Oracle has respected the case sensitivity.)
I created one object in Oracle 11g:
CREATE OR REPLACE TYPE MyType AS OBJECT (
some_property NUMBER(20),
CONSTRUCTOR FUNCTION MyType(some_property number default 123) RETURN SELF AS RESULT
) NOT FINAL;
/
CREATE OR REPLACE TYPE BODY MyType AS
CONSTRUCTOR FUNCTION MyType(some_property number default 123)
RETURN SELF AS RESULT
AS
BEGIN
SELF.some_property := some_property;
RETURN;
END;
END;
/
---Created a table of my object
CREATE TABLE MYTABLE OF MYTYPE ;
---issued the statement.
SELECT max(some_property) FROM MYTABLE;
Its working fine for me without quotes. Not sure why its not working in your case. Whats your oracle version ?

What's wrong with my sql in oracle?

What's wrong with my sql in oracle? There are some data in my table,I select all of them and I can get them.but I can not search them if I add a condition.When did I add single or double quotation marks in my sql?Now I find that when I write some search statement,I must add single quotation marks.And when I write some insert statement,I must add double quotation marks.Or my sql will run bad.How to judge when should I use the different quotation in my sql?
select * from T_STUDENT
and the result is:
sex(varchar2) phone(varchar2) birthtime(timestamp)
1 13553812147 2016-06-03 16:02:00.799 **
When I add a search condition,but the result is null.
//error:ORA-000904
select * from T_STUDENT where phone='13553812147'
//error:ORA-000904
select * from T_STUDENT where PHONE='13553812147'
//run well but result is null
select * from T_STUDENT where 'phone'='13553812147'
And the same question I meet in the insert statement.
//error:ORA-000904
insert into T_STUDENT (sex,phone,birthtime) values('1','12345645454','2016-06-04 16:02:00.799')
//error:ORA-000928 missing select keyword
insert into T_STUDENT ('sex','phone','birthtime') values('1','12345645454','2016-06-04 16:02:00.799')
//run well but must add double quotation marks
insert into T_STUDENT ("sex","phone","birthtime") values('1','12345645454','2016-06-04 16:02:00.799')
This is because your table was defined using double quotes around the column names:
create table t_student
( "sex" varchar2(1)
, "phone" varchar2(30)
, "birthtime" timestamp
);
Using double quotes makes the names case-sensitive and so for ever after they must be referenced in double quotes, since by default Oracle is nicely case-insensitive. For this reason you should never use double quotes when creating tables, views etc.
I've had the chance to look at this and Tony Andrews' answer is correct, you actually get invalid identifier as error message when you type an invalid column, which includes a case mismatch, though the error message will mention the exact identifier:
SQL> select * from T_STUDENT where phone='13553812147';
select * from T_STUDENT where phone='13553812147'
*
ERROR at line 1:
ORA-00904: "PHONE": invalid identifier
SQL> select * from T_STUDENT where funny_bunny='13553812147';
select * from T_STUDENT where funny_bunny='13553812147'
*
ERROR at line 1:
ORA-00904: "FUNNY_BUNNY": invalid identifier
The only thing missing from his answer is that Oracle will always make an internal cast to uppercase for any unquoted identifier, as the full error message illustrates. That's why phone='13553812147' won't match a column defined as "phone" (but "phone"='13553812147' will do).
Last but not least, single quotes define plain strings rather than object names so when you do this:
select * from T_STUDENT where 'phone'='13553812147'
... you aren't filtering by phone column at all. Instead, you have a constant condition that's always false (text "phone" equals text "13553812147").

"Column ’x’ does not exist" error for string literal ’x’ in PostgreSQL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Column ‘mary’ does not exist
I need to check the values that can be accepted to a column through a check constraint. I need to use the check constraint, because this is for a college assignment.
I use this code to create and add the constraint to the table.
CREATE TABLE Ereignis(
E_Id Serial PRIMARY KEY,
Typ varchar(15),
Zeitpunkt timestamp,
Ort varchar(32),
Anzahl_Pers int
);
ALTER TABLE Ereignis ADD
CONSTRAINT typ_ch CHECK (Typ in (’Verkehrsunfall’, ’Hochwasser’, ’Sonstiges’));
Here is the error I get:
ERROR: column "’verkehrsunfall’" does not exist
As I get from this error it tries to compare column typ with column verkehrsunfall, where as I try to check the values that column try can get is one of the (’Verkehrsunfall’, ’Hochwasser’, ’Sonstiges’) strings.
This is exactly the same syntax what our lecturer showed us at the lecture. I am not sure if it is possible to compare varchars with check? Or what am I doing wrong?
Here is the example from the lecture:
CREATE TABLE Professoren
(PersNr INTEGER PRIMARYKEY,
Name VARCHAR( 3 0 ) NOT NULL ,
Rang CHAR(2) CHECK (Rang in ('C2' ,'C3' ,'C4')) ,
Raum INTEGER UNIQUE) ;
Your text editor or word processor is using so-called smart quotes, like ’, not ordinary single quotes, like '. Use ordinary single quotes (actually apostrophes) ' for literals, or double quotes " for identifiers. You also have some odd commas in there which may cause syntax errors. See the PostgreSQL manual on SQL syntax, specicifically lexical structure.
Don't edit SQL (or any other source code) in a word processor. A decent text editor like Notepad++, BBEdit, vim, etc, won't mangle your SQL like this.
Corrected example:
CREATE TABLE Professoren
(PersNr INTEGER PRIMARYKEY,
Name VARCHAR(30) NOT NULL,
Rang CHAR(2) CHECK (Rang in ('C2' ,'C3' ,'C4')),
Raum INTEGER UNIQUE);
The reason it doesn't cause an outright syntax error - and instead gives you an odd error message about the column not existing - is because PostgreSQL accepts unicode column names and considers the ’ character a perfectly valid character for an identifier. Observe:
regress=> SELECT 'dummy text' AS won’t, 'dummy2' as ’alias’;
won’t | ’alias’
------------+---------
dummy text | dummy2
(1 row)
Thus, if you have a column named test and you ask for the column named ’test’, PostgreSQL will correctly tell you that there is no column named ’test’. In your case you're asking for a column named ’verkehrsunfall’ when you meant to use the literal string Verkehrsunfall instead, hence the error message saying that the column ’verkehrsunfall’ does not exit.
If it were a real single quote that'd be invalid syntax. The 1st wouldn't execute in psql at all because it'd have an unclosed single quote; the 2nd would fail with something like:
regress=> SELECT 'dummy2' as 'alias';
ERROR: syntax error at or near "'alias'"
LINE 1: SELECT 'dummy2' as 'alias';
... because in ANSI SQL, that's trying to use a literal as an identifier. The correct syntax would be with double-quotes for the identifier or no quotes at all:
regress=> SELECT 'dummy2' as "alias", 'dummy3' AS alias;
alias | alias
--------+--------
dummy2 | dummy3
(1 row)
You also have an unwanted space in the varchar typmod; varchar( 3 0 ) is invalid:
regress=> SELECT 'x'::varchar( 3 0 );
ERROR: syntax error at or near "0"
LINE 1: SELECT 'x'::varchar( 3 0 );
BTW, in PostgreSQL it's usually better to use a text column instead of varchar. If you want a length constraint for application or validation reasons, add a check constraint on length(colname).