SELECT max(x) is returning null; how can I make it return 0?
Asked Answered
V

8

84

How do you return 0 instead of null when running the following command:

SELECT MAX(X) AS MaxX
FROM tbl
WHERE XID = 1

(Assuming there is no row where XID=1)

Vo answered 6/11, 2009 at 16:31 Comment(0)
E
88

In SQL 2005 / 2008:

SELECT ISNULL(MAX(X), 0) AS MaxX
FROM tbl WHERE XID = 1
Entrain answered 6/11, 2009 at 16:34 Comment(0)
O
117

or:

SELECT coalesce(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1
Octagon answered 6/11, 2009 at 16:37 Comment(0)
E
88

In SQL 2005 / 2008:

SELECT ISNULL(MAX(X), 0) AS MaxX
FROM tbl WHERE XID = 1
Entrain answered 6/11, 2009 at 16:34 Comment(0)
H
30

Like this (for MySQL):

SELECT IFNULL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1

For MSSQL replace IFNULL with ISNULL or for Oracle use NVL

Hefty answered 6/11, 2009 at 16:32 Comment(3)
In SQL Server it would be ISNULL. I don't know if it is a typo or a valid command in other SQL dialects.Sternick
The OP doesn't specify: MySQL uses IFNULLHefty
I was, possibly incorrectly, assuming SQL Server! So of course, you may NOT have meant ISNULL!!Victorie
S
13

You can also use COALESCE ( expression [ ,...n ] ) - returns first non-null like:

SELECT COALESCE(MAX(X),0) AS MaxX
FROM tbl
WHERE XID = 1
Straightway answered 6/11, 2009 at 16:39 Comment(0)
R
5

Oracle would be

SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;
Rudbeckia answered 6/11, 2009 at 21:46 Comment(0)
T
3

For OLEDB you can use this query:

select IIF(MAX(faculty_id) IS NULL,0,MAX(faculty_id)) AS max_faculty_id from faculties;

As IFNULL is not working there

Tonguelash answered 30/5, 2013 at 9:23 Comment(0)
L
2

Depends on what product you're using, but most support something like

SELECT IFNULL(MAX(X), 0, MAX(X)) AS MaxX FROM tbl WHERE XID = 1

or

SELECT CASE MAX(X) WHEN NULL THEN 0 ELSE MAX(X) FROM tbl WHERE XID = 1
Leban answered 6/11, 2009 at 16:34 Comment(0)
K
0

For my case using max() was creating problem with group by even on outer SELECT statement.

So only thing that saved my day was following by avoiding adding other columns in group by clause or using aggregate on other columns. So I wrote on outer SELECT statement as following:

SELECT username, case when total_post_comments is null then 0 else total_post_comments end total_post_comment FROM (subquery)

Even not directly related to this I hope it will help other people.

Knopp answered 10/7, 2023 at 7:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.