Technically speaking SQL does not guarantee a sort order, but implementation can give a perceived or realized sort. It makes sense for file processing that SQL would not "merge" union results unless directed by ORDER BY if one isn't using parallelism. Perhaps there are some conditions where the query optimizer will perform the union "out of order" which explains why the perceived order is reversed.
Some SQL features, for example using the MS SQL Server WITH ROLLUP clause, cause the results to be sorted by the optimizer in order for subtotaling (rollup) to occur. However, ROLLUP is an OLAP feature which causes the optimizer to behave differently than regular OLTP queries.
Can you run the queries in debug, perhaps it may show why the optimizer sometimes processes the files in a different order than specified in UNION?
--Loyd
-----Original Message-----
From: midrange-l-bounces@xxxxxxxxxxxx [mailto:midrange-l-bounces@xxxxxxxxxxxx] On Behalf Of Zangare, Basil (GE Comm Fin, non-ge)
Sent: Monday, April 06, 2009 9:22 AM
To: Midrange Systems Technical Discussion
Subject: RE: SQL UNION mystery
The only problem is the user would like to have the order within each table maintained and the tables to be grouped to themselves.
-----Original Message-----
From: midrange-l-bounces@xxxxxxxxxxxx [mailto:midrange-l-bounces@xxxxxxxxxxxx] On Behalf Of Charles Wilt
Sent: Friday, April 03, 2009 11:12 PM
To: Midrange Systems Technical Discussion
Subject: Re: SQL UNION mystery
Repeat after me....
"Without an ORDER BY clause in my SQL statement, nothing can be known (or assumed) about the order in which records will be returned."
If the order matters, you have to have an ORDER BY.
HTH,
Charles
On Fri, Apr 3, 2009 at 5:01 PM, Zangare, Basil (GE Comm Fin, non-ge) <basil.zangare@xxxxxxxxxxx> wrote:
Has anyone run into this problem before?
Through ODBC I have set up an Excel to import into a worksheet the
records from two separate tables with the same record layout. Here is
the code:
SELECT *
FROM LIBRARYA.FILE123 FILE123
UNION ALL
SELECT *
FROM LIBRARYB.FILE123 FILE123
Normally it pulls in the records the way we expect it to with the
records from LIBRARYA appearing before the records for LIBRARYB.
Every few weeks the order is mysteriously reversed, where LIBRARYB
appears before LIBRARYA. The records for each file are still in the
correct order, just the file order is reversed. At first I thought
this had something to do with Excel, but when I run the same code on
our i system I get the same results.
Any enlightenment as to why this is happening would be greatly
appreciated. A solution would cause me to do handstands.
TIA,
Basil Zangare