← Back to PostgreSQL, page 4

postgresql-0079 · Hard senior

Pass a list of ids as one array parameter with = ANY($1) instead of building a long IN list.

WHERE id = ANY($1) with an array parameter keeps one statement text for any list length, so pg_stat_statements groups it as one query and prepared plans can be reused. A generated IN (...) list with many placeholders produces a different statement per length and can hit driver limits on parameter counts. Both use the index the same way.

Full answer

Schema and sample rows:

sql
CREATE TABLE users (id int PRIMARY KEY, name text);
INSERT INTO users SELECT g, 'user' || g FROM generate_series(1, 10000) g;
ANALYZE users;
sql
PREPARE by_ids(int[]) AS SELECT id, name FROM users WHERE id = ANY($1) ORDER BY id; EXECUTE by_ids(ARRAY[5, 42, 9999]);

Result on PostgreSQL 17:

text
  id  |   name
------+----------
 5    | user5
 42   | user42
 9999 | user9999
(3 rows)
sql
EXECUTE by_ids('{}');

Result:

text
 id | name
----+------
(0 rows)
sql
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id = ANY('{5,42,9999}'::int[]);

Output:

text
Index Only Scan using users_pkey on users
  Index Cond: (id = ANY ('{5,42,9999}'::integer[]))
sql
EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id IN (5, 42, 9999);

PostgreSQL returns:

text
Index Only Scan using users_pkey on users
  Index Cond: (id = ANY ('{5,42,9999}'::integer[]))

The same prepared statement serves three ids and an empty list, which returns no rows instead of failing as an empty IN () would. The two plans are identical: PostgreSQL rewrites IN with a list of constants into = ANY of an array, and both use the primary key index. In application code, pass a native array, for example a Python list with psycopg, which adapts it to an int[] parameter. For very large lists, tens of thousands of ids, joining against unnest($1) or a temporary table can plan better than a giant array.

sql
CREATE TABLE users (id int PRIMARY KEY, name text);
INSERT INTO users SELECT g, 'user' || g FROM generate_series(1, 10000) g;
ANALYZE users;

PREPARE by_ids(int[]) AS SELECT id, name FROM users WHERE id = ANY($1) ORDER BY id; EXECUTE by_ids(ARRAY[5, 42, 9999]);

EXECUTE by_ids('{}');

EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id = ANY('{5,42,9999}'::int[]);

EXPLAIN (COSTS OFF) SELECT id FROM users WHERE id IN (5, 42, 9999);

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • = ANY($1) takes an array parameter
  • One statement text for any list length
  • Empty arrays are valid
  • IN lists become = ANY internally
  • Use unnest or temp tables for huge lists

Common mistakes

  • Building IN lists by string concatenation
  • Generating one statement per list length

Follow-ups

  • How does pg_stat_statements normalise IN lists?
  • When would you use a VALUES join instead?

Tips

  • Show the empty-array case