GREATEST is a scalar comparison function that evaluates two or more expressions for every row and returns the highest non-NULL value according to the database’s sorting rules. All arguments are implicitly converted to a common data type if necessary. If every argument is NULL the function returns NULL. When text values are supplied, the comparison follows the database’s collation rules; when numbers are supplied, standard numeric comparison is used. Mixing incomparable data types (e.g., text with date) raises an error. Because evaluation is row-wise, GREATEST can be used both in SELECT lists and in WHERE or ORDER BY clauses. It does not aggregate across rows; use MAX for that purpose.
expression1, expression2, … expressionN
(Any comparable scalar type) - Two or more expressions whose greatest value you want returnedLEAST, COALESCE, MAX, CASE expressions, NULL handling
Oracle 7 (1992); later adopted by PostgreSQL and others
GREATEST compares values within the same row, while MAX aggregates values across multiple rows in a result set.
GREATEST ignores NULLs as long as at least one argument has a value. If all arguments are NULL, it returns NULL. Wrap it in COALESCE if you need a fallback value.
Yes. Because it is a scalar function, you can use it anywhere an expression is allowed, including SELECT, WHERE, ORDER BY, and GROUP BY clauses.
Use a CASE expression like CASE WHEN a > b AND a > c THEN a WHEN b > c THEN b ELSE c END, or CROSS APPLY with VALUES to emulate GREATEST.