Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update a boolean to its opposite in SQL without using a SELECT

Is it possible to upgrade a bool field by telling it to update the field to the opposite of what it is without having to select the value - check it then update accordingly which seems long winded...

A pseudo example of what i mean

UPDATE `table` SET `my_bool` = opposite_of(my_bool)

Currently i have to SELECT my_bool in one query then do a quick check on its value so i can update the table in a second query.

I was hopeing to cut that down to a single query if that is possible ?

like image 565
Sir Avatar asked Mar 03 '13 06:03

Sir


People also ask

How do you update a boolean field in SQL?

You can update boolean value using UPDATE command. If you use the BOOLEAN data type, MySQL internally convert it into tinyint(1). It can takes true or false literal in which true indicates 1 to tinyint(1) and false indicates 0 to tinyint(1).

How do I update conditionally in SQL?

To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.

Can we write update without WHERE clause?

The UPDATE statement in SQL is used to update records in the table. We can modify one or multiple records (rows) in a table using UPDATE statement. If you do not use WHERE clause in UPDATE statement, all the records in the table will be updated.

How do you set a boolean to a false SQL?

Use bit type 1 = true and 0 = false. You won't need to cast, but currently you'd be leaving "false results" as NULL .


1 Answers

use NOT

UPDATE `table` SET `my_bool` = NOT my_bool
like image 178
John Woo Avatar answered Sep 25 '22 07:09

John Woo