SQL — GROUP BY
2 min readDec 13, 2023
- Group By: A feature to display data in groups. The
GROUP BY
statement groups rows that have the same values into summary rows - The
GROUP BY
statement is often used with aggregate functions (COUNT()
,MAX()
,MIN()
,SUM()
,AVG()
) to group the result-set by one or more columns.
Example: How to find number of order for each product??
Product 3 has been ordered 3 time
Product 2 has been ordered 1 time
Product1 has been ordered 2 times
NO X — this is incorrect
So , we can use count() aggregate function
but we do not want to count all the product? Then what should we do? We want order per product. Then the group by come it.
Solution:
If you want to see the product sorted by the most order you can use order by counting the product. And order by has to go at the end after the group by.
If you want to find the total price for each product
select product_id, sum(order_value) from orders group by product_id;
References: