An alias is a temporary name given to a table or column in a SQL query.
- Aliases do not change the actual table or column names in the database.
- Useful for making column names more readable, simplifying queries, or renaming tables in joins.
Syntax:
- Column alias:
- Table alias:
The
ASkeyword is optional for both column and table aliases.
Step 1: Example table
Assume the Employees table:
| EmployeeID | FirstName | LastName | Department | Salary |
|---|---|---|---|---|
| 1 | John | Doe | IT | 5000 |
| 2 | Jane | Smith | HR | 4500 |
| 3 | Mike | Brown | IT | 6000 |
Step 2: Column alias
Example: Rename Salary column to MonthlySalary
Result:
| FirstName | LastName | MonthlySalary |
|---|---|---|
| John | Doe | 5000 |
| Jane | Smith | 4500 |
| Mike | Brown | 6000 |
AS MonthlySalarygives a temporary name to the column in the result set.
Step 3: Table alias
Example: Use a table alias e for Employees
Result:
| FirstName | Department |
|---|---|
| John | IT |
| Jane | HR |
| Mike | IT |
Table alias
eis useful in joins or long table names.
Step 4: Using alias in calculations
Example: Calculate Annual Salary with column alias
Result:
| FirstName | Salary | AnnualSalary |
|---|---|---|
| John | 5000 | 60000 |
| Jane | 4500 | 54000 |
| Mike | 6000 | 72000 |
AnnualSalaryis a friendly name for the calculated column.
Step 5: Aliases in JOINs
Example: Joining Employees with Departments table using aliases
- e → Employees
- d → Departments
Shorter names make complex queries easier to read.
