How can I implement `set field = max(1, x)` in SQL?
I'm attempting to update a field in a series of records with an expression that will evaluate to an integer which may be negative. I want the lower bound of the column to be 1; any rows for which the expression evaluates to less than 1 should have their field set to 1. This might be best expressed by the following pair of pseudo-SQL statements:
update posts set field = [expensive expression];
update posts set field = 1 where field < 1;
How can I implement this in a single SQL update
statement? Is there some equivalent to max(a, b)
in PostgreSQL, to which I can pass max([expression], 开发者_如何学Python1)
?
Use the function GREATEST
.
Or, a more general approach for conditions:
SELECT
CASE WHEN condition
THEN valueForTrue
ELSE valueForFalse
END
FROM ...
Yes, use GREATEST([expensive expr], 1)
Use GREATEST(1, [your expression])
.
精彩评论