SQL ISNULL
The SQL ISNULL function is used to handle NULL values in a database. It allows users to replace NULL with a specified default value in query results, ensuring that missing or undefined data does not cause issues in calculations or display.
In this tutorial, we will explore the ISNULL function in SQL, its syntax, and how to use it effectively with real-world examples.
Syntax of SQL ISNULL Function
The basic syntax of the SQL ISNULL function is:
</>
Copy
SELECT ISNULL(column_name, replacement_value)
FROM table_name;
Explanation:
- column_name: The column to check for NULL values.
- replacement_value: The value that replaces NULL in the result.
Step-by-Step Examples Using SQL ISNULL
1 Handling NULL Values in a Query
Let’s create a students table to demonstrate the use of ISNULL:
</>
Copy
CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT,
marks INT
);
Insert some sample data:
</>
Copy
INSERT INTO students (name, age, marks)
VALUES
('Arjun', 16, 85),
('Ram', 17, NULL),
('Priya', 16, 90);
Now, let’s use ISNULL to replace NULL values in the marks column with a default value of 0:
</>
Copy
SELECT name, age, ISNULL(marks, 0) AS marks
FROM students;
