Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of WITH TIES keyword in SELECT statement in SQL Queries?

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.

like image 471
user3098256 Avatar asked Dec 31 '13 07:12

user3098256


People also ask

Can we use with clause in SELECT statement?

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.

What value does using the WITH TIES option on the top clause provide?

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.

How do you break tie orders in SQL?

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.

What is the advantage of WITH clause in Oracle?

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.


1 Answers

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

SQL Fiddle DEMO

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.

like image 57
Adriaan Stander Avatar answered Oct 03 '22 23:10

Adriaan Stander