SQL Tutorial on SQL Alias Syntax

you can rename a table or a column temporarily by giving another name known as alias. the use of table aliases is to rename a table in a specific sql statement. the renaming is a temporary change and the actual table name does not change in the database. the column aliases are used to rename a table's columns for the purpose of a particular sql query.

syntax

the basic syntax of a table alias is as follows.

select column1, column2....
from table_name as alias_name
where [condition];

the basic syntax of a column alias is as follows.

select column_name as alias_name
from table_name
where [condition];

example

consider the following two tables.

table 1 − customers table is as follows.

+----+----------+-----+-----------+----------+
| id | name     | age | address   | salary   |
+----+----------+-----+-----------+----------+
|  1 | ramesh   |  32 | ahmedabad |  2000.00 |
|  2 | khilan   |  25 | delhi     |  1500.00 |
|  3 | kaushik  |  23 | kota      |  2000.00 |
|  4 | chaitali |  25 | mumbai    |  6500.00 |
|  5 | hardik   |  27 | bhopal    |  8500.00 |
|  6 | komal    |  22 | mp        |  4500.00 |
|  7 | muffy    |  24 | indore    | 10000.00 |
+----+----------+-----+-----------+----------+

table 2 − orders table is as follows.

+-----+---------------------+-------------+--------+
|oid  | date                | customer_id | amount |
+-----+---------------------+-------------+--------+
| 102 | 2009-10-08 00:00:00 |           3 |   3000 |
| 100 | 2009-10-08 00:00:00 |           3 |   1500 |
| 101 | 2009-11-20 00:00:00 |           2 |   1560 |
| 103 | 2008-05-20 00:00:00 |           4 |   2060 |
+-----+---------------------+-------------+--------+

now, the following code block shows the usage of a table alias.

sql> select c.id, c.name, c.age, o.amount 
   from customers as c, orders as o
   where  c.id = o.customer_id;

this would produce the following result.

+----+----------+-----+--------+
| id | name     | age | amount |
+----+----------+-----+--------+
|  3 | kaushik  |  23 |   3000 |
|  3 | kaushik  |  23 |   1500 |
|  2 | khilan   |  25 |   1560 |
|  4 | chaitali |  25 |   2060 |
+----+----------+-----+--------+

following is the usage of a column alias.

sql> select  id as customer_id, name as customer_name
   from customers
   where salary is not null;

this would produce the following result.

+-------------+---------------+
| customer_id | customer_name |
+-------------+---------------+
|           1 | ramesh        |
|           2 | khilan        |
|           3 | kaushik       |
|           4 | chaitali      |
|           5 | hardik        |
|           6 | komal         |
|           7 | muffy         |
+-------------+---------------+