Mastering COALESCE in PostgreSQL: Fix NULL Arithmetic Results
This guide shows how NULL values break numeric calculations in PostgreSQL and demonstrates using the COALESCE function to substitute default numbers, with step‑by‑step SQL examples that turn unexpected NULL results into accurate sums.
When a numeric column contains NULL, any arithmetic operation involving that column also returns NULL, which often leads to disappointing results. The COALESCE function can replace NULL with a specified default value, allowing calculations to proceed normally.
COALESCE Syntax
COALESCE(column_name, default_value)Demo Setup
su - postgres psql music CREATE TABLE test_null(id INT, num1 INT, num2 INT);
Insert Sample Data
INSERT INTO test_null VALUES (1,100,100); INSERT INTO test_null VALUES (2,200,200); INSERT INTO test_null VALUES (3,NULL,100); INSERT INTO test_null VALUES (4,300,NULL); INSERT INTO test_null VALUES (5,NULL,500);
View Table Contents
SELECT * FROM test_null;
Result:
id | num1 | num2
----+------+------
1 | 100 | 100
2 | 200 | 200
3 | NULL | 100
4 | 300 | NULL
5 | NULL | 500
(5 rows)Direct Arithmetic Without COALESCE
SELECT num1 + num2 FROM test_null;
Result shows NULL for rows where either operand is NULL:
?column?
----------
200
400
(NULL rows omitted in display)
(5 rows)Using COALESCE to Handle NULL
SELECT COALESCE(num1,0) + COALESCE(num2,0) FROM test_null;
Result now returns correct sums for all rows:
?column?
----------
200
400
100
300
500
(5 rows)The default value supplied to COALESCE can be any number appropriate to the domain—zero for generic arithmetic, 36 for human body temperature, 0 for the freezing point, 100 for the boiling point, etc.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
