21

PostgreSQL has a useful function called GREATEST. It returns the largest value of those passed to it as documented here.

Is there any equivalent in SQLite?

As a note, I only need it to work with 2 arguments.

2 Answers 2

31

SELECT MAX(1,2,..)

ref: https://sqlite.org/lang_corefunc.html#maxoreunc

max(X,Y,...)

The multi-argument max() function returns the argument with the maximum value, or return NULL if any argument is NULL. The multi-argument max() function searches its arguments from left to right for an argument that defines a collating function and uses that collating function for all string comparisons. If none of the arguments to max() define a collating function, then the BINARY collating function is used. Note that max() is a simple function when it has 2 or more arguments but operates as an aggregate function if given only a single argument.

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, can someone explain strange behavior of max function with strings. select max ('rb','VISA', 'Visa', 'Visa Card1', 'VISA VISA Card', 'Visaaa') returns 'rb', Why?!?
@zlatko: sounds like a case-sensitive comparison. lowercase is coming after uppercase.
@zlatko - check out an ASCII chart!
Be careful, the behavior with NULL is different: PostgreSQL GREATEST returns NULL only if all arguments are NULL. SQLite MAX returns NULL if any argument is NULL.
1

using a second value in MAX(value1, value2) would be the equivalent
Example:

UPDATE products SET Quantity = MAX(Quantity - @value, 0)...

if (Quantity - value) return a "Negative Number -0" then Max( , 0) will return 0
because 0 is bigger than -0 / -1 / -2 ... and so on
Max( , 1) will return 1 if the same condition (Quantity - value) return 0 or a Negative Number .. etc, you get the idea !

if we assume that both Quantity and @value could be NULL then use the combination: IFNULL(MAX(Quantity-@value,0),0)
IFNULL(..., 0) will return the second value of your choice IF the first one is NULL

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.