
Aliases in MySql
Aliases in MySQL are used to give a temporary, alternative name to a table or a column in a query. They help improve readability and make query results more user-friendly.
1. Column Alias
A column alias renames a column in the output of a query.
Syntax
SELECT column_name AS alias_name FROM table_name;
AS
is optional.- The alias is only used in the result set, not in the actual database.
Example
SELECT first_name AS Name, last_name AS Surname FROM employees;
Result:
+-------+--------+| Name | Surname |+-------+--------+| John | Doe || Jane | Smith |+-------+--------+
Using Alias Without AS
SELECT first_name Name, last_name Surname FROM employees;
This works the same way.
Using Aliases with Spaces
If the alias contains spaces, use backticks (`) or double quotes (""):
SELECT first_name AS "First Name", last_name AS "Last Name" FROM employees;
2. Table Alias
A table alias assigns a temporary name to a table, useful when working with joins or subqueries.
Syntax
Example
SELECT e.first_name, e.last_name, d.department_nameFROM employees AS eJOIN departments AS d ON e.department_id = d.id;
Result:
+-----------+----------+----------------+| first_name | last_name | department_name |+-----------+----------+----------------+| John | Doe | HR || Jane | Smith | IT |+-----------+----------+----------------+
e
is an alias for theemployees
table.d
is an alias for thedepartments
table.
Using Table Aliases Without AS
SELECT e.first_name, e.last_name FROM employees e;
Works the same way.
3. Aliases in Calculated Columns
Aliases are helpful when working with expressions or calculations.
Example
SELECT price, price * 0.9 AS discounted_price FROM products;
Key Points
✅ Aliases are temporary and only last during query execution.
✅ Use them to make queries cleaner and more readable.
✅ Column aliases help rename column headers.
✅ Table aliases simplify complex queries, especially with joins.
Let me know if you need more examples! 🚀