Existence check: COUNT(*) → stop at the first row

A query that only needs to know whether a row exists counts every row. Change it to stop as soon as it finds the first row, and look at how partial range processing works.

SQL

Situation

The code checks "Are there completed orders since 2024?" and then moves on to the next step. The app only looks at if (count > 0). The result is a single row, yet the query takes longer than expected.

Tables

ORDERS (2 million rows) holds orders accumulated at 2,000 per day since 2023-01-01.

ColumnTypeDescription
STATUSVARCHAR2DONE 90%, PAID 7%, CANCELED 3%
ORD_DTDATEOrder date and time
IndexColumns
ORDERS_X2STATUS, ORD_DT, ORD_ID

Check whether completed orders exist

Count the orders in DONE status since 2024-01-01. The app only checks whether this value is greater than 0.

BEFORE · Count everything

SELECT COUNT(*)
FROM orders
WHERE status = 'DONE'
  AND ord_dt >= DATE '2024-01-01'

Run it and check how many Buffers it takes to get one result row, and how many rows (A-Rows) it reads from the index.

Approach

1. Check how the app uses the result

Looking only at the query, a count seems necessary. But the app only checks count > 0. The information actually needed is a single bit: "exists / does not exist". Tuning starts from the requirement, not the query.

2. Compare the amount read with the amount needed

Look at A-Rows and Buffers of the index operation in the execution plan. If it reads every matching entry to the end, there is a large gap between the amount needed (the first row) and the amount read.

3. Ask "can it stop at the first row?"

The matching entries sit contiguously in ORDERS_X2. Finding one row gives the answer, so look for a way to make the execution plan stop at the first row.

  • Put an upper limit on the number of rows read
  • Rewrite it as a construct that asks "does it exist?" from the start

4. Check the effect on the app

After the change, the value the app receives must keep its meaning. If the result is 0 or 1, the count > 0 logic still works.

A suitable index already exists. What changes is "how much it reads before it stops".

Explanation

① Put an upper limit on rows read

AFTER · ROWNUM <= 1

SELECT COUNT(*)
FROM orders
WHERE status = 'DONE'
  AND ord_dt >= DATE '2024-01-01'
  AND ROWNUM <= 1

② Ask with EXISTS

AFTER · EXISTS

SELECT 1
FROM dual
WHERE EXISTS (SELECT 1
              FROM orders
              WHERE status = 'DONE'
                AND ord_dt >= DATE '2024-01-01')

Why it got faster

  • Before counts all of the roughly 1.1 million matching index entries. The information needed is one bit, but it reads thousands of blocks.
  • After shows COUNT STOPKEY, and Buffers drop to 3-4 blocks.
  • The result is 0 or 1. The app logic needs no change.

Why this is optimal

  • All it does is descend from the index root to a leaf and check the first entry. 3-4 blocks equals the index height, so it cannot go lower.
  • It uses only COUNT(*), so it does not visit the table. All the condition columns are in ORDERS_X2.
  • Even when no row matches, the search range is empty, so it ends immediately.

Extended exercise: how partial range processing works

Run the same query while changing the sandbox's "rows to fetch" option.

TRY · Large query without sorting

SELECT *
FROM orders
WHERE status = 'DONE'
  • With rows to fetch set to 20 or 200, Buffers are small. Switch to "fetch all" and Buffers grow to cover the whole range.
  • The DB does not build the whole result in advance. It reads only as much as the client fetches. JDBC's fetchSize and SQL*Plus's arraysize set how much is fetched at a time.

TRY · FIRST_ROWS vs ALL_ROWS

SELECT /*+ FIRST_ROWS(10) */ *
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt
  • Compare execution plans while switching between FIRST_ROWS(10) and ALL_ROWS. The optimizer goal (first-row response vs total throughput) changes whether an index is used and which join method is chosen.

Key points

  • Reading only as much as needed is the basis of tuning. Existence checks, Top-N, and paging are all problems of building "an execution plan that can stop".
  • An operation that must read everything before it finishes, such as a sort, a hash join build, or an aggregation, breaks partial range processing. See scenario 2 and scenario 6 together.