SQL Aliases Tutorial
Example Table
We will use the following table named employees
for our examples:
CREATE TABLE employees (
id INT PRIMARY KEY,
first_name VARCHAR(50),
last_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10, 2)
);
INSERT INTO employees (id, first_name, last_name, department, salary) VALUES
(1, 'John', 'Doe', 'Engineering', 75000.00),
(2, 'Jane', 'Smith', 'Marketing', 65000.00),
(3, 'Sam', 'Brown', 'Engineering', 80000.00),
(4, 'Sue', 'Johnson', 'HR', 60000.00),
(5, 'Mike', 'Davis', 'Marketing', 70000.00);
id | first_name | last_name | department | salary |
---|---|---|---|---|
1 | John | Doe | Engineering | 75000.00 |
2 | Jane | Smith | Marketing | 65000.00 |
3 | Sam | Brown | Engineering | 80000.00 |
4 | Sue | Johnson | HR | 60000.00 |
5 | Mike | Davis | Marketing | 70000.00 |
Using Column Aliases
Column aliases are used to give a column in a table a temporary name. This can make the column header in your result set more readable.
SELECT first_name AS 'First Name', last_name AS 'Last Name', salary AS 'Annual Salary' FROM employees;
Result:
First Name | John |
---|---|
Last Name | Doe |
Annual Salary | 75000.00 |
Using Table Aliases
Table aliases are used to give a table a temporary name, often used to make queries easier to read and write, especially when dealing with multiple tables.
SELECT e.first_name, e.last_name, e.salary FROM employees AS e;
Result:
first_name | John |
---|---|
last_name | Doe |
salary | 75000.00 |
Using Aliases in Joins
Aliases are particularly useful in JOIN operations to distinguish columns from different tables.
CREATE TABLE departments (
id INT PRIMARY KEY,
name VARCHAR(50)
);
INSERT INTO departments (id, name) VALUES
(1, 'Engineering'),
(2, 'Marketing'),
(3, 'HR');
SELECT e.first_name, e.last_name, d.name AS 'Department'
FROM employees AS e
JOIN departments AS d ON e.department = d.name;
Result:
first_name | John |
---|---|
last_name | Doe |
Department | Engineering |