Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the SQL LIKE operator with %%

I had a requirement to create a query in SQL Server where the search condition would include/exclude a table based on user input.

Say I have two tables, TABLE_A and TABLE_B with columns KEYCOLUMN_A and COLUMN_A in TABLE_A and columns FKCOLUMN_B and COLUMN_B in TABLE_B.

And a query like:

SELECT TABLE_A.* FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '%SEARCH2%'

Now if the user does not input SEARCH2, I don't need to search TABLE_B. But this would mean an IF ELSE clause. And as the number of "optional" tables in the query increases, the permutations and combinations would also increase and there will be many IF and ELSE statements.

Instead I decided to keep the statement as it is. So if SEARCH2 is empty, the query will effectively become:

SELECT * FROM TABLE_A, TABLE_B WHERE TABLE_A.KEYCOLUMN_A = TABLE_B.FKCOLUMN_B
AND TABLE_A.COLUMN_A LIKE '%SEARCH%' AND TABLE_B.COLUMN_B LIKE '% %'

Can the SQL optimizer recognize that LIKE %% is as good as removing the condition itself?

like image 560
devanalyst Avatar asked Sep 25 '09 11:09

devanalyst


1 Answers

Wrap an OR around your "B" table, such as:

AND (len(searchString)=0 OR table_b.column_b LIKE "%searchString%" )

This way, if no value for the string, its length would be zero, and the first part of the OR would be evaluated, always come back as true and return that portion of the equation as valid and ignore the other half using the LIKE clause.

You could apply the same for as many linked tables as you need.

like image 169
DRapp Avatar answered Oct 02 '22 23:10

DRapp