Underscores or camelCase in PostgreSQL identifiers, when the programming language uses camelCase?

Zilk picture Zilk · Jun 30, 2012 · Viewed 30.5k times · Source

This has been bothering me for a while, and I can't arrive at a solution that feels right...

Given an OO language in which the usual naming convention for object properties is camelCased, and an example object like this:

{
    id: 667,
    firstName: "Vladimir",
    lastName: "Horowitz",
    canPlayPiano: true
}

How should I model this structure in a PostgreSQL table?

There are three main options:

  1. unquoted camelCase column names
  2. quoted camelCase column names
  3. unquoted (lowercase) names with underscores

They each have their drawbacks:

  1. Unquoted identifiers automatically fold to lowercase. This means that you can create a table with a canPlayPiano column, but the mixed case never reaches the database. When you inspect the table, the column will always show up as canplaypiano - in psql, pgadmin, explain results, error messages, everything.

  2. Quoted identifiers keep their case, but once you create them like that, you will always have to quote them. IOW, if you create a table with a "canPlayPiano" column, a SELECT canPlayPiano ... will fail. This adds a lot of unnecessary noise to all SQL statements.

  3. Lowercase names with underscores are unambiguous, but they don't map well to the names that the application language is using. You will have to remember to use different names for storage (can_play_piano) and for code (canPlayPiano). It also prevents certain types of code automation, where properties and DB columns need to be named the same.

So I'm caught between a rock and a hard place (and a large stone; there are three options). Whatever I do, some part is going to feel awkward. For the last 10 years or so, I've been using option 3, but I keep hoping there would be a better solution.

I'm grateful for any advice you might have.

PS: I do realize where the case folding and the need for quotes is coming from - the SQL standard, or rather PostgreSQL's adaptation of the standard. I know how it works; I'm more interested in advice about best practices than explanations about how PG handles identifiers.

Answer

Mirza Selimovic picture Mirza Selimovic · Dec 10, 2013

If your columns in the PostgreSQL are with underscores, you can put aliases but with doule-quotes.

Example :

SELECT my_column as "myColumn" from table;