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 Alias to rename them as ‘First Name’ or ‘FIRST NAME’.
MySQL Alias Syntax
The basic syntax to write 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 MySQL 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]
TIP: In MySQL Server Alias, 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 the ALIAS Names with example.
MySQL Alias Example 1
In this MySQL example, we are going to rename one column name to make it more meaningful. For this, we are going to rename Name to ‘Country Name.’
USE world; SELECT Name AS 'Country Name', Continent, Region, SurfaceArea, IndepYear, Population, LocalName FROM country;
MySQL Alias Example 2
In this example, we are using the MySQL CONCAT string function to concat or combine the Name, and region. Next, we assigned the name as Country Name using the alias column concept.
USE world; SELECT CONCAT(Name, ' in ', Region) AS 'Country Name', Continent, IndepYear, Population, SurfaceArea, LocalName FROM country;
ALIAS Columns Example 3
We can also apply or assign the Alias names to calculated columns. In this example, we will show you how to attach the Alias names to calculated columns.
USE world; SELECT Name AS 'Country Name', Continent, Region, IndepYear, 2017 - IndepYear AS 'No Of Years', Population, 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 as No of Years and New Population using this Alias name.
MySQL Alias Command Prompt Example
USE world; SELECT Name AS 'Country Name', LocalName AS 'Local Name' FROM country WHERE Continent = 'Asia'