SELECT TOP 5 WITH TIES EmpNumber,EmpName FROM Employee Order By EmpNumber DESC
This above query return more than five result, What is the use of "With Ties" keyword SQL Queries.
The WITH clause allows you, as part of your select statement, to assign a name to a subquery and utilise its results by referencing that name. It is, on first glance, quite jarring. Because the subquery factoring clause brutally transforms the look of a query, making it no longer start with the SELECT keyword.
When the WITH TIES option is specified any rows that have the same column values as the last rows will also be returned. Therefore when you specify the WITH TIES option you might get back more rows than the (expression) value. The TOP clause supports being used with SELECT, INSERT, UPDATE and DELETE statements.
Breaking a "tie" in a sort is as easy as specifying a second column to ORDER BY : use a comma to specify the second (or third or nth) column to use in sorting.
The WITH clause may be processed as an inline view or resolved as a temporary table. The SQL WITH clause is very similar to the use of Global temporary tables. This technique is often used to improve query speed for complex subqueries and enables the Oracle optimizer to push the necessary predicates into the views.
From TOP (Transact-SQL)
Used when you want to return two or more rows that tie for last place in the limited results set.
Note the example
We have a table with 6 entires 1 to 4 and 5 twice.
Running
SELECT TOP 5 WITH TIES * FROM MyTable ORDER BY ID;
returns 6 rows, as the last row is tied (exists more than once.)
Where as
SELECT TOP 5 WITH TIES * FROM MyTable ORDER BY ID DESC;
returns only 5 rows, as the last row (2 in this case) exists only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With