TransWikia.com

why does Postgres raise a not-null constraint error on a serial column?

Database Administrators Asked on December 17, 2021

something strange is happening to my database. my understanding is that the SERIAL datatype is the Postgres equivalent of MySQL’s auto-increment and that omitting it from an INSERT clause will automatically fill it with the next value. I have a simple table of the following structure:

CREATE TABLE data.categories
(
    "categoryId" serial NOT NULL,
    "categoryName" character varying(256) NOT NULL,
    PRIMARY KEY ("categoryId")
)

I’m expecting to be able to add a record without having to specify the id, like this:

INSERT INTO data.categories("categoryName") VALUES('Undefined');

yet, it throws the following error and I don’t understand why, it’s not meant to happen:

ERROR:  null value in column "categoryId" violates not-null constraint
DETAIL:  Failing row contains (1, Undefined, null).
SQL state: 23502

any thoughts on what I’m doing wrong and why this is happening? is this a bug? every answer on stackoverflow "confirms" that my thinking is right and that using serial as the data type should solve the problem of manually managing ids.

One Answer

thanks for all your help, it seems it was my mistake after all. there's another NOT NULL column in the table I'm trying to insert data into, obviously that won't work. having said that, I did changed serial to INT GENERATED ALWAYS AS IDENTITY.

Answered by Chris on December 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP