Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the greatest of two columns values in MySQL?

I'm trying to do something like this:

SELECT MAX(
  ADDDATE(expirationdate, INTERVAL 1 YEAR),
  ADDDATE(now(), INTERVAL 1 YEAR)
)

That is, get "a year from now", or "a year from the expiration date stored in the table", whichever is greater (i'm renewing people's subscriptions).

This obviously doesn't work, since MAX() is for aggregation between rows, not for comparing 2 values. Is there a function that'll do this in MySQL? (i'd like to avoid doing an IF)

like image 476
Daniel Magliola Avatar asked Oct 27 '09 18:10

Daniel Magliola


People also ask

How do I find the greatest value in MySQL?

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

How do I find the maximum number of two numbers in SQL?

Another solution that is described below with code examples can be used to solve the same issue Sql Max Of Two Values. SELECT MAX (column_name) FROM table_name WHERE column_name NOT IN (SELECT Max (column_name) FROM table_name);

How do I find the highest value in a column in SQL?

To find the max value of a column, use the MAX() aggregate function; it takes as its argument the name of the column for which you want to find the maximum value. If you have not specified any other columns in the SELECT clause, the maximum will be calculated for all records in the table.

How do you select the top 3 maximum value in SQL?

To get the maximum value from three different columns, use the GREATEST() function. Insert some records in the table using insert command. Display all records from the table using select statement.


1 Answers

greatest()

like image 171
longneck Avatar answered Sep 18 '22 10:09

longneck