← Binderdex dev log

ORDER BY CASE read 18,787 rows to return 100

#data#product#web#solo-founder

A jumbled pile of grey bars on the left, and on the right two short ordered stacks, the upper one glowing amber with an index marker beside it

The card detail page on Binderdex, my Pokémon card collection and price app, was taking more than 14 seconds on the most popular cards. There was no traffic spike behind it. It was normal evening load, and the hottest cards in the catalog were the slowest pages on the site.

Each card's page shows its prices, a watchlist button and links to shops. The slow part was one query behind it. It fetches a card's latest graded-price rows, meaning recorded prices for copies that a professional grading service has scored. It wants about 100 rows, ordered by source priority first and recency second. Each row comes from one of several sources, and I rank one of them first. Rows from that priority source come before everything else, newest first inside each group.

The sort an index can't serve

I'd written the priority rule the obvious way, as a CASE expression inside the ORDER BY. This one line is the whole problem:

ORDER BY CASE WHEN source = 'priority' THEN 0 ELSE 1 END,
         recorded_at DESC
LIMIT 100

An index keeps rows in a stored order, so the database can walk it and stop as soon as it has enough. The result of a CASE expression isn't stored anywhere. Postgres has no pre-sorted path to follow, so it fetches every matching row, computes the expression for each one, sorts the lot in memory, and only then applies the limit.

For the hottest card that meant reading all 18,787 price rows to return 100, then throwing away 99.5% of what it had just read. On a card with 200 rows you'd never notice, which is why the query survived as long as it did.

BEFORE one ORDER BY CASE the index cannot serve Read all 18,787 rows for the card Sort in memory by CASE, then time Keep 100, discard 99.5% 14.6 s AFTER two filtered queries, each with a LIMIT the index serves Index scan 1: priority source Index scan 2: the rest, if needed Concatenate into 100 rows 49 ms 563 rows touched, on the existing (card_id, recorded_at) index
Same card, same 100 rows out. The work moved from a sort over everything to two short walks along an index.

Two index scans in place of one sort

The table already had an index on (card_id, recorded_at). That index can hand back one card's rows newest-first by walking backward, as long as nothing else needs sorting. The priority rule was the only thing in the way, so I moved it out of the ORDER BY and into two separate queries.

The first asks for the newest rows from the priority source, up to the limit. The second runs only when the first comes back short, and asks for the newest rows from every other source to fill the gap. Then I concatenate the two lists. Each query filters on a plain column and orders by time, which is exactly what the index stores. Here's the shape, simplified from the real code:

// Scan 1: priority source, newest first
const priorityRows = await db.select(cols).from(table)
  .where(and(...filters, eq(source, "priority")))
  .orderBy(desc(recordedAt)).limit(100);

// Scan 2: everything else, only if we need more
const remaining = 100 - priorityRows.length;
const otherRows = remaining > 0
  ? await db.select(cols).from(table)
      .where(and(...filters, sql`${source} is distinct from 'priority'`))
      .orderBy(desc(recordedAt)).limit(remaining)
  : [];

const result = [...priorityRows, ...otherRows];

One detail in the second scan matters. IS DISTINCT FROM keeps rows whose source is NULL. A plain != would silently drop them, because a comparison with NULL is never true.

563 rows and 49 milliseconds

The two scans touch 563 rows where the old query read 18,787. Cold, on the same saturated volume, the query went from 14.6 seconds to 49 milliseconds, roughly 300 times faster.

I compared the output before trusting it. Of the 100 IDs returned, 99 were identical. The one that differed sat among 8 rows tied at the boundary timestamp, where the old query's order was never deterministic in the first place.

The cleanup around it

This fix was one piece of a wider performance push on price history. The two tables that store price history hold 67 million rows between them, and they carried 13 and 11 indexes, most with zero lifetime scans. I converted both to monthly range partitions on recorded_at, managed by pg_partman. The cutover was a sub-second rename swap, guarded by a row-parity gate that aborts if the counts don't match.

The cache backend moved to an in-network Valkey instance, where a cache GET now has a p50 of 1.3 ms. Anonymous API GETs are also cached at the CDN.

Run EXPLAIN on every ORDER BY CASE

If a query sorts by a CASE expression and then applies a LIMIT, read its plan against your largest group of rows, because an average-sized one will look fine. The limit won't protect you. The sort has to finish before the limit can apply.

When the expression only ranks a few groups against each other, express the priority as separate filtered queries, each with a limit the index can serve, and join the results in order. It's more code than one ORDER BY, and it reads a few hundred rows where the sort read every one.

This is the build log for Binderdex (www.binderdex.com) · All entries · Weekly essays