How to Order by Count in SQL? Database: Standard SQL MySQL MS SQL Server PostgreSQL Oracle SQLite Operators: COUNT ORDER BY ASC DESC GROUP BY Table of Contents Problem: Example: Solution: Discussion: Solution: Problem: You aggregated data into groups, but you want to sort the records in descending order by the number of elements in the groups. Example: Our database has a table named user with data in the following columns: id, first_name, last_name, and country. idfirst_namelast_namecountry 1LisaWilliamsEngland 2GaryAndersPoland 3TomWilliamsPoland 4MichaelBrownFrance 5SusanSmithUSA 6AnneJonesUSA 7EllieMillerPoland Let’s create a report on our users. We’ll group the results by country and count the number of users from each country. But we’ll also sort the groups in descending order by number of users. That way, the countries with the greatest number of users will appear at the top. Solution: SELECT country, COUNT(id) FROM user GROUP BY country ORDER BY COUNT(id) DESC; countrycount(id) Poland3 USA2 England1 France1 Discussion: To sort the selected records by the number of the elements in each group, you use the ORDER BY clause. The first step is to use the GROUP BY clause to create the groups (in our example, we group by the country column). Then, in the ORDER BY clause, you use the aggregate function COUNT, which counts the number of values in the column of your choice; in our example, we count distinct IDs with COUNT(id). This effectively counts the number of elements in each group. The ORDER BY clause then sorts the groups according to that computation. As usual, you can use both ascending or descending order with ORDER BY. If you want descending order (as in this example), you use the DESC keyword. Ascending order doesn't need any keyword because it’s the default, but you can use the ASC keyword if you want to be explicit. This is the same example but with results sorted in ascending order: Solution: SELECT country, COUNT(id) FROM user GROUP BY country ORDER BY COUNT(id); Here’s the result: countrycount(id) England1 France1 USA2 Poland3 Recommended courses: SQL Basics SQL Practice Set Standard SQL Functions Recommended articles: SQL Basics Cheat Sheet Where to Practice SQL How to Sort Records with the ORDER BY Clause How to Use COUNT() with GROUP BY: 5 Practical Examples Using GROUP BY and ORDER BY Together: A Guide SQL Aggregate Functions Cheat Sheet Top 9 SQL GROUP BY Interview Questions See also: How to Order Alphabetically in SQL How to Order By Two Columns in SQL? How to Filter Records with Aggregate Function COUNT Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts. Email address How Do You Write a SELECT Statement in SQL? What Is a Foreign Key in SQL? Enumerate and Explain All the Basic Elements of an SQL Query