Database Programming Features · Lesson 81 of 112

Database Views, Materialized Views and Temporary Tables

What you will learn

  • What a view does (a recap of lesson 4.7)
  • What a materialized view is and why it can be stale
  • How to build the same idea by hand in SQLite
  • What a temporary table is and how long it lives
  • How to choose between them

1. Three ways to save a result

Tool What is stored Fresh? Speed
View only the query always current runs the query every time
Materialized view the result (a saved copy) stale until refreshed fast to read
Temporary table a scratch table for one session as of when you built it fast, private

2. A view always shows the latest data

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It adds a view and tables of its own to your browser's copy; run the examples from top to bottom, and Reset data starts again.

You met views in lesson 4.7. Here is one that adds up a table per day.

The Shop's payments, added up per day:

The Bank's ledger, added up per day:

The School's submissions, counted per day:

CREATE VIEW daily AS SELECT paid_on AS day, ROUND(SUM(amount), 2) AS total FROM payments GROUP BY paid_on;
SELECT * FROM daily ORDER BY day LIMIT 3;
day          total
----------  ------
2024-01-05  187.11
2024-01-10    51.1
2024-01-11   18.81
(3 rows)

A new row arrives for the first day. The view is read again:

INSERT INTO payments (order_id, paid_on, method, amount) VALUES (1, '2024-01-05', 'cash', 100.0);
SELECT * FROM daily ORDER BY day LIMIT 3;
day          total
----------  ------
2024-01-05  287.11
2024-01-10    51.1
2024-01-11   18.81
(3 rows)
CREATE VIEW daily AS SELECT txn_date AS day, SUM(amount_cents) AS total FROM transactions GROUP BY txn_date;
SELECT * FROM daily ORDER BY day LIMIT 3;
day          total
----------  ------
2018-02-23  108000
2018-03-07   76000
2018-03-24   23900
(3 rows)

A new row arrives for the first day. The view is read again:

INSERT INTO transactions (account_id, txn_date, kind, amount_cents, balance_after, description) VALUES (154, '2018-02-23', 'deposit', 1000, 54800, 'extra A');
SELECT * FROM daily ORDER BY day LIMIT 3;
day          total
----------  ------
2018-02-23  109000
2018-03-07   76000
2018-03-24   23900
(3 rows)
CREATE VIEW daily AS SELECT submitted_on AS day, COUNT(*) AS total FROM submissions WHERE submitted_on IS NOT NULL GROUP BY submitted_on;
SELECT * FROM daily ORDER BY day LIMIT 3;
day         total
----------  -----
2025-02-14      5
2025-02-15      8
2025-02-16      6
(3 rows)

A new row arrives for the first day. The view is read again:

INSERT INTO submissions (assignment_id, student_id, submitted_on, points) VALUES (1, 360, '2025-02-14', 10.0);
SELECT * FROM daily ORDER BY day LIMIT 3;
day         total
----------  -----
2025-02-14      6
2025-02-15      8
2025-02-16      6
(3 rows)

The view stores no rows. Each time you read it, the database re-runs the SELECT ... GROUP BY, so the new row appears immediately. The cost: if the query is heavy (millions of rows), every read pays for it.

3. Materialized views: a saved copy

A materialized view stores the result of the query like a real table. Reading it is fast, because the work was done earlier. The price is that it can be out of date: new rows do not appear until you refresh it.

PostgreSQL has this built in. Its documentation says that CREATE MATERIALIZED VIEW defines a materialized view of a query, which is run to populate the view when the command is issued, and that the view may be refreshed later using REFRESH MATERIALIZED VIEW, which completely replaces its contents. The basic shapes are:

CREATE MATERIALIZED VIEW daily_saved AS SELECT ... ;
REFRESH MATERIALIZED VIEW daily_saved;

(PostgreSQL syntax, not run here. SQLite has no materialized views.)

You can imitate it in SQLite by hand with an ordinary table that holds the copy:

CREATE TABLE daily_saved AS SELECT * FROM daily;
INSERT INTO payments (order_id, paid_on, method, amount) VALUES (1, '2024-01-05', 'cash', 1000.0);
SELECT 'saved copy' AS source, day, total FROM daily_saved ORDER BY day LIMIT 1;
SELECT 'live view' AS source, day, total FROM daily ORDER BY day LIMIT 1;
source      day          total
----------  ----------  ------
saved copy  2024-01-05  287.11
(1 row)

source     day           total
---------  ----------  -------
live view  2024-01-05  1287.11
(1 row)
CREATE TABLE daily_saved AS SELECT * FROM daily;
INSERT INTO transactions (account_id, txn_date, kind, amount_cents, balance_after, description) VALUES (154, '2018-02-23', 'deposit', 100000, 54800, 'extra B');
SELECT 'saved copy' AS source, day, total FROM daily_saved ORDER BY day LIMIT 1;
SELECT 'live view' AS source, day, total FROM daily ORDER BY day LIMIT 1;
source      day          total
----------  ----------  ------
saved copy  2018-02-23  109000
(1 row)

source     day          total
---------  ----------  ------
live view  2018-02-23  209000
(1 row)
CREATE TABLE daily_saved AS SELECT * FROM daily;
INSERT INTO submissions (assignment_id, student_id, submitted_on, points) VALUES (1, 359, '2025-02-14', 10.0);
SELECT 'saved copy' AS source, day, total FROM daily_saved ORDER BY day LIMIT 1;
SELECT 'live view' AS source, day, total FROM daily ORDER BY day LIMIT 1;
source      day         total
----------  ----------  -----
saved copy  2025-02-14      6
(1 row)

source     day         total
---------  ----------  -----
live view  2025-02-14      7
(1 row)

The saved copy is now stale: it still shows the old total for the first day, while the live view shows the new one. A refresh replaces the contents. Do it inside one transaction so a reader never sees the table half-empty:

BEGIN;
DELETE FROM daily_saved;
INSERT INTO daily_saved SELECT * FROM daily;
COMMIT;
SELECT 'refreshed' AS source, day, total FROM daily_saved ORDER BY day LIMIT 1;
source     day           total
---------  ----------  -------
refreshed  2024-01-05  1287.11
(1 row)
BEGIN;
DELETE FROM daily_saved;
INSERT INTO daily_saved SELECT * FROM daily;
COMMIT;
SELECT 'refreshed' AS source, day, total FROM daily_saved ORDER BY day LIMIT 1;
source     day          total
---------  ----------  ------
refreshed  2018-02-23  209000
(1 row)
BEGIN;
DELETE FROM daily_saved;
INSERT INTO daily_saved SELECT * FROM daily;
COMMIT;
SELECT 'refreshed' AS source, day, total FROM daily_saved ORDER BY day LIMIT 1;
source     day         total
---------  ----------  -----
refreshed  2025-02-14      7
(1 row)

The common refresh policies are: refresh on a schedule (every night), refresh after big loads, or refresh by hand. Dashboards that can be a few minutes old are the classic use (chapter 13).

4. Temporary tables: a private scratchpad

A temporary table exists only for your connection (SQLite) and is removed when the connection closes. Other connections cannot see it. It is useful for storing an intermediate result you will use several times in a long job.

CREATE TEMP TABLE big_days AS SELECT day FROM daily WHERE total > 150;
SELECT COUNT(*) AS big_days FROM big_days;
SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('daily_saved', 'big_days') ORDER BY name;
SELECT name FROM sqlite_temp_master;
big_days
--------
     518
(1 row)

name
-----------
daily_saved
(1 row)

name
--------
big_days
(1 row)
CREATE TEMP TABLE big_days AS SELECT day FROM daily WHERE total > 50000;
SELECT COUNT(*) AS big_days FROM big_days;
SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('daily_saved', 'big_days') ORDER BY name;
SELECT name FROM sqlite_temp_master;
big_days
--------
    1198
(1 row)

name
-----------
daily_saved
(1 row)

name
--------
big_days
(1 row)
CREATE TEMP TABLE big_days AS SELECT day FROM daily WHERE total > 6;
SELECT COUNT(*) AS big_days FROM big_days;
SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('daily_saved', 'big_days') ORDER BY name;
SELECT name FROM sqlite_temp_master;
big_days
--------
     204
(1 row)

name
-----------
daily_saved
(1 row)

name
--------
big_days
(1 row)

The temporary table lives in a separate temp area (sqlite_temp_master), not in the main schema, and a new connection cannot see it. (In the browser, Reset data opens a new connection and the temporary table is gone.) Other products may define the lifetime differently (for example per session or per transaction), so check the documentation of the one you use.

Quick check: rows were added after you built the saved copy. Which of view, materialized view and temporary table shows them without any action?

Only the view. The other two are copies and need to be refreshed or rebuilt.

Worked example: choosing

A manager's dashboard shows revenue by day. The query scans 40 million rows and takes 30 seconds. The manager opens the page 200 times a day, and "up to an hour old" is acceptable.

  • A plain view would run the 30-second query 200 times a day: too slow.
  • A materialized view refreshed every hour runs it 24 times a day, and every page load is instant.
  • A temporary table would help only inside one long job, not for sharing across page loads.

The numbers are made up to show the reasoning. In real life, measure the query first (lesson 7.6).

Common mistakes

  • Forgetting that a materialized view is stale and showing its numbers as live.
  • Refreshing without a transaction, so readers briefly see an empty copy.
  • Using a materialized view for a cheap query that a normal view or index would serve.
  • Expecting a temporary table to be shared with other connections or to survive a restart.

Key takeaways

  • A view stores a query and is always fresh; it pays the query cost on every read.
  • A materialized view stores the result: fast to read, but stale until refreshed.
  • SQLite has no materialized views; a table filled from a query plus a refresh step does the same job.
  • A temporary table is a private scratch table for one connection.
  • Choose by how fresh the data must be and how often and how expensive the reads are.

Practice

1. What does a view store?

Show answer

Only the query, not the rows. The rows are produced when you read the view.

2. Why can a materialized view show wrong (old) numbers?

Show answer

It is a saved copy of the result and is not updated when the underlying tables change, until it is refreshed.

3. In the lesson's example, what did the saved copy say for Tuesday after the 1000 sale, and what did the live view say?

Show answer

The saved copy said 225 and the live view said 1225.

4. Why was the refresh done inside with con:?

Show answer

So the delete and the re-insert happen as one transaction; otherwise a reader could see the copy empty in between.

5. A report job needs the same filtered list five times in one script and nobody else needs it. Which tool fits?

Show answer

A temporary table (private to that connection and removed afterwards).

6. Name one situation where a plain view is better than a materialized view.

Show answer

When the data must always be current, or the query is cheap, so there is no need to store and refresh a copy.