Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql INSERT is asking for primary key value?

Running Postgres 9.6.6. I created a table as follows:

create table person (
id serial primary key,
name text,
role integer references role (id),
phonenumber text);

When I try to insert data as follows:

insert into person values ('This Person',2,'+15105551111');

I get this message:

ERROR: invalid input syntax for integer: 'This Person'

which suggests that Postgres is expecting a value for id. But if id is a serial primary key, shouldn't it be autopopulating and autoincrementing?

like image 920
sigil Avatar asked Mar 24 '18 19:03

sigil


People also ask

Do we need to insert primary key?

If you attempt to insert a row with the same primary key as a previous row, you will get a SQL error (try it in the commented out code below). If you insert a row without specifying the primary key, then SQL will automatically pick one for you that's different from other values.

Is primary key mandatory in Postgres?

A table with no primary key will only send out INSERTs on the logical decoding stream; UPDATEs and DELETEs are lost. Reading the postgres docs at postgresql.org/docs/10/static/…

Can we insert value in primary key column?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values.


1 Answers

If you do not specify the column names, the values will be applied to the first n columns in the table. Thus 'This Person' will be applied to id, and thus the error you're getting. You can (should) specify the columns names in order to avoid this problem:

INSERT INTO person
(name, role, phonenumber) -- Here
VALUES ('This Person', 2, '+15105551111');
like image 102
Mureinik Avatar answered Sep 28 '22 18:09

Mureinik