The AS keyword in SQL is used to rename a column or a table with an alias. This alias is temporary and only exists for the duration of the query. It is often used to make the output more readable or to simplify complex column names.
1. Renaming Columns
You can use AS to rename a column in the output of your query:
SELECT column_name AS alias_name
FROM table_name;
Example:
SELECT first_name AS "First Name", last_name AS "Last Name"
FROM employees;
This will display the column headers as "First Name" and "Last Name" instead of the original column names.
2. Renaming Tables
You can also use AS to create an alias for a table, which is useful in queries with joins or subqueries:
SELECT t.column_name
FROM table_name AS t;
Example:
SELECT e.first_name, e.last_name
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id;
Here, e is an alias for the employees table, and d is an alias for the departments table.
Key Notes:
- The
ASkeyword is optional in most cases. You can simply use a space instead ofASto define an alias. - For example, the following two queries are equivalent:
SELECT first_name AS "First Name" FROM employees; SELECT first_name "First Name" FROM employees;
However, using AS makes the query clearer and more readable.
No comments:
Post a Comment