-->

MySQL ALIAS

Summary: In this chapter, we will learn how to use MySQL alias to improve the readability of the queries.

MySQL Alias To Make Queries More Readable

MySQL aliases are used to temporarily rename a table or a column heading. MySQL aliases are used to give a database table, or a column in a table, a temporary name. Basically aliases are created to make column names more readable.
MySQL supports two kinds of aliases which are column alias and table alias.
We will continue with the branches table data in the sample database as shown in the picture below.

MySQL alias for columns

Sometimes the column’s name are so technical that make the query’s output very difficult to understand. To make a column names more readable we use a column alias.

MySQL alias Syntax for Columns:

The following select query combines the columns city, state, country and postalcode into single column. The column heading is quite difficult to read CONCAT(city,’, ‘,state,’, ‘,Country,’-‘,postalcode). So here we can assign the heading of the output a column alias to make it more readable with Alias name “Address” as the following query.

MySQL alias for tables

we can use an alias to give a table a temporary name. The alias for the table is called table alias. Like the column alias, the AS keyword is optional so you can omit it.

MySQL alias Syntax for tables:

The following MySQL statement selects all the employees’s name from the employees tables with city name from branches table where branch is locate in ‘Pune’ and working on same branch.
1
2
3
4
5
6
SELECT
  e.firstname, e.lastname, b.city
FROM
  employees AS e, branches AS b
WHERE
  e.branchid = b.branchid AND b.city='Pune';
If we do not use alias in the query above, we have to use the table name to refer to its columns, which makes the query lengthy and less readable as the following:
1
2
3
4
5
6
SELECT
  employees.firstname, employees.lastname, branches.city
FROM
  employees, branches
WHERE
  employees.branchid = branches.branchid AND branches.city='Pune';