I had a requirement to create a query in MS SQL 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, COLUMN_A in TABLE_A and columns FKCOLUMN_B, 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 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 '% %'
I wonder whether SQL optimizer can recognize that LIKE %% is as good as removing the condition itself