Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update multiple columns having the same value or different values in SQL?

I want to update multiple columns in a table having the same value. For example if we consider this table.

col1     col2
--------------
2        -99
-99        5
3          6
4        -99

I want to update -99 values in the table to NULL and the expected result looks like this.

col1     col2
--------------
2        NULL
NULL        5
3           6
4        NULL

I am using this way.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

update table_name set col1 = null where col1 = -99;
update table_name set col2 = null where col2 = -99;

Or what if I want to update columns on unique conditions.
For example -99 with null in column1 and 5 with null in column2.

Is there a way to achieve this in a single statement ? Thanks in advance.

>Solution :

You can, by using a case expression, but whats the advantage?

update table_name set
  col1 = case when col1 = -99 then null /* or any new value for col1 */ else col1 end
  , col2 = case when col2 = -99 then null /* or any new value for col2 */ else col2 end
where col1 = -99 or col2 = -99;

Note, as pointed out by Larnu, when you are setting the column to null you can simplify the update to:

update table_name set
  col1 = nullif(col1,-99)
  , col2 = nullif(col2,-99)
where col1 = -99 or col2 = -99;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading