Custom Search
 


Using Control Flow Functions

There are four Control Flow functions in MySQL - CASE operator, IF/ELSE construct, IFNULL, and NULLIF.

Control Flow functions return a value for each row processed. The returned value is a result of comparison or condition evaluated. Control Flow functions can be used in SELECT, WHERE, ORDER BY, GROUP BY (will be covered in aggregate functions section) clause.

No. Name Description
1 CASE CASE is probably more suitable to be called CASE statement rather than CASE function. There are two versions of using CASE statement:

Version 1:

CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END

In this version, result is returned when value is equal to compare_value. If nothing is matched, the result after ELSE is returned, or NULL is returned if there is no ELSE part.

Practice #1-1: Get each supplier's continent from Suppliers table based on the supplier's country.

Practice #1-2: Get each supplier's continent from Suppliers table and use the CASE statement's column alias in ORDER BY clause.

Version 2:

CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END

In this version, if condition is true, result is returned. If nothing is matched, the result after ELSE is returned, or NULL is returned if there is no ELSE part.

Version 2 returns the same result as Version 1 when condition is for equal comparison (=). See Practice #1-3 which returns the same result as Practice #1-1.

condition can use any of the comparison operators covered in Using Comparison Operators, Part I and Part II. See Practice #1-4 where IN and = operator are used.

2 IF(expr1,expr2,expr3) IF function accepts three arguments and the result is returned based on if expr1 is TRUE.

If expr1 is evaluated to TRUE, the function returns expr2. Otherwise, expr3 is returned. See Practice #2-1.

IF() function can also be used in ORDER BY clause. See Practice #2-2.

3 IFNULL(expr1,expr2) If expr1 is not NULL, the function returns expr1. Otherwise it returns expr2. See Practice #3.

IFNULL() returns a numeric or string value, depending on the context in which it is used.

4 NULLIF(expr1,expr2) Returns NULL if expr1 = expr2 is true, otherwise returns expr1.

This is the same as

CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END

See Practice #4.


Practice #1-1: Using CASE statement to get the supplier's continent based on its country.

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
Get the supplier's continent based on its country. For
example, if country is USA, then continent is North America.
If the country is not USA, Canada, Brazil, Japan, Singapore,
Australia, the continent is Europe which is covered in the
ELSE part of the CASE.
*/
SELECT CompanyName,
CASE Country WHEN 'USA' THEN 'North America'
WHEN 'Canada' THEN 'North America'
WHEN 'Brazil' THEN 'South America'
WHEN 'Japan' THEN 'Asia'
WHEN 'Singapore' THEN 'Asia'
WHEN 'Australia' THEN 'Australia'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;

Query result set - 29 rows returned:
Using CASE statement to get the supplier's continent based on its country.

Practice #1-2: Using CASE statement to get the supplier's continent and order result by using column alias.

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
Get the supplier's continent based on its country.
The result is ordered by using column alias Continent.
*/
SELECT CompanyName,
CASE Country WHEN 'USA' THEN 'North America'
WHEN 'Canada' THEN 'North America'
WHEN 'Brazil' THEN 'South America'
WHEN 'Japan' THEN 'Asia'
WHEN 'Singapore' THEN 'Asia'
WHEN 'Australia' THEN 'Australia'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY Continent;

Query result set - 29 rows returned:
Using CASE statement to get the supplier's continent and order result by using column alias

Practice #1-3: Using the second version of CASE statement

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
This query returns the exact result as that returned
by Practice #1-1. But here the second version of CASE
statement is used.
*/
SELECT CompanyName,
CASE WHEN Country = 'USA' THEN 'North America'
WHEN Country = 'Canada' THEN 'North America'
WHEN Country = 'Brazil' THEN 'South America'
WHEN Country = 'Japan' THEN 'Asia'
WHEN Country = 'Singapore' THEN 'Asia'
WHEN Country = 'Australia' THEN 'Australia'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;

Query result set - 29 rows returned:

Practice #1-4: Using the second version of CASE statement

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
This query returns the same result as that in
Practice #1-3 but the query here is shorter.
This is because IN comparison operator is used
with CSV (Comma Separated Values) list.
*/
SELECT CompanyName,
CASE WHEN Country IN ('USA', 'Canada') THEN 'North America'
WHEN Country = 'Brazil' THEN 'South America'
WHEN Country IN ('Japan', 'Singapore') THEN 'Asia'
WHEN Country = 'Australia' THEN 'Australia'
ELSE 'Europe' END AS Continent
FROM Suppliers
ORDER BY CompanyName;

Query result set - 29 rows returned:

Practice #2-1: Using IF control flow function

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
In this query, we categorize products into High Price and
Low Price. If the unit price is equal to or greater than 20,
the product is in High Price group. Otherwise, Low Price group.
*/
SELECT ProductName,
UnitPrice,
IF(UnitPrice>=20, 'High Price', 'Low Price') AS "Price Level"
FROM Products;

Query result set - 77 rows returned:
Using IF control flow function

Practice #2-2: Using IF control flow function in ORDER BY clause

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
In this query, the result is ordered by FirstName or
LastName, depending on if modulo operation result is
0 or not. If the current Unix timestamp modulo 2 is zero,
the query result is ordered by FirstName. Otherwise, LastName.

So if you execute the query multiple times, you would normally
get results in different orders.

Info about UNIX_TIMESTAMP, refer to Date and Time Function.

Info about modulo operator, refer to Comparison Operators.
*/
SELECT FirstName, LastName
FROM Employees
ORDER BY IF(UNIX_TIMESTAMP()%2=0, FirstName, LastName);

Query result set - 9 rows returned and ordered by LastName:
Using IF control flow function in ORDER BY clause

Query result set - 9 rows returned and ordered by FirstName:
Using IF control flow function in ORDER BY clause

Practice #3: Using IFNULL function

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
This query finds out who is the CEO of Northwind Trader.
If ReportsTo is NULL, we want to return 'Is CEO'. Otherwise,
return the ReportsTo value.

The ReportsTo is NULL for Andrew Fuller because he does
not report to anyone.
*/
SELECT FirstName, LastName, IFNULL(ReportsTo, 'Is CEO')
FROM Employees;

Query result set - 9 rows returned:
Using IFNULL function

Practice #4: Using NULLIF function

In Firefox (not IE), copy and paste the following SQL to your SQLyog query window. To execute a query, move your cursor anywhere inside the query and then press F9. Note that the SQL needs to end with semi-colon.

/*
Query 1:

This query uses IF function as inner function and wrapped
it with NULLIF as outer function.

For inner function IF, when Fax is not available
(empty string), it returns No Fax. Otherwise,
returns Got Fax.

In outer function NULLIF, we compare the result of IF function
with the string No Fax. When IF function returns No Fax,
NULLIF function returns NULL. Otherwise, it returns the
result of IF function.
*/
SELECT CompanyName,
Fax,
NULLIF(IF(Fax='', 'No Fax', 'Got Fax'), 'No Fax') AS Note
FROM Customers;

/*
Query 2:

This query is an equivalent query as Query 1 and returns
the same result. But here CASE statement is used instead
of NULLIF function.
*/
SELECT CompanyName,
Fax,
CASE WHEN IF(Fax='', 'No Fax', 'Got Fax')='No Fax' THEN NULL
ELSE IF(Fax='', 'No Fax', 'Got Fax')
END AS Note
FROM Customers;

Query result set - 91 rows returned:
Using NULLIF function





  1. Next tutorial: Using Conversion Functions

  2. Back to Section Index: Single Row Functions

  3. Back to Tutorial Index: MySQL Database How-to Articles and Tutorials


Copyright © 2010 GeeksEngine.com. All Rights Reserved.

This website is hosted by LunarPages.

No portion may be reproduced without my written permission. Software and hardware names mentioned on this site are registered trademarks of their respective companies. Should any right be infringed, it is totally unintentional. Drop me an email and I will promptly and gladly rectify it.

 
Home | Kung Fu Timer | Feedback | Terms of Use | Privacy Policy