Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Math max function in MySQL

How to find the maximum of two explicit values in MySQL? Something like MAXIMUM(1, @foo).

There are group functions like MAX, MIN, AVG, etc that take column name as an argument and work with result sets. Is it possible to convert two explicit values to a result set and use those functions? Some other ways?

P.S.: I need a max function for one of my stored procedures.

like image 264
Alex Avatar asked Dec 17 '09 02:12

Alex


People also ask

What is Max function in MySQL?

MySQL MAX() Function The MAX() function returns the maximum value in a set of values.

How do I find the maximum value of a column in MySQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...) Given two or more arguments, it returns the largest (maximum-valued) argument.


1 Answers

How to find the maximum of two explicit values in MySQL? Something like MAXIMUM(1, @foo).

Use the GREATEST function:

GREATEST(1, @foo)

...will return whichever value is larger - if 1 is larger than the value in @foo, you'll get 1. Otherwise, you'll get whatever value is in @foo. Also, it's not an aggregate function.

The alternative would be to use a CASE statement:

CASE WHEN 1 > @foo THEN 1 ELSE @foo END

...because CASE is ANSI standard - that will work on Oracle, MySQL, SQL Server, Postgres...

like image 180
OMG Ponies Avatar answered Sep 28 '22 00:09

OMG Ponies