Click here to Skip to main content
15,906,574 members
Articles / Database Development / SQL Server
Tip/Trick

TOP WITH TIES clause in SELECT queries

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
23 Nov 2009CPOL 14K   8  
The SELECT TOP N query always returns exactly N records, and randomly drops any record that have the same value as the last record in the group.SELECT TOP 5 price, Booktitle FROM BookTitles ORDER BY price DESCThis query will give 5 records from table BookTitles in descending order by price. ProblemS

The SELECT TOP N query always returns exactly N records, and randomly drops any record that have the same value as the last record in the group.

SELECT TOP 5 price, Booktitle FROM BookTitles ORDER BY price DESC

This query will give 5 records from table BookTitles in descending order by price. 

Problem
Suppose the last book title has a price tag of $19.99 and the table contains two more books with the same price, but it will not come in the result as they are ignored by the TOP clause. 

To see those recrods add the WITH TIES clause… 

SELECT TOP 5 WITH TIES price, Booktitle FROM BookTitles ORDER BY price DESC

**WITH TIES will only work with Order by Clause.

Enjoy...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
I am an experienced Software Developer with 11+ years of hands-on experience working with Microsoft.NET technology (ASP.NET, ASP.NET Core, C#, SQL Server, Angular).

Visit Talking Dotnet
For ASP.NET Core, read ASP.NET Core Articles

Comments and Discussions

 
-- There are no messages in this forum --