1

What I have:

CREATE TYPE Item AS (
    a bigint,
    b bigint
);

CREATE TABLE items (
    id bigint NOT NULL,
    a bigint NOT NULL,
    b bigint NOT NULL
);

CREATE OR REPLACE FUNCTION items_insert(
        _id bigint,
        _items Item[]
) RETURNS void AS
...

How can I insert multi columns rows to table items with same _id from _items by ONE multi insert query?

I am using Postgresql-9.2

1
  • Unrelated to your problem, but: Postgres 9.2 is no longer supported you should plan an upgrade as soon as possible. Commented Mar 22, 2021 at 16:12

1 Answer 1

3

I think you mean "insert multiple rows" rather than columns.

Assuming that is correct, I think you are looking for a function like this:

create or replace function items_insert(_id bigint, _items item[]) 
  returns void 
as
$$
  insert into items (id, a, b)
  select _id, it.*
  from unnest(_items) as it(a,b);
$$
language sql;

Online example

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for advance. I found shorter way: INSERT INTO items(id, a, b) SELECT _id, (unnest(_items)).*;
@КонстантинПрименко: using unnest() in the SELECT list is not recommended. It's better to use it in the FROM clause
Why using unnest() in the SELECT list is not recommended?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.