Existence check: COUNT(*) → stop at the first row
Only whether an order exists matters, yet COUNT(*) counts all of them. With LIMIT 1, the index finds the first row and stops.
SQL
Situation
The customer screen shows a "Has orders" badge. The query counts rows and the app checks only whether the count is greater than 0.
Tables
| Table | Column | Type | Description |
|---|---|---|---|
orders | cust_id | int64 | Customer 5 is a heavy customer with 2,018 orders |
| Index | Columns |
|---|---|
orders_x1 | cust_id, ord_dt |
Are there any orders
BEFORE · COUNT(*)
SELECT COUNT(*)
FROM orders
WHERE cust_id = 5
Approach
1. See what answer is needed
"Yes/no" is decided the moment the first row is found. The count is not needed.
2. Write it in a shape that can stop at the first row
LIMIT 1 stops the step chain once it receives one result row. There is no sort, so it ends at the first row found in the index.
Explanation
COUNT(*) → LIMIT 1
AFTER · LIMIT 1
SELECT ord_id
FROM orders
WHERE cust_id = 5
LIMIT 1
Why it got faster
- In Before,
IndexProbe ordersfinds all 2,018 orders of customer 5 (a table page per row) andAGGREGATEcounts them. Buffers 2,019. - After reads the first row under
QUOTA limit=1and stops. Buffers 2. - A 0-row result means there are no orders. The app checks only whether a row exists.
Variation
TRY · Regular customer
SELECT COUNT(*)
FROM orders
WHERE cust_id = 5001
- For a customer with about 18 orders,
COUNT(*)also stays under 20 pages. The gap grows with heavy customers. Even if only 1% of all customers are like this, their screens get slow.
Key points
- Write existence checks with
LIMIT 1(orEXISTSin condition position).COUNT(*)reads every row. - In KDBS,
LIMITalso reduces the amount read when there is no sort, or when index or tuple key order replaces the sort.