1

In PostgreSQL database I have table called services which has 4 columns. Is it possible to make a mass update via arrays? I tried such code but it raise error:

SQL Error [0A000]: ERROR: set-returning functions are not allowed in WHERE

SQL:

UPDATE SERVICES
SET
    NAME = UNNEST(ARRAY['NAME OF THE FIRST SERVICE', 'NAME OF THE SECOND SERVICE']),
    ACTIVE = UNNEST(ARRAY[FALSE, TRUE]),
    DESCRIPTION = UNNEST(ARRAY['DESCRIPTION OF THE FIRST SERVICE', 'DESCRIPTION OF THE SECOND SERVICE'])
WHERE
    ID = UNNEST(ARRAY['e1433cd2-7591-4a74-b910-33ea89d87ecd', '6c27c413-4be2-4a89-bea0-e713445ebfe1']);

1 Answer 1

3

You can unnest them in a subquery:

UPDATE services s
    SET name = x.name,
        active = x.active,
        description = x.description
FROM (SELECT UNNEST(ARRAY['NAME OF THE FIRST SERVICE', 'NAME OF THE SECOND SERVICE']) as name,
             UNNEST(ARRAY[FALSE, TRUE]) as active,
             UNNEST(ARRAY['DESCRIPTION OF THE FIRST SERVICE', 'DESCRIPTION OF THE SECOND SERVICE']) as description
             UNNEST(ARRAY['e1433cd2-7591-4a74-b910-33ea89d87ecd', '6c27c413-4be2-4a89-bea0-e713445ebfe1']) as id
     ) x
WHERE s.id = x.id;

When there are multiple unnest()s in a single select, Postgres unnests them in parallel (rather than generating a Cartesian product). The number of rows is the number of rows of the biggest array, with shorter arrays being padded with nulls.

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

3 Comments

I think you miss SET keyword in your SQL statement. In my case type of ID column is uuid. When I try to test your code it raise error: ERROR: operator does not exist: uuid = text. Do you have any ideas about it?
As I understand array of ids must be like this: UNNEST(ARRAY[uuid('e1433cd2-7591-4a74-b910-33ea89d87ecd'), uuid('6c27c413-4be2-4a89-bea0-e713445ebfe1')]).
Also other way is UNNEST(ARRAY['e1433cd2-7591-4a74-b910-33ea89d87ecd', '6c27c413-4be2-4a89-bea0-e713445ebfe1']::uuid[])

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.