⬅ Previous Topic
SQL Functions – String, Numeric, Date & AggregateNext Topic ⮕
SQL Stored Procedures⬅ Previous Topic
SQL Functions – String, Numeric, Date & AggregateNext Topic ⮕
SQL Stored ProceduresNot all data is always available — sometimes a student's city is missing, or marks haven't been entered yet. In SQL, these unknown or missing values are called NULL. But handling NULLs isn’t as simple as checking for blank strings — they need special care. Let’s explore how to work with NULLs properly in SQL.
NULL
represents an unknown, missing, or inapplicable value. It is not the same as zero or an empty string. You must use specific operators like IS NULL
or COALESCE
to handle NULL values.
CREATE TABLE students (
roll_no INT,
name VARCHAR(50),
marks INT,
city VARCHAR(30)
);
INSERT INTO students VALUES
(1, 'Aarav Sharma', 85, 'Delhi'),
(2, 'Diya Iyer', NULL, 'Chennai'),
(3, 'Sneha Patil', 78, NULL),
(4, 'Mehul Agarwal', NULL, 'Delhi'),
(5, 'Saira Bano', 90, NULL);
SELECT name
FROM students
WHERE marks IS NULL;
name
--------------
Diya Iyer
Mehul Agarwal
SELECT name, city
FROM students
WHERE city IS NOT NULL;
SELECT name, COALESCE(city, 'Unknown') AS display_city
FROM students;
name | display_city
----------------+---------------
Aarav Sharma | Delhi
Diya Iyer | Chennai
Sneha Patil | Unknown
...
Different SQL dialects provide similar functions:
SELECT name, IFNULL(marks, 0) AS safe_marks
FROM students;
-- Wrong: This returns 0 rows
SELECT * FROM students WHERE marks = NULL;
Always use IS NULL
instead of = NULL
.
Aggregate functions like AVG()
or SUM()
ignore NULLs:
SELECT AVG(marks) AS avg_marks
FROM students;
avg_marks
-----------
84.33
Only non-NULL marks are used in the average.
In a school database:
IS NULL
or IS NOT NULL
.COALESCE
or IFNULL
to avoid NULLs in outputs.NULLs represent uncertainty — and that requires precision. From filtering missing data to replacing it for cleaner reports, handling NULLs properly is a critical SQL skill. It helps ensure your queries reflect the real world — even when the data is incomplete.
Next, we’ll dive into SQL CASE expressions — to apply logic and decisions directly within SELECT queries.
SELECT COALESCE(mobile_no, 'Not Provided') FROM students;
⬅ Previous Topic
SQL Functions – String, Numeric, Date & AggregateNext Topic ⮕
SQL Stored ProceduresYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.