65.9K
CodeProject is changing. Read more.
Home

TOP WITH TIES clause in SELECT queries

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2 votes)

Nov 24, 2009

CPOL
viewsIcon

14055

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...