- Suppose we want to know how many different products each vendor (vend_id) can supply.
SELECT vend_id,
COUNT(*) AS AantalProducten
FROM Products;
Error Code: 1140. In aggregated query without GROUP BY, expression
- This query combines incompatible result levels: it would return several vend_id values but only one total row count. This does not work!
- Use GROUP BY to combine aggregate functions with fields that return several values
- GROUP BY combines rows into groups that can be evaluated together
- It lets you apply aggregate functions to a subset of rows
SELECT vend_id,
COUNT(*) AS AantalProducten
FROM Products
GROUP BY vend_id;
| vend_id | AantalProducten |
| BRS01 | 3 |
| DLL01 | 4 |
| FNG01 | 2 |
- A GROUP BY clause can contain multiple columns
- As a rule, include every non-aggregated SELECT column in GROUP BY
- Whether aliases are allowed in GROUP BY depends on the DBMS
Select prod_id and the total quantity ordered for each product from OrderItems
SELECT prod_id,
SUM(quantity) AS TotaalBesteld
FROM OrderItems
GROUP BY prod_id;
| prod_id | TotaalBesteld |
| BNBG01 | 360 |
| BNBG02 | 360 |
| BNBG03 | 360 |
| BR01 | 120 |
| BR02 | 10 |
| BR03 | 165 |
| RGAN01 | 55 |