use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

Answer from Luc M on Stack Overflow
Top answer
1 of 3
270

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

2 of 3
46

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)
🌐
PostgreSQL
postgresql.org › docs › current › functions-conditional.html
PostgreSQL: Documentation: 18: 9.18. Conditional Expressions
3 weeks ago - NULL values in the argument list are ignored. The result will be NULL only if all the expressions evaluate to NULL. (This is a deviation from the SQL standard. According to the standard, the return value is NULL if any argument is NULL.
🌐
TablePlus
tableplus.com › blog › 2019 › 09 › sql-if-null-then-0.html
SQL IF NULL THEN 0 | TablePlus
September 11, 2019 - In MySQL you can also use IFNULL function to return 0 as the alternative for the NULL values: SELECT emp_no, salary, from_date, to_date, IFNULL(bonus, 0) FROM salaries; In MS SQL Server, the equivalent is ISNULL function: SELECT emp_no, salary, from_date, to_date, ISNULL(bonus, 0) FROM salaries; ...
🌐
Neon
neon.com › postgresql › postgresql-tutorial › postgresql-nullif
PostgreSQL NULLIF function
SELECT ( SUM (CASE WHEN gender = 1 THEN 1 ELSE 0 END) / NULLIF ( SUM (CASE WHEN gender = 2 THEN 1 ELSE 0 END), 0 ) ) * 100 AS "Male/Female ratio" FROM members; ... The NULLIF function checks if the number of female members is zero, it returns null.
🌐
EnterpriseDB
enterprisedb.com › postgres-tutorials › how-use-coalesce-postgresql
How to use COALESCE in PostgreSQL | EDB
4. To overcome this result, we can use COALESCE to make NULL values return 0 in this particular case. postgres=# SELECT amount - coalesce(discount,0) AS "final bill" FROM sales; final bill ------------ 990 1480 800 500 <== Correct value generated ...
🌐
CommandPrompt Inc.
commandprompt.com › education › postgresql-isnull-function-with-examples
PostgreSQL ISNULL Function With Examples — CommandPrompt Inc.
October 3, 2022 - So, all in all, the COALESCE() function will find the NULL values in the emp_bonus column and replace all the occurrences of the NULL values with the “0”: The result set proves the working of COALESCE() function.
🌐
DB Vis
dbvis.com › thetable › isnull-postgresql-example
PostgreSQL ISNULL Function: The Missing ISNULL Function
July 5, 2024 - In this query, unknown_status will contain 1 if stock_level is NULL, and 0 otherwise. This SELECT-generated column makes it easier to read the results and keep track of the stock data status. ... Note the "true" and "false" values in the results. Similarly, the IS NULL operator will return a boolean representing the status of the stock level associated with each product. Congrats! The absence of ISNULL in PostgreSQL is no longer a problem!
🌐
Baeldung
baeldung.com › home › sql basics › how to replace null with 0 in sql
How to Replace NULL With 0 in SQL Baeldung on SQL
January 27, 2025 - We can use the COALESCE function to replace NULL values with 0. The COALESCE function is a standard SQL function that finds and returns the first non-NULL value from its argument list.
Find elsewhere
🌐
Percona
percona.com › home › why postgresql null values break your queries (and how to fix them)
Why PostgreSQL NULL Values Break Your Queries (And How to Fix Them)
July 7, 2025 - The output confirms that in C, NULL is simply 0. Java takes a different approach, treating null as a special reference value rather than a number. You still use the same equality operators for comparison, but when you print it, you’ll see the literal word “null” (always lowercase in Java). ... PostgreSQL’s NULL means “no value.” It is not 0, an empty string, or a single space, and it won’t cooperate with ordinary equality operators.
🌐
GeeksforGeeks
geeksforgeeks.org › postgresql › postgresql-nullif-function
PostgreSQL - NULLIF() Function - GeeksforGeeks
July 15, 2025 - Simplifying CASE Statements: Instead of complex CASE logic, NULLIF can be a simpler alternative (e.g., NULLIF(column, 0)). Mastering the NULLIF function in PostgreSQL helps you efficiently handle NULL and empty values in your database. By combining NULLIF with COALESCE and applying it in SELECT and INSERT statements, we can improve data handling and simplify SQL queries.
🌐
Educative
educative.io › answers › what-is-the-nullif-function-in-postgresql
What is the NULLIF function in PostgreSQL?
Line 14: We check whether the price of a product is equal to 1000. If the price is 1000, the NULLIF function returns null. We choose 0 instead of null using the COALESCE function.
🌐
Squash
squash.io › tutorial-on-the-isnull-function-in-postgresql
How to Use the ISNULL Function in PostgreSQL
If it is null, the result will be 'Unknown', otherwise, it will be 'Known'. ... This code snippet selects all rows from the employees table where the age column is null. SELECT name, ISNULL(age, 0) AS age FROM employees; This code snippet selects ...
🌐
Reddit
reddit.com › r/sql › replace null count with a zero (0)
r/SQL on Reddit: Replace null count with a zero (0)
December 22, 2022 -

Hello,

This is my query

SELECT ordertype, 
status, 
sum (COUNT (printdate)) over (), 
date(char(1900000+requestdate)), 
businessunit 
FROM Casepallet

WHERE date(char(1900000+requestdate)) IN (current date, current date + 1 days) 
AND business unit='         SCS' 
AND ordertype!='T1' 
AND status = 'X'

group by ordertype, business unit, request date, status, printdate

order by printdate desc limit 1

Sometimes the sum/count of printdate returns nothing, it's null. If it's null I want it to return 0.

I tried doing it like this: COALESCE (sum (COUNT (printdate)) over (), 0), but it doesn't work, it still returns null.

Can anyone guide me here on where I go wrong?

🌐
CastorDoc
castordoc.com › how-to › how-to-use-ifnull-in-postgresql
How to use ifnull in PostgreSQL?
Learn how to effectively use the ifnull function in PostgreSQL to handle null values and improve data consistency.
🌐
DB Vis
dbvis.com › thetable › postgresql-nullif-conditional-logic-made-easier
PostgreSQL NULLIF: Conditional Logic Made Easier
September 11, 2024 - Now, when stock_1 is 0, the NULLIF function will return NULL, preventing the error. This is because a division by NULL in PostgreSQL produces a NULL value.