SQL - Select As

The AS clause in SQL is used to provide an alias or alternative name for a column or table in a query. It allows you to assign a temporary name to a column or table, making the query results more readable and facilitating the use of calculated values or joins. The AS clause is optional, but it can greatly enhance the clarity and understandability of complex queries.

Syntax:

The AS clause can be used in two different contexts:

Alias for a Column:

SELECT column_name AS alias_name
FROM table_name;

Alias for a Table:

SELECT column_name
FROM table_name AS alias_name;

Example:

Let's assume we have a "Customers" table with the following columns:

CustomerID (unique identifier for each customer)

CustomerName (name of the customer)

City (city where the customer is located)

Age (age of the customer)

1. Alias for a Column:

To provide an alias for the CustomerName column as "Name" in the query result, we can use the following query:

SELECT CustomerName AS Name, Age
FROM Customers;

2. Alias for a Table:

To provide an alias for the "Customers" table as "C" in the query, we can use the following query:

SELECT C.CustomerName, C.City, C.Age
FROM Customers AS C;

Explanation:

In the first example, the AS clause is used to assign an alias "Name" to the CustomerName column. As a result, the query output will display the column name as "Name" instead of "CustomerName".

In the second example, the AS clause is used to provide an alias "C" for the "Customers" table. This allows us to refer to the table using the shorter and more readable alias "C" throughout the query.

By using aliases, you can make your SQL queries more expressive and concise, especially when dealing with complex joins, subqueries, or calculated values. Aliases can be helpful in improving the readability of query results, especially when working with large datasets or complex queries involving multiple tables.