The English word “alias” means an assumed or additional name that a person sometimes uses. This meaning is not very far from what it stands for in SQL.
Aliases in SQL are names that you can allocate to a table or table column for use in a single SQL query. In other words, an alias is a makeshift variable or temporary name for these tables and columns.
You can use an alias for the following scenarios:
join
statement, as it can prevent confusion."AS"
keyword.SELECT column_name AS alias_name FROM table_name AS alias_name;
SELECT
and FROM
: query commands.column_name
: the name of the table column to be renamed."AS"
: the keyword used to create aliases.alias_name
: temporary alias name to be used to replace the original column name.table_name
: the name of the table being queried.
In the syntax above, we create an alias for both the column and table, and we can keep using these aliases in the query if it continues.Below is a products table and a category table. cat_id
is a foreign key in the products
table, which is equal to the id
column on the category
table.
id | Product_name | price | cat_id | product_no |
1 | Miler Table Fan | $300 | 2 | JH353 |
2 | Rollex Goldwatch | $1000 | 1 | 7858ty |
3 | Magic Blender | $50 | 2 | GT45Y |
4 | Rew Rotatable Chair | $200 | 3 | 456hu |
id | cat_name |
1 | Fashion Accessories |
2 | Home Electronics |
3 | Office Accessories |
4 | Kitchen Accessories |
Let’s use aliases to query these tables.
SELECT p.product_name, p.price, p.product_no, c.cat_nameFROM products AS p JOIN category AS cON p.cat_id = c.idWHERE c.cat_id = 2;
Imagine having to write out product.column_name
or category.column_name
for every column in the query; we will surely have a long SQL query block.
Upon successful execution, the output of the query will be as follows.
product_name | price | product_no | cat_name |
Miller Table Fan | $300 | JH353 | Home Electronics |
Magic Blender | $50 | GT45Y | Home Electronics |