Mode disclosure
All modes use one coherent workspace; only disclosure and guidance change. Learn mode keeps theory, concept names, full schema help, progressive hints, and solution review available.
HAVING, Conditional Aggregation, and Safe Ratios / compare queries
M15-A05 - Alternative - express the same metrics with aggregate FILTER
M15-A05 - Alternative - express the same metrics with aggregate FILTER. Filter groups, compute conditional metrics, and calculate safe rates.
- Result grain
- one customer_id group comparing conditional aggregate syntax
- Exact columns
- customer_id; completed_orders; cancelled_orders
SQL editor shortcuts: Ctrl or Command Enter runs the query, Ctrl or Command Shift Enter checks it, Alt H opens the next hint, Ctrl or Command slash toggles a line comment, Ctrl or Command Shift F formats the SQL, and Escape closes transient UI.
Cursor at line 1, column 1.
Scenario
Filter grouped reports and calculate conditional metrics deliberately: separate WHERE from HAVING, make conditional populations explicit, and protect ratios with numeric division and NULLIF.
HAVING, Conditional Aggregation, and Safe Ratios / compare queries
One-sentence task
M15-A05 - Alternative - express the same metrics with aggregate FILTER. Filter groups, compute conditional metrics, and calculate safe rates.
Learn mode disclosure
Theory, concept names, full schema help, and progressive hints are available.
Structured output contract
- Result grain
- one customer_id group comparing conditional aggregate syntax
- Exact columns
- customer_id; completed_orders; cancelled_orders
- Source population
- Use the prompt setup plus FROM, JOIN, WHERE, and subquery predicates as the source population. Visible rows are only examples.
- Grouping
- Group only at the requested output grain: one customer_id group comparing conditional aggregate syntax.
- Ordering
- return completed_orders; return cancelled_orders; order by customer_id nulls last
- Validation
- select-only; hidden deterministic variants.
Relevant tables
Time and difficulty
- Estimated time
- 9 minutes
- Difficulty
- 4/5
Objective and concepts
Debug the requested SQL output contract for having, conditional aggregation, and safe ratios using source grain, columns, ordering, and edge-case evidence.
Glossary links
Concept material
SQL Trail treats every query as an evidence trail: identify source grain, transform rows deliberately, then compare output to a shared contract.
A passing query must handle hidden nulls, ties, boundaries, and no-match rows when the contract makes them relevant.
Syntax card
SELECT <requested_columns>
FROM <source_table>
WHERE <source_population_filter>
GROUP BY <result_grain_columns>
ORDER BY <deterministic_tie_breakers>;- <requested_columns> means the exact output columns, aliases, and order from the visible contract.
- <source_population_filter> means the row population definition, not a copied visible-row value.
- <deterministic_tie_breakers> means all ordering and tie rules needed for repeatable output.
Why this works
Each CASE contributes 1 for matching rows and 0 otherwise, so every group reports both conditional metrics.
Edge cases
Hidden variants preserve nulls, ties, duplicates, boundaries, no-match rows, and alternate row order when those risks apply.
PostgreSQL note
The local engine uses PostgreSQL-compatible syntax, including explicit NULL predicates, deterministic ORDER BY clauses, and transactional grading.
Worked example
SELECT customer_id, SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END)::int AS completed_orders, SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)::int AS cancelled_orders FROM orders GROUP BY customer_id ORDER BY customer_id NULLS LAST;Assumptions, dialect notes, and common traps
- Duplicate policy
- Preserve duplicate facts unless the prompt explicitly asks for distinct tuples or set semantics.
- Null policy
- Preserve NULL, empty string, zero, and false as distinct values unless the contract says to display a fallback.
- Tie-breakers
- Use every ordering rule in the contract and end tied business metrics with deterministic secondary keys when needed.
- Zero-related entities
- Do not invent zero rows unless the contract asks for preserved parents, missing entities, or complete periods.
- Numeric tolerance
- Use exact semantic comparison unless the activity explicitly declares a numeric tolerance.
PostgreSQL-compatible local checks
Queries run in a local PGlite worker with PostgreSQL-style syntax and transactional grading.
- WHERE cannot see aggregate values: A COUNT, SUM, or rate condition is placed in WHERE and fails before groups are formed. Repair: Filter source rows in WHERE, then filter grouped aggregate results in HAVING.
- Conditional counts need explicit zeroes: A CASE expression omits ELSE 0 and nonmatching rows stop contributing to the intended count. Repair: Return 1 for matching rows and 0 for nonmatches, or use FILTER on the aggregate.
- Integer division hides real rates: A rate looks like 0 or 1 because both operands stayed integer until after division. Repair: Cast the numerator or denominator to numeric before dividing.
- Population definitions must match the metric: A numerator, denominator, or HAVING condition uses a plausible but different set of rows. Repair: Name each population explicitly and keep the same denominator for the reported rate.
Opened hints
No hints opened yet.