Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the minimum of 3 values where some of them may be null in MySQL using LEAST()?

Tags:

sql

mysql

I found this question ( How to get the max of two values in MySQL? ) while looking for ways to compare discrete set of values.

I want to be able to get the minimum of few selected values where some of them may be null because they are optional but the MySQL docs says:

If any argument is NULL, the result is NULL.

like image 565
antitoxic Avatar asked Feb 23 '23 17:02

antitoxic


2 Answers

Use a COALESCE() function on the nullable values:

select LEAST(COALESCE(@foo, <max int>), COALESCE(@bar, <max int>));

if you get the max int value, then both were null (unless there's a decent chance you could actually have the max int value as a real argument, then more logic is necessary)

like image 156
Jeremy Holovacs Avatar answered Apr 30 '23 23:04

Jeremy Holovacs


How about this:

LEAST(COALESCE(col1, col2, col3),
      COALESCE(col2, col3, col1),
      COALESCE(col3, col1, col2))

Obviously this doesn't scale well to more than 3 values.

like image 43
Mark Byers Avatar answered May 01 '23 01:05

Mark Byers