One phrase, NULLS LAST, blocks sort avoidance
Changing the 20 most recent paid orders to ORDER BY ord_dt DESC NULLS LAST makes the reverse index scan disappear, and 140,000 paid orders are read and sorted. This is because reading the index backward returns NULLs first. Splitting non-NULL rows and NULL rows with UNION ALL brings Buffers back from 19,417 to 9.
SQL
Situation
A payment screen shows the 20 most recent paid orders. After an inquiry that orders with an empty order timestamp appear at the top, the developer added NULLS LAST. Since then the screen has been slow.
Tables
| Table | Columns | Description |
|---|---|---|
orders | status, ord_dt | 140,577 paid orders. ord_dt has no NOT NULL constraint (currently 0 NULLs) |
| Index | Columns |
|---|---|
orders_x2 | status, ord_dt, ord_id (default ASC NULLS LAST) |
Query
BEFORE · NULLS LAST
SELECT ord_id, ord_dt, amt
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC NULLS LAST
LIMIT 20
Remove NULLS LAST, run it, and compare the result and the execution plan.
Approach
1. See where the index puts NULLs
The default order of a PostgreSQL B-tree index is ASC NULLS LAST. Read backward it is DESC NULLS FIRST, which is also the default of ORDER BY … DESC. DESC NULLS LAST is an order that reading the index in either direction does not produce.
2. See whether a condition removes the NULL position problem
Adding WHERE ord_dt IS NOT NULL leaves no NULLs in the result, so NULLS LAST and NULLS FIRST are the same order. Run it to see whether the planner notices this and skips the sort.
3. Split the sort order into two index orders
DESC NULLS LAST is "non-NULL rows in descending order, then NULL rows". The first part and the last part can each be read in index order. Once the first part fills 20 rows, the last part is barely read.
Explanation
Top-N with non-NULL rows and NULL rows split
AFTER · Split with UNION ALL
(SELECT ord_id, ord_dt, amt FROM orders
WHERE status = 'PAID' AND ord_dt IS NOT NULL
ORDER BY ord_dt DESC
LIMIT 20)
UNION ALL
(SELECT ord_id, ord_dt, amt FROM orders
WHERE status = 'PAID' AND ord_dt IS NULL
LIMIT 20)
ORDER BY ord_dt DESC NULLS LAST
LIMIT 20
Why it got faster
- Before cannot use the index order, so it reads all 140,577 paid orders with a
Bitmap Heap Scan(18,722 heap blocks) and picks 20 withtop-N heapsort. Buffers 19,417. - The first branch of After reads
orders_x2withIndex Scan Backwardand stops at 20 rows (6 blocks). The second branch finds thestatus = 'PAID' AND ord_dt IS NULLrange and confirms 0 rows (3 blocks). Only the at most 40 rows combined byAppendare sorted again. Buffers 9. - The result is the same as Before. If NULLs appear, as long as there are 20 or more non-NULL rows, the second branch's rows are pushed to the back by the outer sort and cut off.
- A PostgreSQL B-tree also stores NULLs in the index, so an
IS NULLcondition is also found through the index.
Why this is optimal
- Compared with the original plan without
NULLS LAST(6 blocks), it reads only the 3 extra blocks of the second branch. That is the minimum cost of confirming that there really are no NULL rows. - If the column has a
NOT NULLconstraint,NULLS LASTdoes not affect the result, so removing it is simplest. Without the constraint, the current data having no NULLs is not a basis.
Variation: adding only the IS NOT NULL condition
TRY · IS NOT NULL + NULLS LAST
SELECT ord_id, ord_dt, amt
FROM orders
WHERE status = 'PAID' AND ord_dt IS NOT NULL
ORDER BY ord_dt DESC NULLS LAST
LIMIT 20
- The result cannot contain NULLs, yet the planner does not choose to skip the sort. Buffers 19,417, the same as Before. The planner compares the
NULLSposition of the sort key with the index order literally, so the sort clause must be written by hand to match the index order.
TRY · NULLS LAST removed (NULLs at the top)
SELECT ord_id, ord_dt, amt
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC
LIMIT 20
- It stops at 20 rows with
Index Scan Backward. Buffers 6.
Key points
- To skip a sort through an index, not only the direction of
ORDER BYbut also the NULL position must match the order in which the index is read. The default of a PostgreSQL index isASC NULLS LAST; read backward it isDESC NULLS FIRST. - A sort that differs from the index order can regain partial range processing by splitting it into parts readable in index order and combining them with
UNION ALL. - When changing a sort clause, check not only the result but also whether a new
Sortappeared in the execution plan.