Skip to the content

The order of the clauses

SQL · Unit 6: Grouping

Back at the store. The owner wants to reward a customer. Counting what's been sold up to today, January 15, and only among customers who have ordered at least twice, who has bought the most units?

The question has several parts, and each one is a clause you already know. Together they always go in this sequence: SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY, and LIMIT. You don't have to use them all. The ones you do use keep that sequence.

SELECT customer_id,
  SUM(quantity) AS units
FROM orders
WHERE placed <= '2026-01-15'
GROUP BY customer_id
HAVING COUNT(*) >= 2
ORDER BY units DESC
LIMIT 1;

Returns

customer_idunits
27

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Put the lines in order

    Today, January 15, isn't over yet, so it doesn't count. Of the days before it, and among those that had two orders, which was the slowest in units? Put the query in order.

  2. 2. Predict the output

    The query that opened the lesson said customer 2, with 7 units up to today. This one has had its HAVING removed. Customer 4 placed a single order, for 10 units, on January 9. What does it return?

  3. 3. Predict the output

    Orders 1 and 2, the first two in the table, belong to customer 1, who has three in all. Customer 2 has three too. What does this query return?

  4. 4. Complete the code

    Which sections have something available for under 100, and starting at what price? Out-of-stock products don't count. Fill in the blanks so that each filter gets its word.

  5. 5. Find the bug

    How many units of each product have been ordered up to today, January 15? Here SQL answers near "GROUP": syntax error. Which line has the problem?

  6. 6. Multiple choice

    In PostgreSQL, HAVING units > 5 is an error even though the SELECT says SUM(quantity) AS units. Here it gets through. Going by the order a query is worked out in, why does it fail there, and what do you write so it runs in both?

  7. 7. Multiple choice

    In this unit you saw that, next to GROUP BY category, the SELECT can't ask for a bare name. Going by the order a query is worked out in, why?

  8. 8. Put the lines in order

    Orders of 2 to 5 units get a quantity discount. Which customers have gotten it more than once? Put the query in order. One line doesn't belong.

  9. 9. Write the code

    The store is going to open its first pickup location in the city where it has the most customers. Customers with no city on file don't count, however many there are. Write a query that returns a single row with two columns, in this order: the city and how many customers it has.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →