devxlogo

Select Maximum Five Result

Select Maximum Five Result

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

Answer:
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 pubsgoselect top 3 title_id,sum(qty)from salesgroup by title_idorder 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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist