Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL boolean - flipping the value?

Tags:

mysql

boolean

MySQL uses TinyINT to serve as a boolean field. Given the possible options of 0 and 1, I decided that I'd flip values like this:

UPDATE table
SET boolean_field = ABS(boolean_field - 1)
WHERE Circle-K = 'Strange things are afoot'

So you either go 1 -> 0 -> ABS(0) = 0

or 0 -> -1 -> ABS(-1) = 1

now I'm curious if this is acceptable or horrifying to the real programmers?

/me is a beginner

like image 954
Drew Avatar asked Aug 16 '10 05:08

Drew


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.

Why is boolean changed to Tinyint?

Yes, MySQL internally convert bool to tinyint(1) because tinyint is the smallest integer data type.

How do you set a boolean to true in MySQL?

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).

Why MySQL boolean is Tinyint?

In MySQL, TINYINT(1) and boolean are synonymous. Because of this, the MySQL driver implicitly converts the TINYINT(1) fields to boolean if the the Java tinyInt1isBit configuration property is set to true (which is the default) and the storage size is 1. Stitch then interprets these columns as BIT(1)/boolean .


2 Answers

Why not simply use:

UPDATE the_table
   SET boolean_field = NOT boolean_field
WHERE ...

Makes your intention a lot easier to read

like image 159
a_horse_with_no_name Avatar answered Oct 02 '22 12:10

a_horse_with_no_name


You can also use field = 1 - field or field = ! field

like image 43
zerkms Avatar answered Oct 02 '22 12:10

zerkms