readable, organized, and efficient. Instead of referring to a long, complicated column name,
you can give it a simpler, friendlier name that's easier to work with.
For example, suppose you have a table called sales_data that looks like this:
id | product_name | price | quantity | total
--------------------------------------------------
1 | Super Great Gizmo | 50 | 2 | 100
2 | Fantastic Gadget | 75 | 1 | 75
3 | Amazing Thingamajig | 100 | 3 | 300
If you wanted to calculate the average price of the products, you could use a query like this:
SELECT AVG(price) FROM sales_data;
But what if you want to give the result a more descriptive name, like average_product_price?
That's where column aliases come in! You can modify the query like this:
SELECT AVG(price) AS average_product_price FROM sales_data;
Now, when you run the query, the result will be labeled as average_product_price instead of
just AVG(price). This makes it much easier to understand what the result represents.
Column aliases can also be used to make complex queries more readable. Suppose you
have a table called employee_data that looks like this:
id | name | department_name | salary
---------------------------------------------
1 | John Smith | Sales | 50000
2 | Jane Doe | Marketing | 60000
3 | Bob Brown | IT | 70000
4 | Alice White | Sales | 55000
5 | Charlie Green | Marketing | 65000
6 | David Black | IT | 75000
If you wanted to calculate the average salary for each department, you could use a query
like this:
SELECT department_name, AVG(salary) FROM employee_data GROUP BY
department_name;
But this query can be difficult to read, especially if the department_name column has long,
complicated names. To make it more readable, you can use column aliases like this:
SELECT department_name AS dep, AVG(salary) AS avg_salary FROM employee_data
GROUP BY dep;
Now, the result will be labeled with the friendlier names dep and avg_salary, making it easier
to understand and work with.
Another useful feature of column aliases is that they can be used to rename columns in a
table. Suppose you have a table called old_table that looks like this: