100 Days of SQL

sql

Day 55 – SQL AS Keyword

SQL AS keyword is used to give an alias or a temporary name to a table or a column in the query result. It is often used to make the output more meaningful or to simplify the syntax of the query.

The syntax for using the AS keyword to assign an alias to a column is as follows:


SELECT column_name AS alias_name
FROM table_name;

Here, column_name is the name of the column in the table that you want to alias, and alias_name is the temporary name that you want to assign to the column.

For example, the following SQL statement selects the customer name and the total amount of orders, and assigns an alias TotalAmount to the calculated column:


SELECT Customers.CustomerName, SUM(Orders.Amount) AS TotalAmount
FROM Customers
JOIN Orders ON Customers.CustomerID = Orders.CustomerID
GROUP BY Customers.CustomerName;

In this case, the SUM function is used to calculate the total amount of orders for each customer, and the AS keyword is used to assign an alias TotalAmount to the calculated column in the query result.

The AS keyword can also be used to give an alias to a table or a subquery, like this:


SELECT *
FROM (SELECT column_name FROM table_name) AS alias_name;

In this case, the AS keyword is used to assign a temporary name alias_name to the subquery result set, which can then be used as a table in the outer query.