What are MySQL Aliases?
MySQL Aliases are the temporary names given to the MySQL tables and columns for ease of understanding. We can provide any user’s understandable name to the columns or table. This name is given by using AS keyword. Note that we will be using the same ‘students’ table we created earlier.
We will see how we can use MySQL Aliases on the table as well as on columns one by one.
- Using Aliases on columns
Syntax:
select column_name AS alias_name from schema.table_name where condition;
Example: if we want to select the name column from the table but if we want to call that column as ‘student_name’ then we can give the alias name as shown below.
select name as student_name from students;
We can also select multiple columns and give alias names to each one as shown below. Make sure we are giving different aliases for each column.
Query:
select roll_num as student_no,
name as student_name,
marks as student_mark,
class as student_class,
gender as student_gender
from students;
- Using Aliases on MySQL table
Syntax:
select * from schema.table_name AS alias_name where condition;
As shown in the below example we have given an alias name for the ‘students’ table as ‘stu’ so we can use this name wherever required.
Query:
select * from students as stu where stu.roll_num > 20;
This is helpful when we have to select from multiple tables.
For example, we have two tables, students and users and we need to select the data from both tables.
Assume we have
the ‘Students’ table as
roll_num | name | marks | class | gender |
1 | KMS | 465 | 4 | M |
2 | MYG | 489 | 2 | F |
3 | BBH | 480 | 1 | M |
4 | DKS | 492 | 4 | M |
And the ‘users’ table as
user_id | user_name | user_email | user_number | user_status | user_password | created_on | birthdate |
1 | DKS | dks.com | 9999120193 | ACTIVE | ABCD123 | 2023-01-05 18:02:28 | 1993-01-12 18:02:28 |
2 | BBH | bbh.com | 9999060592 | ACTIVE | abcd123 | 2023-01-04 16:47:27 | 1992-05-06 05:30:00 |
3 | PCY | pcy.com | 9999271192 | ACTIVE | abcd123 | 2023-01-04 16:47:33 | 1992-11-27 05:30:00 |
4 | KMS | kms.com | 9999260390 | ACTIVE | abcd123 | 2023-01-06 17:51:44 | 1990-03-26 05:30:00 |
If we want to select names for students as well as users whose roll_num and user_id are matching. We can write a query as follows:
SELECT
stu.roll_num, usr.user_id, stu.name AS student_name, usr.user_name
FROM
students AS stu,
users AS usr
WHERE
stu.roll_num = usr.user_id;