← Back to Chapters

MySQL Aliases

? MySQL Aliases

? Quick Overview

In MySQL, an alias is a temporary name assigned to a table or column for the duration of a query. Aliases improve readability and simplify queries — especially joins or queries with long identifiers.

? Key Concepts

  • Column Alias: Rename columns in the result set (optional AS keyword).
  • Table Alias: Temporary table name, commonly used in joins and subqueries.
  • Scope: Aliases exist only for the duration of the query execution — they don't change schema.
  • Readability: Use clear, descriptive aliases to make complex SQL easier to follow.

? Syntax / Theory

? View Code Example
-- Syntax for Column Alias (rename a column in SELECT)
SELECT column_name AS alias_name
FROM table_name;
-- Syntax for Table Alias (give a temporary name to a table)
SELECT column_name
FROM table_name AS alias_name;

? Code Example(s)

? View Code Example
-- Using column alias to rename 'student_name' as 'name' and 'student_id' as 'id'
SELECT student_name AS name, student_id AS id
FROM students;
-- Using table alias 's' for the 'students' table and filtering by age
SELECT s.student_name, s.student_id
FROM students AS s
WHERE s.student_age > 18;

? Live Output / Explanation

Explanation

  • Column Alias: When you use student_name AS name, the result set column will be labeled name.
  • Table Alias: students AS s lets you reference the table as s (handy for joins or long table names).
  • AS is optional: SELECT student_name name also works, but using AS increases clarity.

✅ Tips & Best Practices

  • Prefer descriptive aliases (e.g., customer_total instead of ct) for maintainability.
  • Use table aliases to disambiguate columns when joining multiple tables with similar column names.
  • Avoid spaces in alias names; use underscores or camelCase if needed.

? Try It Yourself

  • Write a query to select product_name and price from products, aliasing them to name and cost.
  • Join students (alias s) with courses (alias c) and select student name and course title.
  • Show first name and last name of employees as first and last using column aliases.