Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set 0 with MAX function when it is NULL?

Tags:

null

mysql

max

zero

I would like to understand how to set 0 value of the attribute when it is NULL with MAX function. For example:

Name columns: number - date  Values: 10 - 2012-04-04 11 - 2012-04-04 12 - 2012-04-04 13 - 2012-04-15 14 - 2012-06-21  1 - 2013-07-04 

Number is incremental field, but it has set itself 1 when new year has come. But result of:

SELECT (MAX(number)+1) number WHERE date LIKE "2014%"  

is NULL and not 1 because MAX(number) is NULL and not 0

like image 655
Donovant Avatar asked Apr 16 '12 10:04

Donovant


People also ask

Does Max work with NULL values?

MAX ignores any null values. MAX returns NULL when there is no row to select.

How do you avoid NULL values in Max function?

You can use COALESCE() along with aggregate function MAX() for this. Insert some records in the table using insert command. Display you all records from the table using select statement. Here is the case when table is empty.

Can NULL values be avoided?

Nulls cause some queries to return results that are "incorrect" (i.e. the results won't correspond with the intended meaning of the database). Unfortunately SQL and SQL-style databases can make nulls difficult, though not necessarily impossible, to avoid.


2 Answers

Well, as there is no date like 2014, you would expect null, because the maximum of nothing is actually not anyting.

But do this:

COALESCE(MAX(number),0) 

Which means: get the first non-null thing from the next list, so if your max is null, it'll give you 0

like image 195
Nanne Avatar answered Oct 17 '22 12:10

Nanne


COALESCE works, but IFNULL seems clearer to me.

IFNULL(MAX(number), 0) 

If the first expression is not NULL, IFNULL() returns the expression itself, otherwise it returns the second parameter. IFNULL() returns a numeric or string value, depending on the context in which it is used.

like image 22
Demis Palma ツ Avatar answered Oct 17 '22 12:10

Demis Palma ツ