SQL Aliases
SQL aliases are used to give a table or a column in a table a temporary name. This can be helpful for simplifying queries, making the output more readable, and dealing with tables or columns that have complex or lengthy names.
Column Aliases
A column alias allows you to rename a column for the duration of a query. This is done using the AS
keyword.
Example:
Suppose you have a table named employees
with the following columns: emp_id
, first_name
, last_name
, and salary
.
SELECT emp_id AS ID, first_name AS "First Name", last_name AS "Last Name", salary AS "Monthly Salary"
FROM employees;
Output:
ID | First Name | Last Name | Monthly Salary |
---|---|---|---|
1 | John | Doe | 5000 |
2 | Jane | Smith | 6000 |
3 | Mike | Johnson | 5500 |
Table Aliases
A table alias allows you to rename a table for the duration of a query. This is particularly useful in complex queries involving multiple tables, especially in JOIN operations.
Example:
Suppose you have two tables: employees
and departments
. The employees
table has columns emp_id
, first_name
, last_name
, dept_id
, and the departments
table has columns dept_id
and dept_name
.
SELECT e.emp_id, e.first_name, e.last_name, d.dept_name
FROM employees AS e
JOIN departments AS d
ON e.dept_id = d.dept_id;
Output:
emp_id | first_name | last_name | dept_name |
---|---|---|---|
1 | John | Doe | HR |
2 | Jane | Smith | Finance |
3 | Mike | Johnson | IT |
Combined Example
You can combine column and table aliases to simplify your query even further.
Example:
SELECT e.emp_id AS ID, e.first_name AS "First Name", e.last_name AS "Last Name", d.dept_name AS "Department"
FROM employees AS e
JOIN departments AS d
ON e.dept_id = d.dept_id;
Output:
ID | First Name | Last Name | Department |
---|---|---|---|
1 | John | Doe | HR |
2 | Jane | Smith | Finance |
3 | Mike | Johnson | IT |
In this example, the table employees
is aliased as e
, the table departments
is aliased as d
, and columns are also given more readable names.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.