In this SQL tutorial for beginners, you will learn about SQL SELECT AS
Alias with the help of examples.
The AS
keyword is used to give columns or tables a temporary name that can be used to identify that column or table later.
SELECT last_name AS name
FROM Customers;
Here, the SQL command selects the last_name column from the Customers table. However, the column name is changed to name in the result set.
The syntax of the SQL AS
command is:
SELECT column_1 AS alias_1,
column_2 AS alias_2,
…... column_n AS alias_n
FROM table_name;
Here,
column_1, column_2,...column_n
are the table columnsalias_1, alias_2,...alias_n
are the aliases of the table columnsFor example,
SELECT first_name AS name
FROM Customers;
Here, the SQL command selects the first_name column of Customers. However, the column name will change to name in the result set.
Example: SQL AS Alias
We can also use aliases with more than one column.
For example,
SELECT customer_id AS cid, first_name AS name
FROM Customers;
Here, the SQL command selects customer_id as cid and first_name as name.
We can combine data from multiple columns and represent it in a single column using the CONCAT()
function. For example,
SELECT CONTACT(first_name, ' ', last_name) AS full_name
FROM Customers;
Here, the SQL command selects first_name and last_name. And, the name of the column will be full_name in the result set.
However, our online compiler does not support the CONCAT()
function since it uses the SQLite library. Instead, you need to use the concatenation operator ||
to perform this task.
For example, here's an equivalent code that will run in our compiler.
-- concatenate first_name, empty space, and last_name into a single column named full_name in the result set
SELECT first_name || ' ' || last_name AS full_name
FROM Customers;
Here, the SQL command will concatenate the first_name and last_name columns in the result set as full_name.
Notice that we have also concatenated an empty space ' '
between first_name and last_name. This ensures that the data from these columns are separated by a space in the result set.
Example: SQL AS Alias With Expression
#sql