In the previous article, "
SQL For Beginners: Null Values", we have seen an example in which SQL Aliases are used. Let us explore the SQL Aliases in depth in this article.
Suppose you have a friend named "
Shamsheshwar Prasad Agnihotri". Will it be easy for you to call him with his exact name again and again? Will you remember this name? Is this name simple?
No. Right?
No one likes complex names. No one remembers them. So, suppose we have such a person in our friends list, then we give him a nick name like "Sam" or "
Prasad" or "
Shamu" or some people may also call them "SPA". But calling "
Shamsheshwar Prasad Agnihotri" as "SPA" doesn't change his original name, his original name remains the same. Such nicknames are temporary names created by us for our convenience.
Similarly, in the world of SQL, we create such type of names for the SQL tables/columns and these temporary names are referred to as "
Aliases" in SQL.
SQL Aliases are the temporary name given to the table or columns.
Example:
We have a "
numbers" table as shown below:
Now, suppose I write the following query:
Then, the output will be:
As you can see the output, we are getting the sum of columns a and b without any column name at the top. This looks quite unreadable.
Now let us write the same query with Aliases.
- Select a+b as Sum from numbers;
Here, a+b will do the same addition operation. The keyword "as" is used to give Alias. And, the Alias name is Sum. Output for the same will be:
As you can see the output, we gave the column a temporary name "
Sum" using Alias.
Let us see one more example for the same.
- Select *, (a+b) as Sum, (a*b) as Product from numbers;
Output:
In the similar manner, we can create aliases for tables too. Mostly Aliases for tables are created while using SQL Joins. Now, you would be wondering that what are SQL Joins?
SQL allows us to join two or more related tables using SQL Joins. We will learn about them in the upcoming articles of this series.