Sub topic 9
Building Views on Top of Views
What this chapter assumes
You can create and query a simple view, and you know JOIN, GROUP BY, and WHERE. You have the employees and departments tables from the sample schema. The examples use PostgreSQL syntax. Where other systems behave differently, the text says so.
Why stack views
A view is a named query, and a query can read from any table-like object. That includes another view. A view built on another view is a nested view (also called a stacked or layered view).
Nesting lets you put each rule in one place:
- Filtering rules. For example, "an active employee is a row with
status = 'active'". - Join rules. For example, "an employee belongs to a department through
department_id". - Business measures. For example, "payroll is the sum of active salaries per department".
Each layer reuses the layer below it. If the definition of "active" changes, you edit one view and every view above it picks up the change.
A three-layer example
The first layer filters the base table:
CREATE VIEW active_staff AS
SELECT id, name, salary, department_id
FROM employees
WHERE status = 'active';The second layer reads from active_staff, not from employees. It joins to departments and aggregates:
CREATE VIEW department_payroll AS
SELECT d.id AS department_id,
d.name AS department,
COUNT(*) AS headcount,
SUM(s.salary) AS total_salary
FROM active_staff s
JOIN departments d ON d.id = s.department_id
GROUP BY d.id, d.name;The third layer reads from department_payroll and keeps only the large departments:
CREATE VIEW large_departments AS
SELECT department, headcount, total_salary
FROM department_payroll
WHERE headcount >= 5;A caller now writes a short query:
SELECT department, total_salary
FROM large_departments
ORDER BY total_salary DESC;The caller does not need to know that three views and two tables are involved.
What the database does with the stack
A regular view stores no rows. It stores only its query text, so a nested view stores a query that mentions another view. When you run a query against large_departments, the database expands each view reference into that view's definition. It repeats this until only base tables remain. Then it plans and runs one combined query.
For the example above, the expanded query is logically equivalent to this one:
SELECT d.name AS department,
COUNT(*) AS headcount,
SUM(e.salary) AS total_salary
FROM employees e
JOIN departments d ON d.id = e.department_id
WHERE e.status = 'active'
GROUP BY d.id, d.name
HAVING COUNT(*) >= 5;The outer WHERE headcount >= 5 has become a HAVING clause, because it filters on an aggregate. Most optimizers merge simple layers (filters, projections, plain joins) into one query. Layers that contain GROUP BY, DISTINCT, LIMIT, or window functions are harder to merge. The optimizer may compute them as a separate step and then filter the result. The performance chapter covers this in detail. For now, remember that nesting is a naming and organizing tool. It does not create stored intermediate results.
Dependencies between views
Each nested view depends on the objects it reads. The database records these dependencies and uses them to protect you from breaking a view by accident. In PostgreSQL, trying to drop a view that another view uses fails:
DROP VIEW active_staff;
-- ERROR: cannot drop view active_staff because other objects depend on itYou can drop the view together with everything above it by adding CASCADE:
DROP VIEW active_staff CASCADE;
-- Also drops department_payroll and large_departmentsCheck what will be removed before you run this. The database lists the dependent objects in a notice, but it does not ask for confirmation.
The same protection applies to base tables. Dropping or retyping a column that a view uses is refused until you deal with the views.
ALTER TABLE employees DROP COLUMN salary;
-- ERROR: cannot drop column salary of table employees because other objects depend on itSystems differ here, so do not rely on one behavior:
| System | `DROP VIEW` on a view that other views use |
|---|---|
| PostgreSQL | Fails unless you add `CASCADE` |
| MySQL | Succeeds. `CASCADE` is accepted but ignored. Dependent views fail when queried. |
| Oracle | Succeeds. Dependent views become invalid and fail when queried. |
| SQL Server | Succeeds. Dependent views fail when queried. |
On systems that allow the drop, the damage shows up later, when someone queries the broken view. Check dependencies before you drop anything.
Listing what a view depends on
The standard catalog view information_schema.view_table_usage lists the tables and views that each view reads:
SELECT view_name, table_name
FROM information_schema.view_table_usage
WHERE table_schema = 'public'
ORDER BY view_name, table_name;For the stack above, table_name shows employees for active_staff, and active_staff and departments for department_payroll. In PostgreSQL this view shows only objects owned by a role you currently have. Other systems offer their own dependency catalogs, such as pg_depend in PostgreSQL or ALL_DEPENDENCIES in Oracle.
Common problems with stacked views
Frozen column lists with SELECT *
If a view uses SELECT *, most systems expand the star into the actual column list when the view is created. Columns added to the table later do not appear in the view:
CREATE VIEW staff_all AS
SELECT * FROM employees;
ALTER TABLE employees ADD COLUMN hired_on DATE;
SELECT * FROM staff_all;
-- hired_on is missing in PostgreSQL; the view still has the old column listIn a stack, the mismatch spreads: a new column is missing from every layer that was built from the starred view. List columns explicitly in each layer.
Costs that hide in the stack
A one-line query against the top view can read many tables. This is easy to forget when you are several layers away. Each layer also adds a place where a filter or join may not be pushed down, so a query that looks cheap can be slow. When a query on a nested view is slow, expand the definitions by hand, or use EXPLAIN to see the real plan.
Repeated or conflicting logic
Two views at the same level may each re-implement "active employee" in different ways. Then their totals disagree. Build both from one lower view instead of copying the WHERE clause.
Ordering and depth
An ORDER BY inside a lower view does not guarantee the order of the final result. Put the ORDER BY in the outermost query. Deep stacks are also harder to read and debug. If you need more than three or four layers, ask whether some of them should be merged.
Access rights through the stack
In PostgreSQL, a view reads its underlying objects with the privileges of the view's owner, not of the caller. For large_departments to work for a user with SELECT on it, the owner of large_departments needs SELECT on department_payroll. The owner of department_payroll needs access to active_staff, and so on. Other systems have different rules, so check how yours handles them.
When to nest and when to stay flat
Nest when a rule is shared by several views, or when a layer has a clear meaning of its own, such as "active staff" or "department payroll". Stay flat when a view is used once and its logic is short. A single view with a clear definition is easier to maintain than three layers that each add one condition.
A practical test: can you describe each layer in one sentence, without mentioning the layers around it? If yes, the layer earns its place.
Exercise
In PostgreSQL, DROP VIEW department_payroll; fails because large_departments depends on it. Name two ways to proceed, and say which one you would use if you want to keep large_departments.
Show answer
You can drop the dependent view first (DROP VIEW large_departments; and then DROP VIEW department_payroll;), or use DROP VIEW department_payroll CASCADE;, which removes both. To keep large_departments, use neither. Instead, change department_payroll with CREATE OR REPLACE VIEW, keeping the same output columns and types, so the dependent view stays valid.
Exercise
Write a view named engineering_payroll that is built on department_payroll and returns only the row for the department named 'Engineering'. Why is this a better choice than reading employees directly?
Show answer
CREATE VIEW engineering_payroll AS SELECT department_id, department, headcount, total_salary FROM department_payroll WHERE department = 'Engineering'; It reuses the active-employee filter and the payroll calculation that already live in the lower layers, so there is only one definition of each rule. If "active" or "payroll" changes, engineering_payroll follows automatically.