Home > Database > Mysql Tutorial > body text

Usage of if statement in sql

清浅
Release: 2019-03-21 10:35:12
Original
19673 people have browsed it

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.

Usage of if statement in sql

【Recommended course: SQL Tutorial

Usage of if statement

Grammar structure:

if(expr1,expr2,expr3)
Copy after login

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"),"不相等","相等");
-> 不相等
Copy after login

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
Copy after login

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 )
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template