Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows using CASE WHEN - ORACLE

Tags:

sql

oracle

I have the table ACCOUNT of structure as follow:

ACCOUNT_ID  | ACCOUNT_STATUS| 
004460721   |      2        | 
042056291   |      5        | 
601272065   |      3        | 

I need to update the three rows at once using one SELECT statement such that, the second column will be 5, 3, 2 respectively.
I used the following query but seems there is something missing

UPDATE ACCOUNT
SET ACCOUNT_STATUS = CASE   
WHEN ACCOUNT_STATUS = '004460721' THEN 5  
WHEN ACCOUNT_STATUS = '042056291' THEN 3  
WHEN ACCOUNT_STATUS = '601272065' THEN 2  
WHERE ACCOUNT_ID IN ('004460721','042056291','601272065')  

My question, is this way correct? if no, can I use CASE WHEN statement and how or I only have choice of using SUB-SELECT to acheive that in one statement?
Kindly, notice this is for SQL ORACLE

like image 506
Hawk Avatar asked Dec 05 '22 09:12

Hawk


1 Answers

Ok based on the fiddle you have given i have tried these and it worked for me

create table account(  account_id number primary key,
                           account_status varchar2(30));

insert into account values(1, '5');
insert into account values(2, '3');
insert into account values(3, '2');

select * from account


update account
set account_status= case
when account_id=1 then '2'
when account_id=2 then '5'
when account_id=3 then '3'
END

select * from account

I didn't use the where condition

like image 145
Sarathi Kamaraj Avatar answered Dec 26 '22 23:12

Sarathi Kamaraj