MySQL NULL Explained: Meaning, Queries, Functions, Indexing, Sorting, and Best Practices

目次

1. Introduction

MySQL is a database management system used in many applications and systems. Within MySQL, the concept of NULL is one of the topics that can be difficult for beginners to understand. Accurately understanding what NULL is and how to handle it is extremely important when working with MySQL.

In this article, we provide a comprehensive explanation—from the basic definition of NULL in MySQL to how to manipulate it, how to search with it, useful functions related to NULL, and important points to watch out for. We also include an FAQ section that answers common questions about NULL.

This article is intended for readers such as:

  • Beginners using MySQL for the first time
  • Intermediate learners who understand basic SQL and want to learn more deeply
  • Engineers involved in database design and operations

By the end of this article, you will be able to:

  • Correctly understand what NULL is
  • Manipulate and search data that includes NULL
  • Learn best practices to avoid NULL-related trouble

Now, let’s walk through the fundamentals of NULL step by step.

2. NULL Basics

When working with databases, the concept of NULL is extremely important. However, NULL is also one of the most commonly misunderstood elements. In this section, we explain the basic definition and properties of NULL in detail.

Definition of NULL

NULL represents a special state that means “no value exists” or “an unknown value.” This is different from an empty string (“”) or zero (0). Here is an example showing the differences:

  • NULL: No value exists (an undefined state)
  • Empty string (“”): A value exists, but its contents are empty
  • Zero (0): A value exists, and that value is 0

Properties of NULL

  1. How NULL behaves in comparisons
    In SQL, NULL is handled with special rules. For example, note the results of these comparisons:
   SELECT NULL = NULL; -- Result: NULL
   SELECT NULL <> NULL; -- Result: NULL
   SELECT NULL IS NULL; -- Result: TRUE
  • Comparing NULL with normal comparison operators (=, <, >, etc.) results in NULL.
  • To evaluate NULL correctly, you must use IS NULL or IS NOT NULL.
  1. NULL in arithmetic operations
    Any arithmetic operation that includes NULL always returns NULL.
    Example:
   SELECT 10 + NULL; -- Result: NULL
   SELECT NULL * 5; -- Result: NULL
  1. Logical operations with NULL
    When a condition includes NULL, the result can also become NULL. See the examples below:
   SELECT NULL AND TRUE; -- Result: NULL
   SELECT NULL OR FALSE; -- Result: NULL

Why NULL causes trouble

If you don’t handle NULL properly, you may run into issues such as:

  • Unexpected search results
    For example, the following query excludes rows where age is NULL.
  SELECT * FROM users WHERE age > 20;

As a solution, you need to include NULL in the condition:

  SELECT * FROM users WHERE age > 20 OR age IS NULL;
  • Calculation mistakes and misunderstanding blank data
    Aggregate functions (SUM, AVG, etc.) ignore NULL when calculating. As a result, datasets with many NULL values can produce unintended results.

Summary of basic NULL rules

  • NULL represents a state where “no value exists.”
  • Because normal comparison operators do not handle NULL properly, use IS NULL or IS NOT NULL.
  • If NULL is included in arithmetic or logical operations, the result also becomes NULL.

3. How to Manipulate NULL

When working with NULL in MySQL, you need to understand the correct ways to handle it. In this section, we explain specific methods for inserting, updating, and deleting NULL in detail.

How to set NULL when inserting data

When inserting a new record into a database, you can set a column to NULL. Below are concrete examples.

  • Explicitly specify NULL
  INSERT INTO users (name, age) VALUES ('Taro', NULL);

In this query, the age column is not given a value, and NULL is inserted.

  • NULL as the default value
    If NULL is configured as the default value, omitting the value will automatically insert NULL.
  CREATE TABLE users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(50),
      age INT DEFAULT NULL
  );

  INSERT INTO users (name) VALUES ('Hanako');

In this example, since no explicit value is provided for the age column, the default NULL is inserted.

How to set NULL when updating data

You can also update existing data to set a column value to NULL. Here are examples.

  • Update a value to NULL
  UPDATE users SET age = NULL WHERE name = 'Taro';

This query sets the age column to NULL for the record whose name is “Taro”.

  • Conditional updates
    You can add conditions to set NULL in specific situations.
  UPDATE users SET age = NULL WHERE age < 18;

Here, the age column is set to NULL for all records where the age is less than 18.

How to use NULL as a condition when deleting data

When deleting data that includes NULL, you must include NULL in the condition. Use IS NULL, not a comparison operator.

  • Delete rows where a column is NULL
  DELETE FROM users WHERE age IS NULL;

This query deletes records where the age column is NULL.

  • Delete NULL rows with multiple conditions
  DELETE FROM users WHERE age IS NULL AND name = 'Taro';

In this example, only records where age is NULL and name is “Taro” are deleted.

Important notes when manipulating NULL

  1. Use IS NULL correctly
    When using NULL in a condition, always use IS NULL or IS NOT NULL, not the = operator.
   SELECT * FROM users WHERE age = NULL; -- Incorrect
   SELECT * FROM users WHERE age IS NULL; -- Correct
  1. Design your application with NULL handling in mind
    When manipulating data from an application, being careful about how you handle NULL helps prevent unintended behavior.
  2. Use transactions
    For data operations involving NULL, consider using transactions to avoid unintended data changes.

4. Searching Data That Includes NULL

When searching data in MySQL, handling NULL correctly is extremely important. Because NULL behaves differently from normal values, it requires special care. In this section, we explain how to search efficiently when NULL is involved.

Basic ways to search for NULL

To search for NULL, use IS NULL and IS NOT NULL rather than normal comparison operators (=, <, >).

  • Search for NULL
  SELECT * FROM users WHERE age IS NULL;

This query retrieves all records where the age column is NULL.

  • Search for non-NULL values
  SELECT * FROM users WHERE age IS NOT NULL;

This query retrieves all records where the age column is not NULL.

Searching with complex conditions that include NULL

Because NULL cannot be handled correctly with comparison operators, take care when using it in complex conditions.

  • Including NULL in a condition
  SELECT * FROM users WHERE age > 20 OR age IS NULL;

This query retrieves records where age is greater than 20 or is NULL.

  • NOT operator and NULL
  SELECT * FROM users WHERE NOT (age > 20 OR age IS NULL);

This query retrieves records where age is 20 or less and is not NULL.

Using NULL with the LIKE operator

The LIKE operator cannot be used against NULL. Because NULL means no value exists, the following query does not return NULL rows:

SELECT * FROM users WHERE name LIKE '%a%';
-- NULL values are not matched by this condition

Instead, you need to add a NULL check:

SELECT * FROM users WHERE name LIKE '%a%' OR name IS NULL;

Aggregate functions and searching with NULL

NULL is ignored by many aggregate functions (SUM, AVG, etc.). To get correct results, you need to account for NULL.

  • COUNT function
  SELECT COUNT(*) AS total_records, COUNT(age) AS non_null_ages FROM users;
  • COUNT(*): Counts all records, including those with NULL
  • COUNT(column): Counts records excluding NULL
  • Other aggregate functions
  SELECT AVG(age) AS average_age FROM users WHERE age IS NOT NULL;

This calculates the average excluding NULL values.

Notes when searching for NULL

  1. Difference between IS NULL and =
    Because NULL cannot be handled by normal comparisons, always use IS NULL or IS NOT NULL.
   SELECT * FROM users WHERE age = NULL; -- Incorrect
   SELECT * FROM users WHERE age IS NULL; -- Correct
  1. Handling multiple conditions
    If NULL may be present, you must explicitly include it in the condition to avoid unintended results.
   SELECT * FROM users WHERE age > 20; -- NULL is excluded
   SELECT * FROM users WHERE age > 20 OR age IS NULL; -- Includes NULL
  1. Performance impact
    When including NULL in conditions, index usage may be limited in some cases. We recommend verifying index effectiveness.
EXPLAIN SELECT * FROM users WHERE age IS NULL;

Summary

Searching for NULL correctly is essential to getting the intended results. When searching data that includes NULL, use IS NULL and IS NOT NULL appropriately, and consider performance and indexing impacts.

5. NULL, Indexes, and Performance

To optimize database performance, proper use of indexes is essential. However, operations on columns that contain NULL can affect index efficiency. In this section, we explain the relationship between NULL and indexes, their performance impact, and optimization strategies.

Creating indexes on columns that include NULL

In MySQL, you can create indexes on columns that contain NULL. For example:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50),
    age INT,
    INDEX (age)
);

In this case, the index on the age column is valid even if the column contains NULL values.

Using indexes with IS NULL and IS NOT NULL

When searching with conditions that include NULL, the index may or may not be used depending on the query.

  • When the index is used
  SELECT * FROM users WHERE age IS NULL;

In this query, the index can be used, allowing efficient searching.

  • When the index is not used
    If you use complex conditions like the following, the index may not be applied.
  SELECT * FROM users WHERE age + 1 IS NULL;

Whether an index is used depends on the structure of the query condition.

NULL and composite indexes

Even when using composite indexes, columns containing NULL receive special handling.

  • Example of a composite index
  CREATE TABLE employees (
      id INT AUTO_INCREMENT PRIMARY KEY,
      department_id INT,
      salary INT,
      INDEX (department_id, salary)
  );

If department_id is NULL, part of the composite index (department_id, salary) may not be fully utilized.

Performance impact of NULL

  1. Index effectiveness
  • Searches that include NULL conditions often still benefit from indexes. However, if the condition becomes complex, index usage may be limited.
  1. Large volumes of data
  • If many NULL values exist in an indexed column, the index size may increase and potentially reduce query performance.
  1. Design strategies to avoid excessive NULL
  • For columns that frequently contain NULL, defining a default value to reduce NULL usage may improve performance in some cases.

Performance optimization tips

  • Verify index usage
    Use EXPLAIN to check whether an index is being applied:
  EXPLAIN SELECT * FROM users WHERE age IS NULL;
  • Design to minimize NULL
    Apply NOT NULL constraints and default values to avoid NULL in your schema:
  CREATE TABLE users (
      id INT AUTO_INCREMENT PRIMARY KEY,
      age INT NOT NULL DEFAULT 0
  );
  • Re-evaluate indexes
    Depending on data volume and query patterns, consider adding or removing indexes to optimize performance.

Summary

NULL can coexist with indexes, but under certain conditions it may affect performance. By designing appropriate indexing strategies and defining a clear policy for NULL usage, you can achieve efficient database operations.

6. NULL and Sorting

When sorting data in MySQL, understanding how NULL is handled is important. Because NULL behaves differently from normal values, knowing the default sort order and how to customize it helps you achieve the intended results. In this section, we explain the basic rules and advanced techniques for sorting with NULL.

Default sort order of NULL

In MySQL, NULL is handled as follows:

  • Ascending (ASC): NULL values appear first.
  • Descending (DESC): NULL values appear last.

Example:

SELECT * FROM users ORDER BY age ASC;
-- NULL appears first

SELECT * FROM users ORDER BY age DESC;
-- NULL appears last

Controlling the position of NULL explicitly

You can override the default sort behavior to force NULL values to appear first or last.

  • Place NULL values first
  SELECT * FROM users ORDER BY age IS NULL DESC, age ASC;

In this query, rows where age is NULL appear first, followed by non-NULL rows sorted in ascending order.

  • Place NULL values last
  SELECT * FROM users ORDER BY age IS NULL ASC, age ASC;

Here, non-NULL values appear first, and NULL values are placed at the end.

Sorting by multiple columns with NULL

When sorting by multiple columns, you can specify NULL handling per column.

  • Example with multiple conditions
  SELECT * FROM users ORDER BY department_id ASC, age IS NULL DESC, age ASC;

This query sorts data in the following order:

  1. department_id in ascending order
  2. Rows where age is NULL
  3. Non-NULL age values in ascending order

Sorting performance and NULL

When sorting on a column that contains NULL, whether an index is used depends on the query structure. If the index is not used, sorting may take more time.

  • Check index usage
  EXPLAIN SELECT * FROM users ORDER BY age ASC;

Use EXPLAIN to verify whether the index is applied.

Important notes when sorting

  1. Consider column data types
  • If a column containing NULL has an inappropriate data type, unexpected results may occur. Pay special attention to differences between numeric and string types.
  1. Clarify sorting conditions
  • To make query results explicit, use IS NULL or IS NOT NULL when handling NULL intentionally.
SELECT * FROM users WHERE age IS NULL ORDER BY age DESC;

Summary

By default, NULL appears first in ascending order and last in descending order. However, you can customize the query to control the position of NULL values. By specifying appropriate conditions, you can achieve the intended sort order.

7. Useful Functions for Handling NULL

MySQL provides several convenient functions for handling NULL efficiently. By using these functions, you can write cleaner queries and process data more effectively when NULL values are involved. In this section, we explain the most commonly used functions and how to use them.

COALESCE Function

COALESCE returns the first non-NULL value from the specified arguments. It is useful when you want to replace NULL with a default value.

  • Basic syntax
  COALESCE(value1, value2, ..., valueN)
  • Example
  SELECT COALESCE(age, 0) AS adjusted_age FROM users;

In this query, if age is NULL, it returns 0; otherwise, it returns the value of age.

  • Example with multiple arguments
  SELECT COALESCE(NULL, NULL, 'Default Value', 'Other Value') AS result;

The result will be “Default Value”.

IFNULL Function

IFNULL returns a specified value if the expression is NULL. It is similar to COALESCE but limited to two arguments.

  • Basic syntax
  IFNULL(expression, alternate_value)
  • Example
  SELECT IFNULL(age, 0) AS adjusted_age FROM users;

If age is NULL, this returns 0.

  • Difference from COALESCE
  • IFNULL accepts only two arguments, while COALESCE can accept multiple arguments.

NULL-Safe Equal Operator (<=>)

The <=> operator allows safe comparison of NULL values. Using this operator makes it possible to compare NULL values directly.

  • Example
  SELECT * FROM users WHERE age <=> NULL;

This query accurately retrieves records where age is NULL.

  • Difference from the normal equality operator (=)
  • With the = operator, NULL = NULL returns NULL, but with <=>, it returns TRUE.

ISNULL Function

ISNULL checks whether a value is NULL. Although IS NULL and IS NOT NULL are usually sufficient, ISNULL is useful when you need a function-based check.

  • Basic syntax
  ISNULL(expression)
  • Example
  SELECT ISNULL(age) AS is_null FROM users;

If age is NULL, it returns 1; otherwise, it returns 0.

NULLIF Function

NULLIF returns NULL if the two arguments are equal; otherwise, it returns the first argument.

  • Basic syntax
  NULLIF(expression1, expression2)
  • Example
  SELECT NULLIF(salary, 0) AS adjusted_salary FROM employees;

If salary is 0, it returns NULL; otherwise, it returns the value of salary.

How to choose the right NULL function

  • To set a default value: Use COALESCE or IFNULL
  • To compare NULL safely: Use the <=> operator
  • To explicitly check for NULL: Use ISNULL or IS NULL
  • To return NULL under specific conditions: Use NULLIF

Summary

MySQL provides a rich set of functions for handling NULL. By choosing the appropriate function, you can write simpler and more efficient queries. Use these functions to optimize how your application handles NULL values.

8. Best Practices for Handling NULL

NULL plays an important role in database operations, but due to its unique characteristics, it can also cause confusion and trouble. By handling NULL correctly, you can maintain data integrity and ensure efficient operation. In this section, we explain best practices for working with NULL.

Handling NULL in database design

  1. Deciding whether to allow NULL
  • NULL represents “no value exists,” but not every column should allow NULL.
  • Examples:
    • Required fields (e.g., username, email address) should have a NOT NULL constraint.
    • Fields that may legitimately have no value (e.g., intermediate score, optional settings) may allow NULL.
   CREATE TABLE users (
       id INT AUTO_INCREMENT PRIMARY KEY,
       name VARCHAR(50) NOT NULL,
       email VARCHAR(100) NOT NULL,
       age INT NULL
   );
  1. Setting default values
  • To minimize NULL usage, define appropriate default values where possible.
   CREATE TABLE orders (
       id INT AUTO_INCREMENT PRIMARY KEY,
       status VARCHAR(20) NOT NULL DEFAULT 'pending'
   );

Managing NULL in the application layer

  1. Validate input data
  • When users submit data through forms, verify that required fields are filled.
  • Add server-side validation to prevent unintended NULL values from being inserted into the database.
  1. Standardize NULL handling
  • Ensure consistent handling of NULL throughout the application codebase.
  • Example: Provide a helper function to convert NULL to a default value.
   def handle_null(value, default):
       return value if value is not None else default

Important considerations when writing queries

  1. Safe NULL comparisons
  • Always use IS NULL or IS NOT NULL when comparing NULL.
   SELECT * FROM users WHERE age IS NULL;
  1. Handling NULL in complex conditions
  • When writing queries with multiple conditions, explicitly account for NULL.
   SELECT * FROM users WHERE age > 20 OR age IS NULL;
  1. Considering NULL in aggregate results
  • Aggregate functions (SUM, AVG, etc.) ignore NULL values. If you need to check how many NULL values exist, add explicit conditions.
   SELECT COUNT(*) AS total_records, COUNT(age) AS non_null_records FROM users;

Improving performance and readability

  1. Indexes and NULL
  • If using indexes on columns that contain many NULL values, verify index efficiency.
  • Rebuild or adjust indexes when necessary.
  1. Minimizing NULL
  • Reducing unnecessary NULL usage during the design phase improves database readability and performance.
  • Use default values or flags instead of relying heavily on NULL.
   CREATE TABLE users (
       id INT AUTO_INCREMENT PRIMARY KEY,
       age INT NOT NULL DEFAULT 0
   );

Common real-world issues and solutions

  1. Issue: Unexpected search results due to NULL
  • Solution: Properly use IS NULL or IS NOT NULL in queries.
   SELECT * FROM users WHERE name = 'Taro' OR name IS NULL;
  1. Issue: Unexpected behavior in aggregate functions
  • Solution: Add conditions to exclude or explicitly handle NULL.
   SELECT COUNT(age) FROM users WHERE age IS NOT NULL;
  1. Issue: NULL and data integrity
  • Solution: Enforce NOT NULL constraints at the database level and validate input at the application level.

Summary

NULL is a powerful concept, but if not handled properly, it can lead to problems. By defining a clear policy during database design and maintaining consistent handling in your application, you can minimize NULL-related issues.

9. Frequently Asked Questions (FAQ)

When learning about NULL in MySQL, both beginners and intermediate users often have similar questions. In this section, we summarize frequently asked questions and their answers regarding NULL.

Q1: What is the difference between NULL, an empty string (“”), and zero (0)?

  • A1:
  • NULL: Indicates that no value exists (undefined).
  • Empty string (“”): A value exists, but its content is empty.
  • Zero (0): A value exists, and its numeric value is 0.
  • Example:
    INSERT INTO users (name, age) VALUES ('Taro', NULL); -- age is NULL INSERT INTO users (name, age) VALUES ('Hanako', ''); -- age is an empty string INSERT INTO users (name, age) VALUES ('Jiro', 0); -- age is zero

Q2: Why does NULL = NULL not return TRUE?

  • A2:
  • According to SQL specifications, NULL represents an “unknown value.” Comparing unknown values results in an undefined outcome (NULL), not TRUE or FALSE.
  • When comparing NULL, you must use IS NULL or IS NOT NULL.
  • Example:
    SELECT NULL = NULL; -- Result: NULL SELECT NULL IS NULL; -- Result: TRUE

Q3: What should I be careful about when searching data that includes NULL?

  • A3:
  • If you use comparison operators (=, <, >, etc.) with NULL, you will not get the expected results. Use IS NULL or IS NOT NULL instead.
  • Example:
    SELECT * FROM users WHERE age = NULL; -- Incorrect SELECT * FROM users WHERE age IS NULL; -- Correct

Q4: Are there any considerations regarding NULL and indexes?

  • A4:
  • You can create indexes on columns that contain NULL, but index efficiency depends on the query conditions.
  • In particular, complex conditions (e.g., those including calculations) may prevent index usage.
  • How to check index usage:
    EXPLAIN SELECT * FROM users WHERE age IS NULL;

Q5: What is the difference between COALESCE and IFNULL?

  • A5:
  • COALESCE: Accepts multiple arguments and returns the first non-NULL value.
  • IFNULL: Accepts two arguments and returns the second if the first is NULL.
  • Example:
    SELECT COALESCE(NULL, NULL, 'Default Value', 'Other Value'); -- Result: 'Default Value' SELECT IFNULL(NULL, 'Default'); -- Result: 'Default'

Q6: How can I design my database to avoid NULL?

  • A6:
  • NOT NULL constraints: Add constraints to required fields to prevent NULL.
  • Default values: Use default values instead of NULL where appropriate.
  • Example:
    CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, age INT NOT NULL DEFAULT 0 );

Q7: Do aggregate functions behave differently with NULL?

  • A7:
  • Aggregate functions (SUM, AVG, COUNT, etc.) ignore NULL values. However, if you want to check how many NULL values exist, you need to add explicit conditions.
  • Example:
    SELECT COUNT(*) AS total_records, COUNT(age) AS non_null_ages FROM users;

Q8: Can NULL cause issues in JOIN operations?

  • A8:
  • When performing JOIN operations on columns that contain NULL, NULL values are treated as non-matching. As a result, you may not get the expected results.
  • Solution: Write queries that explicitly account for NULL or use the COALESCE function to replace NULL with a default value.
  SELECT *
  FROM table1 t1
  LEFT JOIN table2 t2 ON COALESCE(t1.key, 0) = COALESCE(t2.key, 0);

Summary

NULL is a value that requires special handling in MySQL database operations. Use this FAQ section as a reference to deepen your understanding of NULL and learn how to handle it effectively.

10. Conclusion

Understanding how to handle NULL in MySQL is an essential skill in database design and operations. In this article, we covered everything from the basic definition of NULL to manipulation methods, searching, sorting, indexing, useful functions, and best practices.

Key Takeaways

  1. NULL basics and characteristics
  • NULL represents “no value exists” or an “unknown value,” and it is different from an empty string (“”) or zero (0).
  • Use IS NULL and IS NOT NULL for safe comparisons involving NULL.
  1. Working with and searching NULL data
  • You learned how to correctly insert, update, delete, and search data that includes NULL.
  • Using syntax and functions such as IS NULL and COALESCE allows flexible and efficient operations.
  1. NULL and performance
  • We discussed the impact of indexes on columns containing NULL and design strategies to optimize performance.
  • Setting default values when appropriate can help minimize excessive NULL usage.
  1. Convenient NULL functions
  • Functions such as COALESCE, IFNULL, and NULLIF help solve common NULL-related problems.
  • Use the <=> operator for safe comparisons to prevent unintended behavior.
  1. Best practices
  • Minimize unnecessary NULL usage in database design and apply proper validation in the application layer to maintain data integrity.
  • Standardizing NULL handling in SQL queries improves readability and maintainability.

Benefits of Understanding NULL

  • Efficient data operations: Correct handling of NULL prevents unnecessary errors and enables efficient query writing.
  • Improved data integrity: Defining a clear policy for NULL usage during database design leads to more consistent data management.
  • Increased application reliability: Properly handling NULL in the application layer prevents unexpected behavior and bugs.

Next Steps

To deepen your understanding of NULL, consider the following:

  • Review how NULL is used in your current projects and identify areas for improvement.
  • Experiment with functions and operators such as IS NULL, COALESCE, and IFNULL using real datasets.
  • Further tune indexes and performance strategies based on your workload.

By studying this article, you should now have a solid understanding of how NULL works in MySQL and how to handle it in practice. Use this knowledge to improve your database operations and application development workflows.