Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make MySQL MAX() consider NULL the smallest possible value?

Tags:

sql

null

mysql

max

I have a query that looks a bit like this:

SELECT weekEnd, MAX(timeMonday)
FROM timesheet
GROUP BY weekEnd

The valid values for timeMonday are: null, -1, 0, 1-24. At the moment, MAX() places the preference of those values in the order null, -1, 0, 1-24, however what I actually want is -1, null, 0, 1-24, so that null is considered higher than -1. I know MAX cant do this, so what's the easiest way to achieve it?

like image 733
Jack Sleight Avatar asked Nov 26 '25 02:11

Jack Sleight


2 Answers

SELECT weekEnd, MAX(coalesce(timeMonday,-.5)) FROM timesheet GROUP BY weekEnd

Then convert -.5 back to null

like image 56
Gratzy Avatar answered Nov 27 '25 15:11

Gratzy


SELECT weekEnd, CASE WHEN maxTimeMonday = -0.5 THEN NULL ELSE maxTimeMonday END maxTimeMonday 
FROM (
   SELECT weekEnd, MAX(CASE WHEN timeMonday IS NULL THEN -0.5 ELSE timeMonday END) maxTimeMonday 
     FROM timesheet
    GROUP BY weekEnd) T

replacing NULL by -0.5 when calculating MAX then reverting it to NULL.

(MS SQL Server syntax)

like image 32
manji Avatar answered Nov 27 '25 16:11

manji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!