devxlogo

Improve Your Search Algorithms

Improve Your Search Algorithms

A normal practice in implementing a search is to use the “like” operator. As long as you are searching for your keyword in only one column, there will be no problem. However, what if you encounter a situation where you want to search/different keyword(s) from more than 2 or 3 columns?

Let us say you’ve got table “tblsearch” with fields fld1,fld2,fld3.

For a single column search, you can use:

  --//////////////////////////////////////SELECT * from tblsearch where fld1 like '%something%' --For multi column search : SELECT * from tblsearch where fld1 like '%something%' or     fld2 like '%something%' or     fld3 like '%something%' --//////////////////////////////////////

This will work fine if you want to search only one keyword. However, if you want to search more than one keyword, use this approach:

  --////////////////////////////////////// --Single keyword: SELECT * from tblsearch where (fld1+fld2+fld3) like '%something%' --Multiple keywords: SELECT * from tblsearch where (fld1+fld2+fld3) like '%first%'      or (fld1+fld2+fld3) like '%second%' --//////////////////////////////////////

This second query is better than the first query for two reasons has been proven to be more efficient and uses less resources.

If you use a clustering index, then it will increase the performance of first query. But only one clustered index can be created per table. It also wins out over the first query in optimization and readability.

In an extra bonus, the second method makes use of the Derived tables concept. Look at this additional query:

 select * from(select (fld1+fld2+fld3) as myfld,* from tblsearch) Awhere A.myfld like '%first%'or A.myfld like '%second%'
See also  11 Effective Keyword Research Tools and Techniques
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist