Introduction to MySQL IF Function
MySQL IF Function is a control function in MySQL that helps us to manage and manipulate decision-making related work on the conditional basis. There might be a situation when you want to execute certain function or retrieve certain value from the table on basis of some condition fulfillment and if their is any failure of that condition then you might want to execute some other code or retrieve some other value. Here, MySQL IF function comes to rescue and can be used to make the execution of MySQL statements on conditional basis.
IF function is one of the control flow functions of MySQL that help us to perform a certain operation on the successful result of the condition and some other kind of operation of behavior on the failure of the conditional expression. Hence, if the function of MySQL is also referred to as IF THEN ELSE or IF-ELSE function in MySQL.
Syntax and Working of MySQL IF Function
Given below is the syntax of MySQL IF Function:
IF(expression,true_expression,false_expression)
Expression can be any condition or statement or function that will return boolean value. If this condition evaluates to true then the code or functions that are specified will execute in the second parameter that is true_expression is executed. If the condition doesn’t evaluate to true then the function or code that you want to execute that is specified in the third parameter that is false_expression is executed. This is the syntax of if function in MySQL.
Note that if statement and if the function are two different things in MySQL. Whenever a null or zero value is evaluated from the expression then the false_expression is executed. The type of the value returned by the if function depends on how we use it and what kind of task are we performing in the if function based on expression result.
Usage of MySQL IF Function
We can use this if function in query statements, to handle NULL values in the columns of the table records, use the if function along with aggregate functions to achieve the desired result sets with the help of expressions of query statements that will ultimately return to a boolean value.
Example of MySQL IF Function
We will now consider one example where we will store the data of certain number of persons that will contain all the details of persons like its name and age and then determine the eligibility to vote for each of that person.
Let us first create a table of person_records:
Code:
CREATE TABLE `person_records` (
`id` int(11) PRIMARY KEY,
`firstName` varchar(10) COLLATE latin1_danish_ci NOT NULL,
`age` int(3) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci;
Output:
Let us insert some records in the table.
Code:
INSERT INTO `person_records` (`id`, `firstName`, `age`) VALUES
(1, 'Payal', '23'),
(2, 'Vyankatesh', '17'),
(3, 'Omprakash', '15'),
(4, 'Parineeta', '36');
Output:
Let us now retrieve name and eligibility of that person and use the if function to do so as shown in the below query statement.
Code:
SELECT firstName, IF(age<=17,'You are not eligible to vote!','You are eligible to vote!') as eligibility FROM `person_records`;
The output of the above functions when copied and pasted on MySQL terminal command prompt is as follows.
Output:
Displaying Not Applicable(N/A) instead of null values of columns.
We can use the IF function to handle NULL values of the columns and change the value of that column to be displayed in case if NULL is stored in it.
Let us consider a simple example by creating an educba_writers table and inserting some null values in a certain column.
Code:
CREATE TABLE `educba_writers` (
`id` int(11) PRIMARY KEY,
`firstName` varchar(10) COLLATE latin1_danish_ci NOT NULL,
`rate` decimal(5,2) DEFAULT NULL,
`joining_date_time` datetime
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci;
The output of the above functions when copied and pasted on MySQL terminal command prompt is as follows.
Output:
Code:
INSERT INTO `educba_writers` (`id`, `firstName`, `rate`, `joining_date_time`) VALUES
(1, 'Payal', '750.00', '2020-05-28 16:02:34'),
(2, 'Vyankatesh', '700.00', NULL),
(3, 'Omprakash', '600.00', '2020-05-28 20:32:50'),
(4, 'Parineeta', '980.00', NULL);
Output:
Let us now retrieve the records.
Code:
SELECT * FROM educba_writers;
Output:
Code:
SELECT id, firstName, rate, IF(joining_date_time IS NULL,"N/A",joining_date_time) as joining_date_time FROM educba_writers;
Output:
Using IF function with Aggregate Functions
We can make the use of if function along with other aggregate functions to get the required results.
For example, suppose that we consider the writers whose rate of an article with more than 700 as the high paid writers. Now, if we want to calculate the total count of the writers that are high paid then we can combine the usage of aggregate function SUM and IF function in a single select query statement as shown below.
Code:
SELECT SUM(IF(rate>700, '1', '0')) as "count of high paid writers" FROM educba_writers;
Output:
From the above output we can say that 2 writers are high paid writers whose rate is greater than 700 and from the table contents we can see that two writers named payal and parineeta have rate of articles 750 and 980 respectively that are greater than 700.
Conclusion
IF function is the control function available in MySQL that provides us with the capability to execute and perform certain tasks or define the behaviour of working of MySQL statements based on certain conditions. If the condition evaluates to true then some code will get execute and if condition results in false some other code will get execute. If the function can be used in query statements, manage NULL values of the columns, use it along with aggregate functions in which we can define the expression. Note that the expression should evaluate to a boolean value. The if function can be embedded in the SELECT query statements to retrieve the results on conditional basis and the expressions can be defined on column values, literals, numbers, strings, booleans and many more.
Recommended Articles
This is a guide to MySQL IF Function. Here we discuss the introduction to MySQL IF Function, usage, using IF function with aggregate functions and examples. You may also have a look at the following articles to learn more –
12 Online Courses | 10 Hands-on Projects | 92+ Hours | Verifiable Certificate of Completion
4.5
View Course
Related Courses