Search code examples
arrayspostgresqlmany-to-manysql-insert

PostgreSQL insert array many-to-many relationship


Let many users belong to many groups.

Write a function that creates a group with a name and a list of users.


Solution

  • CREATE FUNCTION groups_create(varchar(50), bigint[]) RETURNS SETOF bigint AS
    $$
        WITH g AS (
            INSERT INTO groups (name)
            VALUES ($1)
            RETURNING id
        ), gm AS (
            INSERT INTO group_members
            SELECT id, unnest($2) FROM g
        )
        SELECT id FROM g
    $$
    LANGUAGE SQL;
    

    http://sqlfiddle.com/#!15/9e408/9