Aliases are a way to give a table or column a temporary name in a SQL query. This can
make the query easier to read and write, especially when dealing with long table or column
names.
For example, consider the following query:
SELECT customer_name, order_date, order_total
FROM customer_orders
WHERE customer_name = 'John Doe';
In this query, we're selecting the customer_name, order_date, and order_total columns from
the customer_orders table, and filtering the results to only include rows where the
customer_name is 'John Doe'. This query works fine, but it could be more difficult to read if
the table and column names were longer.
To make the query easier to read, we could use aliases, like this:
SELECT co.customer_name, co.order_date, co.order_total
FROM customer_orders AS co
WHERE co.customer_name = 'John Doe';
In this query, we've given the customer_orders table the alias co, and used that alias to refer
to its columns. This makes the query a little easier to read, especially if the table and column
names were longer.
There are a few things to keep in mind when using aliases in SQL queries:
Aliases can be used for both tables and columns. In the example above, we used an alias
for the customer_orders table, but we could also have used aliases for the customer_name,
order_date, and order_total columns.
Aliases can be given using either the AS keyword or by simply assigning the alias with no
keyword. In the example above, we used the AS keyword to assign the co alias to the
customer_orders table, but we could have also written it like this: FROM customer_orders
co.
Aliases must be unique within the query. This means that you can't use the same alias for
both a table and a column in the same query.
Aliases are not case-sensitive in most databases. This means that you can use either
uppercase or lowercase letters when assigning and using Aliases, and it won't make a
difference.
Suppose we have a table called employee_salaries, with the following columns:
employee_id, first_name, last_name, department, salary.
If we want to find the total salary for each department, we could write the query like this:
SELECT department, SUM(salary) as total_salary
FROM employee_salaries