Sub topic 3
Building views on top of views
This chapter assumes you know the employee_directory view from earlier in the tutorial, and that you can write joins and GROUP BY queries. You also need CREATE and GRANT privileges to follow the examples.
A view can select from another view as if that view were a table. The database expands each view into its underlying query, so nesting adds no storage cost. Stacking views can make logic easier to read, but deep stacks are harder to debug.
CREATE VIEW engineering_staff AS
SELECT id, name
FROM employee_directory
WHERE department = 'Engineering';How the database runs a query against a view
When you query a view, the database does not read stored rows from the view. It replaces the view name with the view's saved SELECT and then plans the full query against the base tables.
Because of this, a filter on the view can use indexes on the base tables.
Materialized views: storing the result
A materialized view is a view whose result is saved on disk. Reads are fast because the database skips the join or aggregation. The saved data does not update on its own, so it can be out of date.
CREATE MATERIALIZED VIEW department_salary_totals AS
SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;Refreshing a materialized view
Run REFRESH to recompute the saved result:
REFRESH MATERIALIZED VIEW department_salary_totals;Finding and inspecting views in the catalog
In PostgreSQL, information_schema.views lists regular views, and pg_matviews lists materialized views. To see the stored definition of a view, use pg_get_viewdef:
SELECT matviewname FROM pg_matviews;
SELECT pg_get_viewdef('employee_directory', true);Limitations and common pitfalls
> callout note
Watch for these problems:
- A stale materialized view returns old numbers until you refresh it.
- Deep nesting hides the base tables from the person reading the query.
Exercise
Why might a query on a view built on another view run slowly even though each view is simple?
Show answer
Each view expands into its underlying query, so the planner may combine many joins and filters that the database cannot simplify well. Querying the base tables directly, or using a materialized view for the heavy part, can help.