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

[SQL Fiddle Demo]

Share:
11,483
Bellash
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, 2022

Comments

  • Bellash
    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 or IIF() I want something like following

    UPDATE mytable SET IsEditable = !IsEditable
    
  • Bellash
    Bellash about 9 years
    This is good but I thing is slower since it is using bitwise xor! anyway, voted up
  • Ionic
    Ionic about 9 years
    Well 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
    Ionic about 9 years
    Well as fast as the bitwise or. :-D
  • Bellash
    Bellash about 9 years
    sorry ! didn't test but as per definition C=A^B=(A&(~B))|(B&(~A)) which seems slower than C=~C but I think by xoring to B and B being equals to 1 there're no speed issue. Thank you @Ionic
  • Ionic
    Ionic about 9 years
    Well no problem. :-) Nice that it helped.
  • Bellash
    Bellash about 9 years
    Could not upvote twice this! But it works perfectly thank you @shA.t
  • potashin
    potashin about 9 years
    Didn't mean to impose any style, I was just trying to reduce them to the one.
  • Ionic
    Ionic about 9 years
    I 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
    Yair Maron about 2 years
    So simple and nice! This should be the accepted answer