Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with SQL column names that look like SQL keywords?

Tags:

sql

sql-server

People also ask

Can we use SQL keywords as column name?

In SQL, certain words are reserved. These are called Keywords or Reserved Words. These words cannot be used as identifiers i.e. as column names in SQL.

How do you use reserved words as column names in SQL?

You cannot use an SQL reserved word as an SQL identifier (such as the name for a table, a column, an AS alias, or other entity), unless: The word is delimited with double quotes ("word"), and. Delimited identifiers are supported.

How do I display only column names in SQL?

In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .


Wrap the column name in brackets like so, from becomes [from].

select [from] from table;

It is also possible to use the following (useful when querying multiple tables):

select table.[from] from table;

If it had been in PostgreSQL, use double quotes around the name, like:

select "from" from "table";

Note: Internally PostgreSQL automatically converts all unquoted commands and parameters to lower case. That have the effect that commands and identifiers aren't case sensitive. sEleCt * from tAblE; is interpreted as select * from table;. However, parameters inside double quotes are used as is, and therefore ARE case sensitive: select * from "table"; and select * from "Table"; gets the result from two different tables.


While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).

SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName

These are the two ways to do it:

  1. Use back quote as here:

SELECT `from` FROM TableName

  1. You can mention with table name as:

SELECT TableName.from FROM TableName