ALIAS
An Alias is a way to assign a temporary name to a table or column. Aliases are used to simplify long table or column names and generally make the code more readable. To assign an alias, we use the keyword AS. We typically see aliases when temporarily renaming a column or table. Let's look at each example.
Column Alias
Column aliases are used to change the name of the output of the columns, usually to something that is concise, readable and meaningful in the context of the query. For Example, we can write a query on the customers table to return first_name, last_name, and customer_id aliased as Name, SurName and ID respectively. The query would look like this:
select
customer_id as ID,
first_name as Name,
last_name as SurName
from customers
| ID | Name | SurName |
| ---- | ----- | -------- |
| 2001 | Alice | Johnson |
| 2002 | Bob | Williams |
| 2003 | Carol | Brown |
| 2004 | David | Davis |
| 2005 | Emma | Miller |
| 2006 | Frank | Wilson |
| 2007 | Grace | Moore |
| 2008 | Henry | Taylor |
| 2009 | Ivy | Anderson |
| 2010 | Jack | Thomas |
Using alias in this manner is useful in mapping the column names to useful output names depending on your context and needs.
Table Aliases
Similarly, using aliases on tables is primarily used to make the query readable. Table names are usually long and on more advanced queries that have joins and other executions that reference specific columns can become cumbersome to write and worst-case unreadable. You will see why in the intermediate and advanced section but for now, let's demonstrate how to assign aliases to tables.
Using the previous query, we assign the alias
select
C.customer_id as ID,
C.first_name as Name,
C.last_name as SurName
from customers C
limit 15
| ID | Name | SurName |
| ---- | ------ | --------- |
| 2001 | Alice | Johnson |
| 2002 | Bob | Williams |
| 2003 | Carol | Brown |
| 2004 | David | Davis |
| 2005 | Emma | Miller |
| 2006 | Frank | Wilson |
| 2007 | Grace | Moore |
| 2008 | Henry | Taylor |
| 2009 | Ivy | Anderson |
| 2010 | Jack | Thomas |
| 2011 | Kate | Jackson |
| 2012 | Liam | White |
| 2013 | Mia | Garcia |
| 2014 | Noah | Martinez |
| 2015 | Olivia | Rodriguez |