Wednesday, June 26, 2013

ORDER BY Problem in UNION Query

Sometimes when you are doing query you may need to UNION 2 queries and order the results by one column. We cannot do that with the column name

Wrong way 

SELECT name,city FROM students where age > 10
UNION
SELECT name,city FROM teachers where age > 20
ORDER BY city

Correct way 

SELECT name,city FROM students where age > 10
UNION
SELECT name,city FROM teachers where age > 20
ORDER BY 2

From number 2 we are mentioning the position of the required column that needs to be order

No comments:

Post a Comment