Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the max of two values in MySQL?

Tags:

mysql

max

I tried but failed:

mysql> select max(1,0); 
 ERROR 1064 (42000): You have an error in your SQL syntax; check the manual  that corresponds to your MySQL server version for the right syntax to use  near '0)' at line 1 
like image 293
Mask Avatar asked Oct 14 '09 11:10

Mask


2 Answers

Use GREATEST()

E.g.:

SELECT GREATEST(2,1); 

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

like image 87
NinethSense Avatar answered Sep 29 '22 16:09

NinethSense


To get the maximum value of a column across a set of rows:

SELECT MAX(column1) FROM table; -- expect one result 

To get the maximum value of a set of columns, literals, or variables for each row:

SELECT GREATEST(column1, 1, 0, @val) FROM table; -- expect many results 
like image 21
cs_alumnus Avatar answered Sep 29 '22 18:09

cs_alumnus