ScottMcGready
ScottMcGready

Reputation: 1622

MySQL IF(SELECT) statement

I've got a MySQL statement that's failing to compile, can anyone give me a basic example of how it should work? Semi pseudo-code:

IF (SELECT 'id' FROM terms WHERE name = 'thename' IS NULL) THEN
# Do this...
ELSE
# do this...
END IF

I just can't get any IF statement to work at all, not even a test one like:

IF(1=1) 
THEN SELECT "works"
END IF

Upvotes: 3

Views: 9294

Answers (1)

Kermit
Kermit

Reputation: 34055

For your first example, you're not evaluating the condition. You need to move the IS NULL outside the SELECT:

IF (SELECT 'id' FROM terms WHERE name = 'thename') IS NULL THEN
...

If you're running this inside a SELECT statement, you may want to use CASE:

SELECT
    CASE
        WHEN (SELECT 'id' FROM terms WHERE name = 'thename') IS NULL THEN ...
    END

Otherwise, see the IF documentation.

Upvotes: 6

Related Questions