I come from frontend background and I am trying to write a stored proc that can accept null parameter. Here’s a simplified version:
CREATE PROCEDURE get_item(IN item_id INT(11))
BEGIN
SELECT * FROM item a WHERE a.item_id = IF(item_id IS NULL, a.item_id, item_id);
END;;
So I want to SELECT everything if item_id is null, otherwise, I want the WHERE clause to apply. Is this the way to do it? It seems to work, but I am not sure if there is a better way.
I think I can also write it like this:
SELECT * FROM item a WHERE ((item_id IS NULL) OR (a.item_id = item_id));
is a performance killer: instead of using no WHERE, it will evaluate your
IFfor every row, as it is not a constant expression.is a good way, as the query planner will see, that the
WHEREevaluates to a contant expression ofTRUEMy way would be to put an
IFinto the stored procedure top level, that decides between two queries, one having aWHERE, the other not. While this is quite verbouse, it is also quite readable.