80

I would like to have an UPDATE statement like this:

 SELECT *
 FROM Employee
 WHERE age = CASE 
 WHEN (age < 20) THEN age=15
 WHEN (age > 20) THEN age= 20

Is this not possible in SQL Server / MySQL? I do not want to use the stored procedures or other things.

Suggest me a suitable way around this problem.

0

3 Answers 3

153

I think what you want is:

UPDATE EMPLOYEE
SET age =
CASE WHEN AGE < 20 THEN 15
ELSE 20 END
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.. It works good. I am working with it on MS SQL Server and MySQL Server too. UPDATE testingtable SET dob = CASE WHEN DATEDIFF(CURRENT_TIMESTAMP,ADDDATE(dob, INTERVAL -2 day)) > 1 THEN ADDDATE(dob,INTERVAL -2 DAY) ELSE CURRENT_TIMESTAMP END WHERE username='bob';. Thanks for your reply.
If looking to leave value if does not meet condition then set the value to the fieldname. For example above the ELSE 20 END would be ELSE age END
37

You can use a case statement in an update as follows...

UPDATE Employee 
SET Age = CASE WHEN (age < 20) THEN 15
              ELSE 20 END

4 Comments

ha, we must have just crossed paths typing out answers -- i didn't see any others when i submit:-D
i like how the only different from op's code and yours is the update instead of select and you added an else clause
and made the assignment a CASE instead having it in the where!
@EBarr - the reason you didn't see any other answers when you submitted is because you were first...
1

In SQL Server and MySQL, you can use an UPDATE statement with a CASE expression directly in the SET clause to conditionally update values based on certain conditions. Here’s how you can structure the query:

UPDATE Employee SET age = CASE 
         WHEN age < 20 THEN 15
         WHEN age > 20 THEN 20
         ELSE age  -- Keep the current age if it's exactly 20
      END WHERE age <> 20;  --Optional: Only update rows where age is not already 20

Explanation:

  1. CASE expression in SET: The CASE checks each row's age and applies the appropriate value.
  2. WHERE clause: Using WHERE age <> 20 (optional) prevents unnecessary updates for rows where age is already 20.

This query will update age to 15 if it’s less than 20, to 20 if it’s greater than 20, and leave age unchanged if it’s exactly 20.

This method avoids the need for stored procedures and is compatible with both SQL Server and MySQL.

Comments

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.