adsense

Saturday, January 30, 2010

Order By union

Unions are used to display joined results from two queries with the same list of fields.
Ex:
Select f1,f2 --f1,f2 are the fields
from tbl1 --table
where f1<1
union
Select f1,f2
from tbl1
where f1>1

If you want to order the displayed results you'd have definitely tried following way

Select f1,f2
from tbl1
where f1<1
order by f1
union
Select f1,f2
from tbl1
where f1>1
order by f1

Sadly this is not going to work. If you want to order the displayed results the above query should be modified as follows

SELECT * FROM
(
SELECT f1,f2
from tbl1
where f1<1
order by f1
union
SELECT f1,f2
from tbl1
where f1>1
order by f1
) A
ORDER BY f1,f2

Happy coding..............!

No comments:

Post a Comment