简体   繁体   中英

How can I test an IF statement in MySQL?

How can I test an IF statement in MySQL ?

I need to know, what happens when a query is into a IF statement and it returns nothing (0 row selected) ?

In other word, what a SELECT query returns when the no row is selected? Will it return NULL ? If yes, so will this throw an error? IF ( NULL ) THEN ... ? Or in this case just the statement of that IF won't execute?


In reality, I have a code like this:

IF ( SELECT banned FROM users WHERE id=new.user_id ) THEN 
// do stuff

Note: banned column contains either 0 or 1 .

All I want to know, is my code safe when that query doesn't return any row? I mean will it throw an error or nothing happens (just that IF statement doesn't execute) ?


Noted that I wanted to test it myselft, but I don't know how can I test a IF statement in MySQL. For example, I wanted to test it by this code:

BEGIN
    IF ( SELECT banned FROM users WHERE id=new.user_id ) THEN 
       SELECT 'test';
    ENDIF;
END

But code above doesn't even run. That's why I've asked this question.

An IF statement can be tested in the context of a MySQL stored program (a procedure, function or trigger.) MySQL doesn't support anonymous blocks.

To test an IF statement, you can create a procedure

DELIMITER $$

CREATE PROCEDURE foo
BEGIN
  IF ( some_condition ) THEN
     SELECT 'evaluation of some_condition returned TRUE' AS msg;
  ELSE
     SELECT 'evaluation of some_condition did NOT return TRUE' AS msg;
  END IF;
END$$    

DELIMITER ;

CALL foo;

I need to know, what happens when a query is into a IF statement and it returns nothing (0 row selected) ?

What you're actually asking about here is a scalar subquery.

Scalar subqueries return exactly one column and exactly one or zero rows. Returning NULL and matching zero rows are equivalent, and neither will throw an error. In both cases, the subquery's return "value" is NULL .

You will , however, throw an error if you manage to write a scalar subquery that returns more than one row (such as when you forget WHERE in the subquery. But zero rows is perfecty valid.

IF tests for truthiness, and anything that IS TRUE ... which technically means any expression that both IS NOT FALSE and IS NOT NULL -- satisfies the IF . If the return value is FALSE (0) or NULL then the ELSE branch will be followed, if present.

I highlighted keyword phrases like IS NOT FALSE , above, to emphasize the point that these are logical operators in SQL.

Try queries like SELECT 0 IS FALSE (returns 1, because it is) or SELECT NULL IS NOT TRUE (returns 1, because it isn't) or SELECT NULL IS NOT FALSE (also returns 1, because it isn't) SELECT NULL IS FALSE (returns 0, because it isn't) to see what I mean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM