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