Introduction

This is a SQL Server puzzle or an interview question asked often. I want to dedicate this article to one of my leads, Saab. Whenever he did an interview he asked this question for sure shot.

Now the puzzle is you have a table with some records, 0 & 1. You need to replace column value 1 with 0 and 0 with 1 as in the following.



Now we have many ways to solve this.

Solution 1

Use CASE

UPDATE INDICATOR SET VALUE= CASE VALUE WHEN 1 THEN 0 WHEN 0 THEN 1 END



Solution 2

UPDATE INDICATOR SET VALUE= (VALUE -1) * -1



Solution 3
Use a Temp table as in the following:
  1. -- Original Record
  2. SELECT * FROM INDICATOR
  3. -- Update Command
  4. CREATE TABLE #TMPWith0
  5. (
  6. Value INT
  7. )
  8. CREATE TABLE #TMPWith1
  9. (
  10. Value INT
  11. )
  12. INSERT INTO #TMPWith0 SELECT * FROM Indicator WHERE Value=0
  13. INSERT INTO #TMPWith1 SELECT * FROM Indicator WHERE Value=1
  14. UPDATE #TMPWith0 SET Value=1
  15. UPDATE #TMPWith1 SET Value=0
  16. DELETE FROM Indicator
  17. INSERT INTO Indicator SELECT * FROM #TMPWith0
  18. INSERT INTO Indicator SELECT * FROM #TMPWith1
  19. DROP TABLE #TMPWith0
  20. DROP TABLE #TMPWith1
  21. --Record After Update
  22. SELECT * FROM INDICATOR