SQL GREATEST and LEAST: Row-Level Min and Max Explained
By Sharon Ben-Moshe · October 9, 2026 · 1 min read
Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Understand the difference between row-level GREATEST/LEAST and column aggregate MAX/MIN. Learn NULL behavior across PostgreSQL, MySQL, and SQL Server.
Quick answer
GREATEST() and LEAST() evaluate expressions across columns within a single row to return the largest or smallest value. Unlike aggregate MAX() and MIN() (which collapse multiple rows vertically into one value), GREATEST and LEAST evaluate horizontally across columns without collapsing rows.
FAQs
How do GREATEST and LEAST handle NULL values?
In PostgreSQL and ANSI SQL, if any argument is NULL, GREATEST/LEAST ignores NULLs unless all arguments are NULL. In Oracle and MySQL, by default if any argument is NULL, the entire function returns NULL. Always check your engine's documentation.
Does SQL Server support GREATEST and LEAST?
Yes! Starting in SQL Server 2022 (and Azure SQL), GREATEST and LEAST are natively supported and ignore NULL values.
How do I replace GREATEST in older SQL Server versions?
On SQL Server 2019 and older, replace GREATEST with a CROSS APPLY (SELECT MAX(v) FROM (VALUES (col1), (col2), (col3)) AS t(v)) pattern or a verbose CASE statement.
Can GREATEST compare strings or dates?
Yes, GREATEST and LEAST compare numbers, strings, and dates according to standard collation and chronological ordering rules.
Keep reading
The Comprehensive Guide to SQL Data Types: Storage, Precision, and Cross-Dialect Portability
By Sharon Ben-Moshe · Oct 13, 2026
The complete guide to SQL data types across PostgreSQL, MySQL, SQL Server, and SQLite. Numeric precision, character sets, timestamps, and JSON.
Read postThe Definitive Guide to SQL Window Functions: Syntax, Framing, and Real-World Recipes
By Sharon Ben-Moshe · Oct 13, 2026
The comprehensive guide to SQL window functions. Master OVER, PARTITION BY, ORDER BY, window frames (ROWS vs RANGE), and ranking recipes.
Read postTry it now
Paste your SQL into sqlfmt — format, validate, and catch typos free in your browser.