views:

180

answers:

4

Query 1 = select top 5 i.item_id from ITEMS i

Query 2 = select top 5 i.item_id, i.category_id from ITEMS i

Even if I remove the top 5 clause they still return different rows.

if I run "select top 5 i.* from ITEMS i" this returns a completely different result set !!

+7  A: 

Because the results of a "TOP N" qualified SELECT are indeterminate if you do not have an ORDER BY clause.

RBarryYoung
Strictly, the results of any SELECT without ORDER BY is indeterminate. The TOP just restricts n rows to 5 rows, so instead of all rows in whatever order, you get 5 different ones.
gbn
Heh. Well *strictly* only their order is normally indeterminate (which in SQL technically dos not exist without an ORDER BY anyway). However, with TOP, the actual *contents* are indeterminate without an ORDER BY.
RBarryYoung
We're both right... but the TOP is consequence of indeterminate ordering ;-) I still gave you + 1 for first answer
gbn
+3  A: 

Without an ORDER BY clause, you cannot predict what order you will get results. There is probably an interesting underlying reason for why SQL Server processes those queries differently, but from a user's perspective the solution is simply to impose the ORDER BY clause that's relevant to your query, thus guaranteeing you'll know which five items come first.

VoteyDisciple
+2  A: 

The reason is simple: you did not specify an ORDER BY clause. So, for example, the optimizer could choose to use different indexes to satisfy two different queries, if there is a lean index that contains ItemID but not CategoryID it can be touched to satisfy the first query. A very common question, has a canned naswer:

Without ORDER BY, there is no default sort order.

AlexKuznetsov
+3  A: 

Since you're not specifying an ORDER BY clause, the optimizer will determine the most efficient way to do the query you're asking to do. This means there might be a different indexing done for the two columns you've indicated in your two queries, which results in what you're seeing.

Joseph
While others are correct based on language itself, this is spot-on for SQL Server. If you investigate the Estimated Execution Plan, you will likely see many different indices used. However, my gut tells me the table in question does not have an index.
Austin Salonen
+1 from me, by the way.
Austin Salonen