IN condition and Top-N: cut per value, then merge
The 20 latest orders whose status is PAID or CANCELED. With an IN list, the (status, ord_dt) index order differs from ord_dt order, so the sort cannot be skipped. Getting the Top-20 per value and merging with Merge Append reads 40 rows instead of 200,000.
SQL
Situation
The "orders needing action" list on a CS screen. It shows paid (PAID) and canceled (CANCELED) orders newest first, 20 at a time. It was fast with one status (scenario 2), but slowed down when the statuses grew to two. The index is unchanged.
Tables
| Table | Columns | Description |
|---|---|---|
orders | status, ord_dt | PAID 140,577 rows, CANCELED 59,493 rows |
| Index | Columns |
|---|---|
orders_x2 | status, ord_dt, ord_id |
Query
BEFORE · IN list + ORDER BY
SELECT ord_id, ord_dt, status, amt
FROM orders
WHERE status IN ('PAID', 'CANCELED')
ORDER BY ord_dt DESC
LIMIT 20
Run it and check how many rows come up under Sort. Also compare it with the result of running with the status changed to 'PAID' alone.
Approach
1. Draw the order the index provides
orders_x2 is sorted first by status, and by ord_dt within the same status. Reading the index backward yields PAID newest → PAID oldest → CANCELED newest … in that order. With one status this order is exactly ord_dt DESC, but with two it is split into two runs, so as is it is not ord_dt DESC.
2. See how much needs sorting
The whole result does not need sorting. There are already two runs sorted per status, so it is enough to merge them by comparing only the front of each run. The 20 latest rows are always within "PAID's 20 latest" and "CANCELED's 20 latest".
3. Split the query so the planner can build that shape
The planner does not split a single IN list this way. Also check whether splitting with UNION ALL alone is not enough. Each run must show "where to stop" for the index to be read only 20 rows per run.
Explanation
Get the Top-20 per value and merge
AFTER · Top-20 per status + Merge Append
SELECT ord_id, ord_dt, status, amt
FROM (
(SELECT ord_id, ord_dt, status, amt FROM orders
WHERE status = 'PAID' ORDER BY ord_dt DESC LIMIT 20)
UNION ALL
(SELECT ord_id, ord_dt, status, amt FROM orders
WHERE status = 'CANCELED' ORDER BY ord_dt DESC LIMIT 20)
) t
ORDER BY ord_dt DESC
LIMIT 20
Why it got faster
- Before finds all 200,070 orders of the two statuses with
Bitmap Index Scan, reads 18,729 table blocks, then keeps 20 rows withtop-N heapsort. Buffers 19,785. The sort memory is small at 27kB, but all the cost goes into building the 200,000 rows to feed the sort. - In After,
Index Scan Backwardreadsorders_x2backward per status, and theMerge Appendabove merges by comparing the front of the two runs.Limitstops at 20 rows, so only 15 PAID and 6 CANCELED rows were read (including 1 for the last comparison). Buffers 11. - The inner
LIMIT 20matters. WithORDER BY … LIMITonly on the outside and a plainUNION ALLinside, the planner reads both statuses fully withBitmap Heap Scanand does aSort(Buffers 37,788, actually worse). Only with the innerORDER BY … LIMITdoes each run become a sorted input using index order, which makesMerge Appendpossible.
Why this is optimal
- Each run reads only the blocks from the index root down to the leaf and the table blocks holding result rows. With k statuses the cost is only about k times, regardless of how many orders each status has.
- No sort remains.
Merge Appendonly merges already sorted inputs.
Variation: a screen where the status list changes
If the status list is chosen on screen, the number of UNION ALL branches is not fixed. Unnesting an array and getting the Top-20 per status with LATERAL has the same effect.
TRY · Array + LATERAL
SELECT o.ord_id, o.ord_dt, o.status, o.amt
FROM unnest(ARRAY['PAID', 'CANCELED']) AS s(status)
CROSS JOIN LATERAL (
SELECT ord_id, ord_dt, status, amt
FROM orders
WHERE orders.status = s.status
ORDER BY ord_dt DESC
LIMIT 20
) o
ORDER BY o.ord_dt DESC
LIMIT 20
- It reads exactly 20 rows per status, 40 in all, and picks 20 with a small
Sort. Buffers about 17. It does not stop midway likeMerge Append, but statuses × 20 rows is the upper bound.
Variation: next page
The next page puts the previous page's last ord_dt into each branch and reads by keyset (scenario 3). The default value is the 20th row of the first page.
TRY · Next page (keyset)
SELECT ord_id, ord_dt, status, amt
FROM (
(SELECT ord_id, ord_dt, status, amt FROM orders
WHERE status = 'PAID' AND ord_dt < :last_dt ORDER BY ord_dt DESC LIMIT 20)
UNION ALL
(SELECT ord_id, ord_dt, status, amt FROM orders
WHERE status = 'CANCELED' AND ord_dt < :last_dt ORDER BY ord_dt DESC LIMIT 20)
) t
ORDER BY ord_dt DESC
LIMIT 20
- Buffers about 10, the same as the first page. In this data
ord_dtvalues do not overlap, so the keyset usesord_dtalone. If orders can share the same time, write(ord_dt, ord_id) < (:last_dt, :last_id).
Key points
- On index
(a, b),a = constant ORDER BY bskips the sort, buta IN (…) ORDER BY bcannot. The index order is broken at eacha. - Get the Top-N per broken run and merge. The key is writing
ORDER BY … LIMITdirectly in each branch. Merge Appendis a node that merges several sorted inputs. The same shape appears in Top-N over partitioned tables.- DB difference: Oracle solves the same problem by putting
FETCH FIRST(orROWNUM) in eachUNION ALLbranch and sorting outside, and the outer sort remains asSORT ORDER BY STOPKEY. There is no node like PostgreSQL's that only merges sorted inputs.