How to select the top n from a union of two queries where the resulting order needs to be ranked by individual query?
Posted
by
Jedidja
on Stack Overflow
See other posts from Stack Overflow
or by Jedidja
Published on 2011-05-25T21:42:37Z
Indexed on
2012/10/01
21:38 UTC
Read the original article
Hit count: 611
Let's say I have a table with usernames:
Id | Name
-----------
1 | Bobby
20 | Bob
90 | Bob
100 | Joe-Bob
630 | Bobberino
820 | Bob Junior
I want to return a list of n
matches on name for 'Bob' where the resulting set first contains exact matches followed by similar matches.
I thought something like this might work
SELECT TOP 4 a.* FROM
(
SELECT * from Usernames WHERE Name = 'Bob'
UNION
SELECT * from Usernames WHERE Name LIKE '%Bob%'
) AS a
but there are two problems:
- It's an inefficient query since the sub-select could return many rows (looking at the execution plan shows a join happening before top)
- (Almost) more importantly, the exact match(es) will not appear first in the results since the resulting set appears to be ordered by primary key.
I am looking for a query that will return (for TOP 4)
Id | Name
---------
20 | Bob
90 | Bob
(and then 2 results from the LIKE query, e.g. 1 Bobby and 100 Joe-Bob)
Is this possible in a single query?
© Stack Overflow or respective owner