Could someone explain how Count works in this SQL query?

reporting-services, sql, sql-server

Solution

I don't know exactly how the Count function knows what the heck I want it to count

There is only one thing that `COUNT` is able to count - it can count rows in which an expression evaluates to a non-null value. If you use `COUNT(1)` in a regular query, you would get `1` on each row. With `GROUP BY`, however, the `COUNT` will return the number of rows in the specific group. In your case, that would be the number of rows with the same `Customers.name`, because that is what you use for `GROUP BY`.

As far as passing `1` to `COUNT` goes, a more common practice these days is to pass an asterisk, i.e. to write `COUNT(*)`, because in most RDBMS engines there is no performance penalty for that.

Problem

I'm making a table in SSRS that contains customer names in column 1 and their corresponding number of orders in column 2. This query works for what I'm trying to accomplish, but I don't know exactly how the Count function knows what the heck I want it to count and what table I'm wanting it to count from. Could someone please explain this to me so I can better understand in the future? Thanks a ton. ``` SELECT Customers.name ,Count(1) AS OrderCount FROM Customers INNER JOIN Orders ON Customers.id = Orders.customer_id GROUP BY Customers.name ```

Original source