BeginnerCoder

Lesson 19 — GROUP BY + HAVING + ORDER

The full query order

A complete query is written in this order: SELECT → FROM → (JOIN) → WHERE → GROUP BY → HAVING → ORDER BY → LIMIT. It helps to read it in the order the database runs it: pick rows (FROM, WHERE), group them, filter groups (HAVING), compute SELECT, then sort and cut.

SELECT city, AVG(price) FROM sales
WHERE year = 2026 GROUP BY city HAVING COUNT(*) >= 2
ORDER BY AVG(price) DESC LIMIT 2

Why it matters: most "my query gives an error" problems are clauses in the wrong order. Knowing the order makes complex reports easy to write.

Want it another way?
Task

Write the HAVING and ORDER BY lines: cities with total >= 100, biggest total first. Expected: Almaty 210.0, Astana 120.0.

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with Databases & SQL

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.