Bob Bob - 23 days ago 6
MySQL Question

Getting mysql to ignore where condition

Is there to make mysql ignore conditions if a variable isn't set, e.g.

SELECT *
FROM foo
WHERE id = $id
AND bar = $baz


If $baz is set run query as normal, else run the query minus the AND clause?

Thanks

Answer
SELECT *
FROM foo
WHERE id = $id
AND ( bar = $baz OR $baz [equals null, empty string, zero, whatever] )

I don't know if MySQL ever uses short circuit evaluation in its execution plan, but it may be beneficial to put the cheaper comparison first, like:

SELECT *
FROM foo
WHERE id = $id
AND ( $baz [equals null, empty string, zero, whatever] OR bar = $baz )

You can use this methodology with multiple parameters.

SELECT *
FROM foo
WHERE id = $id
AND ( $baz [equals null, empty string, zero, whatever] OR bar = $baz )
AND ( $x = 0 or x = $x )
AND ( $y IS NULL OR y = $y )

-- etc.
Comments