Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Bug -> Postgress lastInsertId always returns false

Hi evryone,

I changed my PDO adapter from Mysql to Postgresql and I have problem with method lastInsertId (). In Postgresql adapter this method always returns false value. When I put seqence name like argument of this function I have correct result but it's not frendly for programmer. Is it another option to get lastInsertId?

var_dump($db->lastInsertId('translations_id_seq'));
var_dump($db->getInternalHandler()->lastInsertId('translations_id_seq'));

return correct value

var_dump($db->lastInsertId();
var_dump($db->getInternalHandler()->lastInsertId());

return false



34.0k
Accepted
answer

PostgreSQL does not have the concept of auto_increment columns like MySQL, it requires serial columns that have sequences associated, so to know the current value of the sequence you need to pass the name of sequence.

Create a table like:

CREATE TABLE tablename (
    colname SERIAL
);

It's equivalent to:

CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
    colname integer NOT NULL DEFAULT nextval('tablename_colname_seq')
);
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

So, PDO wouldn't know which sequence you need to obtain the current value if you don't pass the name of the sequence.