Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: SQL Server
Expertise: Beginner
Mar 21, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Select Maximum Five Result

How do I find out the top-five best sale items? I want the maximum five items to be listed.

In version 7, SQL Server has conveniently provided the TOP keyword. So, using the pubs database for an example, the following query will return the books with the top three sales:

use pubs
select top 3 title_id,sum(qty)
from sales
group by title_id
order by sum(qty) desc
Please note that the keyword TOP does not mean "highest" or "maximum"; it simply means the first n rows of the result set. That is why, in order to get the three books with the highest sales, I had to sort the result set in descending order. Had I allowed the default sort order of ascending, I would have received the three books with the lowest sales.

Another option with the TOP keyword is to use TOP N PERCENT. This limits the result set to the first n percentage of rows.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date