Video in progress
In psql the query takes 2 ms, but from the application the same query takes 3 seconds. Where do you start looking?
The most common causes: the application sends the parameter with a different type and the index isn't used, the prepared statement's generic plan is different, or the application session's settings differ. I take the exact query and parameters the application sent and run EXPLAIN under the same conditions.
📖 Answer
In psql you test with a literal value, while the application uses a parameter. Those are two different queries.
1. Type mismatch. The column is varchar but Java bound the parameter as a different type, or the column is bigint and the parameter is numeric. The planner converts the column and the index isn't used. In the auto_explain log or in pg_stat_statements you'll see a cast like $1::numeric.
2. A generic plan. A prepared statement gets a custom plan for each value for the first 5 runs, then switches to a generic plan if it looks cheaper. A generic plan doesn't know the value. With a skewed distribution (status = 'PENDING' is 0.01%, 'DONE' is 99%), it adapts to the average case and picks a Seq Scan.
Reproducing it:
PREPARE q(text) AS SELECT * FROM task WHERE status = $1 ORDER BY id LIMIT 50;
EXECUTE q('PENDING'); -- run it 6 times
EXPLAIN EXECUTE q('PENDING'); -- now it's the generic plan
As a fix, you can set plan_cache_mode = force_custom_plan for just that session or role.
3. Other differences. search_path, work_mem or statement_timeout may be different in the application's session. Or the application sends the same query through the ORM with a different ORDER BY or an extra JOIN: turn on Hibernate's SQL log and get the exact text.
4. The time isn't in the database. The 3 seconds may have gone to the network, reading a big result, creating entities, or waiting for a connection from the pool. If mean_exec_time in pg_stat_statements says 2 ms, the problem is on the application side.
Sign up to mark studied questions and save your progress.