// conditional reference

SQL GREATEST function

Returns the largest of two or more expressions.

Categoría
Condicional
Returns
highest-precedence argument type (Oracle: first argument's type)
In this category
11 of 43

Sintaxis

GREATEST(a, b, ...) | max(a, b, ...)

Soporte del motor

MotorSupportNotas
SQL Server Sí SQL Server 2022+; skips NULLs
PostgreSQL Sí Supported under this name.
MySQL Sí Supported under this name.
SQLite Different name or syntax SQLite spells it max(a, b, ...) with two or more arguments
Oracle Sí result type comes from the first argument

Ejemplos

PostgreSQL

SELECT GREATEST(updated_a, updated_b) FROM sync_state;

MySQL

SELECT GREATEST(NULL, 3) AS n, GREATEST(COALESCE(NULL, 0), 3) AS safe;

SQLite

SELECT max(a, b) FROM t;

Conviene saberlo

  • NULL semantics split the engines: PostgreSQL and SQL Server skip NULLs and return the largest non-NULL one, while MySQL, Oracle and SQLite's max() return NULL if any argument is NULL.
  • For uniform NULL-skipping, wrap each argument in COALESCE, but only when a NULL should really mean 'ignore me'.
  • Oracle converts every argument to the first one's type: GREATEST('10', 9) compares as strings and returns '9'. Other engines pick the highest-precedence type instead.
  • SQLite has no GREATEST spelling: max(a, b) with several arguments is the scalar form, distinct from the aggregate max(col).

Questions about GREATEST

What does GREATEST do with NULL?

Engine-dependent: PostgreSQL and SQL Server ignore it; MySQL, Oracle and SQLite's max() return NULL. COALESCE each argument for predictable behaviour.

Does SQL Server have GREATEST?

Yes, since SQL Server 2022; older versions need a CASE or IIF chain.

How does SQLite do it?

max(a, b) with two or more arguments is the scalar max; max(a) alone is the aggregate.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.