23.1. The Mode

The mode is the most frequently occurring value in a set. If there are two such values in a set, statisticians call it a bimodal distribution; three such values make it trimodal; and so forth.

Most SQL implementations do not have a mode function, since it is easy to calculate. A simple frequency table can be written as a single query in SQL-92.

This version is from Shepard Towindo, and it will handle multiple modes.

SELECT salary, COUNT(*) AS frequency
  FROM Payroll
 GROUP BY salary
HAVING COUNT(*)
      >= ALL (SELECT COUNT(*)
                   FROM Payroll
                  GROUP BY salary);

As an exercise, here is a version that does not use a GROUP BY clause to compute the mode. However, the execution time might be a bit longer than you would like.

SELECT DISTINCT salary ...

Get Joe Celko's SQL for Smarties, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.