Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Enterprise
Expertise: Intermediate
Mar 21, 2003

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) A
where A.myfld like '%first%'
or A.myfld like '%second%'
Harinatha Reddy
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date