Open In App

SQL | Aliases

Pre-Requisites:SQL table

Aliases are the temporary names given to tables or columns for the purpose of a particular SQL query. It is used when the name of a column or table is used other than its original name, but the modified name is only temporary.



Syntax for Column Alias 

SELECT column as alias_name FROM table_name;

column: fields in the table



alias_name: temporary alias name to be used in 

replacement of original column name 

table_name: name of table

Parameter Explanation

The following table explains the arguments in detail:

 Syntax for Table Alias

SELECT column FROM table_name as alias_name;

column: fields in the table 

table_name: name of table

alias_name: temporary alias name to be used in replacement 

of original table name

Lets see examples for SQL Aliases. 

CREATE TABLE Customer(
CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50),
LastName VARCHAR(50),
Country VARCHAR(50),
Age int(2),
Phone int(10)
);
-- Insert some sample data into the Customers table
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
Select * from Customer;

Output:

 

Example 1: Column Alias

To fetch SSN from the customer table using CustomerID as an alias name.

Query:

SELECT CustomerID AS SSN FROM Customer;

Output:

 

Example 2: Table Alias

Generally, table aliases are used to fetch the data from more than just a single table and connect them through field relations.

To fetch the CustomerName and Country of the customer with Age = 21.

Query:

SELECT s.CustomerName, d.Country 
FROM Customer AS s, Customer
AS d WHERE s.Age=21 AND
s.CustomerID=d.CustomerID;

Output:

 

Advantages of SQL Alias

  1. It is useful when you use the function in the query.
  2. It can also allow us to combine two or more columns.
  3. It is also useful when the column names are big or not readable.
  4. It is used to combine two or more columns.
     

Please comment if you find anything incorrect or want to share more information about the topic discussed above.

Article Tags :