1820 shaares
TL;DR
Standard IN Clause
A standard IN clause with 5,000 IDs forces the database to tokenize each element individually, resulting in high Planning Time. The problem is that the parser needs to parse each constant and build a massive expression tree before execution starts.
EXPLAIN (ANALYZE, BUFFERS)
SELECT reading_value
FROM device_metrics
WHERE device_id IN (101, 102, 103, ... 5000);
ANY(ARRAY[])
When you use ANY(ARRAY[]) syntax, you tell PostgreSQL to treat the thousands of IDs as a single object rather than thousands of individual constants. This drastically reduces the query's structural complexity.
EXPLAIN (ANALYZE, BUFFERS)
SELECT reading_value
FROM device_metrics
WHERE device_id = ANY(ARRAY[101, 102, 103, ... 5000]::int[]);Calculation Method:
(
(
(hashint4extended(id, 8816678312871386365)::numeric + 5305509591434766563
) % 256
)::int + 256
) % 256
Or
(case
when
(hashint4extended(id, 8816678312871386365)::numeric + 5305509591434766563) % 256 < 0
then
256 + (hashint4extended(id, 8816678312871386365)::numeric + 5305509591434766563) % 256
else
(hashint4extended(id, 8816678312871386365)::numeric + 5305509591434766563) % 256
end)::int