Quick revision
The short answer
We inner join customers to orders, keep only orders in 2025 with a half-open range on created_at, and group by c.id and c.name to get COUNT(*) and SUM(o.total). The inner join already drops customers without a 2025 order, which is exactly the requirement. Grouping by the id keeps two customers with the same name apart, and an index on orders(customer_id, created_at) supports the join and the filter.
What to remember
In this answer, we listed customers with their 2025 order count and spend by inner joining customers to orders, filtering orders with a half-open date range, and grouping by c.id and c.name. The inner join naturally excludes customers without 2025 orders, grouping by the primary key keeps customers with equal names apart, and the range filter lets an index on orders(customer_id, created_at) help. To include customers with zero orders, we switch to a LEFT JOIN with the date in ON, count o.id and COALESCE the sum.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We inner join customers to orders, keep only orders in 2025 with a half-open range on created_at, and group by c.id and c.name to get COUNT(*) and SUM(o.total). The inner join already drops customers without a 2025 order, which is exactly the requirement. Grouping by the id keeps two customers with the same name apart, and an index on orders(customer_id, created_at) supports the join and the filter.
Background to this question
Counting and summing per parent row is the bread and butter of reporting SQL, and this question checks the details that separate a correct query from a nearly correct one: which join type matches the requirement, what to group by when names repeat, and how to write a date filter that an index can serve. In this answer, we will recap what an inner join returns, write the query, look at why each part is the way it is, discuss the index that makes it fast, and then answer the natural follow-up: how to include customers with zero orders.
1A Quick Recap of Inner Joins
An inner join returns one row for every pair of rows from the two tables that satisfy the join condition. A customer with three matching orders appears three times, once with each order, and a customer with no matching order does not appear at all. That last property is the one we will rely on: an inner join keeps only rows that have a partner on both sides.
Once the rows are paired, GROUP BY collapses them back to one row per customer, and aggregate functions such as COUNT(*) and SUM(total) summarise each group.
2Writing the Query
Tables are customers(id, name, city) and orders(id, customer_id, total, created_at).
- JOIN customers to ordersone row per (customer, order) pair
- WHERE: orders in 2025 onlyhalf-open range on created_at
- Customers without a 2025 orderhave no rows left, so they drop out
- GROUP BY c.id, c.nameone group per customer
- COUNT(*) and SUM(o.total)per group
5 steps in order. Play them, or step through them one at a time.
The result has one row per customer who ordered in 2025. Notice the two customers called Ana Silva: they are different people with different ids, and the report keeps them apart. We look at why in a moment.
3Why an Inner Join Fits the Requirement
The requirement says only customers who ordered at least once in 2025. With the inner join and the date filter, a customer whose orders are all from 2024, or who never ordered, has no joined rows left after WHERE, so no group is formed for them. The requirement is met by the join type itself; we do not need a HAVING COUNT(*) > 0 or an EXISTS.
Because every surviving row has a real order, COUNT(*) counts orders correctly here. That would change with an outer join, as we will see in the follow-up.
4Group by the Key, Not Only the Name
It is tempting to write GROUP BY c.name, because the name is all we display. But names are not unique. Two customers called Ana Silva would be merged into one group, with their orders counted and summed together, and the report would show one Ana with 13 orders. Grouping by c.id, the primary key, keeps each customer separate, and c.name is added to the GROUP BY so it can appear in SELECT.
PostgreSQL knows that c.name is functionally dependent on the primary key c.id, meaning that one id determines one name, so it accepts GROUP BY c.id alone with c.name in SELECT. MySQL accepts it too, with its ONLY_FULL_GROUP_BY mode recognising the dependency. Listing both is portable and harmless.
5A Date Filter That Can Use an Index
A common way to write the year filter is WHERE EXTRACT(YEAR FROM o.created_at) = 2025. It is correct but not sargable: the database must compute the year for every order before comparing, so an index on created_at cannot be used to jump to 2025's rows. The half-open range, from the first moment of 2025 up to but not including the first moment of 2026, leaves created_at alone on one side of each comparison, so the index can be used, and it does not need an awkward end value like '2025-12-31 23:59:59.999'.
If created_at is a timestamptz and the business year is in a specific time zone, the boundaries should be expressed in that zone, for example TIMESTAMP '2025-01-01 00:00' AT TIME ZONE 'Europe/Berlin'.
6The Index That Helps
An index on orders(customer_id, created_at) serves both the join and the filter. Its entries are sorted by customer first and date second, so for each customer the 2025 orders sit together in one small range of the index. If total is added as an included column, CREATE INDEX ON orders (customer_id, created_at) INCLUDE (total) in PostgreSQL, the query can often be answered from the index alone. For a report over all customers, the planner may instead scan 2025's orders using an index on created_at and hash join to customers; both indexes are reasonable, and EXPLAIN on realistic data shows which one wins.
7Follow-up questions
How would you include customers with zero orders?
Change the JOIN to a LEFT JOIN and move the date condition into the ON clause: LEFT JOIN orders o ON o.customer_id = c.id AND o.created_at >= DATE '2025-01-01' AND o.created_at < DATE '2026-01-01'. If the condition stayed in WHERE, it would remove the NULL rows and undo the outer join. Then use COUNT(o.id) instead of COUNT(*), because COUNT(*) counts the NULL-extended row as 1, and COALESCE(SUM(o.total), 0) so customers without orders show 0 rather than NULL.
Would WHERE EXISTS be better here?
Not when we need the count and the sum, because we need the order rows anyway. EXISTS is the right tool when we only want to know whether a customer has orders, without any order data.
What if a customer has thousands of orders?
The query still works, since aggregation handles it, but the join produces one row per order before grouping. If the report runs often over large data, aggregating orders by customer_id first and then joining customers can be cheaper, and a summary table updated daily may be better still.
8Conclusion
In this answer, we listed customers with their 2025 order count and spend by inner joining customers to orders, filtering orders with a half-open date range, and grouping by c.id and c.name. The inner join naturally excludes customers without 2025 orders, grouping by the primary key keeps customers with equal names apart, and the range filter lets an index on orders(customer_id, created_at) help. To include customers with zero orders, we switch to a LEFT JOIN with the date in ON, count o.id and COALESCE the sum.
Open with
I would join customers to orders on customer_id with an inner join, filter orders to 2025, and group per customer. So: select c.id, c.name, COUNT star as order_count and SUM of o.total as spent, from customers c join orders o on o.customer_id equals c.id, where o.created_at is greater or equal to 2025-01-01 and less than 2026-01-01, group by c.id and c.name.
Then, if they want more
The inner join is deliberate, because the requirement is only customers who ordered in 2025, and a customer with no 2025 order has no rows after the filter, so they drop out without any extra condition.
I group by the id and not just the name, because names are not unique, and grouping by name would merge two different Ana Silvas into one row with combined totals. PostgreSQL would actually accept grouping by the id alone, since the name depends on the primary key, but listing both is portable.
For the date I use a half-open range rather than EXTRACT of the year, because applying a function to created_at stops an index from being used, and the range avoids an awkward end-of-year timestamp. An index on orders customer_id and created_at, possibly including total, supports the join and the filter.
If the follow-up is to include customers with zero orders, I switch to a LEFT JOIN, move the date condition into the ON clause, count o.id instead of star, and coalesce the sum to zero.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Tables: customers(id, name, city), orders(id, customer_id, total, created_at). Write SQL...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/97a125c4f4/