Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to INSERT to a column whose name is a sql keyword

Tags:

sql

insert

I need a table that stores key-value pairs, so I created one with a column called "Key" and a column called "Value".

This fails:

insert into mykeyvalues (Key,Value) values ('FooKey', 'FooValue')

"Incorrect syntax near the keyword 'key'."

Maybe I shouldn't call it "Key", but I just wonder if it is possible to work with a column whose name is a sql keyword?

Thanks

like image 522
Kurt Avatar asked May 30 '09 03:05

Kurt


People also ask

Can I use SQL keyword as column name?

SQL AS keyword is used to give an alias to table or column names in the queries.

How do you reference a column name in SQL?

You use column-ref to reference a column (database field), optionally qualified by a table and/or schema name. The column reference comprises the data type of the database field that the column represents (see Data Types).

Is name reserved keyword in SQL?

SQL Server does not have to distinguish this as a reserved keyword. Transact-SQL reserved keywords can be used as identifiers or names of databases or database objects, such as tables, columns, views, and so on. Use either quoted identifiers or delimited identifiers.


2 Answers

You can surround column names like that with [ ] brackets. Therefore:

insert into mykeyvalues ([Key],[Value]) values ('FooKey', 'FooValue') 
like image 173
John Christensen Avatar answered Oct 16 '22 02:10

John Christensen


Use either backticks (`) or double quotes (") around the identifiers in your query. For example:

INSERT INTO mykeyvalues ("Key", "Value") values ('FooKey', 'FooValue') 

But in the long-run, this just reduces portability. It's easier to use a different name.

like image 23
James Skidmore Avatar answered Oct 16 '22 03:10

James Skidmore