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...
- ColdFusion returning empty response with server-error: true
- Careful applying CF11u16, CF2016u8, CF2018u2
- Sessions don't work in Chrome but do in IE
- csrfVerifyToken does not invalidate the token
- The cf_sql_ is optional in cfqueryparam
- Cookie Expires / Max-Age 1969-12-31T23:59:59.000Z
- Burst Throttling on AWS API Gateway Explained
- How to Resolve Java HTTPS Exceptions