Dealing with some legacy code and in trying to get a poorly designed database to display what we want I did a self-union on a table to display an intersection of records in a certain order – simplified e.g.
SET @setOfRecords = 1234
SET @subsetOfRecords = 4567
--Set A
SELECT *
FROM results
WHERE
resultSet = @setOfRecords AND
resultSubset = 4567
UNION
--Set B
SELECT *
FROM results
WHERE
resultSet = @setOfRecords AND
resultSubset <> 4567
Displays correctly, i.e.
Set A
Set B
However, if I parametrise the subset id this order is reversed – e.g.
SET @setOfRecords = 1234
SET @subsetOfRecords = 4567
--Set A
SELECT *
FROM results
WHERE
resultSet = @setOfRecords AND
resultSubset = @subsetOfRecords
UNION
--Set B
SELECT *
FROM results
WHERE
resultSet = @setOfRecords AND
resultSubset <> @subsetOfRecords
Displays incorrectly, i.e.
Set B
Set A
I am aware that this is not an ideal method, however other constraints have lead to the necessity of this implementation. My question is purely on why the ordering is affected by parametrisation on the resultSubset ID.
Any ideas? Running on SQL Server 2008.
Thanks,
Paul
Why do you expect any specific order? You haven’t included an
ORDER BYclause. Therefore SQL Server is free to return the rows in any order it deems most efficient.If you want a predictable order, include an
ORDER BYclause. If you don’t include one, you’re telling SQL Server that you don’t care about order.In this case you can compare the actual execution plans and you will probably find a difference in at least one sort operator. This could be due to a variety of reasons, including parameter sniffing, statistics, etc…