what is alias in mysql?
MySQL ALIASES can be used to create a temporary name for columns or tables.
COLUMN ALIASES are used to make column headings in your result set easier to read.
TABLE ALIASES are used to shorten your SQL to make it easier to read or when you are performing a self join (ie: listing the same table more than once in the FROM clause).
Syntax :-
The syntax to ALIAS A COLUMN in MySQL is:
column_name [ AS ] alias_name
OR
The syntax to ALIAS A TABLE in MySQL is:
table_name [ AS ] alias_name
ALIAS a column
aliases are used to make the column headings in your result set easier to read.
SELECT department, MAX(salary) AS highest FROM employees GROUP BY department;
In this example, we've aliased the MAX(salary) field as highest. As a result, highest will display as the heading for the second column when the result set is returned.
it would have been perfectly acceptable to write this example using quotes as follows:
SELECT department, MAX(salary) AS "highest" FROM employees GROUP BY department;
Example
SELECT department, MAX(salary) AS "highest salary"
FROM employees
GROUP BY department;
In this example, we've aliased the MAX(salary) field as "highest salary". Since there are spaces in this alias_name, "highest salary" must be enclosed in quotes.
ALIAS a Table
When you create an alias on a table, it is either because you plan to list the same table name more than once in the FROM clause (ie: self join), or you want to shorten the table name to make the SQL statement shorter and easier to read.
SELECT p.product_id, p.product_name, suppliers.supplier_name
FROM products p
INNER JOIN suppliers
ON p.supplier_id = suppliers.supplier_id
ORDER BY p.product_name ASC, suppliers.supplier_name DESC;
When creating table aliases, it is not necessary to create aliases for all of the tables listed in the FROM clause. You can choose to create aliases on any or all of the tables.
SELECT p.product_id, p.product_name, s.supplier_name
FROM products p
INNER JOIN suppliers s
ON p.supplier_id = s.supplier_id
ORDER BY p.product_name ASC, s.supplier_name DESC;
Previous
Next