Explain Codes LogoExplain Codes Logo

Are PostgreSQL column names case-sensitive?

sql
database-migration
sql-standards
best-practices
Alex KataevbyAlex Kataev·Dec 20, 2024
TLDR

In PostgreSQL, unquoted column names are lowercase. Use double quotes for case sensitivity:

  • Without quotes (treats as lowercase):

    -- the gentleman does not see uppercase SELECT columnname FROM table;
  • With quotes (keeps original case):

    -- as picky as a cat - only "ColumnName" will do! SELECT "ColumnName" FROM table;

To dodge the confusion, don't use quotes altogether, or remember to always quote with the exact case.

Unmasking PostgreSQL's treatment of column names

Living in the lowercase world

When you don't use quotes, PostgreSQL:

  • Transforms identifiers to lowercase:

    -- Firstname? Never met him, did you mean 'firstname'? SELECT firstname FROM people;
  • Keeps identifiers and strings completely separate:

    -- Whoa! 'FirstName' is a string, not a column, buddy. SELECT 'FirstName' FROM people;

Embracing case sensitivity

When you do use double quotes:

  • PostgreSQL follows your exact case and characters:

    -- Finally, "FirstName" has arrived! SELECT "FirstName" FROM people;
  • Requires consistent quoting in every reference, which might turn into an exercise of accurate memory!

Sticking to lowercase

Using only lower-case names:

  • Eliminates the need to type quotes:

    -- Cool as cucumber! No case worries. SELECT first_name FROM people;
  • Makes your SQL queries more readable and less error-prone.

Steering clear of reserved words

Staying away from SQL reserved words:

  • Avoids potential syntax conflicts:

    -- 'user'... hmm, haven't I seen you somewhere? SELECT user FROM accounts;
  • Promotes use of more descriptive and unambiguous identifiers.

Application & portability considerations

Impact on application development

Maintaining consistency: Inconsistencies can lead to errors in application development, especially with ORMs:

# Assumes the accurate spelling and case is 'first_name'. Person.objects.get(first_name='John')

Handling database migrations

Transferring or transitioning databases can sometimes turn into a puzzle game. To modify column names to lowercase:

-- Changing lives, one column at a time. ALTER TABLE "People" RENAME COLUMN "FirstName" TO first_name;

Understanding SQL standards

PostgreSQL is like the rebellious teenager of SQL databases:

  • SQL is set to default fold unquoted names to upper case.
  • But PostgreSQL, being the cool kid, folds to lower case.

Dealing with literal constants vs. identifiers

  • Wrap string literals or constants in single quotes:

    -- Who's 'John'? Oh! You meant value 'John' for 'first_name'. SELECT * FROM people WHERE first_name = 'John';
  • Reserve double quotes for exact-case column names:

    -- Please reserve the seat for "FirstName". SELECT "FirstName" from people;