Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple fields based on multiple Criteria in one Query

Tags:

sql-update

I am trying to update 3 different columns in a table based on 3 different conditions in the where clause. (I have the updated data in a different table, so I am joining them on the primary keys)

For example, if I did not have a value previously in field1 for a customer but now I do, I should be able to update the column 'field1'. Similarly, I would like to update columns field2 and field3.

Can I accomplish this in a single Update statement.

To Update one column you can write something like this:

Update tblCustomer 
SET tblCustomer.Order_Date = tblCustomerInfo.Order_Date
FROM tblCustomer 
LEFT JOIN tblCustomerInfo ON (tblCustomer.CustomerID = tblCustomerInfo.CustomerID)
WHERE tblCustomer.Order_Date <> tblCustomerInfo.Order_Date 
  AND tblCustomer.Order_Date is NULL;

How about updating 3 different Columns in single go based on different where conditions (if the data was missing for that column was missing previously, and is now available)

like image 634
user1601472 Avatar asked Sep 10 '12 20:09

user1601472


People also ask

How do you update multiple columns with multiple conditions?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.

How do you update multiple values in multiple columns in SQL?

We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required.

Can we use multiple set in update query?

No, only 1 table can be updated with an UPDATE statement.

How do you update multiple entries in SQL?

There are a couple of ways to do it. INSERT INTO students (id, score1, score2) VALUES (1, 5, 8), (2, 10, 8), (3, 8, 3), (4, 10, 7) ON DUPLICATE KEY UPDATE score1 = VALUES(score1), score2 = VALUES(score2);


1 Answers

UPDATE categories
    SET display_order = CASE id
        WHEN 1 THEN 3
        WHEN 2 THEN 4
        WHEN 3 THEN 5
    END,
    title = CASE id
        WHEN 1 THEN 'New Title 1'
        WHEN 2 THEN 'New Title 2'
        WHEN 3 THEN 'New Title 3'
    END
WHERE id IN (1,2,3)
like image 196
Thushar Avatar answered Sep 28 '22 01:09

Thushar