Skip to content
Learn Netverks

Lesson

Step 20/36 56% through track

aggregates-postgresql

Aggregates and GROUP BY

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

This lesson

This lesson teaches Aggregates and GROUP BY: the SQL patterns, schema habits, and query reasoning you need before advancing in PostgreSQL.

Teams query Aggregates and GROUP BY on every PostgreSQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply Aggregates and GROUP BY in contexts like: Modern startups, geospatial apps, and analytics-friendly OLTP systems.

Copy Postgres SQL into psql, local PostgreSQL, or DB Fiddle (PostgreSQL dialect)—use \d and EXPLAIN ANALYZE where lessons show them. The in-browser lab ships later; psql is the practice path now.

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

Aggregate functions collapse rows: COUNT, SUM, AVG, MIN, MAX. FILTER clause adds conditional aggregates without extra subqueries.

GROUP BY basics

SELECT customer_id,
       COUNT(*) AS order_count,
       SUM(total) AS revenue
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 100;

Practice: Seed customers/orders tables from earlier lessons, then run queries in psql or DB Fiddle (PostgreSQL).

FILTER clause

SELECT
  COUNT(*) FILTER (WHERE status = 'shipped') AS shipped,
  COUNT(*) FILTER (WHERE status = 'pending') AS pending
FROM orders;

GROUPING SETS preview

SELECT customer_id, status, COUNT(*)
FROM orders
GROUP BY GROUPING SETS ((customer_id, status), (customer_id), ());

Rollup/cube reports use GROUPING SETS—handy for analytics dashboards.

Important interview questions and answers

  1. Q: WHERE vs HAVING?
    A: WHERE filters rows before grouping; HAVING filters groups after aggregation.
  2. Q: COUNT(*) vs COUNT(col)?
    A: COUNT(*) counts rows; COUNT(col) ignores NULLs in col.

Self-check

  1. Where do you filter on SUM(total)?
  2. What does FILTER add to aggregates?

Pitfall: Non-aggregated columns must appear in GROUP BY in strict SQL.

Interview prep

FILTER clause?

Conditional aggregates without extra subqueries.

HAVING vs WHERE?

HAVING filters groups; WHERE filters rows before GROUP BY.

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

  • FILTER clause?
  • GROUPING SETS?

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