Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Multiple Columns with and without NULL values

Tags:

mysql

5, Not sure what am I doing wrong, please help. As it seems in a query on multiple column comparison to find least value, NULL continues to show up as a Resultant instead of least value

SELECT
  IF(col1 IS NULL OR col2 IS NULL OR col3 IS NULL OR col4 IS NULL OR col5 IS NULL, 
      COALESCE(col1,col2,col3,col4,col5), 
      LEAST(col1,col2,col3,col4,col5)
  ) As Resultant 
from db.tablename 
Group by Id;

Alternatively tried CASE select without much success. Thanks

like image 921
Charan Singh Avatar asked Jan 22 '26 10:01

Charan Singh


1 Answers

if null is considered 0

select least(ifnull(col1,0),ifnull(col2,0),ifnull(col3,0),ifnull(col4,0),ifnull(col5,0))
as Resultant
from db.tablename
Group by Id;

if null is condered max

select least(ifnull(col1,~0>>1),ifnull(col2,~0>>1),ifnull(col3,~0>>1),ifnull(col4,~0>>1),ifnull(col5,~0>>1))
as Resultant
from db.tablename
Group by Id;
like image 123
mdprotacio Avatar answered Jan 25 '26 07:01

mdprotacio



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!