Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right syntax of IF statement in MySQL?

I have a small and simple MySQL code. But whenever I run it, I get error #1064. Can you tell me what is my mistake here?

IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN
    BEGIN
        SELECT * FROM tbl_cities;
    END
END IF

I also used some other conditions like the below one, but again I got an error.

IF (1=1) THEN
    BEGIN
        SELECT * FROM tbl_cities;
    END
END IF

What I actually want to do is something like this:

IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN
    BEGIN
        UPDATE ...
    END
ELSE
    BEGIN
        INSERT ...
    END
END IF
like image 989
Mohammad Saberi Avatar asked Jul 11 '12 07:07

Mohammad Saberi


1 Answers

If it is a procedure you're writing you should try:

BEGIN
    IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN
        SELECT * FROM tbl_cities;
    END IF
END

If it is a query, BEGIN and END have nothing to do here.

Edit

Well, there is not really more to say, IF ((SELECT COUNT(id) FROM tbl_states) > 0) THEN SELECT * FROM tbl_cities; END IF is simply not respecting the basic MySQL SELECT statement.

You should start with SELECT... etc...

like image 101
Olivier Coilland Avatar answered Sep 22 '22 07:09

Olivier Coilland