Open In App

SQL - SELECT NULL

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In SQL, the term NULL represents a missing or undefined value in a table. A NULL value is different from a zero or an empty string; it signifies that no data exists for that field. Understanding how to work with NULL values is crucial for accurate data retrieval and manipulation.

In this article, we will cover the basics of handling NULL values in SQL, along with detailed explanations and practical examples.

What is a NULL Value in SQL?

A NULL value in SQL indicates that a field has no value. It is not equivalent to a zero or a blank space. Columns in a table can have NULL values when no data is explicitly provided during the record creation process.

  • NULL values are placeholders for missing information.
  • NULL is not equal to zero or an empty string.
  • Queries must use specific conditions to handle NULL values effectively.
  • Handling NULL Values in SQL

Handling NULL Values in SQL

There are two primary conditions for working with NULL values. We will use the given department table for working on these two Conditions.

department-table
department table

1. Selecting Rows Where a Column is NULL

Retrieve rows from the department table where the salary column has NULL values. To fetch rows where a specific column contains NULL values, use the IS NULL condition

Syntax:

SELECT * FROM TABLANAME WHERE COLUMNNAME IS NULL;

Query:

SELECT * FROM department WHERE salary IS NULL;

Output

Selecting-Rows-where-Column-is-NULL
Where Column is NULL

Explanation:

  • The IS NULL condition checks for fields where the salary column has no value.
  • Rows matching this condition are returned.

2. Selecting Rows Where a Column is NOT NULL

Retrieve rows from the department table where the salary column has non-NULL values. To fetch rows where a specific column contains non-NULL values, use the IS NOT NULL condition.

NOT NULL denotes that the column must always consider an explicit value of the specified data type. We did not use NOT NULL in two columns, which means these columns may be NULL.  A field with a NULL value was left blank during the record creation process.

Syntax:

SELECT *
FROM TABLANAME
WHERE COLUMNNAME IS NOT NULL;

Query:

SELECT * FROM department WHERE salary IS NOT NULL;

Output

Where-Column-is-NOT-NULL
Where Column is NOT NULL

Explanation:

  • The IS NOT NULL condition filters out rows with NULL values in the salary column.
  • Only rows with valid (non-NULL) data in the column are returned.

Conclusion

Handling NULL values in SQL is essential for accurate data querying and database integrity. Using conditions like IS NULL and IS NOT NULL, along with constraints such as NOT NULL, ensures that we can effectively manage missing data. By mastering these techniques, we can write more robust and reliable SQL queries that handle NULL values efficiently.


Next Article
Article Tags :

Similar Reads