tags:

views:

49

answers:

3

I am experiencing some strange behaviour and I really don't have test date/ environments, so Will this query return top 5 rows ordered by count, or will it take top 5 rows and sort them then. What would be the query for the first?

  select top 5 l.userId, count(*) "count" from Log l
  where ...
  group by l.userId
  order by "count" desc
+3  A: 

It couldn't possibly have taken more than a few minutes to create some test data, but yes, that query does what you want it to do. TOP does its job after ORDER.

Matti Virkkunen
Maybe not the test *data* but the *environment* (i.e. SQL Server) is the problem? Just a thought...
scherand
@scherand: The Express Edition is free. And even though it takes a while to install, it's something you'll want to have around for testing in any case, if you don't happen to have another database to play around with.
Matti Virkkunen
well, actually environments were not the problem, but the fact that i got strangely different results on two environments. and one was customer's test environment on which i couldn't create more data. Thanks for help, much appreciated
the berserker
+3  A: 

It will return top 5 rows after group by and order by.

More on this

http://msdn.microsoft.com/en-us/library/ms189463.aspx

It will return top 5 results from the query you have without using top.

hgulyan
+3  A: 

This will execute whatever query you define, then return the first five rows of that query.

Matthew Scharley