Postgres error: null value in column "id" - during insert operation
Happened to me after reading a PostgreSQL10 dump into 9.6 database server. After that, the sequences that are to auto-create sequential IDs were lost.
This can be shown like this (in psql):
SELECT column_name
, column_default
FROM information_schema.columns
WHERE table_name = 'django_migrations'
ORDER BY
ordinal_position;
where django_migrations
is the table name. It should show something like this:
column_name | column_default
-------------+-----------------------------------------------
id | nextval('django_migrations_id_seq'::regclass)
[...]
If the value in 'column_default' is empty, then the sequence is lost.
The serial
keyword is expanded at parse time and cannot be seen afterward.
From the version Postgresql 10
there is the following alternative:
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
It is supposed to conform to the SQL standard and thus be compatible with Oracle.
See this blog for more details.
You aren't inserting a value for id
. Since you don't explicitly set it, it's implicitly given a null
value, which is, of course, not a valid value for a primary key column. You can avoid this entire situation by defining this column as serial
instead of a plain old integer
, and leave all the heavy lifting to the database.