Explain Codes LogoExplain Codes Logo

What exactly do quotation marks around the table name do?

sql
sql-queries
case-sensitivity
orm-consistency
Anton ShumikhinbyAnton Shumikhin·Nov 24, 2024
TLDR

Quotation marks " " in SQL preserve case sensitivity and allow the use of special characters and keywords in table names. Examples:

  • Without quotes: SELECT * FROM casesensitivename; might fail if the table name is actually "CaseSensitiveName".
  • With quotes: SELECT * FROM "CaseSensitiveName"; ensures querying the correct table.

If a reserved keyword is used as a table name:

CREATE TABLE "SELECT" (id INT);

It's particularly crucial when default settings are case-insensitive or when using special elements.

Diving deeper

Why care about case sensitivity?

Default Oracle SQL identifiers (e.g., table, column names) are case-insensitive. Both these queries are identical:

SELECT * FROM employees; SELECT * FROM EMPLOYEES;

But when you use double quotes, things change:

SELECT * FROM "Employees"; // This is not the same as "EMPLOYEES", it's more like an undercover secret agent in a tuxedo.

Now, the identifier needs to match exactly as it was created—including the same case —, otherwise, you might bump into "table or view does not exist" errors, and that's never fun.

Quotation marks and special characters

Quotation marks let you use special characters or reserved keywords in table names without triggering the SQL's natural defense mechanism, for instance:

  • Special characters: "my-table#with$chars"
  • Reserved keywords: "CREATE"

Don't forget though, you must always use the exact quoted identifier when referencing the table.

ORM consistency matters

When dealing with ORMs like NHibernate, consistent usage is key. Imagine a table named "User":

session.QueryOver<User>().List(); //Just like James Bond, always matches his tuxedo with his bow tie

If the table name and the ORM class don't match (e.g., class User but table "user"), things get messy real quick.

Deep dive scenarios

Case sensitivity traps

Maybe you created a table with quotes like "Employee", be sure to access it with quotes as well:

SELECT * FROM Employee; -- Rookie mistake: "employee" does not exist, did you mean "Employee"?

Export/import consistency

Maintaining proper case is also crucial while exporting and importing databases. An export file with case-sensitive table names requires consistent quoting during imports to prevent missing table errors.

Cross-database compatibility

While Oracle and PostgreSQL treat quoted identifiers as case-sensitive, databases like MySQL or SQLite follow different rules. Understanding this is a good step towards writing cross-database compatible SQL scripts.