#0335 – SQL Server – Using the WITH TIES option in the TOP clause of SELECT queries


When working with the AdventureWorks database, assume that we have the following requirement:

Please provide the list of customers with TOP 100 orders from Australia with the highest order totals.

The following query is the first one that comes to mind:

USE AdventureWorks2012;
GO
SELECT TOP 100 soh.CustomerID, 
               soh.TotalDue, 
               soh.TerritoryID
FROM Sales.SalesOrderHeader AS soh
INNER JOIN Sales.SalesTerritory AS sst ON soh.TerritoryID = sst.TerritoryID
WHERE sst.CountryRegionCode = 'AU'
ORDER BY soh.TotalDue DESC;
GO

image

This query would work in most cases, but analyzing the requirement, we realize that we don’t want the TOP 100 orders, we want all customers with the TOP 100 orders. These two requirements are different, and here’s why:

  • TOP 100 orders by total value = this means that we should have only 100 orders being returned, in the order defined by the ORDER BY clause
  • Customers with TOP 100 orders by total value = this means that we need to first fetch the TOP 100 order totals and then look for all customers which have orders with these totals. In this case, the number of orders being returned may be more than 100

In this case, we need to use the WITH TIES clause when defining the TOP statement. Here’s the query:

USE AdventureWorks2012;
GO
SELECT TOP 100 WITH TIES 
        soh.CustomerID, 
        soh.TotalDue, 
        soh.TerritoryID
FROM Sales.SalesOrderHeader AS soh
INNER JOIN Sales.SalesTerritory AS sst ON soh.TerritoryID = sst.TerritoryID
WHERE sst.CountryRegionCode = 'AU'
ORDER BY soh.TotalDue DESC;
GO

image

NOTES:

  • The TOP…WITH TIES can only be used in a SELECT statement
  • It cannot be used without an accompanying ORDER BY clause (a normal TOP can)
  • The TOP…WITH TIES also works with the TOP (n) PERCENT option

Until we meet next time,

Be courteous. Drive responsibly.

Advertisement

1 thought on “#0335 – SQL Server – Using the WITH TIES option in the TOP clause of SELECT queries

Let me know what you think about this post by leaving your feedback here!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.