SQL MIN function
Returns the smallest non-null value in a group. It works on numbers, dates and strings; for text, the column's collation decides what smallest means.
- Категория
- Aggregates
- Returns
same type as the expression- In this category
- 4 of 52
Синтаксис
MIN(expression)
Поддержка движка
| Движок | Support | Заметки |
|---|---|---|
| SQL Server | Да | Supported under this name. |
| PostgreSQL | Да | Supported under this name. |
| MySQL | Да | Supported under this name. |
| SQLite | Да | Supported under this name. |
| Oracle | Да | Supported under this name. |
Примеры
Any engine
SELECT MIN(created_at) AS first_order FROM orders;
Any engine
SELECT customer_id, MIN(amount) AS smallest_order FROM orders GROUP BY customer_id;
Полезно знать
- MIN ignores NULLs; MIN of a group whose values are all NULL returns NULL.
- On text columns the result follows the column's collation, so case and accent rules decide the smallest value on SQL Server and MySQL.
- Booleans do not work everywhere: SQL Server rejects MIN on a bit column (cast it to int), and PostgreSQL has no MIN(boolean); use bool_and instead.
Questions about MIN
Does MIN work on dates?
Yes. MIN(created_at) returns the earliest timestamp, which is the usual way to find a customer's first order. Text columns compare by collation order.
Does MIN ignore NULL?
Yes. Rows where the expression is NULL never win the minimum. If every value is NULL, MIN returns NULL.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Delete duplicates keeping one row Snippet
- Keep the oldest row per key Snippet
- Transitive closure with a recursive CTE Snippet
- Walk a bill of materials Snippet
- Detect missing days in date data Snippet
- SQL aggregation & HAVING interview questions Interview questions
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.