PostgreSQL function for last inserted ID

后端 未结 11 1212

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:29

    For the ones who need to get the all data record, you can add

    returning *
    

    to the end of your query to get the all object including the id.

    0 讨论(0)
  • 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'));
    
    0 讨论(0)
  • 2020-11-22 14:31
    SELECT CURRVAL(pg_get_serial_sequence('my_tbl_name','id_col_name'))
    

    You need to supply the table name and column name of course.

    This will be for the current session / connection http://www.postgresql.org/docs/8.3/static/functions-sequence.html

    0 讨论(0)
  • 2020-11-22 14:34

    See the RETURNING clause of the INSERT statement. Basically, the INSERT doubles as a query and gives you back the value that was inserted.

    0 讨论(0)
  • 2020-11-22 14:34

    I had this issue with Java and Postgres. I fixed it by updating a new Connector-J version.

    postgresql-9.2-1002.jdbc4.jar

    https://jdbc.postgresql.org/download.html: Version 42.2.12

    https://jdbc.postgresql.org/download/postgresql-42.2.12.jar

    0 讨论(0)
提交回复
热议问题