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.


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

2 comments:

healthdurbar com said...

this is a useful sql tip

Dominos India said...

Nice tip and really useful