PgPostgreSQL Lab
GitHub
Browser investigation

Work with sets and windows

A revenue dashboard doubles an order's amount after joining its two events. Repair the query's row multiplicity before tuning its plan.

You will learn to reason about join fan-out, aggregate at the correct grain, choose a window frame, and use LATERAL for a per-row lookup. Join fan-out occurs when one input row matches several rows on the other side. Prerequisites include joins, GROUP BY, and basic plans.

The page loads a fresh order dataset automatically. Select Run SQL in each numbered editor in order. The editors share one database, so later experiments use changes from earlier ones.

Sections on this page

Reproduce the double count

The grain of a relation describes what one row represents. An order row represents an order; an event row represents an event. Predict the number of rows after joining these tables.

Enable JavaScript to start the browser database.
SQL 01
Ctrl / ⌘ + Enter

In the row table, find the two entries for order 1 and the gap where order 3 would be. joined_total adds the amount once for every row the join returns. SUM(DISTINCT amount) is not a general repair: two different orders may legitimately have the same amount.

Match the intended grain

If events only determine whether an order qualifies, use an existence test. If the dashboard needs event counts, aggregate events before joining. Predict whether the second query preserves order 3.

SQL 02
Ctrl / ⌘ + Enter

The grouped event relation has at most one row per order. The left join preserves orders without events. A common table expression, or CTE, names a query result within the statement. It does not universally force materialization: PostgreSQL may fold a suitable CTE into its parent. Inspect EXPLAIN before using a CTE as a performance boundary.

Choose a window frame

A window function computes across related rows without collapsing them into a single aggregate row. Its frame chooses which rows contribute to a particular row's result. Predict whether two orders with the same amount receive the same running total under the default frame.

SQL 03
Ctrl / ⌘ + Enter

With ORDER BY, the default frame includes peers equal on the ordering keys. Both amount-200 rows therefore share the peer total. The explicit ROWS frame with the unique ID tie-breaker advances one row at a time in a deterministic order. Ordering inside OVER defines the computation; the final ORDER BY defines the presentation.

Ask a question for each row

A LATERAL subquery can refer to an earlier FROM item. Use it to get each order's newest event. Predict why LEFT JOIN matters for order 3.

SQL 04
Ctrl / ⌘ + Enter

The left join emits a NULL event for an order without one. An inner join would drop that order. On a large event table, (order_id, event_time DESC) is a candidate index for repeated lookups. A set-based alternative may be better when processing most orders; compare workload size and plans.

Explain the result

Which query keeps orders without events? In the window output, compare the two rows with amount 200. Why can their totals tie under one ordering and differ under another?

A hint for explaining the results

Write the grain beneath each intermediate relation. Count rows before computing money.

Worked explanation

The original join repeats order 1's amount and omits order 3. EXISTS preserves one row per qualifying order, while a grouped left join preserves every order with an event count. The window examples answer different questions about equal-valued peers. LATERAL expresses a per-order lookup and the left join retains orders without matches. Correct cardinality comes before choosing an index.

Go deeper: how the engine works

After fixing row multiplicity, which side of a hash join is held in memory and why does that choice matter? Read Joins (opens in a new tab) in Query Engine Book. For GROUP BY state and group cardinality, also read Hash aggregation (opens in a new tab). Its DuckDB examples and teaching engine explain the general principle; PostgreSQL's operators and implementation details can differ. This reading is optional.

Transfer the idea

After running the original editors, add INSERT INTO demo_orders VALUES (5, 100); above the first statement in SQL 02. Predict which result will change, then select Run SQL. Compare total_with_events and the table of id, amount, and events with your original results. Why does a new order appear in one result without raising the total in the other?

Next: give JSONB a job.

Primary sources: Table expressions, window functions, and WITH queries.