SQL Aliases
SQL aliases are used to give a table or a column in a table a temporary name. Aliases are often used to make column names more readable.
Column Alias
A column alias is created with the AS
keyword. It is used to rename a column for the duration of a query.
Syntax
SELECT column_name AS alias_name
FROM table_name;
Example 1: Column Alias
SELECT first_name AS name
FROM employees;
This query selects the first_name
column from the employees
table and renames it to name
.
Example 2: Multiple Column Aliases
SELECT first_name AS name, salary AS income
FROM employees;
This query selects the first_name
and salary
columns from the employees
table and renames them to name
and income
respectively.
Table Alias
A table alias is created with the AS
keyword. It is used to rename a table for the duration of a query.
Syntax
SELECT column_name(s)
FROM table_name AS alias_name;
Example 3: Table Alias
SELECT e.first_name, e.last_name
FROM employees AS e;
This query selects the first_name
and last_name
columns from the employees
table and uses the alias e
for the table.
Example 4: Table Alias with JOIN
SELECT o.order_id, c.customer_name
FROM orders AS o
JOIN customers AS c ON o.customer_id = c.customer_id;
This query selects the order_id
from the orders
table and customer_name
from the customers
table, using aliases o
and c
respectively, and joins them on the customer_id
.
Benefits of Using Aliases
- Makes column and table names more readable and understandable.
- Shortens the query when using long table names or column names.
- Improves query clarity, especially when using JOIN operations.
Tips
- Aliases only exist for the duration of the query.
- Column aliases are displayed in the result set.
- Table aliases are used to reference tables in the query.
SQL aliases are powerful tools for making your SQL queries more readable and maintainable. By using aliases, you can simplify complex queries and make them easier to understand.