SQL AS

The SQL AS keyword is a powerful tool in SQL that is used to assign a temporary alias (or name) to a table or a column. This alias can make complex SQL queries more readable and concise. Aliases are often used when you want to refer to a table or column with a different name within the query itself.

Aliases are especially helpful when:
- You need to simplify long column or table names.
- You want to make a query more readable by giving descriptive names to columns or tables.
- You are performing calculations or using expressions where the result needs a temporary name.

It's important to note that the alias name is only used within the context of the query and does not affect the actual table or column names in the database.

The AS keyword can be used for both columns and tables:

When renaming a table, the alias is often given as a short abbreviation, especially in queries that involve multiple tables. For example, you might rename a table Orders as O to simplify the query.

Example

In this example, we will use the AS keyword to give a temporary alias to the column name and table name for simplicity. This allows us to reference the columns in a more readable way.

Code Example


-- Using AS to give an alias to the column and table
SELECT Product AS ProductName, Price AS ProductPrice
FROM Orders AS O;
            

Output

ProductName ProductPrice
Laptop 1200.00
Phone 800.00
Tablet 600.00

Explanation

- In the query, we used the AS keyword to rename the Product column as ProductName and the Price column as ProductPrice.
- We also used AS to assign an alias O to the Orders table, simplifying the query.
- By renaming the columns and tables, we make it easier to understand the output and also prevent confusion in more complex queries, especially when dealing with joins or calculations.

The AS keyword is often used in reports and analytics where clarity and brevity are important, especially when working with large datasets.