In SQL, table and column aliases are used to provide alternative names for tables and columns in a query. Aliasing can make the query more concise, improve readability, and can be especially useful when dealing with complex queries or when joining multiple tables.
Table of Contents
ToggleAliasing Tables
Table aliases provide a shorter or more meaningful name for a table in a query. They are specified after the table name using the AS keyword or by simply placing a space between the table name and the alias.
SELECT alias.column1, alias.column2, ...
FROM table_name AS alias;
Or you can completely omit AS keyword and SQL will figure it out:
SELECT alias.column1, alias.column2, ...
FROM table_name alias;
- alias: Represents the alternative name for the table. Once declared, you can use it instead of original table name.
Let’s explore a query that retrieves employee information from a table named “employees”. We can assign the alias “emp” to the table:
SELECT emp.employee_id, emp.first_name, emp.last_name
FROM employees AS emp;
This query retrieves the “employee_id”, “first_name”, and “last_name” columns from the “employees” table using the “emp” alias.
Aliasing Columns
Just like tables, you can also create aliases for columns.
Column aliases provide alternative names for columns in the query result set. Aliased columns can be derived from expressions, functions, or existing column names. They are specified after the column name using the AS keyword or by simply placing a space between the column name and the alias.
SELECT column_name AS alias
FROM table_name;
- column_name: Represents the original column name.
- alias: Represents the alternative name for the column.
Consider a query that calculates the total salary for each employee using the SUM function (we will talk about SUM function in details later on). We can assign the alias “total_salary” to the calculated column:
SELECT employee_id, SUM(salary) AS total_salary
FROM employees
GROUP BY employee_id;
The query above retrieves the “employee_id” column along with the calculated sum of salaries for each employee, using the alias “total_salary”.
Using aliases for tables and columns can enhance the readability and clarity of your SQL queries, especially when dealing with large or complex queries. Aliases provide a convenient way to refer to tables and columns with shorter or more descriptive names, making the query more concise and understandable for other users.