MySQL Aliases
An alias is a temporary name for a column or a table. It exists only while the query runs. You create it with AS.
Column alias
SELECT name AS student_name, marks AS score FROM students LIMIT 2;
Result
| student_name | score |
|---|---|
| Robin | 85 |
| Maria | 92 |
The headers of the result are now the alias names. This is useful for calculated columns.
SELECT name, marks + 5 AS marks_with_bonus FROM students LIMIT 2;
Result
| name | marks_with_bonus |
|---|---|
| Robin | 90 |
| Maria | 97 |
If the alias has a space, put it in backticks: AS `total marks`.
Table alias
A table alias is a short name for a table. It makes long queries shorter, and it is needed when you join a table with itself.
SELECT s.name, c.course_name
FROM students AS s
JOIN courses AS c ON s.course_id = c.id
ORDER BY s.id
LIMIT 2;
Result
| name | course_name |
|---|---|
| Robin | Python |
| Maria | Java |
You can leave out the word AS: FROM students s works the same. Learn JOINs in a later chapter.
Note:
You cannot use a column alias in the WHERE clause, because WHERE runs before the alias is created. You can use it in ORDER BY and GROUP BY.
Summary
column AS aliasrenames a column in the result.table AS tgives a short name to a table.- Next: Aggregate functions.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |