1

i'm having a sql table consisting of three columns ID,KEY and VALUE now i want to update this table's specific rows based the KEY column associated with that row.

i tried following UPDATE query to update multiple rows in a single update query.

UPDATE TABLE_NAME
SET VALUE=(CASE WHEN [KEY]='KEY1' THEN 'VALUE 1 MODIFIED'
                WHEN [KEY]='KEY3' THEN 'VALUE 3 MODIFIED'
          END)

but this query updated the unmatched rows with NULL value as shown in below fig.

enter image description here

is their any other way to write single UPDATE query to modify different columns based on different conditions?

1
  • 1
    You need to include an ELSE VALUE END in the CASE statement. If no when matches, the CASE returns null. Commented Nov 2, 2013 at 7:53

1 Answer 1

3
UPDATE TABLE_NAME
SET VALUE=(CASE WHEN [KEY]='KEY1' THEN 'VALUE 1 MODIFIED'
                WHEN [KEY]='KEY3' THEN 'VALUE 3 MODIFIED'
            ELSE ''
          END)

This will set the unmatched rows to an empty string '' but you can set a default value if you want. But if you want that column to retain its value then you could so something like this.

UPDATE TABLE_NAME
SET VALUE=(CASE WHEN [KEY]='KEY1' THEN 'VALUE 1 MODIFIED'
                WHEN [KEY]='KEY3' THEN 'VALUE 3 MODIFIED'
            ELSE VALUE
          END)
Sign up to request clarification or add additional context in comments.

1 Comment

I'll prefer this: UPDATE TABLE_NAME SET VALUE=(CASE WHEN [KEY]='KEY1' THEN 'VALUE 1 MODIFIED' WHEN [KEY]='KEY3' THEN 'VALUE 3 MODIFIED' END) where KEY in ('KEY1','KEY2') as this query will only update required two records. So, if the KEY column is indexed, it will be faster. Retaining old value in Else part is avoided, causing better performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.