In SQL, an alias is a temporary name given to a column or table in a query. The purpose of using aliases is to make column names or table names more readable or to change the name of a column or table for the duration of a query.
To use an alias, you can use the AS
keyword in the SELECT
statement, followed by the desired alias name. Here is an example:
SELECT column_name AS alias_name
FROM table_name;
For example, consider a sales
table with the following data:
date | product_name | quantity | price |
---|---|---|---|
2021-01-01 | Apple | 10 | 2.00 |
2021-01-01 | Orange | 15 | 1.50 |
2021-01-02 | Apple | 20 | 2.00 |
2021-01-02 | Orange | 25 | 1.50 |
The following query returns the total sales for each product, along with the product name:
SELECT product_name, SUM(quantity * price) AS total_sales
FROM sales
GROUP BY product_name;
Result:
product_name | total_sales |
---|---|
Apple | 50.00 |
Orange | 57.50 |
In this example, the AS
keyword is used to create an alias for the calculated column SUM(quantity * price)
, which is given the name total_sales
.
You can also use aliases for table names. For example:
SELECT s.date, s.product_name, SUM(s.quantity * s.price) AS total_sales
FROM sales AS s
GROUP BY s.product_name;
In this example, the table sales
is given the aliases
.
In conclusion, aliases in SQL can be used to make column names or table names more readable or to change the name of a column or table for the duration of a query. Using aliases can make your SQL code more readable and understandable.
Also check WHAT IS GIT ? It’s Easy If You Do It Smart
You can also visite the Git website (https://git-scm.com/)