Toggle a Bit with SQL
I am working on a management dashboard for a client, which uses some AJAX here and there. One simple but really nice feature is that you can enabled or disable things just by clicking on an icon, the state is updated in the background using AJAX (I also add some animation to let the user know that it has been updated).
I wanted to be able to toggle the state of the
bit field without a care of the current state. Here's how you can do that in SQL:
UPDATE companies SET active_ind = active_ind ^ 1 WHERE id = ?
I'm using a
^ Bitwise (Exclusive OR or XOR) operator here to do this. To understand what's going on here let's look at a truth table for XOR:
|p||q||p ^ q|
- Dan Dan
DECLARE @Trend AS BIT
SET @Trend = 0
SELECT @Trend, ABS(@Trend-1)
since when it turned into 0-1
UPDATE user SET vis=IF(vis&4,vis&~4,vis|4) WHERE id=$authuserid LIMIT 1
The value "4" can be replaced with 2^bitposition, ie. 1,2,4,8,16,32,64...
- Burst Throttling on AWS API Gateway Explained
- How to Resolve Java HTTPS Exceptions
- Tomcat Java 10 on Windows CreateJavaVM Failed
- SameSite Cookies with IIS
- Facebook API Now Requires Review for user_friends Permission
- Docker Container exited with code 137
- Why is my cron.daily script not running?
- Announcing FuseGuard Version 3