In MySQL, aliases are temporary names assigned to columns or tables in a SQL query. They are used to make the output of a query more readable or to simplify complex queries. Here's how aliases are used:
You can use aliases to rename columns in the output of a query.
Syntax:
SELECT column_name AS alias_name FROM table_name;
Example:
SELECT first_name AS "First Name", last_name AS "Last Name" FROM employees;
In this example, `first_name` and `last_name` columns are given aliases "First Name" and "Last Name" respectively.
You can also use aliases to provide shorter or more meaningful names for tables, especially when dealing with multiple tables in a query.
Syntax:
SELECT t1.column_name, t2.column_name FROM table1 AS t1, table2 AS t2 WHERE t1.column_name = t2.column_name;
Example:
SELECT e.first_name, d.department_name
FROM employees AS e
JOIN departments AS d ON e.department_id = d.department_id;
In this example, `employees` table is given an alias `e` and `departments` table is given an alias `d` to simplify the query.
Aliases are particularly useful in complex queries involving multiple tables or calculations, where they can improve query readability and maintainability. They can also be used with aggregate functions and subqueries to provide meaningful names to calculated values or result sets.