MySQL Alias

The MySQL Alias keyword is to temporarily rename the column names or table names within a Database. Sometimes column names may not be user-friendly in real time.

For example, we store the First Name as either FirstName or First_Name. When the user reads the data, it won’t be very pleasant to see the column heading like that. So, while we SELECT the data, we use this MySQL Alias to rename them as ‘First Name’ or ‘FIRST NAME’.

MySQL Alias Syntax

The basic syntax for writing MySQL Table Alias Names is as shown below:

SELECT tab1.[Column Name 1], 
       tab1.[Column Name 2],..., 
       tab1.[Column Name N]
FROM [Table_Name] AS tab1

And the syntax to write Column Alias Names is as shown below:

SELECT [Column Name 1] AS Name, 
       [Column Name 2] AS Country, 
       [Column Name N] AS Continent
FROM [Table_Name]

--OR You can Simply Write without using AS Keyword
SELECT [Column Name 1] Name, 
       [Column Name 2] Country, 
       [Column Name N] Continent
FROM [Table_Name]

In MySQL, AS Keyword is optional. It is up to you to include it or not. We are going to use the below-shown Database data to explain this one with an example.

Table Records 1

MySQL Alias Example

In this example, we are going to rename one column name to make it more meaningful. For this, we are going to rename the Name to ‘Country Name.’

USE world;
SELECT Name AS 'Country Name', 
       Continent, Region,
       SurfaceArea, IndepYear, Population, LocalName
FROM country;

MySQL Alias Names Example 2

In this example, we are using the CONCAT string function to concat or combine the Name and region. Next, we assigned the name as Country Name using this column concept.

USE world;
SELECT CONCAT(Name, ' in ', Region) AS 'Country Name', 
       IndepYear, Population,
       SurfaceArea, LocalName 
FROM country;
Example 4

Alias Columns Example 3

We can also apply or assign the MySQL Alias names to calculated columns. In this example, we will show you how to attach the names to calculated columns.

USE world;
SELECT Name AS 'Country Name', 
       Continent, Region,
       2017 - IndepYear AS 'No Of Years', 
       Population + 15000 AS 'New Population'
FROM country;

We subtracted the Independent Year from 2017 and also added 15000 to each record of the Population column. Next, we renamed them a No of Years and New Population using this one.

ALIAS Names 3

Alias Command Prompt Example

In this example, we will write a SELECT query in the Command prompt to demonstrate this one along with the Where clause.

USE world;
SELECT Name AS 'Country Name', 
       LocalName AS 'Local Name'
FROM country
WHERE Continent = 'Asia'
AS Names Command prompt Example 5