Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Databases
  • SQL
  • MySQL
  • PostgreSQL
  • PL/SQL
  • MongoDB
  • SQL Cheat Sheet
  • SQL Interview Questions
  • MySQL Interview Questions
  • PL/SQL Interview Questions
  • Learn SQL and Database
Open In App
Next Article:
MySQL Handling NULL Values
Next article icon

MySQL Handling NULL Values

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In MySQL, NULL values represent the absence of data or a missing value. Understanding how to handle NULL values is crucial for effective database management and querying. This article will cover various aspects of working with NULL how to handle them in queries, update statements, and table definitions.

Defining NULL Values

When creating tables in MySQL we can specify whether a column allows the NULL values or not. By default, columns can contain NULL values unless specified otherwise.

In MySQL, NULL represents a missing, unknown, or undefined value. It is not equivalent to the empty string ('') or zero (0). The NULL is used to indicate the absence of any data in a field. When a field is defined as NULL which is different from having the zero or an empty string as a value.

Key Characteristics of NULL Values

  • Indeterminate Value: The NULL signifies that the value is unknown or not applicable.
  • Non-Comparable: The NULL cannot be compared using traditional operators like = or !=. Instead, special operators like IS NULL or IS NOT NULL are used.
  • Impact on Operations: The Operations involving the NULL generally result in the NULL. For example, adding the number to the NULL results in the NULL.
  • Ignored in Aggregates: The Aggregate functions typically ignore the NULL values.

Creating a Table with NULL Values

CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NULL,
salary DECIMAL(10, 2) NULL
);

Creating a Table with the NOT NULL Constraints:

CREATE TABLE employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary DECIMAL(10, 2) NOT NULL
);

Inserting NULL Values

We can insert NULL values into the columns that allow them:

INSERT INTO employees (name, salary) VALUES ('Alice', NULL);
INSERT INTO employees (name, salary) VALUES (NULL, 50000.00);

Querying NULL Values

To handle NULL values in queries we must use specific SQL functions and operators. The Standard comparison operators like = or != do not work with the NULL.

Checking for NULL Values

To check if a column is NULL use the IS NULL or IS NOT NULL operators.

SELECT * FROM employees WHERE salary IS NULL;
SELECT * FROM employees WHERE name IS NOT NULL;

Output:

IMAGE_1
Output

Using COALESCE to Handle NULL Values

The COALESCE function returns the first non-NULL value in the list of the arguments.

SELECT name, COALESCE(salary, 0) AS salary FROM employees;

Output:

Output
Output

Updating NULL Values

When updating records we can set columns to NULL explicitly.

UPDATE employees SET salary = NULL WHERE name = 'Alice';

Handling NULL Values in Aggregations

The Functions like COUNT(), SUM(), AVG() etc. handle NULL values in specific ways:

  • COUNT(column_name) counts the number of the non-NULL values in the column.
  • SUM(column_name) ignores NULL values in the summation.
  • AVG(column_name) calculates the average of the non-NULL values.

Example:

SELECT COUNT(salary) AS count_salary, SUM(salary) AS total_salary, AVG(salary) AS average_salary FROM employees;
Output
Output

Using Default Values

We can specify default values for the columns that are set when NULL values are inserted.

CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
price DECIMAL(10, 2) DEFAULT 0.00
);
INSERT INTO products (name) VALUES ('Laptop');

In this example, if the price is not provided it will default to the 0.00.

NULL Values and Indexes

The NULL values can affect the indexing and query performance. Be mindful of how NULL values impact index creation and optimization.

Creating an Index with NULL Values

CREATE INDEX idx_salary ON employees(salary);

The Indexes will include NULL values which can affect query performance.

Examples of MySQL Handling NULL Values

Example 1: Handling NULL in SELECT Queries

Scenario: The Retrieve employees with known and unknown salaries.

SELECT name, COALESCE(salary, 'Not Provided') AS salary_status FROM employees;

Output:

IMAGE_1
Output

Example 2: Using NULL in Aggregations

Scenario: The Calculate total and average salary excluding NULL values.

SELECT SUM(salary) AS total_salary, AVG(salary) AS average_salary FROM employees;

Output:

IMAGE_1
Output

Conclusion

The Handling NULL values in MySQL is essential for the maintaining data integrity and ensuring accurate query results. By understanding how to define, insert, query and manage NULL values we can effectively manage the database and make informed decisions based on the data.


Next Article
MySQL Handling NULL Values

V

vinod19ldr
Improve
Article Tags :
  • Databases
  • MySQL

Similar Reads

    Foreign Key with a Null Value in MySQL
    In databases, foreign keys are like links connecting two tables. They make sure that data in one table matches data in another. But a common question is whether a foreign key can be NULL. In this article, We will explain what NULL values mean for foreign keys, how they work with the help of examples
    5 min read
    NULL values in SQL
    In SQL, some records in a table may not have values for every field, and such fields are termed as NULL values. These occur when data is unavailable during entry or when the attribute does not apply to a specific record. To handle such scenarios, SQL provides a special placeholder value called NULL
    4 min read
    How to Update NULL Values in a Field in MySQL
    There is a situation where we need to update certain columns with NULL values in a MySQL database, you're in the right place. It's a common task when you're working with databases and dealing with incomplete or undefined data. In this article, we'll walk through the process, break down the syntax, a
    3 min read
    MySQL IS NULL Operator
    The IS NULL operator in MySQL is a powerful tool for handling records with missing or incomplete data. It enables precise querying and data management by allowing users to identify and act upon fields where values are absent.In this article, We will learn about the MySQL IS NULL Operator by understa
    3 min read
    MySQL NOT NULL Constraint
    In the database management system maintaining data reliability and data accuracy is very important. MySQL is a popular relational database management system, which offers various constraints to provide security and ensure the integrity of the stored data. There are various key constraints present in
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences