Goal: summarize groups, filter them, and distinguish HAVING from WHERE.
Connect to beer_db as the beer_db user. GROUP BY and HAVING exercises use beers and breweries.
In the connection command, -U beer_db selects the SQL role and -d beer_db selects the database. Expect the psql welcome message and a beer_db=> prompt; run the following SQL there.
Goal: produce one summary per style.
Summarise all 25 styles with their beer counts and average ABV. Sort by the unrounded average, then style for ties. Notice 25 output rows: one per style, not one per beer.
COUNT(*) and AVG(abv) operate separately within each group. ROUND formats the average only. Expect Imperial Stout first at 9.80, with 11 beers; the complete result has 25 groups.
Goal: filter by a property of an entire group.
Add HAVING to the previous query to show only styles where the average ABV exceeds 7.0%. Remember: HAVING filters groups, not rows — it runs after GROUP BY.
Expect four groups: Imperial Stout, Double IPA, Belgian Tripel, and Baltic Porter. The predicate tests the full-precision average; it does not require every beer in a retained group to exceed 7%.
Goal: observe row filtering before grouping and group filtering afterwards.
Count the beers left by WHERE abv >= 4.0: 381 of 400. Group those rows by style without HAVING: 24 groups. Then add HAVING COUNT(*) > 10: 22 groups remain, containing 362 beers. Keep the WHERE unchanged so this is a controlled comparison.
WHERE tests each beer’s ABV; HAVING COUNT(*) > 10 tests the count within each resulting style group. Exactly ten beers is insufficient because the comparison is strict. Compare all three results in order.
Goal: group on a combination of two properties.
Join each beer to its brewery, then group by country AND style. Keep combinations with at least two beers. There are 75 qualifying country–style groups; LIMIT 10 previews ten of them.
Each distinct (country, style) pair is a group; a style in two countries produces two separate summaries. HAVING COUNT(*) >= 2 keeps pairs with at least two beers. Expect ten preview rows, each with a count of two or more.
Goal: recognize and repair an ambiguous grouped SELECT.
Try selecting name while grouping only by style. PostgreSQL rejects it: a style has many beer names. Fix the ambiguity with MIN(name), then preview five groups. Here MIN chooses one example name, not an arbitrary row.
The first error is intentional. A group cannot supply a single name without a selection rule; MIN(name) supplies one. The failed standalone statement leaves psql usable. Success is the grouping error followed by five valid summaries, not merely suppressing the error.