Learn SQL
-- subqueries.views

Views — Saved Queries in SQL

Name a query once, use it like a table forever

--concept

A view is a named SELECT stored in the database. CREATE VIEW eng_earners AS SELECT … saves the query; afterwards you SELECT from eng_earners like any table. The query runs fresh at every use, so a view always shows current data. Views hide complexity, standardise business definitions (what counts as an “active customer”), and can restrict access by exposing only some columns.

--how it works
1

Save the query, not the rows

CREATE VIEW eng_earners AS SELECT id, name, salary FROM employees WHERE department = 'Engineering' — the definition is stored; no data is copied.

2

Query it like a table

SELECT * FROM eng_earners — the engine expands the stored query and runs it against the current data, fresh every time.

3

It stays correct automatically

Insert, update or delete employees and the view reflects it on the next select — there is nothing to refresh.

4

Views compose

A view may select from other views — building a library of named business definitions layer by layer.

5

Manage the lifecycle

CREATE OR REPLACE VIEW updates the definition; DROP VIEW removes it. Permissions are granted per view, independently of the base table.

--visualization
employees (base table)AliceEngineeBobSalesCynthiaEngineeDavidMarketiElenaSalesFaridEnginee👁 eng_earners — stored DEFINITION onlySELECT id, name, salary FROM employeesWHERE department = 'Engineering'writing the definition…— nothing materialised yet —
view definition (stored query) changed / freshly included row
Stage 1 / 3
CREATE VIEW eng_earners AS SELECT id, name, salary FROM employees WHERE department = 'Engineering' — note: nothing is copied.
--example
query.sql
1CREATE VIEW eng_earners AS
2 SELECT id, name, salary FROM employees WHERE department = 'Engineering';
3SELECT * FROM eng_earners ORDER BY salary DESC;
Result
idnamesalary
3Cynthia91000
1Alice85000
6Farid73000

The stored query runs at SELECT time, so it reflects every INSERT since the view was created. If Farid is promoted into Engineering tomorrow, he appears in eng_earners automatically — no maintenance.

--variants

Create, then select

The saved query runs live at every use.

query.sql
1CREATE VIEW eng_earners AS
2 SELECT id, name, salary FROM employees WHERE department = 'Engineering';
3SELECT * FROM eng_earners ORDER BY salary DESC;
Result
idnamesalary
3Cynthia91000
1Alice85000
6Farid73000
1The CREATE stores the definition — instant, zero data movement.
2The SELECT expands to the stored query and executes it now.
3Ordering, joins and aggregates work on the view exactly as on a table.

The view tracks its base table

New Engineering hires appear without touching the view.

query.sql
1INSERT INTO employees (id, name, department, salary, age)
2VALUES (7, 'Grace', 'Engineering', 81000, 31);
3SELECT name FROM eng_earners;
Result
name
Alice
Cynthia
Farid
Grace
1The view stores no rows, so it cannot go stale.
2Grace’s insert lands in employees; the next view select includes her.
3This is the difference from a copied snapshot table, which would need a refresh job.

Views as a security boundary

Expose the safe columns; hide salary and id.

query.sql
1CREATE VIEW staff_directory AS
2 SELECT name, department FROM employees;
3SELECT * FROM staff_directory;
4-- GRANT SELECT ON staff_directory TO analyst; -- base table stays hidden
Result
namedepartment
AliceEngineering
BobSales
CynthiaEngineering
DavidMarketing
ElenaSales
FaridEngineering
1The view projects only name and department — salary never leaves the base table.
2Analysts get SELECT on the view only; they cannot query employees directly.
3One definition, enforced centrally: the salary column simply does not exist for them.

One name for one business rule

“Active customer” means one thing everywhere.

query.sql
1CREATE VIEW active_customers AS
2 SELECT * FROM customers
3 WHERE last_order_at >= NOW() - INTERVAL '90 days';
4SELECT COUNT(*) FROM active_customers;
Result
count
4217
1The 90-day rule is written once, in SQL, in the database.
2Every dashboard and script selecting from active_customers inherits it — no divergent copies in application code.
3Change the rule once (CREATE OR REPLACE) and every consumer updates simultaneously.
--key facts
Definition, not dataa view stores the query; a table stores rows — materialised views are the hybrid
Security patterngrant analysts access to a salary-free view instead of the base table
Same engine plansthe optimiser treats a view exactly like an inlined subquery
--use cases
Access control: expose de-identified or column-limited views instead of base tables
Standard report definitions: revenue, churn, active users — versioned in migrations
Simplifying legacy schemas for new applications behind friendly names
Layered analytics: staging views → business views → dashboards
--under the hood
Simple views are inlined into the query plan — querying a view costs exactly what querying its definition costs.
Materialised views (Postgres, Oracle) DO store rows for speed, at the price of REFRESH — the snapshot trade-off.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Take the queries you just visualized and see the data structures that power real databases.