x

SQL – ALIAS

Prev     Next

  • ALIAS in SQL is used to rename a column or table temporarily by giving some other name.
  • This will not impact the actual name of a column or table. Syntax for SQL ALIAS is given below.

SQL Syntax for ALIAS:

Syntax for column ALIAS  SELECT


column_name1 AS alias_name,

column_name2 AS alias_name, etc

FROM table_name;

Syntax for table ALIAS SELECT column_name1, column_name2 etc
FROM table_name AS alias_name;

Please consider the following table with few records as given below.

Table name (for example): student
Column names in this table: Student_ID, Student_name, City, Age, Department, College and Rank
Available records: 4 rows

sql-table34

Example1: how to use SQL column ALIAS:

  • Assume that you need to rename 2 columns as below temporarily.
    ‘Student_ID’ to be renamed as ‘Id’
    ‘Student_name’ to be renamed to ‘Selected_candidates’
  • When we execute below SQL query, the result will be displayed with a new name aliased as given in below output.

SQL query:

SELECT Student_ID AS ID, Student_name AS Selected_candidates from student;

SQL query Output:

sql-table39

Example2: how to combine more than one column & use ALIAS:

  • Assume that we need to combine 4 columns (Student_name, Department, College and Rank) and alias them with a single name.
  • When we execute below SQL query, the result will be displayed with a new name aliased as given in below output.

SQL query:

SELECT Student_ID, Student_name+‘, ‘+Department+’, ‘+College AS Students_Full_Details from student;

SQL query Output:


sql-table36

Example3: how to use SQL table ALIAS:

Please consider following 2 tables with few records as given below.

Table1:

Table name (for example): student1
Column names in this table: Student_ID, Student_name, City and Age
Available records: 4 rows

sql-table1

Table2:

Table name (for example): student2
Column names in this table: Student_ID, Department, College and Rank
Available records: 4 rows

sql-table37

Please execute below query in SQL to know how to use table ALIAS.

SQL Query:

SELECT s1.Student_name, s1.City, s2. Department, s2.Rank
FROM student1 AS s1, student2 AS s2
WHERE
S1.Student_ID = s2.Student_ID;

Description:

  • In the above SQL query, 4 columns are selected from 2 different tables by joining common field ‘Student_ID’ from 2 tables called student1 & student2. Student1 table is aliased as s1 and student2 table is aliased as s2.
  • After table alias, we are not needed to use the full table name. Instead, we can use the alias names ‘s1’ and ‘s2’ to represent the tables, to select the columns from the respective tables and to apply conditions in a WHERE clause in SQL query.
  • s1.Student_ID is equivalent to student1.Student_ID and s2.Student_ID is equivalent to student2.Student_ID

SQL query Output:

sql-table38

Prev     Next



Like it? Please Spread the word!