0
0
MySQLquery~5 mins

Table aliases in MySQL

Choose your learning style9 modes available
Introduction
Table aliases let you give a short name to a table in a query. This makes writing and reading queries easier, especially when using multiple tables.
When you join two or more tables and want to write shorter names.
When a table name is long and you want to type less.
When the same table is used twice in a query and needs different names.
When you want to make your query clearer by using meaningful short names.
Syntax
MySQL
SELECT column_name(s) FROM table_name AS alias_name;
The keyword AS is optional. You can write: FROM table_name alias_name
Alias names only exist during the query execution and do not change the actual table name.
Examples
Here, 'customers' table is given the alias 'c'. We select the 'name' column using 'c'.
MySQL
SELECT c.name FROM customers AS c;
Two tables 'orders' and 'customers' are aliased as 'o' and 'c' to shorten the query.
MySQL
SELECT o.id, c.name FROM orders o JOIN customers c ON o.customer_id = c.id;
The same table 'employees' is used twice with aliases 'e1' and 'e2' to compare employees and their managers.
MySQL
SELECT e1.name, e2.name FROM employees e1 JOIN employees e2 ON e1.manager_id = e2.id;
Sample Program
We create a simple 'customers' table and insert two rows. Then we select all customers using the alias 'c'.
MySQL
CREATE TABLE customers (id INT, name VARCHAR(20));
INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob');

SELECT c.id, c.name FROM customers AS c;
OutputSuccess
Important Notes
Aliases help avoid confusion when joining tables with similar column names.
Always use meaningful alias names to keep queries readable.
You cannot use aliases outside the query where they are defined.
Summary
Table aliases give short names to tables in queries.
They make queries easier to write and read.
Aliases are especially useful when joining multiple tables or the same table twice.