Aggregation (GROUP BY)

GROUP BY is used to group data and calculate stats.

For example, to count orders per user:

SELECT user_id, COUNT(*) AS order_count
FROM orders
GROUP BY user_id;

This shows how many orders each user made.


Common aggregation functions

  • COUNT() : count
  • SUM() : sum
  • AVG() : average
  • MIN() : minimum
  • MAX() : maximum

Filtering Grouped Results (HAVING)

WHERE filters before grouping, while HAVING filters after grouping.

For example, to see only users who have 2 or more orders:

SELECT user_id, COUNT(*) AS order_count
FROM orders
GROUP BY user_id
HAVING COUNT(*) >= 2;

Now you have the core flow of SQL.