Search code examples
sqloraclereserved-wordsquoted-identifier

How do I use quoted identifier for user + table name combination in Oracle?


In my Oracle DB setup all the tables are created under dedicated user account SYS0MYUSER. When executing following query on my system I got SQL Error: ORA-00903: invalid table name

SELECT COUNT(*) FROM SYS0MYUSER.USER;

I tried to escape the reserved keyword like this:

SELECT COUNT(*) FROM "SYS0MYUSER.USER";

But then I got another error SQL Error: ORA-00942: table or view does not exist

What is the correct way to escape user name + reserved keyword combination ?

UPDATE: What's about table alias do I have to use double quotes too ?


Solution

  • If you have created the table using quoted identifier, then you must always use double-quotation marks wherever you refer the object.

    From documentation,

    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.

    For example,

    SQL> CREATE TABLE "USER"(A NUMBER);
    
    Table created.
    
    SQL>
    SQL> SELECT COUNT(*) FROM LALIT.USER;
    SELECT COUNT(*) FROM LALIT.USER
                               *
    ERROR at line 1:
    ORA-00903: invalid table name
    
    
    SQL>
    SQL> SELECT COUNT(*) FROM LALIT."USER";
    
      COUNT(*)
    ----------
             0
    
    SQL>
    

    So, you need to refer the table as a quoted identifier:

    SELECT COUNT(*) FROM SYS0MYUSER."USER";
    

    Update OP updated his question regarding table alias.

    What's about table alias do I have to use double quotes too ?

    Table alias has nothing to do with the quoted identifier.

    For example,

    SQL> SELECT t.* FROM LALIT."USER" t;
    
    no rows selected
    
    SQL>