matheuscscp
matheuscscp

Reputation: 878

MySQL: SELECT inside SELECT IF() statement

Can I have something like this?

SELECT IF((SELECT COUNT(id) FROM table WHERE id = 1) = 0, 1, <nothing_to_happen>) AS Available

My goal is select this:

+---------+
|Available|
+---------+
|1        |
+---------+

Only if there is no row selected from this query:

SELECT id FROM table WHERE id = 1

If the row with id = 1 exists in table, I want my query to return zero rows! Is that possible?

Upvotes: 3

Views: 1575

Answers (2)

Justin
Justin

Reputation: 9724

Query:

SELECT CASE
           WHEN COUNT(id) = 0 THEN 1
           ELSE 0
       END AS Available
FROM `TABLE`
WHERE id = 1

Upvotes: 0

Quassnoi
Quassnoi

Reputation: 425491

SELECT  1
FROM    dual
WHERE   NOT EXISTS
        (
        SELECT  NULL
        FROM    mytable
        WHERE   id = 1
        )

Upvotes: 5

Related Questions