Views — Named, Reusable Queries
7 min read
Views
A view is a named SELECT query stored in the database. You can query a view just like a table. Views are useful for hiding complex joins, presenting a simplified interface to end users, and enforcing consistent column definitions across multiple queries.
sql
-- Create a view that joins all three tables
CREATE VIEW enrolment_details AS
SELECT
s.name AS student_name,
c.title AS course_title,
e.enrolled_at,
e.score
FROM enrolments e
INNER JOIN students s ON s.id = e.student_id
INNER JOIN courses c ON c.id = e.course_id;
-- Use the view like any other table
SELECT student_name, course_title, score
FROM enrolment_details
WHERE score >= 80
ORDER BY score DESC;
-- Remove a view (does not delete underlying data)
DROP VIEW enrolment_details;Views do not store data themselves (in most databases). Each time you query a view, the database executes the underlying SELECT. Materialised views (available in PostgreSQL and others) cache the result for faster reads at the cost of needing periodic refreshes.
Views are a great way to expose read-only, joined data to reporting tools or junior developers without giving them direct access to raw tables. They act as a clean API layer inside the database.
Ready to test yourself?
Practice SQL— quiz & coding exercises