Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query SQL Server 2008 database for first and last name and order by relevance?

Basically I have a table like this:

CREATE TABLE Person(
    PersonID int IDENTITY(1,1) NOT NULL,
    FirstName nvarchar(512) NOT NULL,
    LastName nvarchar(512) NULL
)

And I need to find the top n results based on a user-query like this:

"Joh Smi"

The following query returns the results I need (I think). Just not in the relevant order.

SELECT
    PersonID, FirstName, LastName
FROM
    Person
WHERE
    FirstName LIKE 'Joh%' OR
    LastName LIKE 'Joh%' OR
    FirstName LIKE 'Smi%' OR
    LastName LIKE 'Smi%'

If the following names were in the database and our user-query was "Joh Smi" the names should appear in the following order (or similar)

  1. John Smith
  2. Johnny Smith
  3. John Jacob
  4. David Smithsonian
  5. Daniel Johnson

I'm hoping to get it to work similar to facebook's autocomplete friend-search.

So, how do I return the top n most relevant rows in SQL Server 2008?

like image 343
David Murdoch Avatar asked Mar 04 '10 22:03

David Murdoch


People also ask

How do I fetch first name and last name in SQL?

Code: SELECT. left(NAME, charindex(' ', NAME) - 1) AS 'FirstName', REVERSE(SUBSTRING(REVERSE(NAME), 1, CHARINDEX(' ', REVERSE(NAME)) - 1)) AS 'LastName'

How do I sort SQL by date from oldest to newest?

If you'd like to see the latest date first and the earliest date last, you need to sort in descending order. Use the DESC keyword in this case. ORDER BY ExamDate DESC ; Note that in T-SQL, NULL s are displayed first when sorting in ascending order and last when sorting in descending order.

How do you use ORDER BY clause with SQL statement what is its use?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I get the first and last observation in SQL?

To get the first and last record, use UNION. LIMIT is also used to get the number of records you want.


1 Answers

I recommend implementing Full Text Search (FTS) for two reasons:

  1. Simplify the query (shouldn't need the ORs, which'll perform poorly)
  2. Utilize the FTS ranking functionality - see this article
like image 66
OMG Ponies Avatar answered Oct 24 '22 17:10

OMG Ponies