Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping keyword-like column names in Postgres

Tags:

sql

postgresql

People also ask

How do I escape keywords in PostgreSQL?

Within an escape string, a backslash character ( \ ) begins a C-like backslash escape sequence, in which the combination of backslash and following character(s) represent a special byte value, as shown in Table 4.1. Any other character following a backslash is taken literally.

How do I use like keyword in PostgreSQL?

The PostgreSQL LIKE operator is used to match text values against a pattern using wildcards. If the search expression can be matched to the pattern expression, the LIKE operator will return true, which is 1. The percent sign represents zero, one, or multiple numbers or characters.

What is excluded keyword in PostgreSQL?

Introduction to PostgreSQL EXCLUDE. PostgreSQL excludes statements in PostgreSQL is used to compare any two rows from the specified column or expression by using the operator specified in PostgreSQL. At the time of excluding the column, the comparison operator will return the null or false value as output.


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.


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.