Views and materialized views
Create reusable saved queries with views, and learn when a materialized view earns its keep.
- Create a view that wraps a frequently used query
- Explain when a view is a good fit
- Create and refresh a materialized view
- Describe the read-only and staleness trade-offs
In plain English
A view is a saved query that you can use like a table; it does not store data on its own, it just runs the query each time you select from it. You use a view when you want a simpler, reusable way to read data without writing the same joins or filters over and over. A materialized view is different because it actually stores the query result as a snapshot, which is faster to read but can go out of date until you refresh it. Both are effectively read-only, so they are for looking at data rather than editing it.
Step by step
- 1Write the query you find yourself repeating, then wrap it with CREATE VIEW name AS.
- 2Use the view name in future queries exactly like a table.
- 3If reads are slow and freshness is less critical, create a materialized view to store the result.
- 4Run REFRESH MATERIALIZED VIEW to rebuild the stored result after the data changes.
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price NUMERIC(10, 2) NOT NULL,
stock INTEGER NOT NULL DEFAULT 0
);
CREATE VIEW low_stock AS
SELECT id, name, stock
FROM products
WHERE stock < 5;
CREATE MATERIALIZED VIEW product_count_by_name AS
SELECT name, COUNT(*) AS copies
FROM products
GROUP BY name;
REFRESH MATERIALIZED VIEW product_count_by_name;Common mistakes
- Expecting a materialized view to update automatically, when it must be refreshed explicitly.
- Trying to insert or update rows through a plain view as if it were a real table.
- Creating a materialized view for data that must always be perfectly current.
- Duplicating a complex query in many places instead of saving it once as a view.
Create a cheap products view
Create a view named cheap_products that shows only the id, name, and price of products that cost less than 20. The products table already has these columns.
CREATE VIEW cheap_products AS
What is the key difference between a view and a materialized view?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.