201

How do I find the maximum (or minimum) of two integers in Postgres/SQL? One of the integers is not a column value.

I will give an example scenario:

I would like to subtract an integer from a column (in all rows), but the result should not be less than zero. So, to begin with, I have:

UPDATE my_table
SET my_column = my_column - 10;

But this can make some of the values negative. What I would like (in pseudo code) is:

UPDATE my_table
SET my_column = MAXIMUM(my_column - 10, 0);
HRJ
  • 16,207
  • 11
  • 52
  • 78
  • Relatedly you can create a union data set and then max that, in sql-server at least https://stackoverflow.com/questions/124417/is-there-a-max-function-in-sql-server-that-takes-two-values-like-math-max-in-ne – Kzqai Mar 28 '20 at 18:31

2 Answers2

407

Have a look at GREATEST and LEAST.

UPDATE my_table
SET my_column = GREATEST(my_column - 10, 0);
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
Mark Byers
  • 767,688
  • 176
  • 1,542
  • 1,434
20

You want the inline sql case:

set my_column = case when my_column - 10 > 0 then my_column - 10 else 0 end

max() is an aggregate function and gets the maximum of a row of a result set.

Edit: oops, didn't know about greatest and least in postgres. Use that instead.

ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
Donnie
  • 43,578
  • 10
  • 63
  • 85