How to negate a bit column value in SQL
11,483
Solution 1
You can use bitwise NOT operator:
update mytable set IsEditable = ~IsEditable
Solution 2
Just use this:
UPDATE mytable SET IsEditable=IsEditable^1
If you want to test it:
SELECT CONVERT(bit,0)^1, CONVERT(bit,1)^1
Solution 3
As a math solution, you can use this
update mytable set IsEditable = 1 - IsEditable;
-
IsEditable = 0
=>1 - IsEditable = 1
-
IsEditable = 1
=>1 - IsEditable = 0
-
IsEditable = Null
=>1 - IsEditable = Null
![Bellash](https://i.stack.imgur.com/Qn4KM.jpg?s=256&g=1)
Author by
Bellash
(Web) developer, in love with .net C#, JavaScript, TypeScript, jQuery PHP, HTML5, CSS, Java, Pascal and Python .net Core, ASP.NET, Angular 12, angularJS, Symfony, Zend Framework, JSP, Java Android, Java EE SQL Server, MySQL, PowerBI, Wordpress SAP Business One, Prestashop, NopCommerce.
Updated on June 20, 2022Comments
-
Bellash about 2 years
How do I update a table column in order to revert its value(set true if value is false and false for true! null remains null).
Please exclude solutions where one uses
case when
orIIF()
I want something like followingUPDATE mytable SET IsEditable = !IsEditable
-
Bellash about 9 yearsThis is good but I thing is slower since it is using bitwise
xor
! anyway, voted up -
Ionic about 9 yearsWell I've tested it with 1.000.000.000 rows in a fast test. Both produce the same time and consumes the same cpu (
STATISTICS TIME ON
). Well don't think that there is a real difference. :-) -
Ionic about 9 yearsWell as fast as the bitwise or. :-D
-
Bellash about 9 yearssorry ! didn't test but as per definition
C=A^B=(A&(~B))|(B&(~A))
which seems slower thanC=~C
but I think byxor
ing toB
andB
being equals to1
there're no speed issue. Thank you @Ionic -
Ionic about 9 yearsWell no problem. :-) Nice that it helped.
-
Bellash about 9 yearsCould not upvote twice this! But it works perfectly thank you @shA.t
-
potashin about 9 yearsDidn't mean to impose any style, I was just trying to reduce them to the one.
-
Ionic about 9 yearsI know. I just edited it to match it. :-) I normally prefer upper cased functions, for a faster/better reading. I know that you just wanted to match them. :-)
-
Yair Maron about 2 yearsSo simple and nice! This should be the accepted answer