Video in progress

Why is sending 10,000 ids in a `WHERE id IN (...)` list a bad idea, and what do you do instead?

An IN list of a different length is a new SQL text every time: parsing and planning over and over, and the plan cache and pg_stat_statements fill up. In PostgreSQL a single array parameter, id = ANY(?), is much cleaner.

📖 Answer

Hibernate or hand-written code builds IN (?, ?, ?, ...) with 10,000 placeholders. The problems:

  • the JDBC protocol doesn't allow more than 32,767 parameters in one query, so past that the query doesn't go out at all;
  • a different count means a different SQL text, so the prepared statement isn't reused;
  • the query text is large and parsing takes a lot of time.

In PostgreSQL, with an array:

Long[] ids = idList.toArray(Long[]::new);
jdbcTemplate.query(
    "SELECT id, name FROM product WHERE id = ANY(?)",
    ps -> ps.setArray(1, ps.getConnection().createArrayOf("bigint", ids)),
    (rs, i) -> new ProductRow(rs.getLong(1), rs.getString(2)));

The SQL text is always the same and there is one parameter.

If the list is really huge (hundreds of thousands), I COPY it into a temporary table and JOIN. In Hibernate, hibernate.query.in_clause_parameter_padding=true also helps: it pads the list length up to a power of 2 and reduces the number of plans.