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

TableColumnsDescription
ordersstatus, ord_dtDONE is 90%; about 1.14 million completed orders since 2024
IndexColumns
orders_x2status, 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. EXISTS runs once as an InitPlan, and LIMIT 1 makes 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 EXISTS or LIMIT 1. COUNT(*) > 0 counts 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) or EXISTS; PostgreSQL uses LIMIT 1 or EXISTS. PostgreSQL can take EXISTS out directly as a value, as in SELECT EXISTS (…).