MySQL - Alias for Table & Columns

In SQL, an alias is a temporary name assigned to a table or column in a SQL statement. An alias is used to make a SQL statement more readable and to provide a shorter or more meaningful name for a table or column.

An alias can be assigned to a table or column using the AS keyword, which is optional in most cases. Here are some examples of how to use aliases in SQL:

Alias for a table:

SELECT * FROM employees AS e WHERE e.salary > 50000;

In this example, the table "employees" is given an alias "e". This makes it easier to refer to the table in the WHERE clause, where we want to select employees with a salary greater than 50000.

Alias for a column:

SELECT e.first_name AS fname, e.last_name AS lname FROM employees AS e;

In this example, the columns "first_name" and "last_name" from the "employees" table are given aliases "fname" and "lname", respectively. This makes the output of the SELECT statement more readable and concise.

Alias for a subquery:

SELECT e.first_name, e.last_name, e.salary, (SELECT MAX(salary) FROM employees) AS max_salary FROM employees AS e;

In this example, a subquery is used to find the maximum salary in the "employees" table. The subquery is given an alias "max_salary", which is used in the SELECT statement to display the maximum salary along with the first name, last name, and salary of each employee.

Aliases can be useful when working with large SQL queries that involve multiple tables and complex joins. They help to make the SQL statement more readable and easier to understand by providing shorter and more meaningful names for tables and columns.