A MySQL alias assigns a temporary, readable name to a column or table for the duration of a single query. Aliases are created with the AS keyword and never rename the underlying schema in your database.
SUM(total_amount) or CONCAT() clean JSON-friendly key names in your result set.demo_customers AS c) so multi-table joins and self-joins stay concise and unambiguous.SELECT c.first_name AS customer_name, COUNT(o.id) AS total_orders
FROM demo_customers AS c
LEFT JOIN demo_orders AS o ON o.customer_id = c.id
GROUP BY c.id, c.first_name;
This query combines table aliases (o, c) and descriptive column aliases to summarize customer spending:
SELECT
c.id AS customer_id,
c.email AS customer_email,
COUNT(o.id) AS order_count,
COALESCE(SUM(o.total_amount), 0.00) AS lifetime_spend
FROM demo_customers AS c
LEFT JOIN demo_orders AS o
ON o.customer_id = c.id
AND o.status = 'paid'
GROUP BY c.id, c.email
ORDER BY lifetime_spend DESC;
| customer_id | customer_email | order_count | lifetime_spend |
|---|---|---|---|
| 1 | [email protected] | 4 | 645.00 |
| 2 | [email protected] | 2 | 290.50 |
WHERE before SELECT, you cannot use a SELECT column alias inside WHERE. However, MySQL allows column aliases inside GROUP BY, HAVING, and ORDER BY.AS total_revenue instead of AS "Total Revenue".AS for Columns: Writing AS before column aliases (price * qty AS line_total) prevents bugs if you accidentally forget a comma between two column names.AS keyword mandatory for aliases in MySQL?No, AS is optional for both column and table aliases, though keeping AS for columns makes missing-comma bugs obvious.
WHERE lifetime_spend > 100 throw an "Unknown column" error?SQL evaluates WHERE before SELECT computes aliases, so move aggregate filters to HAVING or repeat the raw expression in WHERE.
Yes, when joining a table to itself you must give each reference a distinct alias so MySQL can tell the left and right rows apart.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.