user7810882
user7810882

Reputation: 233

Make MIN(column) return NULL if column contains NULL

SELECT MIN(column) FROM table;

will return minimum from nonnull elements.

I would like to write a query that will treat NULL as if it were the smallest value possible.

I have seen tricks with dates using a special value like here: https://stackoverflow.com/a/32240382/7810882

But what if the column is of type int and there is no special value that I can map NULL to?

Upvotes: 0

Views: 99

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269623

You can do this using a case expression:

SELECT (CASE WHEN COUNT(*) = COUNT(COLUMN) THEN MIN(column) END)
FROM table;

Upvotes: 3

Related Questions