Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch entries starting with the given string from a SQL Server database?

Tags:

I have a database with a lot of words to be used in a tag system. I have created the necessary code for an autocomplete box, but I am not sure of how to fetch the matching entries from the database in the most efficient way.

I know of the LIKE command, but it seems to me that it is more of an EQUAL command. I get only the words that looks exactly like the word I enter.

My plan is to read every row, and then use C#'s string.StartsWith() and string.Contains() functions to find words that may fit, but I am thinking that with a large database, it may be inefficient to read every row and then filter them.

Is there a way to read only rows that starts with or contains a given string from SQL Server?

like image 626
Erlend D. Avatar asked Jul 27 '10 17:07

Erlend D.


2 Answers

When using like, you provide a % sign as a wildcard. If you want strings that start with Hello, you would use LIKE 'Hello%' If you wanted strings with Hello anywhere in the string, you would use LIKE '%Hello%'

As for efficiency, using Like is not optimal. You should look into full text search.

like image 145
Fosco Avatar answered Oct 06 '22 02:10

Fosco


I know of the LIKE command, but it seems to me that it is more of an EQUAL command. I get only the words that looks exactly like the word I enter.

That's because you aren't using wildcards:

WHERE column LIKE 'abc%' 

...will return rows where the column value starts with "abc". I'll point out that when using wildcards, this is the only version that can make use of an index on the column... er column.

WHERE column LIKE '%abc%' 

...will return rows where the column value contains "abc" anywhere in it. Wildcarding the left side of a LIKE guarantees that an index can not be used.

SQL Server doesn't natively support regular expressions - you have to use CLR functions to gain access to the functionality. But it performs on par with LIKE.

Full Text Search (FTS) is the best means of searching text.

like image 44
OMG Ponies Avatar answered Oct 06 '22 03:10

OMG Ponies