MODULE 3 OF 8: AGGREGATE QUERIES • LESSON 2 OF 4~20 min read

GROUP BY and HAVING

GROUP BY turns detailed records into one summary row per category or category combination. HAVING filters those groups after aggregation. Together they power common interview and reporting tasks such as employee counts by unit, revenue by month, and customers with several purchases.

•

GROUP BY turns detailed records into one summary row per category or category combination. HAVING filters those groups after aggregation. Together they power common interview and reporting tasks such as employee counts by unit, revenue by month, and customers with several purchases.

Key Takeaways at a Glance:

  • •GROUP BY collapses rows sharing identical values into summary rows.
  • •HAVING filters aggregated groups based on summary conditions (e.g. HAVING COUNT(*) > 5).
  • •Execution sequence: WHERE filters rows -> GROUP BY forms groups -> HAVING filters groups -> SELECT projects -> ORDER BY sorts.
  • •Under ONLY_FULL_GROUP_BY, selected columns must either appear in GROUP BY or be enclosed in aggregate functions.

In Simple Words (The Mental Model)

GROUP BY organizes your data into categorized buckets (like putting all Engineering employees in one bucket and Sales in another). Once the buckets are full, HAVING lets you throw away buckets that don't meet your criteria (e.g. 'only keep departments with more than 10 people').

Real-World Analogy

Think of sorting coins into separate piggy banks: one for quarters, one for dimes, one for nickels (GROUP BY). After counting each piggy bank, you say: 'Only take the banks that have more than $10 total to the coin counter' (HAVING).

Foundational Principles

Core Concept Breakdown

Essential database invariants, relational theory, and execution behavior.

1How grouping changes the result

GROUP BY collects rows that share the same value in one or more grouping expressions. A query grouped by unit_id produces one output group per distinct unit_id value, including a group for NULL when such rows exist. Aggregate functions then summarize the rows inside each group. Without an aggregate or grouping, a query returns row-level results instead.

Free Preview Limit Reached (2/2 Lessons Used)

Sign In to Unlock Full Lesson Content

Visitors are limited to 2 free preview lessons. Create a free StudyVex account to unlock all 38 comprehensive theory chapters, runnable query walkthroughs, visual input & result tables, and interactive placement quizzes.