Combine SQLite Count() with GROUP BY to Add a “Count” Column to your Result Set

If you need to add a “count” column to the result set of a database query when using SQLite, you can use the count() function to provide the count, and the GROUP BY clause to specify the column for which to group the results.

Example

Here’s a quick example to demonstrate.

SELECT ArtistId, count(Title)
FROM Album
GROUP BY ArtistId
LIMIT 10;

Result:

ArtistId    count(Title)
----------  ------------
1           2           
2           2           
3           1           
4           1           
5           1           
6           2           
7           1           
8           3           
9           1           
10          1           

In this case, each artist’s ID is listed in the ArtistId column, and the number of albums for that artist is listed in the count(Title) column.

To make this slightly easier to read, here’s a similar query, but this time I return the artist’s name instead of the ID. I do this by performing an inner join with the Artist table.

In this case, I add a WHERE clause to return only those artists that start with the letter D.

SELECT 
  ar.Name, 
  count(al.Title)
FROM Album al
INNER JOIN Artist ar
ON ar.ArtistId = al.ArtistId
WHERE ar.Name LIKE 'D%'
GROUP BY ar.Name;

Result:

Name             count(al.Title)
---------------  ---------------
David Coverdale  1              
Deep Purple      11             
Def Leppard      1              
Dennis Chambers  1              
Djavan           2              
Dread Zeppelin   1              

Ordering by Count()

We can modify this slightly so that the result set is ordered by the count. In other words, we can order it so that those artists with the most albums are listed first, and vice-versa.

SELECT 
  ar.Name, 
  count(al.Title)
FROM Album al
INNER JOIN Artist ar
ON ar.ArtistId = al.ArtistId
WHERE ar.Name LIKE 'D%'
GROUP BY ar.Name
ORDER BY count(al.Title) DESC;

Result:

Name                  count(al.Title)
--------------------  ---------------
Deep Purple           11             
Djavan                2              
David Coverdale       1              
Def Leppard           1              
Dennis Chambers       1              
Dread Zeppelin        1              

Actually, we can go a step further and add an alias for the count(). This will relieve us from having to duplicate that in the ORDER BY clause.

SELECT 
  ar.Name, 
  count(al.Title) AS AlbumCount
FROM Album al
INNER JOIN Artist ar
ON ar.ArtistId = al.ArtistId
WHERE ar.Name LIKE 'D%'
GROUP BY ar.Name
ORDER BY AlbumCount DESC;

Result:

Name                  AlbumCount
--------------------  ----------
Deep Purple           11        
Djavan                2         
David Coverdale       1         
Def Leppard           1         
Dennis Chambers       1         
Dread Zeppelin        1