Skip to Main Content
  • Questions
  • exception handling in select a query not pl/sql block

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, Kamrul Hasan.

Asked: October 27, 2016 - 6:33 am UTC

Last updated: October 27, 2016 - 2:12 pm UTC

Version: oracle 11g

Viewed 1000+ times

You Asked

Query;

update accounts set product_code=( select product from products);

from the query the sub query return multiple rows. So i want to update it with null value. so how could i do this exception handling from this query??

and Chris said...

You are going to join the subquery back to the main table, right? Otherwise it'll always return all the rows in the products table!

Anyway, you could do something like:

- Use count(*) over (partition by <join cols>) to see how many rows there are in products for the account
- Only return rows from the subquery where this count = 1:

create table t1 (
  x int,
  y int
);
create table t2 (
  x int,
  z int
);

insert into t1 values (1, 1);
insert into t1 values (1, 2);
insert into t1 values (2, 2);

insert into t2 values (1, 0);
insert into t2 values (2, 0);
           
update t2 
set    z = (select y
            from   (select x, y, count(*) over (partition by x) c from t1) t1 
            where  t1.x = t2.x
            and    c = 1
            );
            
select * from t2;

X  Z  
1     
2  2 


Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.