7

I have a query like this:

IF EXISTS(SELECT 1 FROM table1 WHERE col1 = ? LIMIT 1) THEN
DELETE FROM table2 WHERE col2 = ?
END IF

But I don't know why above query does not work. Also this does not work too:

IF  EXISTS(SELECT 1 FROM table1 WHERE col1 = ? LIMIT 1) BEGIN
DELETE FROM table2 WHERE col2 = ?
END

MySQL tell my there is a syntax error, How can I fix it?

Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
  • 4
    MySQL is (generally) not a procedural programming language; you can't use `IF` statements outside of a procedure. The documentation does state this. If you were to actually _read_ it, you may also find the answer to your question. Is there some reason you were unable to read the documentation? – Lightness Races in Orbit Sep 28 '15 at 13:22
  • Yeah. So you're pretty much stuck with doing the `IF` in your application logic. – Ifedi Okonkwo Sep 28 '15 at 13:24
  • @LightnessRacesinOrbit actually I saw [this answer](http://stackoverflow.com/questions/639854/check-if-a-row-exists-otherwise-insert#639874) and thought maybe it is possible to using `IF` in mysql! anyway ok thanks. – Shafizadeh Sep 28 '15 at 13:27

1 Answers1

14

You can move the condition into the WHERE clause of DELETE to achieve the same effect, like this:

DELETE FROM table2
WHERE col2 = ?
  AND EXISTS(SELECT 1 FROM table1 WHERE col1 = ? LIMIT 1)

Note that the two ?s have switched places with relation to the original query.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523