You are on page 1of 11

1/8/22, 20:37 Learn MySQL: Control Flow functions

SQLShack SQL Server training


Español

Learn MySQL: Control Flow functions


March 19, 2021 by Nisarg Upadhyay

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.

The following script creates the database and tables:

create database SchoolDB;


create table `SchoolDB`.`tblStudent` (ID int auto_increment primary key, Studen
tName varchar(250), ClassRoom char(1), Grade char(2));
create table `SchoolDB`.`tblMarks`(ID integer auto_increment primary key, stu-
dent_id int, subject varchar(50), Marks int);

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

insert into tblStudent (StudentName,ClassRoom,Grade) values ('Nisarg Upadhyay',


'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);

The following query inserts dummy data in tblMarks table:

insert into tblMarks (student_id, subject, Marks ) values (3,'Maths',100);


insert into tblMarks (student_id, subject, Marks ) values (1,'SS',80);
insert into tblMarks (student_id, subject, Marks ) values (1,'Science',90);
insert into tblMarks (student_id, subject, Marks ) values (2,'SS',45);
insert into tblMarks (student_id, subject, Marks ) values (2,'Maths',50);
insert into tblMarks (student_id, subject, Marks ) values (2,'Science',35);
insert into tblMarks (student_id, subject, Marks ) values (3,'Science',35);

Now, first, let us understand the IF function.

An overview of the IF() function


The IF function returns the value based on the condition specified within the function. The syntax
of the IF
function is the following:

SELECT IF(condition, if_condition_true, if_condition_false)

In the syntax:

Condition is a condition specified in the IF function


If_condition_true is the value returned by the function
If_condition_false is the value returned by the function

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.

Let us understand the concept using examples.

This website uses cookies. By continuing to use this site and/or


The simple IF example
clicking the "Accept" button you are providing consent Accept

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

mysql> select if('nisarg'='nirali','True','False') as 'Simple IF statement';

Output 1

Query 2

mysql> select if('nisarg'='nirali','True','False') as 'Simple IF statement';

Output 2

Print specific text in the output


For the demonstration, I have added two rows in the tblStudent with NULL values in grade and
class columns. For the
reporting purpose, instead of showing NULL, we want to show the Not
available in the query
output.

Query

mysql> Select studentname grade, classroom from tblstudent;

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;

The output is the following:

Use IF to display specific output


Suppose you want to display the name and grade based on the following condition:

Print Brilliant Student for the student who has an A+ grade, else prints
Average Student.

The SELECT statement must be written as follows:

mysql> select studentname , IF(Grade='A+','Brilliant Student','Average Student'


) as 'Student Grade' from tblstudent;

Use IF statement with the COUNT function

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;

Now, let us understand the CASE expression.

An overview of MySQL CASE expression


The CASE statement is one of the most common control flow expressions of MySQL. The case ex‐
pression is used to implement the IF ELSE logic in the query. The CASE expression can be used in
the SELECT, WHERE, and ORDER BY clause.
There are two variants of the CASE expression.

1. The simple CASE expression


2. The searched CASE expression

The simple CASE expression

The simple CASE expression matches the input with the values for equality and returns the corre‐
sponding result.

Following is the syntax of the simple CASE expression:

Select
Case expression
when static_value_1 then output_1
when static_value_2 then output_2
..
Else else_output
End

In the syntax, the case matches the expression with


static_value_1, static_value_2 … and returns
the corresponding
output_1, output_2…
This website uses cookies. values. If to
By continuing theuse
input
thisvalues do not match with any expres‐
site and/or
sion, then
it returns
clicking the the else_output.
"Accept" buttonLet
youusare
understand the concept with an example.
providing consent Accept

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

1. If the student’s grade is A+, then he should be considered an Intelligent


2. If the student’s grade is B+, then he should be considered as an Average Student
3. If the student’s grade is D+ or D- then he should be considered a Weak Student

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.

The query is the following:

select studentname, grade,


case grade
when 'A+' then 'Intelligent'
when 'B+' then 'Average Student'
when 'D' or 'D-' then 'Weak student' end as 'grade description'
from tblstudent;

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

select studentname, grade,


case grade
when 'A+' then 'Intelligent'
when 'B+' then 'Average Student'
when 'D' or 'D-' then 'Weak student' end as 'grade description'
from tblstudent where grade is not null
order by
case grade
when 'A+' then 'Intelligent'
when 'B+' then 'Average Student'
when 'D' or 'D-' then 'Weak student' end   asc

Output

Now, let us understand the searched CASE expression.

This website uses cookies. By continuing to use this site and/or


The Searched CASEbutton
clicking the "Accept" expression
you are providing consent Accept

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

Examples of the searched case expression

Following are the examples of the searched case expression.

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

The query is the following:

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

The IFNULL function


The IFNULL function is another common control flow function of MySQL. If the specified expres‐
sion is NULL then the NULLIF function returns the specific value, else it returns the expression.

Syntax

SELECT IFNULL(NULL, expr2);

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

select studentname, IFNULL(grade, 'Not available') as grade from tblStudent

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

pressions are equal


then it returns the NULL else it returns the first expression.

Syntax

SELECT NULLIF(expr1, expr2);

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

Learn MySQL: Querying


data from MySQL server using the SELECT statement

Learn MySQL: What is pagination

Learn MySQL: Sorting and Filtering data in a


table

Learn MySQL: Add data in tables using


the INSERT statement

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: An overview of the mysqlbinlog utility

Learn MySQL: Run multiple instances of MySQL Server on Windows 10

Learn MySQL: MySQL String Functions

Learn MySQL: Control Flow functions

Learn MySQL: Install MySQL server 8.0.19 using a noinstall Zip archive

Learn MySQL: MySQL Copy table

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.

He has expertise in database design, performance tuning, backup and recov‐


ery, HA and DR setup, database migrations and upgrades. He has completed
the B.Tech from Ganpat University. He can be reached on
nisargupadhyay87@outlook.com

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

ALSO ON SQL SHACK

Database security Executing stored SQL LEFT function in Co


testing using SQL … procedures from … queries dri

6 months ago • 1 comment a year ago • 1 comment 9 months ago • 2 comments 9m

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

0 Comments SQL Shack 🔒 Disqus' Privacy Policy 


1 Login

 Favorite t Tweet f Share Sort by Best

Start the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS ?

Name

Be the first to comment.

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd ⚠ Do Not Sell My Data

© 2022 Quest Software Inc. ALL RIGHTS RESERVED.   |     |     |  

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/ 11/11

You might also like