Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Treat Null as Max

Tags:

sql

null

max

So if I had a table in my database with the values

1
2
3
4
NULL

And I executed the query

SELECT MAX(col1) FROM <table>

I'd get 4. Is there any way to change this so Null would be treated as the maximum as oppose to the minimum?

Thanks!

like image 489
mat-mcloughlin Avatar asked Jan 22 '23 15:01

mat-mcloughlin


2 Answers

SELECT MAX(ISNULL(col1, 2147483647)) FROM <table> 

[2147483647 = 2^31 - 1]

like image 189
Mitch Wheat Avatar answered Feb 01 '23 06:02

Mitch Wheat


Just as a variant, you can do this on Oracle.

SELECT *
  FROM ( SELECT col1 
           FROM <table>
          ORDER BY col1 DESC NULLS FIRST
       )
 WHERE rownum = 1

(OP hasn't specified any particular flavour of database)

like image 24
Mark Baker Avatar answered Feb 01 '23 07:02

Mark Baker