Question

Given this table:

CREATE TABLE rollouts
(
    id           UUID        PRIMARY KEY DEFAULT gen_random_uuid(),
    device_id    TEXT        NOT NULL,
    is_active    BOOLEAN     NOT NULL DEFAULT FALSE
);

How can I flip the is_active flag from one row to another for a given device_id and id?

Eg, go from

ID    DEVICE    IS_ACTIVE
1     D1        TRUE
2     D1        FALSE

to

ID    DEVICE    IS_ACTIVE
1     D1        FALSE
2     D1        TRUE

in single query?

Because this won't clear the flag for ID=1:

UPDATE table SET is_active = true WHERE device=d1 AND ID=2
Was it helpful?

Solution

Just flip it for both:

update the_table
   set is_active = not is_active
where device = 'd1'
  and id in (1,2);

For a more general approach see:
How can I swap two values from particular column in a table in Postgres?

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top