tags:

views:

400

answers:

6

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)

+7  A: 

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
I think you mean ISNULL :)
AdaTheDev
In SQL Server it would be ISNULL. I don't know if it is a typo or a valid command in other SQL dialects.
Konamiman
The OP doesn't specify: MySQL uses IFNULL
Greg
I was, possibly incorrectly, assuming SQL Server! So of course, you may NOT have meant ISNULL!!
AdaTheDev
+10  A: 

In SQL 2005 / 2008:

SELECT ISNULL(MAX(X), 0) AS MaxXFROM tblWHERE XID = 1
Nestor
+2  A: 

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
+11  A: 

or:

SELECT coalesce(MAX(X), 0) AS MaxX
FROM tblWHERE XID = 1
HLGEM
LOL we apprently were typing at same time :)
Mark Schultheiss
+1 COALESCE is SQL:1992 compliant
bobince
+6  A: 

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
+1  A: 

Oracle would be

SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;
Jim