Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to treat MAX() of an empty table as 0 instead of NULL

Tags:

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 ?

like image 246
Mariusz Jamro Avatar asked Mar 18 '13 10:03

Mariusz Jamro


People also ask

Does Max work with NULL values?

MAX ignores any null values. MAX returns NULL when there is no row to select. For character columns, MAX finds the highest value in the collating sequence.

Is empty string better than NULL?

So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

How do you insert an empty value in a table?

You can insert NULL value into an int column with a condition i.e. the column must not have NOT NULL constraints. The syntax is as follows. INSERT INTO yourTableName(yourColumnName) values(NULL);


2 Answers

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 
like image 165
RB. Avatar answered Oct 13 '22 21:10

RB.


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

like image 37
zibidyum Avatar answered Oct 13 '22 21:10

zibidyum