Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Update a field only if a condition is met

Tags:

sql

sql-server

I want to update a column only if a condition is met. So for the column "Type", I want to change its value to "MongoDB" only if its current value isn't "MongoDB" This is what I'm using:

UPDATE Report
    SET Type = 
    CASE
       WHEN Type <> 'MongoDB' THEN 'MongoDB'
       ELSE Type
    END
    WHERE Id = x

The problem is: Even when the Type is "MongoDB" I still see

(1 row(s) affected)

in my SQL result. The whole point of this exercise was to reduce db operations when no needed. Why is it still modifying the record when the condition is not met?

Thanks.

like image 767
90abyss Avatar asked Aug 02 '16 20:08

90abyss


People also ask

How do you UPDATE a column based on a condition?

To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.

How do you UPDATE a table based on condition in SQL?

UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID. we can use the following command to create a database called geeks.

Can I use from clause in UPDATE?

UPDATE statements with a FROM clause are often used to update information in a table based on a table-valued parameter (TVP), or to update columns in a table in an AFTER trigger. For the scenario of update based on a TVP, see Implementing MERGE Functionality in a Natively Compiled Stored Procedure.

Can we write UPDATE statement without WHERE condition?

We can modify one or multiple records (rows) in a table using UPDATE statement. If you do not use WHERE clause in UPDATE statement, all the records in the table will be updated.


1 Answers

Why not simplify it like this?

UPDATE Report
SET Type = 'MongoDB'
WHERE Id = x AND Type <> 'MongoDB'

But to answer your question you are still setting a records value even though its to the existing value. The record also comes back in the where clause so you will always have 1 row affected regardless of your CASE statement.

like image 153
Igor Avatar answered Oct 03 '22 21:10

Igor