Horje
How to Find Most Frequent Value in Column in SQL?

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.

MySQL
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:

Output for the Most Frequent Value in SQL Column

Output

Explanation: Upon executing the above query, you’ll find that in the GetRepeatedValue table, the most repeated value in the Value column is 6.




Reffered: https://www.geeksforgeeks.org


SQL

Related
How To Capitalize First Letter in SQL? How To Capitalize First Letter in SQL?
Scalar Function in SQL Server Scalar Function in SQL Server
Encryption and Schema Binding Option in User Defined Function Encryption and Schema Binding Option in User Defined Function
How To Get the Current Date Without Time in T-SQL? How To Get the Current Date Without Time in T-SQL?
How to Connect Teradata Using SAS in SQL? How to Connect Teradata Using SAS in SQL?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13