Very basic IF EXISTS statement not working

Viewed 284

I really don't understand why my statement:

IF EXISTS (SELECT * FROM people WHERE ID = 168)
THEN SELECT * FROM people
END IF;

is returning this error:

Unknown statement type. (near "IF EXISTS" at position 0)

I'm using MariaDB 10.3. Any ideas?

ADDITIONAL INFO

This is of course a simplified example. What I wanna do is, concretely:

IF EXISTS (SELECT * FROM people WHERE ID = 168)
THEN UPDATE people SET calculated_value = complex_queries_and_calculations
WHERE ID = 168

.., so to update a field of a given record if that record contains a given data, and else do nothing. To generate the data which would be used for the update, I need to query other tables for values and make some calculations. I want to avoid these queries + calculations, if there's actually nothing to update. And in this case, simply do nothing. Hence, I guess that putting for example an EXIST clause inside a WHERE clause of the UPDATEstatement would end in many queries and calculations made in vain.

1 Answers

MySQL and MariaDB only allow IF statements in programming blocks -- stored functions, procedures, and triggers.

Instead, just use:

select p.*
from people p
where exists (select 1 from people p2 where p2.id = 168);

This returns all people if id 168 is in table.

Related