SQL Tutorial

SQL Introduction SQL Aggregate Functions SQL Aliases SQL And SQL Any All SQL Avg SQL Between SQL Case SQL Comments SQL Count SQL Delete SQL Distinct SQL Exists SQL Groupby SQL Having SQL In SQL Insert_into SQL Is Not Null SQL Join SQL Full Outer Join SQL Inner Join SQL Left Join SQL Right Join SQL Self Join SQL Like SQL Min Max SQL NOT Operator SQL Null SQL Operators SQL OR operator SQL OrderBy SQL Select SQL Select Into SQL Top Limit Fetch SQL Store Procedures SQL Sum SQL Union SQL Update SQL Where SQL Wildcards

SQL Database

SQL Alter Table SQL Auto increment SQL BackupDB SQL Check SQL Constrains SQL Create View SQL CreateDB SQL CreateTable SQL Data types SQL Dates SQL DefaultConstrain SQL DropDB SQL DropTable SQL Foreign Key SQL Hosting SQL Index SQL injections SQL Not NULL SQL PrimaryKey SQL Unique SQL Views

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