SQL IF usage

MySQL's IF can be used both as an expression and as a flow control statement in a stored procedure.


1. IF expression

IF(expr1,expr2,expr3)

expr1 is TRUE (expr1 <> 0 and expr1 <> NULL), then the return value of IF() is expr2; otherwise, the return value is expr3.

The return value of IF() is either a numeric value or a string value, depending on the context.

SELECT IF(sex=1,"男","女") AS s FROM t_user;

2. CASE WHEN expression:

SELECT CASE sex
WHEN 1 THEN '男' 
  ELSE '女' 
END AS s 
FROM table_name
WHERE sex != '';

3. IFNULL expression

IFNULL(expr1,expr2)

If expr1 is not NULL, the return value of IFNULL() is expr1; otherwise, the return value is expr2. The return value of IFNULL() is a number or a string, depending on the context in which it is used.

 SELECT IFNULL(2,0);
 -> 2

SELECT IFNULL(NULL,1);
 -> 1

SELECT IFNULL(1/0,'ok');
-> 'ok'

Guess you like

Origin blog.csdn.net/gnwu1111/article/details/128592381