An alias in SQL is a temporary name assigned to a table or column in a query. It is typically used to make column names more readable or to shorten long table names. Aliases are often used when a column name is complex, or when you are working with data from multiple tables.
SQL aliases are created using the AS keyword. Aliases exist only for the duration of the query.
The basic syntax of an alias is as follows:
SELECT column_name AS alias_name
FROM table_name;You can also create an alias for a table like this:
SELECT t.column_name
FROM table_name AS t;Consider the following Products table:
| ProductID | ProductName | Category | Price | 
|---|---|---|---|
| 1 | Apple | Fruit | 1.50 | 
| 2 | Banana | Fruit | 0.75 | 
| 3 | Carrot | Vegetable | 0.90 | 
If you want to make the ProductName column more readable by renaming it as Item, you can use the following query:
SELECT ProductName AS Item, Price
FROM Products;This query will display the ProductName column as Item in the result set.
You can also assign an alias to a table, which is particularly useful in queries involving joins. For example:
SELECT p.ProductName, p.Price
FROM Products AS p;In this case, p is an alias for the Products table, allowing you to refer to it with a shorter name in the query.
The result of the query using the alias for ProductName would be:
| Item | Price | 
|---|---|
| Apple | 1.50 | 
| Banana | 0.75 | 
| Carrot | 0.90 | 
In this case, the ProductName column is now labeled as Item in the output.