LenB
LenB

Reputation: 1172

NULL constraint violated in sql insert

I have a table (Location) shown below. When I try to insert items, I get this error:

ERROR:  null value in column "loc_id" violates not-null constraint
CONTEXT:  SQL statement "insert into Location VALUES ( lng , lat , alt ) RETURNING loc_id"

CREATE TABLE IF NOT EXISTS Location ( 
     longitude double precision check( longitude IS NULL OR -180.0 < longitude AND longitude <= 180.0 ),
     latitude double precision check( latitude IS NULL OR -90.0 <= latitude AND latitude <= 90.0 ),
     altitude double precision  default(0), 
     unique(longitude,latitude,altitude),
     loc_id integer  DEFAULT nextval('loc_seq') 
);

Upvotes: 0

Views: 913

Answers (1)

Simo Kivist&#246;
Simo Kivist&#246;

Reputation: 4473

Actually I couldn't reproduce the error, it worked in my environment (PostgreSQL 9.0). But if you come across this error, I would still recommend to try the following:

If you don't supply values to all the columns in the table define in the INSERT clause the columns you are inserting the values to:

insert into Location (longitude, latitude, altitude) VALUES ( lng , lat , alt ) RETURNING loc_id

Alternatively, you can explicitly add the next value in the sequence with nextval.

insert into Location VALUES ( lng , lat , alt, nextval('loc_seq')) RETURNING loc_id

Upvotes: 1

Related Questions