Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get multiple values from a subquery?

Tags:

sql

oracle

Is there any way to have a subquery return multiple columns in oracle db? (I know this specific sql will result in an error, but it sums up what I want pretty well)

select     a.x,     ( select b.y, b.z from b where b.v = a.v), from a 

I want a result like this:

a.x | b.y | b.z --------------- 1   | 2   | 3 

I know it is possible to solve this problem through joins, but that is not what I am asking for.

My Question is simply if there is any way, to get two or more values out of a subquery? Maybe some workaround using dual? So that there is NO actual join, but a new subquery for each row?

EDIT: This is a principle question. You can solve all these problems using join, I know. You do not need subqueries like this at all (not even for one column). But they are there. So can I use them in that way or is it simply impossible?

like image 424
John Smith Avatar asked Sep 18 '12 08:09

John Smith


People also ask

Can a subquery return multiple values?

Multiple-row subqueries are nested queries that can return more than one row of results to the parent query. Multiple-row subqueries are used most commonly in WHERE and HAVING clauses. Since it returns multiple rows, it must be handled by set comparison operators (IN, ALL, ANY).

How do I SELECT multiple values in a subquery?

You may use the IN, ANY, or ALL operator in outer query to handle a subquery that returns multiple rows. Contents: Using IN operator with a Multiple Row Subquery. Using NOT IN operator with a Multiple Row Subquery.


Video Answer


2 Answers

A Subquery in the Select clause, as in your case, is also known as a Scalar Subquery, which means that it's a form of expression. Meaning that it can only return one value.

I'm afraid you can't return multiple columns from a single Scalar Subquery, no.

Here's more about Oracle Scalar Subqueries:

http://docs.oracle.com/cd/B19306_01/server.102/b14200/expressions010.htm#i1033549

like image 200
Henrique Ordine Avatar answered Sep 25 '22 12:09

Henrique Ordine


It's incorrect, but you can try this instead:

select     a.x,     ( select b.y from b where b.v = a.v) as by,     ( select b.z from b where b.v = a.v) as bz from a 

you can also use subquery in join

 select         a.x,         b.y,         b.z     from a     left join (select y,z from b where ... ) b on b.v = a.v 

or

   select         a.x,         b.y,         b.z     from a     left join b on b.v = a.v 
like image 32
Robert Avatar answered Sep 24 '22 12:09

Robert