Home >Database >Mysql Tutorial >Usage of if statement in sql
There are three parameters in the if statement in sql: expr1, expr2, expr3. When the value of expr1 is true, the return value of the function is expr2. When the value of expr1 is false, the return value of the function is expr3
It is always inevitable to use the database in project development. If you use the sql database Query the data first and then display the data. Such an operation would be cumbersome and inefficient. We can use another method to operate directly in the SQL statement. The information queried from the database is not directly put into the results. Instead, the information is converted into the data that needs to be displayed on the page and then stored in the results. This greatly improves efficiency. In this process, you need to use the if statement. Next, I will introduce the usage of this statement in detail in the article. I hope it will be helpful to everyone.
【Recommended course: SQL Tutorial】
Usage of if statement
Grammar structure:
if(expr1,expr2,expr3)
In the above grammar structure, expr1 represents the judgment condition, expr2 and expr3 is a customized return result that conforms to expr1
When the value of expr1 is true, the return value is expr2; when the value of expr1 is false, the return value is expr3
Example :
SELECT IF(TRUE,1+1,1+2); -> 2 SELECT IF(FALSE,1+1,1+2); -> 3 SELECT IF(STRCMP("111","222"),"不相等","相等"); -> 不相等
Find books with a selling price of 30. If it is a PHP book, it must be marked as sold out, otherwise it must be marked as in stock
select *,if(book_name='PHP','已卖完','有货') as product_status from book where price =30
Note: When there are only two types in the table In this case, you can use the if function
IF NULL expression
Syntax structure:
IF NULL( expr1 , expr2 )
The meaning is expr1 If the value is not NULL, expr1 will be returned, otherwise expr2 will be returned, as follows:
SELECT IFNULL(NULL,"11"); -> 11 SELECT IFNULL("00","11"); -> 00
Summary: The above is the entire content of this article, I hope it will be helpful to everyone.
The above is the detailed content of Usage of if statement in sql. For more information, please follow other related articles on the PHP Chinese website!