82

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)

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

8 Answers8

114

or:

SELECT coalesce(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1
HLGEM
  • 94,695
  • 15
  • 113
  • 186
88

In SQL 2005 / 2008:

SELECT ISNULL(MAX(X), 0) AS MaxX
FROM tbl WHERE XID = 1
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
Nestor
  • 13,706
  • 11
  • 78
  • 119
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

Greg
  • 316,276
  • 54
  • 369
  • 333
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
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
5

Oracle would be

SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;
Jim
  • 81
  • 2
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

Hassan Ali Shahzad
  • 2,439
  • 29
  • 32
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
Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
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.

Hasnat Babur
  • 322
  • 5
  • 14