An interesting error that may happen in PostgreSQL when using prepared statements is:

ERROR: cached plan must not change result type

This may happen when:

  1. A prepared statement is prepared on the server
  2. The tables structure is changed in a way that the result of the prepared statement will change
  3. Prepared statement is executed

Let’s try to reproduce it:

CREATE TABLE phonebook(phone INT);
PREPARE prepsel (INT) AS SELECT * FROM phonebook WHERE phone = $1;
EXECUTE prepsel(1); --all OK here
ALTER TABLE phonebook ADD COLUMN a INT;
EXECUTE prepsel(1);
ERROR:  cached plan must NOT CHANGE RESULT TYPE

The possible solution are:

  1. Re-create the statement, so it will use up-to-date table definition
  2. Stop your application or cause it to drop the database connection otherwise. Prepared statements are allocated per-session.
  3. Change the prepared statement to use minimum columns used, e.g. change SELECT * to SELECT id. This way, only if “id” column changes your statement will become invalid.