1. sql
  2. /references
  3. /aliases

SQL Aliases

Definition

In SQL, an alias is a temporary name that you can give to a table, view, or column. Aliases are often used to make column names more readable, or to make it easier to join tables using columns with different names.

Examples

Below are some examples of how aliases can be used:

Aliasing a table name

Aliasing a table name allows you to use a different name to refer to the table in your query, such as:

SELECT * 
FROM customers AS c

In this example, the customers table is given the alias c. You can then use the alias c to refer to the table in the rest of the query, like this:

SELECT c.customer_name, c.country 
FROM customers AS c

Aliasing a column name

Aliasing a column name allows you to use a different name to refer to the column in your query. For example:

SELECT customer_name AS name, country 
FROM customers

In the example above, the customer_name column is given the alias name. You can then use the alias name to refer to the column in the rest of the query, like this:

SELECT customer_name AS name, country 
FROM customers 
WHERE name LIKE 'A%'

Aliasing an expression

You can also use aliases to give a name to an expression or computed column:

SELECT customer_name, country, order_total*1.1 AS 'total_inc_tax' 
FROM orders

As a result, the expression order_total*1.1 is given the alias total_inc_tax. You can then use the alias total_inc_tax to refer to the expression in the rest of the query, like this:

SELECT customer_name, country, order_total*1.1 AS 'total_inc_tax' 
FROM orders 
WHERE 'total_inc_tax' > 1000

Best Practices

Here are some best practices to consider when using SQL aliases:

  • Choose meaningful alias names. It's a good idea to choose alias names that are meaningful and make sense in the context of your query. For example, if you're aliasing a column that contains customer names, you might use the alias customer_name or name rather than something obscure like col1.
  • Use uppercase letters for SQL keywords and lowercase letters for everything else. This is a common practice that helps to make your queries more readable.
  • Avoid using spaces or special characters in alias names. Some databases don't allow spaces or special characters in alias names. To be safe, it's a good idea to stick to using letters, numbers, and underscores in your alias names.
  • Use table aliases to disambiguate column names. If you're joining multiple tables and some of the tables have columns with the same name, you can use table aliases to distinguish between them.
  • Use column aliases to make your query results more readable. If you're using an expression or computed column in your query, you can use a column alias to give the result a more meaningful name.