Member-only story
Understanding GROUP BY and HAVING
Mastering Data Aggregation in SQL
In the world of relational databases, SQL (Structured Query Language) offers powerful tools for extracting meaningful insights from data. Two essential commands for data analysis are GROUP BY and HAVING — they help summarize and filter information in a sophisticated way.
What is GROUP BY?
The GROUP BY clause is used to divide a result set into smaller groups based on one or more columns. Once these groups are formed, you can apply aggregate functions to each group. Consider these common aggregate functions:
COUNT()
: Returns the number of rows in a group.
SUM()
: Calculates the sum of values within a group.
AVG()
: Finds the average of values within a group.
MIN()
: Retrieves the smallest value within a group.
MAX()
: Returns the largest value within a group.
Example: Analyzing Sales Data
Let’s say you have a table named “sales” containing the following columns:
product_id
salesperson
order_date
quantity