Example 1
Find the most frequently given product rating
Rating 4 appears three times (more than any other), so it is the mode. The GROUP BY rating ORDER BY COUNT(*) DESC LIMIT 1 pattern groups rows by value, counts how many times each value appears, sorts highest-count first, and returns just the top row. PostgreSQL's MODE() WITHIN GROUP (ORDER BY rating) computes the same result directly as an aggregate, resolving ties by returning the smallest value in sort order. For this dataset there is a single clear winner so no tie-breaking is needed.
CREATE TABLE product_ratings (rating INT);
INSERT INTO
product_ratings
VALUES
(3),
(4),
(4),
(4),
(5),
(5),
(2);SELECT
rating AS mode_value
FROM
product_ratings
GROUP BY
rating
ORDER BY
COUNT(*) DESC
LIMIT
1;| mode_value |
|---|
| 4 |
CREATE TABLE product_ratings (rating INT);
INSERT INTO
product_ratings
VALUES
(3),
(4),
(4),
(4),
(5),
(5),
(2);SELECT
TOP 1 rating AS mode_value
FROM
product_ratings
GROUP BY
rating
ORDER BY
COUNT(*) DESC;| mode_value |
|---|
| 4 |
CREATE TABLE product_ratings (rating INT);
INSERT INTO
product_ratings
VALUES
(3),
(4),
(4),
(4),
(5),
(5),
(2);SELECT
MODE () WITHIN GROUP (
ORDER BY
rating
) AS mode_value
FROM
product_ratings;| mode_value |
|---|
| 4 |
PostgreSQL uses the MODE() ordered-set aggregate. SQL Server uses TOP 1 instead of LIMIT 1. MySQL, MariaDB, and SQLite use LIMIT 1.