⬅ Previous Topic
SQL Operators - AND, OR, NOT, IN, BETWEEN, LIKENext Topic ⮕
SQL CASE Statement⬅ Previous Topic
SQL Operators - AND, OR, NOT, IN, BETWEEN, LIKENext Topic ⮕
SQL CASE StatementSometimes column or table names in your database aren't exactly presentation-ready — long, technical, or just unclear. This is where SQL ALIAS
comes in. It lets you rename columns or tables temporarily to make your output more readable and meaningful.
An alias is a temporary name assigned to a column or table in the result set. It only exists while the query is running. You can use it to simplify names or to make column headers look better in reports or dashboards.
SELECT column_name AS alias_name
FROM table_name;
SELECT t.column_name
FROM table_name AS t;
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10),
age INT,
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A', 15, 'Delhi'),
(2, 'Diya Iyer', '9B', 14, 'Chennai'),
(3, 'Sneha Patil', '10A', 15, 'Pune');
Let’s display student names with a better column header:
SELECT name AS student_name, city AS hometown
FROM students;
student_name | hometown
--------------+----------
Aarav Sharma | Delhi
Diya Iyer | Chennai
Sneha Patil | Pune
The AS
keyword is optional — you can write:
SELECT name student_name, city hometown
FROM students;
But using AS
improves readability and is recommended.
You can alias the result of a calculation:
SELECT name, age + 1 AS age_next_year
FROM students;
name | age_next_year
---------------+---------------
Aarav Sharma | 16
Diya Iyer | 15
Sneha Patil | 16
Useful when working with multiple tables or just to shorten queries:
SELECT s.name, s.city
FROM students AS s;
Imagine you have another table with exam results:
CREATE TABLE results (
roll_no INT,
subject VARCHAR(30),
marks INT
);
INSERT INTO results VALUES
(1, 'Maths', 85),
(2, 'Maths', 90),
(3, 'Maths', 88);
Now join using aliases:
SELECT s.name, r.subject, r.marks
FROM students AS s
JOIN results AS r
ON s.roll_no = r.roll_no;
name | subject | marks
---------------+---------+-------
Aarav Sharma | Maths | 85
Diya Iyer | Maths | 90
Sneha Patil | Maths | 88
AS "Student Name"
).SQL aliases help you present your data clearly and professionally. Whether you're simplifying column names, formatting output for a report, or shortening complex queries — AS
makes your SQL more expressive and human-readable.
With aliases mastered, you're ready to dive into SQL Subqueries — a way to use one query inside another for advanced filtering and logic.
SELECT name AS student_name, marks AS score FROM students;
⬅ Previous Topic
SQL Operators - AND, OR, NOT, IN, BETWEEN, LIKENext Topic ⮕
SQL CASE StatementYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.