// conditional reference

SQL LEAST function

Returns the smallest of two or more expressions.

Категория
Условные конструкции
Returns
highest-precedence argument type (Oracle: first argument's type)
In this category
12 of 43

Синтаксис

LEAST(a, b, ...) | min(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 min(a, b, ...) with two or more arguments
Oracle Да result type comes from the first argument

Примеры

PostgreSQL

SELECT LEAST(started_at, finished_at) FROM runs;

MySQL

SELECT LEAST(NULL, 3) AS n, LEAST(COALESCE(NULL, 9999), 3) AS safe;

SQLite

SELECT min(a, b) FROM t;

Полезно знать

  • Same NULL split as GREATEST: PostgreSQL and SQL Server return the smallest non-NULL argument; MySQL, Oracle and SQLite's min() return NULL if any argument is NULL.
  • Wrap arguments in COALESCE when a NULL should be skipped rather than poison the result.
  • SQLite's spelling is min(a, b) with two or more arguments; min(col) with one is the aggregate.

Questions about LEAST

Does LEAST ignore NULLs?

In PostgreSQL and SQL Server yes; in MySQL, Oracle and SQLite's min(a, b) a single NULL makes the result NULL.

SQL Server equivalent?

LEAST since SQL Server 2022; before that, CASE or IIF chains.

LEAST vs aggregate MIN?

LEAST compares expressions within one row; MIN scans a column across rows.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.