28

I try to select max value from table

SELECT MAX(cid) FROM itemconfiguration;

However when table itemconfiguration is empty the MAX(cid) statements is evaluated to NULL while i need a number. How to handle this and treat NULL as 0 ?

Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162

3 Answers3

59

Just use Coalesce or NVL to handle NULLs.

The following code will return 0 if MAX(cid) is NULL

SELECT COALESCE(MAX(cid), 0)
FROM   itemconfiguration
RB.
  • 36,301
  • 12
  • 91
  • 131
  • 1
    `COALESCE` is preferable as it is more general (can take more than two arguments and returns the first non-NULL, while `NVL` is its special case for two arguments), it [does short-circuit](http://stackoverflow.com/a/950103/2157640) (does not evaluate arguments after the first non-NULL) and it was standardized in SQL-92 (while `NVL` is proprietary to Oracle). – Palec Sep 27 '16 at 08:07
7

SELECT NVL(MAX(cid), 0) FROM itemconfiguration;

zibidyum
  • 174
  • 1
  • 8
0

Can replace a number when max return null using ISNULL ,

ISNULL(MAX(cid),0) FROM itemconfiguration;
mrm aadil
  • 1
  • 1