Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL IF(SELECT) statement

Tags:

sql

mysql

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
like image 610
ScottMcGready Avatar asked Jun 06 '26 13:06

ScottMcGready


1 Answers

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.

like image 165
Kermit Avatar answered Jun 09 '26 01:06

Kermit