I am having unexpected results from MariaDB IF EXISTS... in a stored procedure. I created a minimal example to demonstrate the issue:
PROCEDURE testdb.testSearchResults(IN pParam1 INT, IN pParam2 CHAR(2))
BEGIN
IF EXISTS(SELECT COUNT(*) FROM test WHERE intval = pParam1 AND text = pParam2) THEN
SELECT 'Found' AS result;
ELSE
SELECT 'Not Found' AS result;
END IF;
END
No matter what the contents of the file "test" or the parameters I give to the call, this procedure always returns "Found".
Am I doing something wrong?
Thanks.
IF EXISTS (SELECT * FROM ... )will be faster than IF (SELECT COUNT() FROM ... )>0or similar. If the optimiser doesn't spot the equivalence then it may scan an index to make the count to compare to zero, where the explicitEXISTSclause can abort early: as soon as one matching row has been found you know the result of theIFis going to be true so further reading is unneeded. This is true for the simplest caseIF EXISTS(SELECT FROM SimpleTable)` and for cases involving filtering clauses, joining clauses, and other complications. – David Spillett Nov 20 '19 at 14:56IF EXISTS (SELECT 1 ...is no faster thanIF EXISTS (SELECT * ...(this is certainly true for MS SQL Server) though it may depend on which database engine you are using. There should be no circumstance whereSELECT 1is slower though, so you may chose to prefer that just-in-case. See the answers on https://dba.stackexchange.com/questions/159413/exists-select-1-vs-exists-select-one-or-the-other for a more detailed run-down. – David Spillett Nov 20 '19 at 15:02IF EXISTS ( SELECT 1 ... )does a semi-join (stop when first row found), so it is inherently faster than finding all the rows to count them. – Rick James Nov 20 '19 at 22:06