Learn MySQL - Control Flow Functions
Learn MySQL - Control Flow Functions
In this article, we are going to learn about the most common control flow functions. The control
flow function
evaluates the condition specified in it. The output generated by them can be a true,
false, static value or column
expression. We can use the control flow functions in the SELECT,
WHERE, ORDER BY, and GROUP BY clause. Following are
the most common functions:
1. The IF functions
2. The CASE expression
3. The IFNULL function
4. The NULLIF function
In this article, we are going to learn the IF function and CASE expressions that are very important
control flow
functions in MySQL. Moreover, I am including an overview of the IFNULL and NULL of
functions.
Demo Setup
To understand the function in detail, I have created a sample database named SchoolDB. I
have
created two tables named tblStudent and tblMarks in the SchoolDB database.
This website
The following uses cookies.
query inserts By continuing
the database to use
in tblStudent this site and/or
table:
clicking the "Accept" button you are providing consent Accept
'A','A+');
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Nirali Upadhyay',
Quest Software and its affiliates do NOT sell the Personal Data you
'A','A+');
insertprovide to us either when
into tblStudent you register on our websites or
(StudentName,ClassRoom,Grade) when ('Bharti
values you Upadhyay',
do business with us. For more information about our and our data
'A','B+');
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Dixit Upadhyay',
protection efforts, please visit
'B','A+');
insert into tblStudent (StudentName ClassRoom Grade) values ('Hemant Bhatt' 'B'
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 1/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Hemant Bhatt','B'
,'D-');
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Usha Bhatt','A',
'A+');
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Shailja Chauhan',
'B','D');
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Deep Chauhan','A'
,'B+');
insert into tblStudent (StudentName,ClassRoom,Grade) values ('Omkar Bhatt','C',
'A+');
insert into tblStudent (StudentName,ClassRoom,Grade) values (Rajesh Bhatt',NUL
L,NULL);
insert into tblStudent (StudentName,ClassRoom,Grade) values (Vinesh Patel',NULL
,NULL);
In the syntax:
The IF function evaluates the values returned by the SELECT statement with the specified
condi‐
tion. If the function evaluates as TRUE, then it returns the value specified in
if_condition_true. If
the function evaluates as FALSE, then it returns
the value specified in the if_condition_false.
When the input string matches with each other, then print TRUE else, print FALSE. We can use the
Quest Software and its affiliates do NOT sell the Personal Data you
IF function in the
SELECT statement. The query should be written as follows:
provide to us either when you register on our websites or when you
do business with us. For more information about our and our data
Query 1protection efforts, please visit
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 2/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
Output 1
Query 2
Output 2
Query
Output This website uses cookies. By continuing to use this site and/or
clicking the "Accept" button you are providing consent Accept
Quest Software and its affiliates do NOT sell the Personal Data you
provide to us either when you register on our websites or when you
do business with us. For more information about our and our data
protection efforts, please visit
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 3/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
As you can see in the above image, the values of the grade and class column for
Rajesh and
Vinesh are NULL. Now, to display Not Available, the query should be written as
follows:
Select studentname,
IF(classroom IS NULL, 'Not Applicable',classroom) as 'Classroom',
IF(grade IS NULL, 'Not Applicable',grade)as 'Grade'
from tblstudent;
Print Brilliant Student for the student who has an A+ grade, else prints
Average Student.
Suppose you want to get the total number of students with A+, B+, and D- grades. The condition
is:
This website uses cookies. By continuing to use this site and/or
clicking the "Accept" button you are providing consent Accept
1. Count of a student whose grade is A+. These students should be categorized as Brilliant
Students
Quest
2. Count ofSoftware andwhose
the student its affiliates
grade isdo NOT
B+. sellstudents
These the Personal Data
should you
be categorized as Average
provide to us either when you register on our websites or when you
Students
do business
3. Count with us.
of the student For more
whose gradeinformation
is D-. These about ourshould
students and our
be data
categorized as Weak
protection efforts, please visit
Students
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 4/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
To generate the result set, we can use the IF function to evaluate the condition and then use the
COUNT function to
get the number of students with their respective grade.
Query
SELECT
COUNT(IF(Grade='A+',1,NULL)) 'Brilliant Student',
COUNT(IF(Grade = 'B+', 1, NULL)) 'Average Student',
COUNT(IF(Grade = 'D-', 1, NULL)) 'Weak Student'
FROM tblstudent;
The simple CASE expression matches the input with the values for equality and returns the corre‐
sponding result.
Select
Case expression
when static_value_1 then output_1
when static_value_2 then output_2
..
Else else_output
End
Example 1
Quest Software and its affiliates do NOT sell the Personal Data you
provide to us either when you register on our websites or when you
Suppose you want to populate the list of the students, their grades, and grade description. The
do business with us. For more information about our and our data
query output must
show the grade description based on the following condition.
protection efforts, please visit
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 5/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
In the case statement, we can specify an operator as well. I have specified an OR operator
to en‐
sure that the student whose grade is D+ or D should be considered a Weak student.
Output
Example 2
Suppose we want to sort the description of the grades in ascending order. As I mentioned, the
CASE statement can be
used in the ORDER BY clause. To sort the results, we must specify the case
statement after the ORDER BY clause.
Query
Output
The searched case expression evaluates the expression specified in the WHEN clause and returns
Quest Software and its affiliates do NOT sell the Personal Data you
the corresponding
value. The syntax is the following:
provide to us either when you register on our websites or when you
do business with us. For more information about our and our data
Select
Case protection efforts, please visit
when expression 1 then output 1
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 6/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
when expression_1 then output_1
when expression_2 then output_2
..
Else else_expression_output
End
In the syntax, the case matches the input values with expression_1, expression_2 … and returns
the corresponding output_1, output_2… values. If the input values do not match with any expres‐
sion, then it returns the else_expression_output.
Note: If you have a specified character string in the case expression, then the output returned
by the case
expression is a character string. Similarly, if you have specified a numeric value in
the case expression, the
output returned by the case expression is a decimal, an integer, or a
real value
Example 1
Suppose we want to populate the name of the parents based on the name of the surname of the
student. The query must
populate the values of studentname, grade, and classroom columns. The
condition for the CASE expression is following.
1. If the student’s surname is Chauhan, then the father’s name must be Hasmukh Chauhan
2. If the student’s surname is Bhatt, then the father’s name must be Jivan Bhatt
3. If the student’s surname is Upadhyay, then the father’s name must be Lalshankar
Upadhyay
Query
select studentname,
case
when studentname like '%Chauhan%' Then 'Hasmukh Chauhan'
when studentname like '%Bhatt%' then 'Jivan Bhatt'
when studentname like '%Upadhyay%' then 'Lalshankar Upadhyay' end as ParentName
,
classroom,grade
from tblstudent
where classroom is not null;
Output
This website uses cookies. By continuing to use this site and/or
clicking the "Accept" button you are providing consent Accept
Example 2
Quest Software and its affiliates do NOT sell the Personal Data you
provide to us either when you register on our websites or when you
Supposedo
webusiness
want to populate themore
with us. For total subjects studied
information by the
about ourstudent.
and ourTo populate the value of
data
protection
the subject, efforts,tblStudent
we are
joining please visitand tblMarks using left join. The condition for the CASE ex‐
i i f ll i
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 7/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
pression is following:
If the count of the subject studied by the student is zero, then the query should
display
Details not available else; it must display the count of the subject. This
example demon‐
strates the use of the COUNT() function in the CASE expression
select
Studentname,
case when count(subject)=0 then 'Details Unavailable' else count(subject) e
nd as 'SubjectsTaken'
from tblstudent a left join tblMarks b on a.ID=b.student_id
group by student_id, studentname
order by b.student_id desc;
Output
Syntax
In the syntax, if the value of the expr1 is NULL then it returns expr2 else it returns a value of expr1.
Example
Suppose when the query finds the NULL value for the grade column, we want to print details not
available else we
want to print the value of the column. This can be achieved by using the CASE ex‐
pression, but we are using the
IFNULL function.
Query
Output This website uses cookies. By continuing to use this site and/or
clicking the "Accept" button you are providing consent Accept
Quest Software and its affiliates do NOT sell the Personal Data you
The provide
NULLIF function
to us either when you register on our websites or when you
do business with us. For more information about our and our data
protection efforts, please visit
The NULLIF function compares the expressions specified in the function. If the values of the ex‐
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 8/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
Syntax
Example
Query
Select NULLIF(‘Nisarg’,’Nisarg’)
Output
Query
Select NULLIF(‘Nisarg’,’Nirali’)
Output
Summary
In this article, we have learned the most common control flow functions of MySQL. These functions
can be used to manipulate the output generated by the SQL query. The CASE and IF are the condi‐
tional expressions and functions that are used to display the output based on the condition speci‐
fied in the query.
Table of contents
This website
Learn MySQL: uses
Create and dropcookies. By continuing to use this site and/or
temp tables
clicking the "Accept" button you are providing consent Accept
Learn MySQL: Delete and Update Statements
Learn MySQL:
QuestThe Basics of and
Software MySQL
its Stored
Procedures
affiliates do NOT sell the Personal Data you
provide to us either when you register on our websites or when you
Learn MySQL: The Basics of MySQL Views
do business with us. For more information about our and our data
protection efforts, please visit
Learn MySQL: An overview of MySQL Binary Logs
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 9/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
Learn MySQL: Install MySQL server 8.0.19 using a noinstall Zip archive
See more
ApexSQL Database Power Tools for VS Code is an extension for VS Code which allows users to , run
queries and display results, search for objects, export query results into several standard formats,
generate DDL and DML scripts from object explorer on existing platforms like Windows, Linux,
macOS
Nisarg Upadhyay
Nisarg Upadhyay is a SQL Server Database Administrator and Microsoft certi‐
fied professional who has more than 8 years of experience with SQL Server
administration and 2 years with Oracle 10g database administration.
Related Posts:
1. Learn MySQL: MySQL String Functions
2. Learn MySQL: Install MySQL server 8.0.19 using a noinstall Zip archive
3. Learn MySQL: Run multiple instances of MySQL Server on Windows 10
4. Learn
This MySQL: The Basics
website uses of By
cookies. MySQL Views to use this site and/or
continuing
clicking the "Accept" button Accept
5. Learn MySQL: An overview of you are Binary
MySQL providing consent
Logs
MySQL
Quest Software and its affiliates do NOT sell the Personal Data you
provide to us either when you register on our websites or when you
do business with us. For more information about our and our data
3,444 Views
protection efforts, please visit
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 10/11
1/8/22, 20:37 Learn MySQL: Control Flow functions
I will explain how to use and This article will show how to This article will show In t
perform security testing execute a stored procedure comprehensive usage how
using SQL Server … hosted in Azure SQL … details of the SQL LEFT … ins
LOG IN WITH
OR SIGN UP WITH DISQUS ?
Name
Quest Software and its affiliates do NOT sell the Personal Data you
provide to us either when you register on our websites or when you
do business with us. For more information about our and our data
protection efforts, please visit
https://www.sqlshack.com/learn-mysql-control-flow-functions/ 11/11