I'm running a SUM()
query on a Snowflake table, but instead of returning 0 when there are no matching rows, it returns NULL.
For example, I have this table:
CREATE OR REPLACE TABLE sales (
region STRING,
amount NUMBER
);
INSERT INTO sales VALUES
('North', 100),
('South', 200),
('North', NULL),
('East', 150);
Now, I run the following query to sum the sales for a region that doesn’t exist:
SELECT SUM(amount) FROM sales WHERE region = 'West';
- Expected output:
0
- Actual output:
NULL
❌
Why is this happening, and how can I make Snowflake return 0
instead of NULL
?
I'm running a SUM()
query on a Snowflake table, but instead of returning 0 when there are no matching rows, it returns NULL.
For example, I have this table:
CREATE OR REPLACE TABLE sales (
region STRING,
amount NUMBER
);
INSERT INTO sales VALUES
('North', 100),
('South', 200),
('North', NULL),
('East', 150);
Now, I run the following query to sum the sales for a region that doesn’t exist:
SELECT SUM(amount) FROM sales WHERE region = 'West';
- Expected output:
0
- Actual output:
NULL
❌
Why is this happening, and how can I make Snowflake return 0
instead of NULL
?
1 Answer
Reset to default 0First and basic approach: explicitly filter out NULL
before aggregation:
SELECT SUM(CASE WHEN amount IS NOT NULL THEN amount ELSE 0 END) AS total_sales
FROM sales
WHERE region = 'West';
This method ensures that NULL
does not interfere with the SUM
calculation.
✅ Even better: Use COALESCE()
to handle NULL
.
By default, SUM()
returns NULL
if there are no rows that match the condition or if all matching rows contain NULL
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744369822a4570889.html
NULL
- that's what it's defined to be. And applying any operators toNULL
will always again result inNULL
- you cannot "sum up", or get a "max" from nothing ..... you'll just get back nothing again – marc_s Commented Mar 21 at 7:05