EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials MySQL Tutorial MySQL NULLIF()
Secondary Sidebar
MySQL Tutorial
  • 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
  • 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
  • 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
  • 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
  • Interview Questions
    • MySQL Interview Questions

MySQL NULLIF()

By Aanchal SharmaAanchal Sharma

MySQL NULLIF()

Introduction to MySQL NULLIF() Function

MySQL NULLIF() function is defined as a part of flow control MySQL function which is responsible to compare two expressions, that it accepts as arguments to execute the query. Generally, NULLIF() is helpful to avoid the division by zero faults that may occur in MySQL statement during implementation. The MySQL NULLIF() function takes two expressional parameters and performs the comparison similar to CASE statement.If both the expressions passed are equal on execution then, the result will be NULL otherwise the function returns the initial expression as output value if the condition fails. The NULLIF() accepts the expressions as arguments and compares them to return NULLif they are equivalent logically.

Syntax

Here is the elementary syntax code to apply the NULLIF() function in MySQL:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

NULLIF(Expr_1, Expr_2)

The arguments provided above for the function NULLIF() are required terminologies command code to be matched where Expr_1 denotes the first expression and Expr_2 is the second expression for the NULLIF() function in MySQL.

The return value of the NULLIF() function is NULL when both terms are equivalent else, it will display the first parameter specified in the function.

Also, NULLIF() can be explained as identical one to CASE statement which generates the following expression query:

CASE WHEN Expr_1 = Expr_2
THEN NULL
ELSE EXPR_1
END;

Explanation: We should be aware not to get confused with the MySQL NULLIF() function is the same as the IFNULL() function because both functions are slightly different. We use the SELECT statement together with NULLIF() function while writing the query command in MySQL.

How MySQL NULLIF() Function work?

To understand how the MySQL NULLIF() function works:

Step 1:

SELECT NULLIF(2,2);

MySQL NULLIF()1

Explanation: NULLIF(2,2) results NULL as 2 = 2

Step 2:

SELECT NULLIF(3,1);

MySQL NULLIF()2

Explanation: NULLIF(3,1) results in 3 that is the first argument as 3 is not equal to 1

Step 3:

SELECT NULLIF('Education', 'Education');

MySQL NULLIF()3

Explanation: NULLIF(‘Education’, ‘Education’) results NULL as both the expressional string values are same

Step 4:

SELECT NULLIF('Education', 'Educate');

MySQL NULLIF()4

Explanation: NULLIF(‘Education’, ‘Educate’) results in Education as the expressional string values are not identical

Step 5:

SELECT NULLIF(2,NULL);

MySQL NULLIF()5

Explanation: NULLIF(2, NULL) results in 2 as both the expressions are not similar

Step 6:

SELECT NULLIF(NULL,3);

expressions are not similar

Explanation: NULLIF(NULL,3) results NULL as it is the first expressional term and as NULL and 3 are not equal

Examples to Implement NULLIF() function in MySQL

Below are some example of NULLIF() function:

1. Using NULLIF() function with Table Column values in the Database

Let us suppose table by the name ‘Employees’to be created to implement some examples using the table records with NULLIF() function in MYSQL. For this we will write code and then execute on the database having field names and data types:

CREATE TABLE Employees (EmpID INT PRIMARY KEY AUTO_INCREMENT, EmpNameVarchar(255) NOT NULL, EmpProfileVarchar(255) NOT NULL, EmpSalary INT NOT NULL, EmpPF INT);

Also, we need to input some records in the table to perform the NULLIF() query command completion within the field data. Let us query the following statements to process some entries into the Employees table:

Code:

INSERT INTO Employees(EmpID, EmpName,EmpProfile,mpSalary,EmpPF)
VALUES('210', 'Radha ', 'Engineer ', '50000 ', '3600 ');
INSERT INTO Employees (EmpID, EmpName,EmpProfile,mpSalary,EmpPF)
VALUES('211', 'Mohan ', 'Manager ', '40000 ', '2000 ');
INSERT INTO Employees (EmpID, EmpName,EmpProfile,mpSalary,EmpPF)
VALUES('212', 'Dev ', 'Executive ', '32000 ', '1800 ');
INSERT INTO Employees (EmpID, EmpName,EmpProfile,mpSalary,EmpPF)
VALUES('213', 'Madhuri ', 'Blogger ', '20000 ', '');
INSERT INTO Employees (EmpID, EmpName,EmpProfile,mpSalary,EmpPF)
VALUES('214', 'Rita ', 'Pilot ', '48000', '5000 ');

After running these queries, the values will be inserted as rows in the table Employees. We can display the records from the table Employees using the below command in the MySQL:

Output:

records

It will provide the above details filled in the table as a view of the table.

Now, we will use the NULLIF() function on the column values to check the expressions passed as arguments to the function and compare them to provide the desired result and explain the usage of NULLIF() function with the database rows.

We have written the following query to represent the NULLIF() function in a query:

Code:

SELECT EmpName, EmpProfile, EmpSalary,
NULLIF(EmpProfile, 'Engineer') NULLIF_Result FROM Employees;

Output:

usage

Explanation: When we run the above query, it will execute successfully and then, will return the result as shown in the screenshot overhead. The result of the MySQL NULLIF() function checks the column value of EmpProfile as the first argument with the second argument set as Engineer. When the comparison starts on query execution, the Employee profile values are matched against the Engineer value respectively and generates the result as NULL if the values are equivalent otherwise returns the column value if the match does not occur as the NULLIF() function returns first parameter value in the output if the function arguments are not equal. Take to be noted that MySQL will evaluate the first expression value twice with the second one if the matching of the two parameters does not show the valid results or if they are not equivalent.

2. Using NULLIF() function to avoid division by zero error

In a MySQL query, we often practice the use of the NULLIF() function to stop the division by zero faults. If your MySQL server has enabled ERROR_FOR_DIVISION_BY_ZERO mode, then when a division by zero happens it will give an error at execution.

Consider the SQL statement below to show the error occurs:

SELECT  1/0;

As you can see that the query produces an error. For this, we need to use NULLIF() function to remove this division by zero error. The updated query is as follows:

Code:

SELECT 1/NULLIF(0,0);

Output:

avoid division by zero error

Explanation: This is because the NULLIF() function will return NULL value as (0 = 0) zero is equivalent to zero provided in the arguments which will result in NULL and then 1 is divided b NULL, therefore the result of the query above will also be NULL.

Conclusion

With NULLIF() function we got introduced to a MySQL flow control function that is very handy in cases where we require to prevent division by zero error in the respective queries that are executed on the server. The function takes two parameters and after comparing the expressions it provides the results, if the terms are equal then NULL else shows the first term as an output on execution.

Recommended Articles

This is a guide to MySQL NULLIF(). Here we discuss an introduction to MySQL NULLIF(), syntax, how does it work, examples with code and output. You can also go through our other related articles to learn more –

  1. Unique Key in MySQL
  2. IF Statement in MySQL
  3. MySQL Aggregate Function
  4. ANY in MySQL
Popular Course in this category
MySQL Training Program (12 Courses, 10 Projects)
  12 Online Courses |  10 Hands-on Projects |  92+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

MS SQL Training (16 Courses, 11+ Projects)4.9
Oracle Training (17 Courses, 8+ Projects)4.8
PL SQL Training (4 Courses, 2+ Projects)4.7
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
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*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

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