views:

226

answers:

3

If the value of @param is null, which is better to use:

  1. WHERE t.column = COALESCE(@param, '')
  2. WHERE t.column = IFNULL(@param, '')
  3. WHERE (@param IS NULL OR t.column = @param)

Is the OR more expensive than comparing the column to a value that will return all values for the specified column? My understanding is that options 1 & 2 will force a full table scan every time, while #3 would not.

A: 

I recommend trying the three options, using EXPLAIN in front of your query and see what MySQL thinks as it relates to your table and indexes.

Doug Hays
A: 

Option 2 looks like a syntax error; ISNULL only takes one parameter, and returns a boolean.

Options 1 and 3 could return different values. When @param is null, option 1 would return only rows where t.column is the empty string, where option 3 would return all rows. Either one would use a full table scan unless you have an index on t.column; even then, option 3 would use the full scan when @param is null.

eswald
My bad - ISNULL changed to be IFNULL, thanks.
OMG Ponies
Why do you believe option 3 would perform a full table scan if @param were to be null? It would pass the first half of the test; the second part shouldn't be executed.
OMG Ponies
I guess it wouldn't exactly "scan" the full table so much as return the entire thing. Is that what you want?
eswald
With IFNULL, options 1 and 2 should be basically identical. There might be some performance difference, but it should be negligible.
eswald
I want to return records with any t.column value if the @param is null.
OMG Ponies
In that case, option 3 does exactly what you want. There are ways to make something like 1 and 2 do the same thing, but not as efficiently.
eswald
A: 

3 is best because the optimizer will short-circuit that evaluation during the optimizer stage and eliminate the where clause.

longneck