1

I would like to update multiple rows in one single query by using UPDATE CASE scenario in mySQL. I am building my web app using python and Django. Here is my code:

UPDATE order
SET priority_number =
    CASE priority_number
    WHEN 2 THEN 3  
    WHEN 3 THEN 4
    WHEN 1 THEN 5
    WHEN 4 THEN 2
    WHEN 5 THEN 1
END

So this single query will update all field as I desire. My question is, how can I program this if I have an unknown number of rows to update? Lets say all these numbers comes from an array that I will pass into my views and I don’t know how many WHEN and THEN statement I need to write? thanks for your help!

1 Answer 1

1

You can programmatically build up a query, using the conditionals Case and When.

So, for example:

from django.db.models import Case, When

# Make a list of When expressions
when_list = [When(priority_number=2, then=3),
             When(priority_number=3, then=4)]

# Use in a query of your choice, as an example:
Model.objects.update(
    priority_number=Case(
        *when_list))
Sign up to request clarification or add additional context in comments.

5 Comments

Hello, thanks for the respond! where can I pass my array here?
OP search the solution for update not for select
Updated the answer to include a list.
Hi, I created a lists of WHEN as you mentioned. But when I pass it as *when_list into the Case (per your example) it is literally trying to execute *when_list and not whats in that lists. Any advise?
Sorry, I forgot to import. Let me try again!

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.