I have a table TestTable:
IntCol
1
4
6
2
3
8
12
11
9
7
15
13
14
(numbers are from 1 to 15 excluding 10).
When I do…
SELECT * FROM
(SELECT IntCol
FROM TestTable
WHERE IntCol >= 10
ORDER BY IntCol ASC) x1
UNION ALL
SELECT * FROM
(SELECT IntCol
FROM TestTable
WHERE IntCol < 10
ORDER BY IntCol DESC) x2
… result is ok (first from 11 to 15 ASCending, then from 1 to 9 DECSending):
IntCol
11
12
13
14
15
9
8
7
6
4
3
2
1
But when I omit SELECT * FROM and do…
(SELECT IntCol
FROM TestTable
WHERE IntCol >= 10
ORDER BY IntCol ASC)
UNION ALL
(SELECT IntCol
FROM TestTable
WHERE IntCol < 10
ORDER BY IntCol DESC)
… rows aren’t ordered at all (only values greater then 10 are first). The result is:
IntCol
12
11
15
13
14
1
4
6
2
3
8
9
7
My question is: why there is this SELECT * FROM needed when UNIONing ordered rows?
Individual Queries, cannot have
Order Byclause when there is a union in between them.for reference
http://p2p.wrox.com/sql-language/17907-union-order.html
here is an example of how Order By is used with Union
http://www.techonthenet.com/sql/union.php