'How can I update a column based on multiple values from multiple columns

I am new to this. I want to update a column value where based on values of other columns. Example

Product   Make     Model         Years
Hyundai   Getz     1.4 Hatch/3D     5
Hyundai   Getz     1.4 Hatch/5D     5
Hyundai   Getz     1.6 Hatch/5D     7
Hyundai   Getz     1.6 Hatch/5D     7

I tried the following

UPDATE WARRANTY
SET  WARRANTY.period = 
    Case when PRODUCT.grpcode ='Hyundai'  
         and PRODUCT.Make =’Getz’  
         and PRODUCT.Model in ('1.4 Hatch/3D',1.4 Hatch/5D')
then 5
 end 
 end

Is this right?

sql


Solution 1:[1]

So depending on which SQL you are working on, the approach will change. Here's one way to approach this:

update warranty
set period = case  when PRODUCT.grpcode ='Hyundai'  
     and PRODUCT.Make ='Getz'  
     and PRODUCT.Model in ('1.4 Hatch/3D','1.4 Hatch/5D')
then 5
from product
where product.pid = warranty.pid

you will need a column in order to join the 2 tables. I am assuming you would have a column like that. This is an example of postgresql for Mysql you can do something like this:

UPDATE warranty
    INNER JOIN
product ON product.pid = warranty.pid 
SET 
period = case  when PRODUCT.grpcode ='Hyundai'  
     and PRODUCT.Make ='Getz'  
     and PRODUCT.Model in ('1.4 Hatch/3D','1.4 Hatch/5D')
then 5

you will have to do this for all the products and manually change values for all the products and run the code multiple times.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Abdullah Wajahat