January 03, 2011

Select TOP With TIES in SQL Server




The SQL Server TOP Expression returns only the first set of rows that is either a number or a percent of rows. If you want additional rows to be returned from the base result set if duplicate values exists in the qualified set of results, then use TOP..WITH TIES as shown in the example below:

USE Northwind
GO
-- TOP vs TOP WITH TIES
-- By SqlServerCurry.com

-- Using TOP Expression
SELECT TOP 3
OrderID, UnitPrice, Quantity
FROM [Order Details]
ORDER BY Quantity DESC

-- Using TOP WITH TIES
SELECT TOP 3 WITH TIES
OrderID, UnitPrice, Quantity
FROM [Order Details]
ORDER BY Quantity DESC

SQL TOP WITH TIES

Note: TOP..WITH TIES expression is available in SQL Server 2005 and later versions and can be specified only in SELECT statements and only if an ORDER BY clause is specified.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

2 Responses to "Select TOP With TIES in SQL Server"
  1. healthdurbar com said...
    January 4, 2011 at 11:35 AM

    this is a useful sql tip

  2. Dominos India said...
    January 5, 2011 at 3:59 AM

    Nice tip and really useful

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions