Emulating NULLS LAST Blocks Sort Avoidance

Porting Oracle's ORDER BY ord_dt DESC NULLS LAST by putting CASE WHEN ord_dt IS NULL THEN 1 ELSE 0 END ahead of the sort key makes the query read and sort 140K paid orders. SQL Server sorts NULL as the smallest value, so DESC already puts NULL last. Removing the CASE brings Buffers back from 13,201 to 47. An ascending sort with NULL last is split with UNION ALL.

SQL

Situation

A payment screen query used in Oracle was ported to SQL Server. The original query was ORDER BY ord_dt DESC NULLS LAST, but SQL Server has no NULLS LAST, so a developer built the same order with a CASE expression. After the port, the screen became slow.

Tables

TableColumnDescription
ordersstatus, ord_dt139,682 paid orders. ord_dt allows NULL (currently 0 NULLs)
IndexColumns
orders_x2status, ord_dt, ord_id

Query

BEFORE · Emulate NULLS LAST with CASE

SELECT TOP (20) ord_id, ord_dt, amt
FROM orders
WHERE status = 'PAID'
ORDER BY CASE WHEN ord_dt IS NULL THEN 1 ELSE 0 END, ord_dt DESC

Approach

1. Check whether the sort keys are index columns

The CASE expression is a value not in the index. If the first sort key is an expression, the sort cannot be avoided through index order, and all matching rows are read and sorted.

2. Confirm where SQL Server places NULL

SQL Server sorts NULL lower than any value. In ascending order NULL comes first; in descending order NULL comes last. Oracle and PostgreSQL do the opposite and treat NULL as the largest value. Work out whether the ported NULLS LAST is still needed in SQL Server.

3. Split when the sort truly differs from index order

An ascending order with NULL last is an order that a SQL Server index does not produce in either read direction. In that case, consider reading the non-NULL rows and the NULL rows separately in index order and combining them.

Explanation

Remove the CASE: DESC already puts NULL last

AFTER · DESC without CASE

SELECT TOP (20) ord_id, ord_dt, amt
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC

Why it got faster

  • In Before, the sort key is an expression, so index order cannot be used. It reads the clustered index (the table) to the end to pick the 139,682 paid orders and keeps 20 with a TopN Sort. Buffers are 13,201.
  • After reads the PAID range of orders_x2 backward, stops at 20 rows (3 pages), and Key Lookups only those 20 (44 pages). Buffers are 47.
  • The result order is the same as Before. SQL Server's DESC puts NULL last, so the "NULL at the very end" built by the CASE expression is already the default behavior.

NULL last in ascending order: split with UNION ALL

TRY · Ascending + CASE (slow)

SELECT TOP (20) ord_id, ord_dt, amt
FROM orders
WHERE status = 'PAID'
ORDER BY CASE WHEN ord_dt IS NULL THEN 1 ELSE 0 END, ord_dt

TRY · Ascending + UNION ALL

SELECT TOP (20) ord_id, ord_dt, amt
FROM (
  SELECT * FROM (SELECT TOP (20) ord_id, ord_dt, amt, 0 AS null_last
                 FROM orders
                 WHERE status = 'PAID' AND ord_dt IS NOT NULL
                 ORDER BY ord_dt) a
  UNION ALL
  SELECT * FROM (SELECT TOP (20) ord_id, ord_dt, amt, 1 AS null_last
                 FROM orders
                 WHERE status = 'PAID' AND ord_dt IS NULL) b
) u
ORDER BY null_last, ord_dt
  • Showing the oldest paid orders first while keeping NULL at the very end is truly an order different from the index. Written with CASE, Buffers are 13,201.
  • Split into two branches, the first branch reads 20 rows from the front of orders_x2 (47 pages), and the second seeks the ord_dt IS NULL range and confirms 0 rows (3 pages). Only the up to 40 rows combined by Concatenation are sorted again. Buffers are 50.

Why this is optimal

  • After is exactly the original plan without NULLS LAST. The remaining cost is the Key Lookup of the 20 result rows.
  • The ascending split reads only 3 extra pages to confirm that there really is no NULL.

Key points

  • To avoid a sort with an index, not only the ORDER BY direction but also the NULL position must match the order in which the index is read. Putting an expression ahead of the sort key by itself removes sort avoidance.
  • The sort position of NULL differs by DB. In SQL Server NULL is the smallest; in Oracle and PostgreSQL it is the largest. When porting another DB's NULLS FIRST/LAST, first compare it with SQL Server's default order.
  • A sort that differs from index order can recover partial range processing by splitting it into parts that can be read in index order and combining them with UNION ALL.