HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

Postgresql To Return 0 when Null

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlnullreturnwhen

Problem

I am attempting to run a query using MAX() but my issue is that if the field contains a NULL value the data returns nothing. Updating the table is not an option, so how should this query be re-written to return 0 when NULL?

Sample DDL below - and I hardcoded a WHERE clause that returns nothing just for illustrative purposes, ideally I want to return all usernames and the highest logincount for the user

CREATE TABLE Test 
(
 username varchar(50) not null,
 logincount int,
 logindate Date
);

Insert Into Test (username, logincount, logindate) 
VALUES
('er11', 1, '2017-01-01'), ('er11', 2, '2017-01-02'), ('ff12', NULL, NULL)
,('jb88', 1, '2017-01-09');

With maxlogincount As
(
    select max(logincount) As "MaxLoginCount"
    ,username
    FROM Test
    GROUP BY username
)
Select
username
,logincount
,logindate
FROM Test t
inner join maxlogincount mlc
ON t.username = mlc.username
And mlc."MaxLoginCount" = t.logincount
WHERE t.username = 'ff12'
Order by t.username asc

Solution

Use max(coalesce(logincount, 0)) to avoid NULLs

According to Postgres docs (9.6):


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, for example:

Context

StackExchange Database Administrators Q#162903, answer score: 21

Revisions (0)

No revisions yet.