// aggregates reference

SQL MODE function

Returns the most frequent non-NULL value in the group.

Categoría
Aggregates
Returns
same as input
In this category
32 of 52

Sintaxis

mode() WITHIN GROUP (ORDER BY col) | STATS_MODE(col)

Soporte del motor

MotorSupportNotas
SQL Server Not built in No built-in equivalent.
PostgreSQL Sí ordered-set form: mode() WITHIN GROUP (ORDER BY col)
MySQL Not built in No built-in equivalent.
SQLite Not built in No built-in equivalent.
Oracle Different name or syntax no MODE; STATS_MODE(x) does the job

Ejemplos

PostgreSQL

SELECT mode() WITHIN GROUP (ORDER BY status) FROM orders;

Oracle

SELECT STATS_MODE(status) FROM orders;

MySQL

SELECT status FROM orders GROUP BY status ORDER BY COUNT(*) DESC LIMIT 1;

Conviene saberlo

  • Ties resolve by the ORDER BY: PostgreSQL returns the first value in that order among the tied ones. Oracle's STATS_MODE picks one of the tied values with no ordering control.
  • NULLs are excluded; an all-NULL or empty group returns NULL.
  • PostgreSQL's form takes no argument to the function itself: the column lives in the WITHIN GROUP (ORDER BY ...).
  • MySQL, SQL Server and SQLite: GROUP BY the column, ORDER BY COUNT(*) DESC and keep the top row, or ROW_NUMBER over the counts for one mode per group.

Questions about MODE

What happens with ties?

In PostgreSQL the first tied value in the WITHIN GROUP order wins, so mode() WITHIN GROUP (ORDER BY x DESC) returns the largest tied value. Oracle's STATS_MODE gives no such guarantee.

How do I get the mode in MySQL?

GROUP BY the column, ORDER BY COUNT(*) DESC and take the first row.

Does MODE ignore NULLs?

Yes, both PostgreSQL's mode() and Oracle's STATS_MODE skip them. The GROUP BY recipe does not: add WHERE col IS NOT NULL or NULL can win.

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: PostgreSQL, 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.