Usage of MySQL's "IF EXISTS"

Here are two statements that I'd like to work, but which return error messages:

IF EXISTS (SELECT * FROM gdata_calendars WHERE `group` =  ? AND id = ?) SELECT 1 ELSE SELECT 0

and

IF ((SELECT COUNT(*) FROM gdata_calendars WHERE `group` =  ? AND id = ?) > 0)  SELECT 1 ELSE SELECT 0;

The question marks are there because I use parametrized, prepared, statements with PHP's PDO. However, I have also tried executing this with data manually, and it really does not work.

While I'd like to know why each of them doesn't work, I would prefer to use the first query if it can be made to work.


You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

I found the example RichardTheKiwi quite informative.

Just to offer another approach if you're looking for something like IF EXISTS (SELECT 1 ..) THEN ...

-- what I might write in MSSQL

IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
    SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
    INSERT INTO TABLE(FieldValue) VALUES('')
    SELECT SCOPE_IDENTITY() AS TableID
END

-- rewritten for MySQL

IF (SELECT 1 = 1 FROM Table WHERE FieldValue='') THEN
BEGIN
    SELECT TableID FROM Table WHERE FieldValue='';
END;
ELSE
BEGIN
    INSERT INTO Table (FieldValue) VALUES('');
    SELECT LAST_INSERT_ID() AS TableID;
END;
END IF;