Trending

World technology news

→
PostgreSQL 12 CTEs: How to measure the MATERIALIZED decision
Software Engineering · 2019
Software Engineering2019

PostgreSQL 12 CTEs: How to measure the MATERIALIZED decision

Compare two equivalent shipment queries to see how PostgreSQL 12 changed the way the planner handles WITH queries.

Archive retrospective · Topic year 2019

Developer's JournalPublished: Nov 27, 20266 min read
Reading progress0%
In this article
  1. What changed in the PostgreSQL 12 planner
  2. Set up a one-route shipment report
  3. Read more than the final time
  4. Choose deliberately when two consumers share work
  5. Take a small inventory before a version upgrade
  6. Include temporary work in the measurement record

What changed in the PostgreSQL 12 planner

PostgreSQL 12 made it possible to fold qualifying WITH expressions into the outer query. An older plan could evaluate a common table expression separately and prevent an outer restriction from reaching the original table. That was useful when a query wanted to compute an expensive expression once, but it could consume unnecessary work when a report wanted one route from a result built for every route. In PostgreSQL 12 the planner can combine a single use of a nonrecursive, side-effect-free SELECT expression with its parent query. Multiple references have a different default. Start by recording the server version and the actual shape of the query. This walkthrough compares deliberate choices rather than prescribing a rewrite for every WITH expression. Establish equal results before discussing performance, and look for the place where the filtering moved.

Set up a one-route shipment report

A distribution team wants the number of shipments and parcels on a single route after a cutoff. Use a disposable session for the fixture. It creates two hundred thousand synthetic rows. The repeating distribution makes the results reproducible but does not aim to resemble a real company's data. Both variants first express the date restriction in a named query. MATERIALIZED makes the planner preserve a separate result for that named selection. The outer query then selects route seven. NOT MATERIALIZED lets the planner combine the terms where the rules permit. The index can address a route and a date range together. Both queries should report 3333 records and 106666 parcels. Run both statements without EXPLAIN once to confirm that expected pair. If the values differ, inspect the test data and restrictions before interpreting timings. The fixture covers a useful test in which many dates match but very few routes matter.

Database access flowConceptual sketch · summary of the article's technical flow
CREATE TEMP TABLE shipment AS
SELECT k AS id, k % 30 AS route_id,
       DATE '2019-09-01' + (k % 60) AS shipped_on,
       5 + (k % 40) AS parcels
FROM generate_series(1, 200000) AS s(k);

CREATE INDEX shipment_route_day ON shipment(route_id, shipped_on);
ANALYZE shipment;

EXPLAIN (ANALYZE, BUFFERS)
WITH period AS MATERIALIZED (
  SELECT route_id, shipped_on, parcels
  FROM shipment WHERE shipped_on >= DATE '2019-09-15'
)
SELECT COUNT(*), SUM(parcels) FROM period WHERE route_id = 7;

EXPLAIN (ANALYZE, BUFFERS)
WITH period AS NOT MATERIALIZED (
  SELECT route_id, shipped_on, parcels
  FROM shipment WHERE shipped_on >= DATE '2019-09-15'
)
SELECT COUNT(*), SUM(parcels) FROM period WHERE route_id = 7;

Read more than the final time

Look for a CTE Scan and an outer filter where the intermediate result is materialized. Check how many rows that filter discards. In the folded version the restrictions may instead appear in the node accessing the original table. Do not declare that it always needs a plain Index Scan. A bitmap scan or sequential scan can be more useful with other distributions. EXPLAIN ANALYZE actually runs its statement. Use the read-only SELECT fixture on a suitable test system. In BUFFERS output a cache hit differs from a newly read block, and a temporary table can show local buffer use. One run can benefit from the state left by the other. Reverse the order and repeat before comparing. Save plan nodes, actual row counts and buffer figures alongside the duration. Those details help explain a result when timings vary.

Technical referencesPostgreSQL 12 EXPLAIN ↗

Choose deliberately when two consumers share work

Imagine that two consumers use the named input. One needs an individual route and the other needs a company-wide summary. Two very selective consumers can be cheaper when each pushes its filter down to the original tables. Consumers evaluating the same expensive expression across much of the same data may benefit from sharing an intermediate result. Measure both workloads before marking a multiply referenced expression NOT MATERIALIZED. Consider repeated function calls as well as scans. The folding behavior discussed here does not extend to recursive expressions or ones containing volatile functions. Do not change a function's volatility declaration merely to force a plan. Try a second fixture with costly transformation and a wider time window. Compare whether sharing saves repeated work and whether both result sets remain equivalent to the original, ordered where the application requires an ordering.

Take a small inventory before a version upgrade

During an upgrade, start with reports that run frequently or process many records. Save a plan and representative outputs on the old version. Repeat on the new version with comparable statistics and equivalent input. Test a popular route and an uncommon one, then try broader and narrower dates. Record the expected business total as well as a few underlying detail rows. Equal aggregate results alone can miss offsetting row changes in a more complex report. Keep an explicit ORDER BY where a caller relies on display order. A plan node does not promise that order. Explain each explicit materialization choice in the code review so that a later index or version change can revisit it. The useful artifact is a repeatable test and an explanation of where the work happens. That evidence is more durable than a global rule about writing or avoiding common table expressions.

Include temporary work in the measurement record

A large intermediate result can need temporary storage. Check whether the plan shows temporary reads or writes. Remove columns that the report does not use before adding complexity to the query. Preserve comparable settings between runs. Increasing work memory in one session changes more than the materialization decision. Run a modest concurrency check to see how temporary operations behave with other reports running. Record samples for two routes, all routes and an empty time window. SUM uses SQL NULL if no rows match. If the caller displays zero, record and test that rule independently. Keep both row counts and values in the comparison. An identical plan is not required when the allowed date range or data distribution changes.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which alternative architecture would you try for the same problem?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.