How do I retrieve several counts with a single SQL query?

How can I use one SQL query to calculate different counts and return them all in one row? For instance:

SELECT shop_id,
       COUNT(*) AS count_total,
       SUM(CASE WHEN role = 'admin' THEN 1 ELSE 0 END) AS count_admin,
       SUM(CASE WHEN role = 'user' THEN 1 ELSE 0 END) AS count_user
FROM account_records
GROUP BY shop_id;

The example provided is an efficient and popular method to gather multiple counts in one query. In practice, similar formatting with CASE expressions has worked well in large-scale applications. For instance, when dealing with many categories, you can easily extend the pattern without performance penalties. Additionally, if your SQL platform supports the FILTER clause, it can further simplify the syntax. The key is to structure your query such that conditional aggregation is used to compile different measures into a single, cohesive data point.

i think the case approach is solid. maybe play with db-specific optimzations for clarity, but overall its simplest. sometimes a join based method can be easier read if you have lots of conditions.

hey, has anyone tried mixing window functions with these counts? i noticed some performance diffs in certain cases and thought a different approach might help. what do u think—anyone got experance with alternative methods?

Based on my experience, while the CASE approach is straightforward and intuitive, there are scenarios where using nested queries or common table expressions (CTEs) can provide additional flexibility and clarity, especially if the query grows more complex over time. I have found that breaking down the computation into multiple steps using CTEs can make the query easier to maintain and debug. This method proves particularly useful when dealing with multiple conditional values or additional aggregation logic, as it separates concerns and can improve readability without sacrificing performance significantly.

I’ve seen a few folks use separate subqueries joined on common keys. It can help when conditions get pretty complex. might be worth trying if your db has checks where indexes are more tuned to simple aggregates. testing is key to see which method perfroms better.