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, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

healthdurbar com said...

this is a useful sql tip

Dominos India said...

Nice tip and really useful