To find the most frequent value in a column in SQL, use the COUNT() function to get a count of each unique value, sort the result in descending order, and select the first value in the final results set.
In SQL, sometimes we need to find frequent values in a column.
Finding the Most Frequent Value in a Column in SQL
Here, we will see an example of how to find the most frequent value in a column in SQL.
First, let's create a database and demo table.
CREATE DATABASE GFG;
USE GFG;
CREATE TABLE GetRepeatedValue (
Value INT
);
INSERT INTO GetRepeatedValue
VALUES
(2),
(3),
(4),
(5),
(6),
(4),
(6),
(9),
(6),
(8);
SQL query to select the most repeated value in the column
Count each value using the COUNT() function SQL. Then sort those values in descending order using ORDER BY clause. Get the most repeated by selecting the top 1 row with SELECT TOP 1 clause.
Query:
SELECT TOP 1 Value, COUNT(Value) AS count_value FROM GetRepeatedValue GROUP BY Value ORDER BY count_value DESC;
Output:
.png)
Explanation: Upon executing the above query, you'll find that in the GetRepeatedValue table, the most repeated value in the Value column is 6.