Home > Enterprise >  How to use booleans return from SELECT IF in MySQL
How to use booleans return from SELECT IF in MySQL

Time:12-29

So I have a query that I'd like to run which isn't really complicated but MySQL doesn't want to make my life easy and keeps giving error 1064. Here is the overall structure of the query:

IF EXISTS(query) AND IF NOT EXISTS(query)
BEGIN
    INSERT ...
    DELETE ...
END

Now I have used this overall structure but I don't think MySQL supports this because I get error 1064. So instead I have been using the following query:

SELECT IF(
    EXISTS(query) AND NOT EXISTS(query), 1, 0
);

This works well and returns the proper bool value.

My question is how can I now use this bool value returned and do the insert and delete operations I have in the overall structure which I gave above? Perhaps there's even a better way I have yet to come across to get this work.

Thank you!

CodePudding user response:

MySQL's IF syntax requires a THEN and END IF. You don't have either. You need to study the syntax reference and examples carefully: https://dev.mysql.com/doc/refman/en/if.html

Also, MySQL doesn't currently allow IF/THEN/END IF outside of stored routines. https://dev.mysql.com/doc/refman/8.0/en/sql-compound-statements.html says:

This section describes the syntax for the BEGIN ... END compound statement and other statements that can be used in the body of stored programs: Stored procedures and functions, triggers, and events.

If you want conditional logic, you're expected to write code in a client application.

  • Related