Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in MySQL to reverse a boolean field with one query?

Tags:

php

mysql

I have a column in my table titled 'authorised'. Its default is 0. It needs to be changed to 1 when the user is authorised, but it must be able to be reset to 0. I know I could do this easily with 2 queries like so:

$authorised = Db::query('SELECT authorised FROM users WHERE id=2');  $newAuthValue = ($authorised['authorised']) ? 0 : 1;  Db::query('UPDATE users SET authorised=' . $newAuthValue . ' WHERE id=2'); 

What I wanted to know, is there a way to do this with one query? To reverse a boolean value?

like image 978
alex Avatar asked Mar 20 '09 04:03

alex


People also ask

How do you toggle boolean value in SQL?

You can use Boolean Operator for this Here delete is your boolean field. This solution also works for none boolean fields such as int and tinyint where values are set to 0 or 1.

Can MySQL return boolean?

MySQL doesn't really have booleans. TRUE and FALSE are aliases to 1 and 0, and the BOOL column type is just an alias for TINYINT(1) . All expressions that appear to give boolean results actually return 0 or 1.

How does MySQL store boolean?

MySQL does not have a boolean (or bool) data type. Instead, it converts boolean values into integer data types (TINYINT). When you create a table with a boolean data type, MySQL outputs data as 0, if false, and 1, if true.


2 Answers

UPDATE users SET `authorised` = IF (`authorised`, 0, 1) 
like image 60
nickf Avatar answered Sep 19 '22 02:09

nickf


UPDATE `users` SET `authorised` = NOT `authorised` WHERE id = 2 

This query will also work to negate the field, and is more inline with boolean syntax.

like image 25
Alex Marshall Avatar answered Sep 17 '22 02:09

Alex Marshall