4

I have a Boolean type field in my table (PostgreSQL 9.0)

Is there a way to write a query that update this field to the opposite value without knowing what is currently there?

if it's True then it will be updated to False.

if it's False then it will be updated to True.

Basically I'm asking if there is a mechanism that allows treating Boolean type same as 1 bit. For example in C if x can be {1,0} you can simply write x=!x and if it was 0 it will be 1, if it was 1 it will be 0. No need for IF statment etc...

1 Answer 1

8

Why not to use operator NOT?

Update tableName
set c = NOT c 
where ...

http://www.postgresql.org/docs/current/static/functions-logical.html

Example in SqlFiddle

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

2 Comments

It's a syntax error to table-qualify target columns in the SET clause. Must be: SET c = NOT tablename.c
@John, yes there was a syntax error in initial version of my answer, which was pointed out in comments. set tableName.c = is not legal way. Even when from clause is present it is only possible to reference fields of table declared in update clause for changing values. So both works set c = not tableName.c and set c = not c. You can see sqlfiddle for a working solution and play with it to see options

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.