The aliases in MySQL may be used to improve readability of the queries. There are two kinds of aliases supported by MySQL, and these are:
- column alias
- table alias
Column aliases in MySQL
To give a column of a database an alias, the keyword AS is used. The example below shows it how:
SELECT [column | expression] AS `new name`
FROM table;
The keyword AS is optional and may be omitted, so the above example would look like this:
SELECT [column | expression] `new name`
FROM table;
Very often aliases are used in combination with operators such as GROUP BY and HAVING, or clauses such as WHERE. The example below shows how that looks like those clauses applied:
SELECT sizeShoe `Shoe size.`,
SUM (priceShoe * quantityShoe) Total
FROM detailsShoe
GROUP BY ` Shoe size.`
HAVING size > 11.5;
Table aliases in MySQL
Table aliases are used to give table a different, more suitable name. By the default it is create with the keyword AS, but same as with the column aliases, the keyword AS may be omitted.
Table aliases are often used in statements containing INNER JOIN, LEFT JOIN and SELF JOIN, clauses, as well as in sub-queries.
Please take a look at the example below to get a better idea how and when to create a table alias.
Example
Querying two tables by selecting one item from each:
SELECT customerName,
COUNT(o.orderNumber) total
FROM customers c
INNER JOIN orders o ON c.customerNumber = o.customerNumber
GROUP BY customerName
ORDER BY total DESC;
Comments
No comments have been made yet.
Please login to leave a comment. Login now