Search code examples
mysqlsqlcountaggregationhaving

I am unable to figure out how COUNT(*) is calculating number of accounts in this case? It has always been confusing writing count(*)


I am facing a conceptual issue. Would be really grateful for your help.

I have two tables one is accounts(that has id, sales_rep_id, name as columns) and sales_reps( that has id, name as columns). I want to do the following query:

How many of the sales reps have more than 5 accounts that they manage?

I got the answer to it but I have a conceptual issue here, what does COUNT(*) point here ( number of accounts is okay but I am unable to get how could we justify that).

Thank you!

SELECT s.id, s.name, COUNT(*) num_accounts
FROM accounts a
JOIN sales_reps s
ON s.id = a.sales_rep_id
GROUP BY s.id, s.name
HAVING COUNT(*) > 5
ORDER BY num_accounts;

Solution

  • This might be easier to understand if think of it without the join:

    SELECT a.sales_rep_id, COUNT(*) as num_accounts
    FROM accounts a
    GROUP BY a.sales_rep_id
    HAVING COUNT(*) > 5
    ORDER BY num_accounts;
    

    This is counting the number of rows in accounts with the same sales rep. The join is just bringing in the name of the sales_rep; it is not changing the number of rows (assuming that the join keys match).