Existence check: COUNT(*) → stop at the first row
Changes a query that counts everything when only existence matters so that it stops once it finds the first row. Also covers the principle of partial range processing.
SQL
Situation
A screen has the condition "show the settlement menu if there are completed orders since 2024". The developer counts the rows and shows the menu if the count is greater than 0. This check runs every time the screen opens.
Tables
| Table | Column | Description |
|---|---|---|
orders | status, ord_dt | About 1,140,000 completed (DONE) orders since 2024 |
| Index | Columns |
|---|---|
orders_x2 | status, ord_dt, ord_id |
Are there completed orders since 2024?
BEFORE · Count everything
SELECT COUNT(*)
FROM orders
WHERE status = 'DONE'
AND ord_dt >= CAST('2024-01-01' AS datetime2(0))
Run it and check how many rows the Index Seek read.
Approach
1. Ask what information the answer needs
What is needed is "yes/no". The answer is the same whether there are 1,140,000 rows or 1. The answer is settled the moment the first row is found.
2. Tell the DB that "the first row is enough"
With EXISTS or TOP (1), the optimizer builds a plan that finds only the first row (row goal), and execution stops as soon as it returns the first row.
Explanation
COUNT(*) → TOP (1)
AFTER · TOP (1)
SELECT TOP (1) 1 AS found
FROM orders
WHERE status = 'DONE'
AND ord_dt >= CAST('2024-01-01' AS datetime2(0))
COUNT(*) → EXISTS
AFTER · EXISTS
SELECT CASE WHEN EXISTS (SELECT 1
FROM orders
WHERE status = 'DONE'
AND ord_dt >= CAST('2024-01-01' AS datetime2(0)))
THEN 1 ELSE 0 END AS found
Why it got faster
- Before reads all 1,143,391 rows of the condition range in
orders_x2to the end and counts them. Buffers about 3,400. - Both After queries seek the same position, read one first entry, and stop (
ToporLeft Semi Join). Buffers 3.
Why this is optimal
- The 3 pages descended from the index root to the leaf are the minimum cost of "finding one row".
Variation: the price of first-row optimization
TRY · FAST 10 (reading to the end)
SELECT *
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt
OPTION (FAST 10)
TRY · No hint (reading to the end)
SELECT *
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt
OPTION (FAST 10)picks a plan tuned for "the first 10 rows fast" (reading inorders_x2order with Key Lookups). It is fast if only 10 rows are really fetched, but reading to the end as in this exercise takes 139,682 Key Lookups and Buffers of about 402,000. Without the hint, the table is read once and sorted for about 13,200. First-row optimization pays off only when only the first part is really used.
Key points
- Ask about existence with
EXISTSorTOP (1).COUNT(*) > 0counts everything. - The optimizer picks different plans depending on "how many rows are needed" (row goal).
TOP,EXISTS, andOPTION (FAST n)are that signal. - DB differences: Oracle does the same with
ROWNUM <= 1(COUNT STOPKEY) and theFIRST_ROWS(n)hint, and PostgreSQL withLIMIT 1andEXISTS.