⬅ Previous Topic
SQL SubqueriesNext Topic ⮕
SQL Indexes⬅ Previous Topic
SQL SubqueriesNext Topic ⮕
SQL IndexesImagine you write a long query to generate a student report — and you need to run it every week. Wouldn’t it be better to save it like a virtual table and reuse it? That’s what a VIEW
lets you do. SQL Views simplify repetitive queries by treating them as reusable objects.
A View is a virtual table based on a SQL query. It doesn’t store data itself — it stores a query definition. Every time you use the view, the underlying query runs and returns live results.
CREATE VIEW view_name AS
SELECT columns
FROM table_name
WHERE condition;
CREATE TABLE students (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
class VARCHAR(10)
);
CREATE TABLE results (
roll_no INT,
subject VARCHAR(30),
marks INT
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', '10A'),
(2, 'Diya Iyer', '9B'),
(3, 'Sneha Patil', '10A');
INSERT INTO results VALUES
(1, 'Maths', 85),
(2, 'Maths', 92),
(3, 'Maths', 78),
(1, 'Science', 88),
(2, 'Science', 90),
(3, 'Science', 84);
CREATE VIEW student_scores AS
SELECT s.name, s.class, r.subject, r.marks
FROM students s
JOIN results r ON s.roll_no = r.roll_no;
Now, you can query this view like a regular table:
SELECT * FROM student_scores;
name | class | subject | marks
----------------+--------+---------+-------
Aarav Sharma | 10A | Maths | 85
Aarav Sharma | 10A | Science | 88
Diya Iyer | 9B | Maths | 92
Diya Iyer | 9B | Science | 90
Sneha Patil | 10A | Maths | 78
Sneha Patil | 10A | Science | 84
Create a view of students scoring above 85:
CREATE VIEW high_scores AS
SELECT s.name, r.subject, r.marks
FROM students s
JOIN results r ON s.roll_no = r.roll_no
WHERE r.marks > 85;
SELECT * FROM high_scores;
name | subject | marks
----------------+---------+-------
Diya Iyer | Maths | 92
Diya Iyer | Science | 90
Aarav Sharma | Science | 88
SQL doesn’t support direct updates to a view. Instead, you drop and re-create it:
DROP VIEW high_scores;
CREATE VIEW high_scores AS
SELECT s.name, r.subject, r.marks
FROM students s
JOIN results r ON s.roll_no = r.roll_no
WHERE r.marks > 80;
DROP VIEW student_scores;
SQL Views act like saved queries — virtual tables that simplify your life by keeping logic in one place. Instead of repeating joins or filters every time, you define a view once and query it again and again. Think of them as smart shortcuts in your database toolkit.
In the next lesson, we’ll explore Common Table Expressions (CTEs) — which allow temporary result sets for readable, modular queries inside a WITH
clause.
CREATE VIEW student_scores AS SELECT name, marks FROM students JOIN marks ON students.roll_no = marks.roll_no;
⬅ Previous Topic
SQL SubqueriesNext Topic ⮕
SQL IndexesYou 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.