SQL Alias
SQL Alias
This page covers SQL Alias.
At this stage, it is good to comprehend the concepts of aliases, comments, and space characters.
Both statements help with SQL code readability and neatness.
This tutorial covers:
- space characters
- aliases on tables
- aliases on columns
- single-line comments
- multi-line comments
Let’s use the table “student_info” from the previous tutorials.
id | firstName | lastName | age |
---|---|---|---|
1 | John | Smith | 21 |
2 | Patrick | Casey | 26 |
3 | Sam | Adams | 19 |
4 | Mike | Garcia | NULL |
5 | Patrick | Dumont | 21 |
Space characters
When naming tables or columns, sometimes we need to use multiple words.
SQL produces errors when we leave space characters (empty spaces).
To avoid such issues, we can use either square brackets or double quotes.
student_info
The above can also be displayed as:
[Student Information]
"Student Information"
Aliases on tables
The term alias refers to an additional name. The keyword is “as“.
In SQL, it creates a temporary table name (does not change the original table name).
SELECT * FROM student_info AS Students;
The outcome of the above query displays the same table, but it renames the table temporarily as “Students” instead of “student_info“.
Aliases on columns
The term alias refers to an additional name. The keyword is “as“.
In SQL, it creates a temporary column name (does not change the original column name).
SELECT age AS [Student Age] FROM student_info;
Let’s compare the outcome with the original column name. Please note that the original column name does not change.
age | Student Age |
---|---|
21 | 21 |
26 | 26 |
19 | 19 |
NULL | NULL |
21 | 21 |
Single-line comments
Comments are very important in code development.
Single-line comments use two hyphens (–).
They can provide general information, guidelines, or any other relevant instructions.
-- The statement below selects only the "age" column SELECT age FROM student_info;
Multi-line comments
Sometimes, we need to provide more details about a statement.
Multi-line comments use forward slashes (/) and asterisks (*).
The following is a multi-line commenting.
/* The statement below creates a table. The column id holds integers, first and last names are strings, and age also integers. Both string columns allow up to 50 characters. */ CREATE TABLE student_names ( id int, firstName varchar(50), lastName varchar(50), age int );
Next: SQL Filters