SQL Aliases - How to Use Aliases in SQL Queries



Demo wikitechydatabase

  • Below is a selection from the wikitechytable table used in the examples:
sql-aliases-1
  • In SQL, aliases and the AS keyword are used to provide temporary names or labels for tables and columns in queries. They are essential for enhancing the readability of SQL queries and can also be helpful in cases where you need to rename columns or tables for various purposes, such as joining tables or calculating derived values.
  • Here's an explanation of aliases and the AS command in SQL:
sql-aliases-2

1. Table Aliases:

  • Alias without AS : You can assign an alias to a table without explicitly using the AS keyword. This is typically done to make the SQL query more readable or to simplify table references in complex queries. For example:
SELECT w.name, w.gender FROM wikitechytable w WHERE w.gender = 'male'

Output 1:

sql-aliases-2
  • In this query, "w" is an alias for the "wikitechytable" table. It allows you to refer to the table as "w" in the rest of the query, making the code more concise.
  • Alias with AS: You can also use the AS keyword to assign an alias to a table. The following query is equivalent to the one above:
SELECT w.name, w.gender FROM wikitechytable AS w WHERE w.gender = 'male'

Output 2

sql-aliases-3
  • Both of these approaches are valid, and the choice between them is a matter of coding style.

2. Column Aliases:

  • Alias without AS : You can provide an alias for a column without using the AS keyword. This is often used to rename columns in the result set. For example:
SELECT id 'S. No' , name FullName, fees fee FROM wikitechytable 

Output 1:

sql-aliases-4
  • In this query, "S.NO", “FullName” and "fee" are aliases for the "id", “name” and "fees " columns, respectively.
  • Alias with AS : You can use the AS keyword to assign an alias to a column. This is the more common and widely accepted way of creating column aliases:
SELECT id AS 'S. No', name AS FullName, fees AS fee FROM wikitechytable

Output 2

sql-aliases-5
  • Using AS is recommended for column aliases as it's more explicit and universally supported.
  • In summary, aliases and the AS keyword in SQL are used to provide temporary names or labels to tables and columns within queries.
  • They improve query readability, facilitate self-joins, and allow for renaming columns in result sets. While table aliases can be defined with or without AS, it's common and recommended to use AS for column aliases.

Related Searches to SQL Aliases - How to Use Aliases in SQL Queries