Existence check: COUNT(*) → stop at the first row
A query that counts everything when it only needs to know whether a row exists is changed to stop once it finds the first row.
SQL
Situation
Before a batch job, a check asks "is there at least one completed order since 2024". The code compares whether COUNT(*) is greater than 0. This check takes 0.5 seconds every time.
Tables
| Table | Columns | Description |
|---|---|---|
orders | status, ord_dt | DONE is 90%; about 1.14 million completed orders since 2024 |
| Index | Columns |
|---|---|
orders_x2 | status, ord_dt, ord_id |
Is there a completed order since 2024
BEFORE · Count everything
SELECT COUNT(*)
FROM orders
WHERE status = 'DONE'
AND ord_dt >= DATE '2024-01-01'
Run it and check how many rows it read (A-Rows).
Approach
1. Check that the question and the query match
The question is "is there at least one", but the query asks "how many". If the exact count is not needed, it can stop at the first row.
2. Tell the DB that one row is enough
LIMIT 1 or EXISTS means stop as soon as the first row is found.
Explanation
Count everything → stop at the first row
AFTER · EXISTS
SELECT EXISTS (SELECT 1
FROM orders
WHERE status = 'DONE'
AND ord_dt >= DATE '2024-01-01') AS found
AFTER · LIMIT 1
SELECT COUNT(*)
FROM (SELECT 1
FROM orders
WHERE status = 'DONE'
AND ord_dt >= DATE '2024-01-01'
LIMIT 1) t
Why it got faster
- Before reads and counts all 1,143,191 rows matching the condition with
Index Only Scan. Buffers about 5,600. - After stops as soon as it finds the first row. Buffers 6.
EXISTSruns once as anInitPlan, andLIMIT 1makes the result 0 or 1. - Since as many as 90% of rows match, the planner judges that reading the table from the start (
Seq Scan) instead of the index finds one right away in the first blocks, and does so.
Why this is optimal
- It reads only the blocks needed to find one row. If matching rows are rare, one index lookup is the minimum cost.
Key points
- Ask "is there" with
EXISTSorLIMIT 1.COUNT(*) > 0counts everything. - The more rows match, the sooner the first one comes. Conversely, when none exist the check must go to the end, so an index matters for checks that are likely to find nothing.
- DB difference: Oracle uses
ROWNUM <= 1(COUNT STOPKEY) orEXISTS; PostgreSQL usesLIMIT 1orEXISTS. PostgreSQL can take EXISTS out directly as a value, as inSELECT EXISTS (…).