In a SELECT
statement, we can use aliases to temporarily rename columns or tables for better readability. The syntax for creating a column alias is as follows:
SELECT column_name AS alias_name
FROM table_name;
Think of SQL aliases like nicknames. Suppose you have a friend named "Jonathan Vincent Richard." Instead of calling him by his full name every time, you simply call him "Jon." Similarly, SQL aliases are used to temporarily rename columns or tables for the duration of a query. Aliases make SQL queries more readable, concise, and easier to work with, especially when dealing with complex queries.
Aliases exist only for the duration of the query and don’t affect the actual column or table names in the database schema.
SQL aliases are temporary names given to columns or tables in SQL queries. They allow us to simplify references to these elements, making our SQL code more readable and manageable, especially when dealing with complex data operations or long table names.
Aliases are used in SELECT
queries, WHERE
clauses, JOIN
conditions, and more. They don’t modify the original column or table names in the database; they only provide a shorthand for use within a query.
The syntax for defining a column alias is simple. We use the AS
keyword (optional) to assign a new name to a column in the result set. Here's how we can do it:
SELECT column_name AS alias_nameFROM table_name;
column_name
: The name of the column we want to alias.
alias_name
: The temporary name we want to assign to the column.
AS
: The keyword that assigns the alias (optional, can be omitted).
Let's say we have a table called employees
with a column named first_name
. We can assign a column alias to make the result more user-friendly.
-- Step 1: Create the databaseCREATE DATABASE company;-- Step 2: Switch to the databaseUSE company;-- Step 3: Create the employees tableCREATE TABLE employees (employee_id INT AUTO_INCREMENT PRIMARY KEY,first_name VARCHAR(50) NOT NULL,last_name VARCHAR(50) NOT NULL,department VARCHAR(50),salary DECIMAL(10, 2));-- Step 4: Insert sample data into the employees tableINSERT INTO employees (first_name, last_name, department, salary)VALUES('Alice', 'Johnson', 'HR', 60000.00),('Bob', 'Smith', 'Engineering', 75000.00),('Charlie', 'Brown', 'Marketing', 50000.00),('Diana', 'Garcia', 'Engineering', 82000.00),('Eve', 'Martinez', 'Finance', 70000.00);-- Step 5: Run the query to retrieve employee names with an aliasSELECT first_name AS "Employee Name"FROM employees;-- Exercise for Learners-- Modify the query to include last names along with first names:-- SELECT CONCAT(first_name, ' ', last_name) AS "Full Name" FROM employees;
This will display the results with the column header as "Employee Name"
instead of first_name
.
Modify or uncomment the query at line 31 to display full names instead of just first names by concatenating first_name
and last_name
.
AS
keywordWe can omit the AS
keyword, and it will still work the same way.
-- Example 2: Without AS keyword for column alias-- We can omit the AS keyword, and it will still work the same way.-- Step 1: Create the databaseCREATE DATABASE company;-- Step 2: Switch to the databaseUSE company;-- Step 3: Create the employees tableCREATE TABLE employees (employee_id INT AUTO_INCREMENT PRIMARY KEY,first_name VARCHAR(50) NOT NULL,last_name VARCHAR(50) NOT NULL,department VARCHAR(50),salary DECIMAL(10, 2));-- Step 4: Insert sample data into the employees tableINSERT INTO employees (first_name, last_name, department, salary)VALUES('Alice', 'Johnson', 'HR', 60000.00),('Bob', 'Smith', 'Engineering', 75000.00),('Charlie', 'Brown', 'Marketing', 50000.00),('Diana', 'Garcia', 'Engineering', 82000.00),('Eve', 'Martinez', 'Finance', 70000.00);-- Query: Retrieve employee names without using ASSELECT first_name "Employee Name"FROM employees;-- Explanation:-- In this case, the output will still show "Employee Name" as the column header.-- Spaces in alias names: Use double quotes (" ") if the alias has spaces.-- Case sensitivity: Aliases are typically case-insensitive unless enclosed in quotes,-- which makes them case-sensitive in some databases (e.g., PostgreSQL).
In this case, the output will still show "Employee Name"
as the column header.
Parameter explanation:
When using column aliases, there are a few important things to keep in mind:
Spaces in alias names: If we want to use an alias with spaces, enclose the alias in double quotes (" "
). For example, "Employee Name"
.
Case sensitivity: By default, aliases are case-insensitive in most databases, but this behavior can change depending on the database system (e.g., PostgreSQL treats aliases in quotes as case-sensitive).
Using aliases in expressions: We can also create aliases for expressions, such as concatenating columns or performing mathematical operations.
-- Example 3: Alias for expressions-- Step 1: Create the databaseCREATE DATABASE company;-- Step 2: Switch to the databaseUSE company;-- Step 3: Create the employees tableCREATE TABLE employees (employee_id INT AUTO_INCREMENT PRIMARY KEY,first_name VARCHAR(50) NOT NULL,last_name VARCHAR(50) NOT NULL,department VARCHAR(50),salary DECIMAL(10, 2));-- Step 4: Insert sample data into the employees tableINSERT INTO employees (first_name, last_name, department, salary)VALUES('Alice', 'Johnson', 'HR', 60000.00),('Bob', 'Smith', 'Engineering', 75000.00),('Charlie', 'Brown', 'Marketing', 50000.00),('Diana', 'Garcia', 'Engineering', 82000.00),('Eve', 'Martinez', 'Finance', 70000.00);-- Query: Concatenate first_name and last_name to create a "Full Name" columnSELECT CONCAT(first_name, ' ', last_name) AS "Full Name"FROM employees;-- Explanation:-- The CONCAT function combines the first_name and last_name into one string.-- The AS keyword creates a column alias named "Full Name."-- This alias will appear as the header for the concatenated values.
This will display the concatenation of first_name
and last_name
as a new column named "Full Name"
.
While column aliases simplify results, table aliases are equally useful when working with multiple tables in JOIN queries.
Just as we can create column aliases, we can also create aliases for tables. A table alias simplifies queries, especially when working with joins or complex queries.
SELECT column_nameFROM table_name AS alias_name;
table_name
: The name of the table we want to alias.
alias_name
: The temporary name we want to assign to the table.
Let’s say we have a table employees
and we want to join it with another table, departments
, using aliases to make the query easier to read.
-- Example 4: Table alias with AS keyword-- Step 1: Create the databaseCREATE DATABASE company;-- Step 2: Switch to the databaseUSE company;-- Step 3: Create the employees and departments tableCREATE TABLE departments (department_id INT AUTO_INCREMENT PRIMARY KEY,department_name VARCHAR(50) NOT NULL);CREATE TABLE employees (employee_id INT AUTO_INCREMENT PRIMARY KEY,first_name VARCHAR(50) NOT NULL,last_name VARCHAR(50) NOT NULL,department_id INT,salary DECIMAL(10, 2),FOREIGN KEY (department_id) REFERENCES departments(department_id) -- Establish relationship);-- Step 4: Insert sample data into the departments and employees tableINSERT INTO departments (department_name)VALUES('HR'),('Engineering'),('Marketing'),('Finance');INSERT INTO employees (first_name, last_name, department_id, salary)VALUES('Alice', 'Johnson', 1, 60000.00),('Bob', 'Smith', 2, 75000.00),('Charlie', 'Brown', 3, 50000.00),('Diana', 'Garcia', 2, 82000.00),('Eve', 'Martinez', 4, 70000.00);-- Query: Use table aliases for employees and departments tablesSELECT e.first_name, d.department_nameFROM employees AS eJOIN departments AS dON e.department_id = d.department_id;-- Explanation:-- e is the alias for the employees table.-- d is the alias for the departments table.-- These aliases make the query concise and easier to write, especially in joins.
Here, e
is the alias for the employees
table, and d
is the alias for the departments
table. These aliases make the query more concise and easier to write, especially when referencing multiple tables.
AS
for table aliasWe can also create table aliases without using the AS
keyword. This is common in many SQL queries.
-- Example 5: Table alias without AS keyword-- Step 1: Create the databaseCREATE DATABASE company;-- Step 2: Switch to the databaseUSE company;-- Step 3: Create the employees and departments tableCREATE TABLE departments (department_id INT AUTO_INCREMENT PRIMARY KEY,department_name VARCHAR(50) NOT NULL);CREATE TABLE employees (employee_id INT AUTO_INCREMENT PRIMARY KEY,first_name VARCHAR(50) NOT NULL,last_name VARCHAR(50) NOT NULL,department_id INT,salary DECIMAL(10, 2),FOREIGN KEY (department_id) REFERENCES departments(department_id) -- Establish relationship);-- Step 4: Insert sample data into the departments and employees tableINSERT INTO departments (department_name)VALUES('HR'),('Engineering'),('Marketing'),('Finance');INSERT INTO employees (first_name, last_name, department_id, salary)VALUES('Alice', 'Johnson', 1, 60000.00),('Bob', 'Smith', 2, 75000.00),('Charlie', 'Brown', 3, 50000.00),('Diana', 'Garcia', 2, 82000.00),('Eve', 'Martinez', 4, 70000.00);-- Query: Table aliases without the AS keywordSELECT e.first_name, d.department_nameFROM employees eJOIN departments dON e.department_id = d.department_id;-- Explanation:-- Even without the AS keyword, the aliases e and d work the same way.-- The query is functionally identical to Example 4.
Even without AS
, the aliases e
and d
will still work the same way.
Column aliases: Use column aliases to rename fields for readability, especially when displaying results. Use table aliases to simplify complex queries, like JOIN operations, and reduce typing.
Table aliases: Simplify queries, especially when dealing with multiple tables, by assigning shorter names to tables. This helps in complex queries like joins.
Flexibility: Aliases can be used for expressions, making it easier to work with calculated fields in queries.
Quoting aliases: If the alias contains spaces or special characters, enclose it in double quotes. Otherwise, it’s optional to use the AS
keyword.
No impact on database: Aliases don’t modify the actual column or table names in the database; they’re only for use in the current query.
Select the SQL query that shows all the columns and also creates a new column called total_price
, which shows the result of multiplying quantity
by unit_price
for each order.
SELECT order_id, product_name, quantity, unit_price, quantity * unit_price AS total_price
FROM orders;
SELECT order_id, product_name, quantity, unit_price AS total_price
FROM orders;
SELECT order_id, product_name, quantity * unit_price AS total_price
FROM orders;
Ready to learn SQL and become a database expert? Join our Learn SQL course and follow the path to becoming a Database Professional with SQL! Unlock your potential and gain the skills employers seek. Start your journey today!
Haven’t found what you were looking for? Contact Us