Video in progress

What is a VIEW, and does it store data separately?

A VIEW is a named, saved SELECT query. A regular VIEW stores no data: every time you query it, the query inside runs. The variant that stores the result is a MATERIALIZED VIEW.

📖 Answer

CREATE VIEW active_customers AS
SELECT u.id, u.email, count(o.id) AS orders_cnt
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE u.blocked = false
GROUP BY u.id, u.email;

SELECT * FROM active_customers WHERE orders_cnt > 10;

What it gives you:

  • you write a complex JOIN in one place and reuse it everywhere;
  • limiting permissions: you give an analytics user a VIEW with only the columns they need instead of the table.

It doesn't make anything faster: the planner expands the VIEW and optimizes it like a regular query.

A MATERIALIZED VIEW stores the result on disk and stays stale until you run REFRESH MATERIALIZED VIEW. It's handy for heavy reports, but if you use it where people expect "real-time" data, users will see yesterday's numbers.

In Java you can also read a VIEW as a JPA entity. Marking it @Immutable is a good habit, since you can't write to it.