Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of MySQL's "IF EXISTS"

Tags:

mysql

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.

like image 500
C. E. Avatar asked Apr 03 '11 09:04

C. E.


People also ask

How do you use exists in select statement?

The result of EXISTS is a boolean value True or False. It can be used in a SELECT, UPDATE, INSERT or DELETE statement. Syntax: SELECT column_name(s) FROM table_name WHERE EXISTS (SELECT column_name(s) FROM table_name WHERE condition);

When to use exists and not exists?

Use EXISTS to identify the existence of a relationship without regard for the quantity. For example, EXISTS returns true if the subquery returns any rows, and [NOT] EXISTS returns true if the subquery returns no rows. The EXISTS condition is considered to be met if the subquery returns at least one row.

How do you check if a value exists in a table in MySQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

What is the use of exists?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.


1 Answers

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 = ?) 
like image 83
RichardTheKiwi Avatar answered Oct 18 '22 21:10

RichardTheKiwi