Brightlane's regional sales director is building a territory overview that organises customers by country.
Write a query to return each customer's name, email, and country, grouped visually by country and then alphabetised within each country.
Assumptions:
- The
customerstable contains every customer Brightlane has on file. - Sorting by
countryfirst produces contiguous blocks of customers from the same country; sorting bynamewithin each block alphabetises the customers inside that block.
Output:
- One row per customer, with columns
name,email, andcountry, sorted bycountryascending, then bynameascending.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
name,
email,
country
FROM
customers
ORDER BY
country,
name The shape
Two sort keys produce the territory layout in one pass — country first turns the customer list into contiguous country blocks, and name within each block alphabetises the customers inside it.
Clause by clause
SELECT name, email, countryreturns the three columns the regional director wants in the territory overview.FROM customersreads every customer on file. There's no filter; the report covers the full book.ORDER BY country, namesorts ascending by country first, then ascending by name as the secondary key. The first key controls the outer ordering — all the Australian customers land together, all the Canadian customers land together, and so on. The second key only kicks in inside each block of equal country values, alphabetising the customers within that country.
Why this and not two separate queries
A learner reaching for this could write one query per country and stack the results, but ORDER BY with two keys does the same work in a single pass and adapts automatically when new countries appear in the data. The two-key sort doesn't need to know the country list in advance; it just orders countries alphabetically and then orders names alphabetically within each.
The mental model is left-to-right: the first key sets the major order, every subsequent key resolves ties from the keys to its left. This generalises directly to three, four, or more sort keys. The clause reads in priority order, and PostgreSQL evaluates it that way.
You practiced sorting on two keys, where the second key is a tiebreaker only within blocks of equal first-key values. The mental model — sort by key 1, then resolve ties with key 2 — generalises to any number of keys and is how every grouped-and-ordered report is built.