PostgreSQL function for last inserted ID

后端 未结 11 1342

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

    Leonbloy's answer is quite complete. I would only add the special case in which one needs to get the last inserted value from within a PL/pgSQL function where OPTION 3 doesn't fit exactly.

    For example, if we have the following tables:

    CREATE TABLE person(
       id serial,
       lastname character varying (50),
       firstname character varying (50),
       CONSTRAINT person_pk PRIMARY KEY (id)
    );
    
    CREATE TABLE client (
        id integer,
       CONSTRAINT client_pk PRIMARY KEY (id),
       CONSTRAINT fk_client_person FOREIGN KEY (id)
           REFERENCES person (id) MATCH SIMPLE
    );
    

    If we need to insert a client record we must refer to a person record. But let's say we want to devise a PL/pgSQL function that inserts a new record into client but also takes care of inserting the new person record. For that, we must use a slight variation of leonbloy's OPTION 3:

    INSERT INTO person(lastname, firstname) 
    VALUES (lastn, firstn) 
    RETURNING id INTO [new_variable];
    

    Note that there are two INTO clauses. Therefore, the PL/pgSQL function would be defined like:

    CREATE OR REPLACE FUNCTION new_client(lastn character varying, firstn character varying)
      RETURNS integer AS
    $BODY$
    DECLARE
       v_id integer;
    BEGIN
       -- Inserts the new person record and retrieves the last inserted id
       INSERT INTO person(lastname, firstname)
       VALUES (lastn, firstn)
       RETURNING id INTO v_id;
    
       -- Inserts the new client and references the inserted person
       INSERT INTO client(id) VALUES (v_id);
    
       -- Return the new id so we can use it in a select clause or return the new id into the user application
        RETURN v_id;
    END;
    $BODY$
      LANGUAGE plpgsql VOLATILE;
    

    Now we can insert the new data using:

    SELECT new_client('Smith', 'John');
    

    or

    SELECT * FROM new_client('Smith', 'John');
    

    And we get the newly created id.

    new_client
    integer
    ----------
             1
    

提交回复
热议问题