SQL Alias- sql - sql tutorial - learn sql
- Alias is a feature of SQL is supported by most or all, relational database management systems (RDBMSs).
- Aliases will provide database administrators, as well as other database users, with the ability to lesser the amount of code required for a query & to make queries simpler to understand.
- In addition, aliasing will be used as an obfuscation technique to protect the actual names of database fields.
- In SQL, you can alias tables & columns.
- A table alias is also called a correlation name.
- A programmer can use an alias to temporarily assign another name to a table / column for the duration of a SELECT query.
- Assigning an alias doesn’t actually rename the column / table.
- This is often useful when either tables or their columns have very long or complex names.
- Alias name could be anything, but usually it is kept short.
- For eg, it might be common to use a table alias such as "pi" for a table named "price_information".
- The general syntax of an alias is SELECT * FROM table_name [AS] alias_name.
- Note that the AS keyword is entirely optional & is usually kept for readability purposes. Here is some sample data that the queries below will be referencing:
- Alias refers to the practice of using a different temporary name to a database table / a column in a table.
- The main advantage of using an alias is to help make the SQL statement more concise & readable.
- In addition, the output of the SQL statement can become more understandable with the use of an alias.
Syntax
- The syntax for a table alias & a column alias is as follows:
- Both types of aliases are placed directly after the item they alias for, separate by a white space.
Example
- We use the following table for our example.
Table Store_Information
Store_Name | Sales | Txn_Date |
---|---|---|
Los Angeles | 1500 | Jan-05-1999 |
San Diego | 250 | Jan-07-1999 |
Los Angeles | 300 | Jan-08-1999 |
Boston | 700 | Jan-08-1999 |
- We use the same SQL query as Example 1 in the SQL GROUP BY section, except that we have put in both the column alias & the table alias:
Notice that difference in the result:
Store | Total Sales |
---|---|
Los Angeles | 1500 |
Los Angeles | 1800 |
San Diego | 250 |
Boston | 700 |
- The column titles are now different.
- That is the result of using the column alias.
- Instead of the somewhat cryptic "Sum(Sales)", we now have "Total Sales", which is much more understandable, as the column header.
- The advantage of using a table alias is not apparent in this example. However, they will become evident when we look at join operations in SQL.