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?
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.
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With