Assign new name to column or Table using SELECT AS in SQL

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.

Syntax for Column Aliasing:

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_idfirst_namelast_nameagegrade
1JohnDoe21A
2JaneSmith22B
3AlexJohnson20A

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 NameLast NameGrade
JohnDoeA
JaneSmithB
AlexJohnsonA

Example: Using Aliases in WHERE Clause

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_nameStudent Grade
JohnA
AlexA

Using Aliases for Calculated Fields

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_nameAge Difference
John0
Jane1
Alex-1

Aliasing Tables:

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_namegradecourse_name
JohnASQL Fundamentals
JaneBDatabase Design
AlexAAdvanced SQL