"how to toggle a boolean in postgres in one query" Code Answer

4

use not:

update table set boolean_field = not boolean_field where id = :id

when the old value equals false then it turns into true and visa versa. a null field won't flip, there is nothing to flip to.

complete example:

create table test(id serial, boolean_field boolean);

insert into test(boolean_field) 
values(null),(false), (true) 
returning *;

and run the test:

update test
set boolean_field = not boolean_field 
returning *;
By Orion Adrian on August 1 2022

Answers related to “how to toggle a boolean in postgres in one query”

Only authorized users can answer the Search term. Please sign in first, or register a free account.