Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql min ignores null - need workaround/tweak

Tags:

mysql

For this query

SELECT min(date) min_date FROM  order_products group by order_id

min_date ignores the NULL values in a group of order id.

In my case I want min_date = NULL if the group has a order_products tuple with null value in date.

Any idea how can I achieve this ?

like image 215
shikhar Avatar asked Mar 31 '10 13:03

shikhar


People also ask

Does Min ignore nulls SQL?

The MIN function works with numeric values and ignores NULL values.

How do you handle NULL values in MySQL?

By using the assignment operator (“=”), you can set any value of a column to NULL by using the Update Statement.

How do I change not null in MySQL?

To enforce NOT NULL for a column in MySQL, you use the ALTER TABLE .... MODIFY command and restate the column definition, adding the NOT NULL attribute.

IS NULL with Min in SQL?

By default the functions MAX and MIN do not count NULL in their evaluation of your data. If we have a column containing only dates for instance and there is a NULL date, MAX and MIN will both ignore that value.


2 Answers

A simple workAround could be:

SELECT min(IFNULL(date, '1970-01-01')) AS min_date 
FROM order_products 
GROUP BY order_id

So, if 1970/01/01 turns up, you know that there's a NULL value.

like image 89
Bobby Avatar answered Oct 31 '22 21:10

Bobby


select case when count(date)=sum(1) then min(date) else null end

or, when all rows are not null, return min date, else return null.

like image 43
AdrianBR Avatar answered Oct 31 '22 23:10

AdrianBR