A view is a saved SELECT query that behaves like a virtual table. You write a complex join once, give it a name, and then query it as simply as SELECT * FROM view_name.
What You Will Learn
- Create, query and drop a view
- Why views simplify reporting
- Views for security
- Limitations and materialized views
Prerequisites
SQL Basics. We use students(id, name, city, age), courses(id, title, fee) and enrollments(student_id, course_id, marks) – the sample database from SQL Basics.
Create a View
CREATE VIEW student_results AS
SELECT s.name, c.title, e.marks,
CASE WHEN e.marks >= 75 THEN 'Pass' ELSE 'Fail' END AS result
FROM enrollments e
JOIN students s ON s.id = e.student_id
JOIN courses c ON c.id = e.course_id;
Explanation: The view stores the query, not the data. Each time you select from it, the database runs the join on the current tables, so results are always up to date.
Query It Like a Table
SELECT * FROM student_results WHERE result = 'Fail';
SELECT title, COUNT(*) AS students, ROUND(AVG(marks), 1) AS avg_marks
FROM student_results GROUP BY title ORDER BY title;
name | title | marks | result Karan | Python | 68 | Fail Neha | Data Science | 59 | Fail title | students | avg_marks Data Science | 3 | 75.0 Deep Learning | 1 | 88.0 Python | 3 | 81.7
Explanation: Analysts no longer need to remember the joins – they filter and group the view directly.
Change or Remove
CREATE OR REPLACE VIEW student_results AS ...; -- MySQL / PostgreSQL
DROP VIEW IF EXISTS student_results;
Why Use Views
| Benefit | Example |
|---|---|
| Simplicity | Hide multi-table joins behind one name |
| Consistency | Everyone uses the same “Pass” rule |
| Security | Give a reporting user access to a view without the phone or fee columns |
| Compatibility | Keep old reports working after tables are redesigned |
Limitations
- A view is not faster by itself – the underlying query still runs.
- Views with joins, GROUP BY or DISTINCT usually cannot be updated with INSERT/UPDATE.
- Materialized views (PostgreSQL, Oracle, many warehouses) store the result physically for speed and must be refreshed:
REFRESH MATERIALIZED VIEW name;
Series
SQL series: SQL Basics · Advanced SQL · Views · Indexing · Stored Procedures · Database Design · SQL for Analytics · MySQL · PostgreSQL · MongoDB · NoSQL vs SQL · Interview Questions
Interview Questions
Q: View vs table?
A table stores data; a view stores a query and shows its result as a virtual table.
Q: What is a materialized view?
A view whose result is stored on disk for fast reads and refreshed periodically.
Practice Exercises
- Create a view showing revenue per course.
- Create a view that hides the age column from students and grant it to a reporting user.
Summary
Views save complex queries under a name, keep logic consistent and restrict access; materialized views add stored results for speed.
Next: SQL Indexing
Machine Learning Tutorials, Courses and Certifications