Today, I will explain how we can use Ties option with Top.Basically Sqlserver reaturn all the rows from the select Query but with Top Option We can specify criteria on that basis Select Query Return the Records.
–Select Query
Select SaleitemQty from Sales
This Query will return the alll the SaleitemQty from Sales table.
–Select Query with Top Clause
Select Top 10 SaleitemQty from Sales
This Query will return the top 10 SaleitemQty from the Sales table.
Now, we come to Top clause with Ties option.
Create table like this
Create Table Sales (CityName varchar(100),SaleQty int)
Insert Rows in this table
Insert into Sales values(‘Delhi’,15)
Insert into Sales values(‘Bombay’,17)
Insert into Sales values(‘London’,20)
Insert into Sales values(‘Newyork’,22)
Insert into Sales values(‘Tokyo’,15)
Now, we check first for the Only Top option.
— Query with Top clause only
select Top 4 SaleQty,cityname from sales order by SaleQty desc
— Result Set of Top clause
SaleQty cityname
———– ———————————————————–
22 Newyork
20 London
17 Bombay
15 Tokyo
Like that you can see in the result set that, there are Two tables that have saleQty 15 but only one City comes in the result set.
— Query with Top clause and Ties Option
select Top 4 with Ties SaleQty,cityname from sales order by SaleQty desc
— Result Set of Ties option
SaleQty cityname
———– ———————————————————–
22 Newyork
20 London
17 Bombay
15 Delhi
15 Tokyo
Ties option alllows the last place to include multiple rows if those rows have eaual values in the columns used in the order by clause.
In this example Two city has same SaleQty 15, with ties option we can get both the citys In the result set with same SaleQty.
I hope this example will clear the Ties option with Top clause.