SQL
The AS
keyword in SQL is used to alias a column or a table temporarily. This alias provides an alternate name that can be used to reference the column or table in the result set.
SELECT column_name AS alias_name
FROM table_name;
column_name
: The original name of the column.alias_name
: The alternative name or alias you want to assign to the column.Database: Students
student_id | first_name | last_name | age | grade |
---|---|---|---|---|
1 | John | Doe | 21 | A |
2 | Jane | Smith | 22 | B |
3 | Alex | Johnson | 20 | A |
Example: Using SQL SELECT AS for Column Aliasing
-- Alias the 'first_name' column as 'First Name'
SELECT first_name AS 'First Name'
FROM Students;
Output:
First Name |
---|
John |
Jane |
Alex |
Example: Aliasing Multiple Columns
-- Alias columns for better readability
SELECT first_name AS 'First Name', last_name AS 'Last Name', grade AS 'Grade'
FROM Students;
Output:
First Name | Last Name | Grade |
---|---|---|
John | Doe | A |
Jane | Smith | B |
Alex | Johnson | A |
Let’s say you want to filter students based on their grades. You can use aliases in the WHERE clause to simplify the condition:
SELECT first_name, grade AS 'Student Grade'
FROM Students
WHERE 'Student Grade' = 'A';
Output:
first_name | Student Grade |
---|---|
John | A |
Alex | A |
Suppose you want to calculate the age difference from the average age for each student:
SELECT first_name, age - (SELECT AVG(age) FROM Students) AS 'Age Difference'
FROM Students;
Output:
first_name | Age Difference |
---|---|
John | 0 |
Jane | 1 |
Alex | -1 |
Simplify complex queries by aliasing tables.
SELECT s.first_name, s.grade, c.course_name
FROM Students AS s
JOIN Courses AS c ON s.student_id = c.student_id;
Output:
first_name | grade | course_name |
---|---|---|
John | A | SQL Fundamentals |
Jane | B | Database Design |
Alex | A | Advanced SQL |