We can give
alias
to tables or table columns.
In this example table column
first_name
will be displayed as
student_name
SELECT
id,
first_name AS student_name
FROM students
The keyword
AS
is optional, but it's better to use it, because the query is much more readable.
The following query returns the same result
SELECT
id,
first_name student_name
FROM students
We can use
alias
in
ORDER BY
clause to order the result
SELECT *, price * quantity AS total
FROM `orders`
ORDER BY total DESC
If
alias
is given to table, column of the table can be accessed by the alias followed by
.
SELECT
s.id,
s.first_name
FROM `students` s
In
SELF JOIN
alias is required, because MySQL needs to treat the tables as different tables
SELECT
s1.*,
s2.first_name
FROM `students` s1
JOIN `students` s2 ON s2.santa_id = s1.id
quotes
or backticks can be used in alias.
Possible options: single quote
'
, double quote
"
or backtick
`
SELECT
id,
first_name AS 'student_name'
FROM
students
Advantage of using
quotes
is that we can use space separated names in alias
SELECT
first_name,
last_name,
(points + 10) * 2 AS 'points calculated'
FROM students