The AS
clause in SQL is used to create an alias, which is a temporary name for a table or a column in a query. Aliases improve the readability of query results and make it easier to refer to tables or columns, especially when working with complex queries or calculations.
Key Points
For Columns:
TheAS
clause allows you to rename a column in the result set, making the output more descriptive or user-friendly.For Tables:
It simplifies table names, especially when dealing with multiple tables or self-joins.Not Mandatory:
TheAS
keyword is optional. You can directly specify the alias without it, but usingAS
improves clarity.
Examples
1. Renaming a Column
SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;
- Temporarily renames the
first_name
column to "First Name" andlast_name
to "Last Name" in the result set.
2. Using Aliases in Calculations
SELECT salary, salary * 0.10 AS "Tax Amount"
FROM employees;
- Adds a column called "Tax Amount" to the result set, showing 10% of the salary.
3. Renaming a Table
SELECT e.first_name, d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id;
- Renames
employees
toe
anddepartments
tod
for concise references in the query.
4. Without the AS
Keyword
SELECT salary * 0.10 "Tax Amount"
FROM employees;
- Works the same way, but explicitly using
AS
is considered clearer.
5. Combining Aliases with Aggregate Functions
SELECT department_id AS "Department", AVG(salary) AS "Average Salary"
FROM employees
GROUP BY department_id;
- Renames columns to make the result set more readable.
When to Use the AS
Clause
To make query results more readable for end-users or reports.
To simplify table references in complex queries.
To create meaningful names for calculated fields or aggregates.
Common Mistakes to Avoid
Using Aliases in
WHERE
orGROUP BY
Clauses:SELECT salary * 0.10 AS "Tax" FROM employees WHERE "Tax" > 5000; -- Error!
- Aliases cannot be used in
WHERE
orGROUP BY
. Use the actual column or calculation instead.
- Aliases cannot be used in
Forgetting Quotation Marks for Multi-Word Aliases:
SELECT first_name AS Full Name -- Error! FROM employees;
- Multi-word aliases must be enclosed in quotes:
"Full Name"
.
- Multi-word aliases must be enclosed in quotes:
Tips for Beginners
Use meaningful aliases to make your queries self-explanatory.
Always use the
AS
keyword for clarity, even though it’s optional.Remember, aliases are temporary and only exist during the query execution. They do not affect the database schema.
Example Combining Multiple Concepts
SELECT d.department_name AS "Department",
COUNT(e.employee_id) AS "Employee Count",
AVG(e.salary) AS "Average Salary"
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id
GROUP BY d.department_name
ORDER BY "Average Salary" DESC;
Renames columns and tables for readability.
Displays department names, employee counts, and average salaries, sorted by average salary in descending order.