Skip to content
Learn Netverks

Lesson

Step 21/36 58% through track

having-clause

HAVING clause

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~2 min
Level
intermediate

This lesson

This lesson teaches HAVING clause: the SQL patterns, schema habits, and query reasoning you need before advancing in SQL.

Teams query HAVING clause on every SQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply HAVING clause in contexts like: Postgres, MySQL, SQLite, warehouses, and ORMs that still expose SQL.

Copy SQL from each lesson into SQLite (sqlite3), DB Fiddle, or local Postgres—read result grids and row counts. The in-browser SQL lab (sql_sandbox) will run queries when the runner ships; until then, local clients are the practice path.

When you can explain the previous lesson's ideas without copying example queries verbatim.

HAVING filters groups after aggregation—unlike WHERE, which filters rows before grouping. Use it for conditions on COUNT, SUM, AVG, etc.

HAVING basics

SELECT customer_id,
       SUM(total) AS spent
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 100;

Practice: Seed customers and orders sample data, then run each query. Verify row counts manually.

WHERE + HAVING together

SELECT customer_id,
       COUNT(*) AS recent_orders,
       SUM(total) AS recent_spent
FROM orders
WHERE ordered_at >= '2025-01-01'
GROUP BY customer_id
HAVING COUNT(*) >= 2;

WHERE shrinks rows first; HAVING filters grouped results—order matters for readability and performance.

Common mistake

-- Invalid in standard SQL: aggregate in WHERE
-- SELECT customer_id FROM orders WHERE SUM(total) > 100;

SELECT customer_id
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 100;

Repeat the aggregate expression in HAVING or use a subquery/CTE alias pattern in advanced lessons.

Important interview questions and answers

  1. Q: Can WHERE use SUM()?
    A: Not on grouped aggregates—use HAVING or a subquery.
  2. Q: HAVING without GROUP BY?
    A: Valid when treating whole table as one group—rare in practice.

Self-check

  1. Filter groups with total spent over 100—which clause?
  2. Which runs first: WHERE or GROUP BY?

Tip: Filters on SUM/COUNT go in HAVING; filters on raw rows go in WHERE.

Interview prep

Aggregate in WHERE?

Invalid for grouped aggregates—use HAVING.

HAVING vs WHERE order?

WHERE before GROUP BY; HAVING after.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • HAVING vs WHERE?
  • Filter aggregates?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump