Escaping keyword-like column names in Postgres
If the column in Postgres' table has the name year
, how should look INSERT
query to set the value for that column?
E.g.: INSERT INTO table (id, name, year) VALUES ( ... );
gives an error near the year word.
Solution 1:
Simply enclose year
in double quotes to stop it being interpreted as a keyword:
INSERT INTO table (id, name, "year") VALUES ( ... );
From the documentation:
There is a second kind of identifier: the delimited identifier or quoted identifier. It is formed by enclosing an arbitrary sequence of characters in double-quotes ("). A delimited identifier is always an identifier, never a key word. So "select" could be used to refer to a column or table named "select", whereas an unquoted select would be taken as a key word and would therefore provoke a parse error when used where a table or column name is expected.
Solution 2:
If you are not providing quotes in any Fields/Columns, It will be lowercased by Postgres by default. And Postgres will skip checking keyword when it comes to the column name.
In your case, I don't think it's mandatory to add quotes when it comes to the columns
.
But if you are using keywords
(registered by Postgres) as the name of Table
, Schema
, Function
or Trigger
etc, you must have to use either double quotes, or you can specify schema name with dot concatenation.
Let's Suppose, order is the keyword registered by Postgres. And in some scenarios, you must have to use this keyword as a table name.
At that time, Postgres will allow you to create a table with keywords
. That is the beauty of Postgres.
To access the order table, Either you have to use a Double quote or you can you schema name before table name.
E.G.
1.
select * from schema_name.order;
2.
select * from "order";
Likewise, you can use this type of combination. Hope this will help you.