SQL Basics | DML: Data Manipulation Language | AS - Aliases
AS stands for alias. It is used to provide a temporary name, or alias, for a table or a table field. Aliases are often used to make column names easier to read, and they exist only while a query is running.
In short, field aliases are used to make SQL results easier to understand. In the example, summing sales produces the field name SUM(sales). That is fine in this case, but if the field is not a simple sum and becomes a complex expression, the field name also becomes complex. By using an alias for such a field, the field name shown in the result becomes easier to understand.
The second type of alias is a table alias. To add an alias to a table, put one space after the table name in the FROM clause and specify the alias. This is very useful when reading data from different tables with SQL.
AS syntax
Field and table aliases are specified as follows.
SELECT "table_alias"."field1" (AS) "field_alias"
FROM "table_name" (AS) "table_alias";
Basically, both aliases are specified after a table name or field name with one space. You can also explicitly write AS.
AS example
Consider the following store_information table.
store_information table
| store_name | sales | txn_date |
|---|---|---|
| Los Angeles | 1500 | Jan-05-2018 |
| San Diego | 250 | Jan-07-2018 |
| Los Angeles | 300 | Jan-08-2018 |
| Boston | 700 | Jan-08-2018 |
Use GROUP BY as follows and add a field alias and table alias.
SELECT A1.store_name Store, SUM(A1.sales) 'Total Sales'
FROM store_information A1
GROUP BY A1.store_name;
The result is as follows.
| Store | Total Sales |
|---|---|
| Los Angeles | 1800 |
| San Diego | 250 |
| Boston | 700 |
The data itself is the same in the result, but the field headings have changed. This is the use of field aliases. Instead of the heading “Sum (Sales)” for the second field, the heading “Total Sales” is displayed. Clearly, “Total Sales” shows the meaning of the field more clearly than “Sum(sales)”.