EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial IF Statement in MySQL
Secondary Sidebar
MySQL Tutorial
  • Advanced
    • MySQL Formatter
    • MySQL TINYINT
    • MySQL Grant All Privileges
    • MySQL DROP TABLE
    • MySQL rename database
    • MySQL Flush Privileges
    • MySQL super Privilege
    • MySQL Character Set
    • MySQL Log File
    • MySQL Flush Log
    • Grant Privileges MySQL
    • MySQL WHILE LOOP
    • IF Statement in MySQL
    • MySQL CASE Statement
    • MySQL IF Function
    • MySQL IF EXISTS
    • MySQL UUID
    • Views in MySQL
    • MySQL Replication
    • MySQL Partition
    • Toad for MySQL
    • Navicat for MySQL
    • MySQL AES_Encrypt
    • MySQL Performance Tuning
    • MySQL Transaction
    • MySQL? sort_buffer_size
    • MySQL? Sync
    • MySQL? Query Cache
    • MySQL Collation
    • MySQL ODBC Driver
    • MySQL Partitioning
    • MySQL InnoDB
    • MySQL Float vs Decimal
    • MySQL Union vs Union All
  • Basic
    • MySQL floor
    • MySQL DESCRIBE table
    • MySQL encryption
    • Introduction to MySQL
    • Is SQL Server a Database?
    • What is MySQL
    • Is MySQL Programming Language
    • MySQL Server
    • MySQL AB
    • MySQL Community Server
    • How To Install MySQL
    • MySQL Versions
    • MySQL OpenSource
    • MySQL GUI Tools
    • MySQL Grant
    • MySQL Error 1064
    • MySQL Drop Database
    • MySQL not equal
    • MySQL SELECT INTO Variable
    • MySQL Commands
    • MySQL Operators
    • What is MySQL Schema
    • Wildcards in MySQL
    • MySQL Constraints
    • MySQL Administration
    • MySQL Data Type
    • MYSQL COMMIT
    • MySQL FORMAT
    • Timestamp to Date in MySQL
    • MySQL DATEDIFF
    • MySQL?Incremental Backup
    • MySQL JSON Data Type
    • MySQL ENUM
    • MySQL Default Port
    • Cheat Sheet MySQL
  • Queries
    • MySQL Queries
    • MySQL Query Commands
    • SELECT in MySQL
    • MySQL INSERT IGNORE
    • MySQL having
    • ORDER BY in MySQL
    • MySQL Cheat Sheet
    • MySQL ORDER BY Random
    • MySQL ORDER BY DESC
    • MySQL GROUP BY
    • MySQL GROUP BY Count
    • MySQL GROUP BY month
    • MySQL WHERE Clause
    • MySQL WITH
    • MySQL FETCH
    • MySQL DDL
    • MySQL DML
    • MySQL WHERE IN Array
    • MySQL Fetch Array
    • MySQL ISNULL
    • MySQL Index Types
    • Mysql? Export Schema
    • Amazon RDS for MySQL
    • MySQL greatest
  • Database
    • What is Data Modeling
    • What is Data Processing
    • DBMS Architecture
    • DBMS Keys
    • Careers in Database Administration
    • What is MySQL Database
    • MySQL Relational Database
    • How to Connect Database to MySQL
    • MySQL Database Repair
    • RDBMS Interview Questions
    • DBMS Interview Questions
  • Functions
    • MySQL Function
    • MySQL Aggregate Function
    • MySQL String functions
    • MySQL Date Functions
    • MySQL Window Functions
    • MySQL Math Functions
    • MySQL Boolean
    • Cursor in MySQL
    • Condition in MySQL
    • MySQL BETWEEN
    • Insert in MySQL
    • MySQL IFNULL()
    • MySQL TIMESTAMPDIFF()
    • MySQL COALESCE()
    • MySQL count()
    • MIN() in MySQL
    • MySQL Numeric
    • MySQL field()
    • MySQL FIND_IN_SET()
    • MySQL avg()
    • MySQL MAX() Function
    • MySQL BIN()
    • MySQL Concat
    • MySQL DECODE()
    • MySQL REGEXP_REPLACE()
    • MySQL Asynchronous
    • MySQL innodb_buffer_pool_size
    • MySQL key_buffer_size
    • MySQL TRUNCATE()
    • MySQL ROW_NUMBER()
    • NOT in MySQL
    • MySQL IN Operator
    • LIKE in MySQL
    • ANY in MySQL
    • MySQL NOT IN
    • MySQL CHECK Constraint
    • MySQL DISTINCT
    • MySQL ALL
    • MySQL Union
    • MySQL UNION ALL
    • MySQL EXISTS
    • MySQL ON DELETE CASCADE
    • MySQL REGEXP
    • MySQL Index
    • MySQL Add Index
    • MySQL REINDEX
    • MySQL UNIQUE INDEX
    • MySQL Clustered Index
    • MySQL? InnoDB Cluster
    • Table in MySQL
    • ALTER TABLE MySQL
    • MySQL Temporary Table
    • MySQL Clone Table
    • MySQL Repair Table
    • MySQL Lock Table
    • MySQL Optimize Table
    • TRUNCATE TABLE MySQL
    • MySQL?Table?Size
    • MySQL Table Dump
    • MySQL Update Set
    • MySQL ALTER TABLE Add Column
    • MySQL RANK()
    • MySQL CTE
    • MySQL LAG()
    • MySQL GROUP_CONCAT()
    • MySQL EXTRACT()
    • MySQL REPLACE
    • MySQL AUTO_INCREMENT
    • MySQL SYSDATE()
    • MySQL NULLIF()
    • MySQL Substring
    • MySQL SUBSTRING_INDEX()
    • MySQL LOWERCASE
    • MySQL Row
    • MySQL NOW
    • MySQL CEIL
    • MySQL Alias
    • MySQL Trigger
    • MySQL SHOW Triggers
    • MySQL UPDATE Trigger
    • MySQL DELETE Trigger
    • MySQL AFTER UPDATE Trigger
    • MySQL Stored Procedure
    • ROLLUP in MySQL
    • MySQL? INSTR()
    • MySQL Subquery
    • MySQL Timestamp
    • MySQL? Hour()
    • MySQL MOD()
    • MySQL DATE_FORMAT()
    • ALTER Column in MySQL
    • MySQL Rename Column
    • MySQL Interval
    • MySQL CURDATE
    • MySQL BIT
    • MySQL Binlog
    • MySQL Average
    • MySQL TEXT
    • MySQL SHOW
    • MySQL Offset
    • MySQL Timezone
    • mysql_real_escape_string
    • MySQL Datetime
    • MySQL DATE_SUB()
    • MySQL FULLTEXT
    • MySQL DATE_ADD()
    • MySQL sum()
    • MySQL Merge
    • MySQL BigInt
    • MySQL ROUND
    • MySQL VARCHAR
    • MySQL Decimal
    • MySQL Limit
    • MySQL today()
    • MySQL WEEKDAY
    • MySQL Split
    • MySQL Create Function
    • MySQL BLOB
    • MySQL encode()
    • MySQL Primary Key
    • MySQL Foreign Key
    • Unique Key in MySQL
    • MySQL Drop Foreign Key
    • MySQL DROP TRIGGER
    • MYSQL Database
    • Delete Database MySQL
    • MySQL Root
    • MySQL Root Password
    • MySQL Client
    • MySQL Users
    • MySQL?User Permissions
    • MySQL add user
    • MySQL List User
    • MySQL Show Users
    • MySQL User Password
    • MySQL?Cardinality
    • MySQL Workbench
    • MySQL Backup
    • MySQL REVOKE
    • MySQL Dump
    • MySQL Cluster
    • MySQL Full Text Search
    • MySQL Admin Tool
    • MySQL Export Database
    • MySQL Export to CSV
  • Joins
    • Joins in MySQL
    • MySQL Outer Join
    • Left Outer Join in MySQL
    • MySQL Self Join
    • Natural Join in MySQL
    • MySQL DELETE JOIN
    • MySQL Update Join
    • MySQL Cross Join
  • Interview Questions
    • MySQL Interview Questions

IF Statement in MySQL

By Priya PedamkarPriya Pedamkar

IF Statement in MySQL

Introduction to IF Statement in MySQL

The “IF” statement in MySQL is a conditional statement that is used to test a condition(s) or generate a condition-based output. An IF statement is followed by only ELSEIF which is further followed by ELSE statement. The IF statement works sequentially, like, if a condition tests positive on IF itself then subsequent ELSEIF won’t execute, and if condition on ELSEIF turns out to be TRUE then subsequent ELSE will not execute. The IF statement is a type of control-flow statements. In the context of the query language, the control-flow statements assume significance as they allow checking condition for an important metric.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

The syntax of IF-ELSEIF-ELSE statement in MySQL is as follows.

IF <search_condition_1> THEN
Block of statement(s) that will execute when search_condition_1 is TRUE.
[ELSEIF <search_condition_2> THEN
Block of statement(s) that will execute when the search_condition_2 is TRUE.] [ELSE
Block of statement(s) that will execute when no condition is met.] ENDIF

Note: In the above syntax, ELSEIF and ELSE have been shown enclosed in square brackets, which means that these statements will execute only if the condition on the IF statement turns out to be FALSE.

Flow Diagram of IF-ELSEIF-ELSE in MySQL

The flow diagram for IF statement in MySQL is as shown below.

Diagram of IF-ELSEIF-ELSE in MySQL

How IF Statement Works in MySQL?

When a condition is passed in the IF statement then it evaluates if the condition is TRUE. If found TRUE then a block of statements are executed. If the condition evaluates to FALSE then it passes to ELSEIF, where evaluation for another condition happens. If satisfied, the statement of blocks under ELSEIF gets executed otherwise the statement of blocks under ELSE executes.

It must be noted that the block of statements cannot be empty as not permitted by MySQL.

Example #1

In this example, we will find the maximum of two values. For this, we will create a simple function MAXI in MySQL. The function will make use of the IF statement to generate the correct output.  The code for implementing the function has been shown below.

Code:

DELIMITER //
CREATE FUNCTION MAXI(x INT, y INT)
RETURNS VARCHAR (20)
BEGIN
DECLARE s VARCHAR (20);
IF x > y THEN SET s = 'is greater than';
ELSEIF x = y THEN SET s = 'is equal to';
ELSE SET s = 'is less than';
END IF;
SET s = CONCAT(x, ' ', s, ' ', y);
RETURN s;
END //
DELIMITER;

We evaluated the function over some random values to check each of the conditions and obtained the results as shown below.

Instance 1

SELECT MAXI (13, 5);

Output:

IF Statement in MySQL Example 1

Instance 2

SELECT MAXI (4, 6);

Output:

Instance 2 Example 1

Instance 3

SELECT MAXI (7, 7);

Output:

Instance 3 Example 1

As we can find that the code gave us the right results. Let’s see how the code works. There are two important dimensions associated with the code, first the syntax, and second is the logic. We explore the logic which is important though simple. We pass two integer values into the function. Note, the function returns string and so we used VARCHAR. Inside the function, we compare the variables, and based on the condition we assign appropriate statement to the character variable ‘s’. The conditions are checked using the IF statement. Finally, when the IF statement gets over, we concatenate variables and the statement assigned to the variable s.

We validated the result with three sample inputs, which have been shown above, and the result so obtained have been shown by the screenshots subsequent to the SELECT codes. In order to execute the function, we have to execute it with the SELECT statement.

Example #2

The example which we are going to see now demonstrates an out-of-the-box approach. We have a products table that contains various details like price, vendor, product types, product categories for various types of vehicles viz. Classic Cars, Motorcycles, Planes, Ships, Trucks and Busses, and Vintage Cars. We intend to categorize the products based on price. The categorization has to be as: Products with a price of greater than 100 would be categorized as ‘high range’, those having price greater than 50 but less than or equal to 100 would be categorized as ‘mid range’, and lastly, those with the price of less than 50 will be categorized as ‘low range’.

We don’t have Product Type as a column in the table. And so, first, we need to add it to the table. This is as demonstrated below.

ALTER TABLE products
ADD prod_type VARCHAR(20)

Let’s load the products table to check if the column has got added properly or not. The following screenshot shows this.

Output:

Product Type Example 2

As we can see above, the column prod_type has successfully got added to the table.

Now, we intend to have values in this column based on the values of the buyprice. The following code takes into consideration the categorization that we discussed earlier and employs the IF statement to categorize the product based on the buy price. Have a closer look at the code.

Code:

DELIMITER //
CREATE FUNCTION product_category(p DECIMAL)
RETURNS VARCHAR (20)
BEGIN
DECLARE product_typeVARCHAR (20);
IF p > 100 then set product_type = 'high range';
ELSEIF p > 50 then set product_type = 'mid range';
ELSE set product_type = 'low range';
END IF;
RETURN product_type;
END//
DELIMITER

Going through the code, we find that we created a function that takes a decimal variable as a parameter and essentially returns a character result. The IF code enables us to assigns suitable string value to the string variable based on the value of the parameter.

The following UPDATE statement makes use of product_category() function that we defined above.

UPDATE products
SET prod_type = product_category (buyPrice);

The above code will assign appropriate value to each of the entries of the prod_type column based on the value of buyPrice. Here, we didn’t use the WHERE clause, instead, we made use of the IF statement through the use of the function. We thus employed an out-of-the-box approach to accomplish the task.

The following screenshot shows how the above code has successfully updated the table.

Output:

IF Statement in MySQL Example 2

Conclusion

There’s no limitation as to how conditional-flow statements like IF can be employed in MySQL. The implementation of IF statement in MySQL is not as easy as it is in any programming language such as C, C++, Java, VBA, etc. This is owing to the query processing nature of MySQL.

Recommended Articles

This is a guide to IF Statement in MySQL. Here we discuss the Introduction to IF Statement in MySQL and the practical examples and different subquery expressions. You can also go through our suggested articles to learn more –

  1. Introduction to MySQL Operators
  2. Top Differences – Jira vs Github
  3. Top 23 MySQL String functions
  4. MySQL vs SQLite | Top 14 Comparisons
Popular Course in this category
MS SQL Training (16 Courses, 11+ Projects)
  16 Online Courses |  11 Hands-on Projects |  70+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Oracle Training (17 Courses, 8+ Projects)4.9
PL SQL Training (4 Courses, 2+ Projects)4.8
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more