As others have mentioned, SQL is "set based" and a "set" has no explicit or implicit ordering. The data only becomes ordered at the point in time that it returned from the database to the client, and only if you provide a specific ORDER BY
clause.
In this example SQL makes no guarantees about the order of the data returned to the client...
SELECT * FROM (SELECT x, y FROM z ORDER BY x, y) sub
Even though there is an ORDER BY
clause. The existence of the outer query means that the ordering in the inner query is "out-of-scope". It may come in the order you hope, it's just not guaranteed (and in some dialects would give an error for that reason).
Similarly, the ordering of your two queries is obfuscated by their outer queries and the intervening UNION ALL
.
It's also worth noting that when UNION
ing multiple sets, you can then ORDER
the results without needing an outer query...
SELECT x, y FROM z UNION ALL SELECT a, b FROM c ORDER BY x, y
(The ordering applies to the results of the UNION
, which is why it refers to field names that don't even exist in the final SELECT
.
For readability I prefer this type of layout...
SELECT x, y FROM z
UNION ALL
SELECT a, b FROM c
ORDER BY x, y
To get the results you want, you must specify the ORDER BY
in the outermost query. That may mean adding an extra field to the sets which you are UNION
ing...
SELECT 1 AS source, x, y FROM z
UNION ALL
SELECT 2 AS source, a, b FROM c
ORDER BY source, x, y