24

I'm trying to update a row in a postgres table. I want to toggle a boolean field.

Instead of first checking what the value is and updating the field with the opposite, I was wondering if there was a single query to update the field.

I found a solution for MySQL, but its not working for postgres:

 UPDATE table SET boolean_field = !boolean_field WHERE id = :id

 Error: Operator does not exist. ! boolean

Is there an similar syntax in postgres?

2 Answers 2

44

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 *;
Sign up to request clarification or add additional context in comments.

1 Comment

That's great if the boolean isn't nullable (and it shouldn't be), but what if it is, and we need to fill in those vals with false? Is this possible without casting?
6
UPDATE table_name 
  SET bool_col = NOT(COALESCE(bool_col, FALSE)) 
WHERE ...

Comments

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.