Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a column with a keyword name

I have a table named 'test'

It contains a column named 'AND'

For that I use the following queries

insert into test values ('a','abc');
insert into test values ('b','def');

Now I want to select my 'AND' column from the 'test' table

The query select AND from test; wont work because AND is keyword

I tried

select "AND" from test;
select 'AND' from test;

Both queries return the wrong results as show below

enter image description here

How can I select my 'AND' column?

like image 377
Fathah Rehman P Avatar asked Sep 13 '12 06:09

Fathah Rehman P


People also ask

Can I use keyword as column name in SQL?

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.

Can I use MySQL keyword as column name?

Using Keywords in Tables or Columns Generally, SQL developers advise against using reserved words. However, if you want (or need) to use a reserved word as a table or column name, you can place the respective identifier in special quotation marks, so-called backticks (` `), in the SQL statements.

How do I select a specific column in a query?

To select columns, choose one of the following options: Type SELECT , followed by the names of the columns in the order that you want them to appear on the report. Use commas to separate the column names.


1 Answers

From your question:

CREATE TABLE `test` (
    `count` VARCHAR(50) NULL DEFAULT NULL,
    `AND` VARCHAR(50) NULL DEFAULT NULL
----^---^ Why do you use `backtick` (`) in CREATE TABLE statement?
)

Same way you need to use backtick in SELECT statement.

SELECT `AND` FROM test;
-------^---^-----------

See MySQL: Reserved Words

like image 101
Himanshu Jansari Avatar answered Nov 13 '22 13:11

Himanshu Jansari