In SQL, aliases are temporary names assigned to columns or tables in a query to make the SQL statements more readable or concise. They are particularly useful when dealing with long table or column names, performing self-joins, or when using subqueries.
Here's how you can use aliases in SQL:
SELECT column_name AS alias_name
FROM table_name;
SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;
Table Aliases: You can assign aliases to tables in the FROM clause.
SELECT alias_name.column_name
FROM table_name AS alias_name;
SELECT e.first_name, d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id;
Alias for Subqueries: You can also assign aliases to subqueries.
SELECT alias_name.column_name
FROM (subquery) AS alias_name;
SELECT e.first_name, e.last_name, d.department_name
FROM (
SELECT *
FROM employees
WHERE salary > 50000
) AS e
JOIN departments AS d ON e.department_id = d.department_id;
Aliases help to improve the readability of SQL queries, especially in cases where the table or column names are long or complex.