An alias in SQL is a temporary name assigned to a table or a column for the duration of a query. It is mainly used to make column or table names easier to read and refer to, especially in complex queries involving joins, subqueries, or calculations.
SELECT column_name AS alias_name
FROM table_name;
(The AS keyword is optional.)
SELECT column_name
FROM table_name AS alias_name;
You can use an alias to rename a column in the result set.
SELECT FirstName AS First, LastName AS Last
FROM Employees;
First | Last |
---|---|
John | Doe |
Jane | Smith |
Here, FirstName is aliased as First, and LastName is aliased as Last in the query result, making the output more readable.
Table aliases are especially useful in queries with joins or self-joins.
SELECT E.FirstName, D.DepartmentName
FROM Employees AS E
JOIN Departments AS D ON E.DepartmentID = D.DepartmentID;
In this query:
Instead of repeating the full table names Employees and Departments throughout the query, the aliases E and D make the query easier to read and write.