I'm working in a project with MySQL and using stored procedures to make my SELECT queries, so all of them have this same structure:
DELIMITER $$
CREATE PROCEDURE `case_in_where`(IN `column_selector` INT, IN `value` VARCHAR(255))
BEGIN
SELECT * FROM `foo`
WHERE
CASE
WHEN `column_selector` IS NULL THEN 1
WHEN `column_selector` = 1 THEN `foo`.`column_1` = `value`
WHEN `column_selector` = 2 THEN `foo`.`column_2` = `value`
END
;
END $$
DELIMITER ;
But I have seen that when people ask for help using this approach, usually the answers are that it should use AND, OR instead or Dynamic SQL. So, this way is not correct? It's a bad practice or have any difference in performance?
I should use AND, OR or Dynamic SQL or make different queries for every case?
Thanks beforehand.
EXPLAIN {query}
for both forms of this query. I suspect the optimiser doesn't try significantly to unwrap case statements.OR
statements limit range of optimizations significantly too. Show MySQL version and what indexesfoo
has too.col varchar(255) as (IF(column_index=1, column_1, IF(column_index IS NULL, NULL,column_2)))
then your query becomesWHERE col IS NULL OR col = value
and I think there is aIS NULL OR
optimization (could be wrong).column_selector
seems to be the constant/parameter external to the table or the field of another table. If so, no way to use it in generated column.