Page 1 of 1

Doubt in UNION concept

PostPosted: Thu Oct 04, 2012 1:37 am
by gauthamnagpur18
Hi,

I am having doubt in UNION concept . Suppose there are three sub-queries .

select * from a where some cond
union
select * from b where some cond
union
select * from c where some cond

If first query gives you 1 result set ,second & third query gives you none ..

What should be the output after UNION?

As per my understanding , output after UNION should be 1 result set which was retrieved from first query..

Please help me out :roll:

Re: Doubt in UNION concept

PostPosted: Thu Oct 04, 2012 2:11 am
by NicC
have you tried something out to try and verify your thoughts?

Re: Doubt in UNION concept

PostPosted: Thu Oct 04, 2012 9:11 am
by gauthamnagpur18
Hi NicC ,

Ya , I tried .. I am not getting any output after union when only first query is having the result set & second & third query is having none . But when I tried changing the where condition of second query( to get result set of second query) , I got result set after UNION .

Conclusion : If we are doing A union B union C , atleast two of the sub queries should have result set for UNION result .

Thanks,
Gautham

Re: Doubt in UNION concept

PostPosted: Thu Oct 04, 2012 10:51 am
by enrico-sorichetti
Conclusion : If we are doing A union B union C , atleast two of the sub queries should have result set for UNION result .

unfortunately Your conclusion is wrong!

The UNION operator is used to combine the result-set of two or more SELECT statements.

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

The UNION operator selects only distinct values
that' s why it appears that only rows from the first <select> are returned

To allow for duplicate values, and return them use UNION ALL.
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2


The column names in the result-set of a UNION are always equal to the column names in the first SELECT statement in the UNION.