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.

  1. 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; 

  1. 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_numnamemarksclassgender
1KMS4654M
2MYG4892F
3BBH4801M
4DKS4924M

And the ‘users’ table as

user_iduser_nameuser_emailuser_numberuser_statususer_passwordcreated_onbirthdate
1DKSdks.com9999120193ACTIVEABCD1232023-01-05 18:02:281993-01-12 18:02:28
2BBHbbh.com9999060592ACTIVEabcd1232023-01-04 16:47:271992-05-06 05:30:00
3PCYpcy.com9999271192ACTIVEabcd1232023-01-04 16:47:331992-11-27 05:30:00
4KMSkms.com9999260390ACTIVEabcd1232023-01-06 17:51:441990-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;

-A blog by Shwetali Khambe

Related Posts