Unexpected results from MariaDB IF EXISTS ... THEN
SELECT COUNT(*) always returns at least one record (maybe with zero). So IF EXISTS is always true.

You may:


Replace SELECT COUNT(*) ... with SELECT 1 ...
Replace IF EXISTS(SELECT ... with IF 0 &lt; (SELECT ...


I think that 1st variant is more fast. It only checks does at least one record exists, and so it must stop searching after first record found, whereas 2nd query must obtain all matched records, count them, and then compare the result with zero.