Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting mysql to ignore where condition

Tags:

mysql

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

like image 971
Bob Avatar asked Dec 21 '22 04:12

Bob


1 Answers

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.
like image 118
Tim M. Avatar answered Jan 14 '23 06:01

Tim M.