PostgreSQL function for last inserted ID

后端 未结 11 1352

In PostgreSQL, how do I get the last id inserted into a table?

In MS SQL there is SCOPE_IDENTITY().

Please do not advise me to use something like this:

11条回答
  •  一生所求
    2020-11-22 14:30

    See the below example

    CREATE TABLE users (
        -- make the "id" column a primary key; this also creates
        -- a UNIQUE constraint and a b+-tree index on the column
        id    SERIAL PRIMARY KEY,
        name  TEXT,
        age   INT4
    );
    
    INSERT INTO users (name, age) VALUES ('Mozart', 20);
    

    Then for getting last inserted id use this for table "user" seq column name "id"

    SELECT currval(pg_get_serial_sequence('users', 'id'));
    

提交回复
热议问题