MySQL Alias keyword is used 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 First Name as either FirstName or First_Name. When user reads the data it will be annoying 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 data to explain the ALIAS Names in MySQL with example.
MySQL Alias Example 1
In this 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 CONCAT string function to combine the Name, and region, and assigned alias name as Country Name.
USE world; SELECT CONCAT(Name, ' in ', Region) AS 'Country Name', Continent, IndepYear, Population, SurfaceArea, LocalName FROM country;
MySQL Alias Example 3
In MySQL, we can also apply the Alias names to calculated columns. In this example we will show you, How to apply 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 and every record of the Population column and renamed them as No of Years, and New Population.
MySQL Alias – Command Prompt Example
In this example we will write a query in Command prompt to demonstrate the Alias Columns along with the Where clause.
USE world; SELECT Name AS 'Country Name', LocalName AS 'Local Name' FROM country WHERE Continent = 'Asia'
Thank You for Visiting Our Blog