Coding⏱️ 3 min read📅 2026-06-03

How to Fix: Use CASE expression to update some records

Update records in a database table using CASE expression to avoid scanning all records.

Quick Answer: Use the ELSE NULL clause to update only the specified records and leave unaffected rows unchanged.

The provided SQL statement uses a CASE expression to update specific records in the dbo.TestStudents table. However, the ELSE condition is causing an issue where it scans through every record in the table, resulting in unnecessary updates.

This problem affects all users who rely on the current data in the dbo.TestStudents table. The frustration comes from having to re-run the query or update the entire table unnecessarily.

🔍 Why This Happens

  • The primary reason for this issue is that the ELSE condition in the CASE expression does not have a specified value, causing it to default to the original value of LASTNAME.
  • Another possible cause could be the fact that the CASE expression is not properly indexed, leading to slower query performance.

🚀 How to Resolve This Issue

Using the IIF function

  1. Step 1: Replace the ELSE condition with the IIF function, which allows for a more specific and efficient way of handling the default case.
  2. Step 2: Update the SQL statement as follows: UPDATE dbo.TestStudents SET LASTNAME = IIF(LASTNAME = 'AAA', 'BBB', IIF(LASTNAME = 'CCC', 'DDD', IIF(LASTNAME = 'EEE', 'FFF', LASTNAME)))
  3. Step 3: This change will ensure that only the specified records are updated, while leaving the unaffected rows unchanged.

Using a WHERE clause with NOT IN

  1. Step 1: Alternatively, you can use a WHERE clause with the NOT IN operator to exclude the specified records from the update.
  2. Step 2: Update the SQL statement as follows: UPDATE dbo.TestStudents SET LASTNAME = CASE WHEN LASTNAME NOT IN ('AAA', 'CCC', 'EEE') THEN LASTNAME ELSE IIF(LASTNAME = 'AAA', 'BBB', IIF(LASTNAME = 'CCC', 'DDD', IIF(LASTNAME = 'EEE', 'FFF', LASTNAME))) END
  3. Step 3: This approach will also ensure that only the specified records are updated, while leaving the unaffected rows unchanged.

🎯 Final Words

By using either of these two methods, you can efficiently update specific records in the dbo.TestStudents table without scanning through every record unnecessarily. This solution should improve query performance and reduce frustration for users relying on the current data.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions