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?

3
  • 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? Commented Sep 28, 2015 at 13:22
  • Yeah. So you're pretty much stuck with doing the IF in your application logic. Commented Sep 28, 2015 at 13:24
  • @LightnessRacesinOrbit actually I saw this answer and thought maybe it is possible to using IF in mysql! anyway ok thanks. Commented Sep 28, 2015 at 13:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Sajad As far as I know, only limit 1 works with MySql. TOP 1 is Sql Server syntax (related).
The LIMIT 1 is unnecessary; EXISTS sort of does that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.