Page and total count: COUNT(*) OVER () breaks partial range processing

Adding COUNT(*) OVER () to fetch the first 20-row page of a list and the "N total" in one statement makes the NL join that stopped at 20 rows join all 37,000 rows. Counting separately, and dropping the join the count does not need, cuts Buffers from 92,000 to 256. The scenario also examines when dropping the join is allowed.

SQL

Situation

An order management screen shows 2025 paid orders 20 at a time, newest first, with "37,750 total" displayed above. At first the list and the count were queried separately; to save a round trip, they were merged into one statement with COUNT(*) OVER (). Since then the screen has been slow.

Tables

TableColumnsDescription
ordersstatus, ord_dt, cust_id37,750 paid orders in 2025
customerscust_nm, gradeOne customer per order
IndexColumns
orders_x2status, ord_dt, ord_id
customers_pkcust_id

orders.cust_id has no foreign key constraint and allows NULL. The current data has no NULLs, and every cust_id exists in customers.

Query

BEFORE · COUNT(*) OVER ()

SELECT o.ord_id, o.ord_dt, o.amt, c.cust_nm, c.grade,
       COUNT(*) OVER () AS total_cnt
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE o.status = 'PAID'
  AND o.ord_dt >= TIMESTAMP '2025-01-01'
ORDER BY o.ord_dt DESC
LIMIT 20

Remove COUNT(*) OVER (), run it, and compare the Buffers and the A-Rows of Nested Loop.

Approach

1. Check how many rows the window function must receive before emitting its first row

COUNT(*) OVER () is the count of the whole partition, that is, every row matching the conditions. To attach this value to the first row, it must receive the last row. Even with LIMIT 20 above it, the nodes below run to the end.

2. Split the work the list and the count need

List of 20 rows: read 20 entries backward from the index and look up a customer 20 times (scenario 13).

Count: it does have to count rows to the end, but check which columns counting needs. The customer name has nothing to do with the count. If all condition columns are in an index, counting is possible without reading the table.

3. Check that the count stays the same without the join

To drop the customers join when counting, the join must not change the row count. Check separately that the join does not add rows (is the key on the customer side unique?) and does not remove rows (does every order have a customer, and are there no NULLs?). Distinguish what constraints guarantee from what the current data happens to satisfy.

Explanation

Step 1: count separately with a scalar subquery

AFTER · Separate count (join kept)

SELECT o.ord_id, o.ord_dt, o.amt, c.cust_nm, c.grade,
       (SELECT COUNT(*)
        FROM orders o2
        JOIN customers c2 ON c2.cust_id = o2.cust_id
        WHERE o2.status = 'PAID'
          AND o2.ord_dt >= TIMESTAMP '2025-01-01') AS total_cnt
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE o.status = 'PAID'
  AND o.ord_dt >= TIMESTAMP '2025-01-01'
ORDER BY o.ord_dt DESC
LIMIT 20

Why it got faster

  • In Before, Index Scan Backward reads all 37,750 rows to the end (5,413 blocks), and Nested Loop looks up a customer 37,750 times. Memoize hit 8,779 times, but 28,971 times it probed customers_pk (86,913 blocks). Only after WindowAgg attaches the count does Limit return 20 rows. Buffers 92,326.
  • The list part of After #1 stops at 20 rows (6 index blocks + 20 customer lookups at 60 blocks). The count is a subquery uncorrelated with the outer query, so it runs only once as an InitPlan, and the planner picks a hash join that counts in 6,060 blocks. Buffers 6,126.
  • This transformation always gives the same result. It only counts separately with the same conditions and the same join.

Step 2: drop the join from the count

AFTER · Join removed from count

SELECT o.ord_id, o.ord_dt, o.amt, c.cust_nm, c.grade,
       (SELECT COUNT(*)
        FROM orders
        WHERE status = 'PAID'
          AND ord_dt >= TIMESTAMP '2025-01-01') AS total_cnt
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE o.status = 'PAID'
  AND o.ord_dt >= TIMESTAMP '2025-01-01'
ORDER BY o.ord_dt DESC
LIMIT 20

Why it got faster

  • The count subquery is answered from orders_x2 alone. status and ord_dt are both in the index, so Index Only Scan counts 37,750 rows without reading the table (Heap Fetches: 0, 190 blocks). Buffers 256.
  • The result is the same as Before. But it is the same for the current data. The join can be dropped only when both conditions below hold.
ConditionIn this schemaWhen it breaks
The join does not add rowscustomers_pk guarantees cust_id uniquenessIf the customer-side key is duplicated, the count without the join is smaller than the original
The join does not remove rowsNo constraint. The data just happens to have no NULLs or orphan ordersIf cust_id is NULL or refers to a missing customer, the count without the join is larger than the original
  • With a foreign key and a NOT NULL constraint, the second condition is guaranteed as well. Without the constraints, stop at step 1, or agree with the business to redefine the count on the screen as "number of orders".

Why this is optimal

  • The list does only as much work as the 20 rows shown on screen. The count has to count 37,750 rows regardless, but it reads only 190 index leaf blocks. The cost is proportional to the number of matching rows, so there is no way to get an exact count for less.

Variation: the cost of counting alone

TRY · Count only (join kept)

SELECT COUNT(*) AS total_cnt
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE o.status = 'PAID'
  AND o.ord_dt >= TIMESTAMP '2025-01-01'
  • Buffers 6,060. It builds a hash table from all of customers (834 blocks) and reads the 37,750 orders from the table to get cust_id. cust_id is not in orders_x2, so the table must be read.

Key points

  • Window functions over the whole partition, such as COUNT(*) OVER () and SUM(…) OVER (), turn off all partial range processing below LIMIT. Do not use them in paging statements.
  • To keep it in one statement, use an uncorrelated scalar subquery. It runs only once as an InitPlan.
  • The count is a different statement from the list. Dropping the joins and columns the count does not need lets a covering index do the counting. However, confirm with constraints that the join can be dropped. The data being that way right now is not a basis.
  • Also ask again in screen design whether an exact count is really needed. To show only "next page exists", read 21 rows.