Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SQL keyword as alias name of a column

I'm executing the following query but it is giving syntax error. Because the keyword key is registered in SQL

SELECT `id` AS key, `country_name` AS value FROM countries

I also tried using brackets like this but it's not working:

SELECT `id` AS [key], `country_name` AS value FROM countries

How to deal with it?

like image 411
Manish Jangir Avatar asked Dec 05 '14 06:12

Manish Jangir


People also ask

Can we use SQL keyword 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.

Which SQL keyword is used to provide an alias for a column name?

SQL AS keyword is used to give an alias to table or column names in the queries. In this way, we can increase the readability and understandability of the query and column headings in the result set.

How do I give an alias a column name?

You can declare an alias for any column in the select list of the Projection clause. The GROUP BY clause can reference the column by its alias. This temporary name is in scope only while the SELECT statement is executing.

Do you need to use AS in SQL for alias?

SQL allows the use of both column aliases and table aliases. This is done using the SQL AS keyword, which is an optional keyword in many SQL statements including SELECT, UPDATE, and DELETE. Column aliases allow you to use a different and often simpler name for a column in your query.


1 Answers

Use backtick(`) or Single Quote(') to give alias name of column in MySQL.

Try this:

SELECT `id` AS 'key', `country_name` AS value 
FROM countries;

OR

SELECT `id` AS `key`, `country_name` AS value 
FROM countries;
like image 98
Saharsh Shah Avatar answered Sep 30 '22 18:09

Saharsh Shah