SQL GREATEST function
Returns the largest of two or more expressions.
- Категория
- Условные конструкции
- Returns
highest-precedence argument type (Oracle: first argument's type)- In this category
- 11 of 43
Синтаксис
GREATEST(a, b, ...) | max(a, b, ...)
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | SQL Server 2022+; skips NULLs |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Да | Supported under this name. |
| SQLite | Different name or syntax | SQLite spells it max(a, b, ...) with two or more arguments |
| Oracle | Да | result type comes from the first argument |
Примеры
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;
Полезно знать
- 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.
Related on SQLly
- Detect overlapping date ranges Snippet
- Mask payment card numbers in SQL (show last 4) Snippet
- Mask names in query results Snippet
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.