Why Your AI's Customers All Have the Same Revenue
Asked for the top customers by revenue and every row was $4.2 million. The subquery that was supposed to add one customer's orders added everyone's. It never mentioned the customer.
You ask: "Who are our top customers by revenue?" The AI lists ten names. Every one of them is $4.2 million. That is the company total. No customer is that big.
SELECT
c.name,
(SELECT SUM(amount) FROM orders) AS revenue
FROM customers c
ORDER BY revenue DESC
LIMIT 10
The subquery never mentions c. It adds every order, once, and that single number is written on each customer. The sort has nothing to sort. LIMIT 10 then returns ten arbitrary names, all carrying the same revenue.
A subquery is not per-customer until it says so
The outer query walks customers. The inner query does not, unless it points at the customer of the current row.
SELECT
c.id,
c.name,
COALESCE(SUM(o.amount), 0) AS revenue
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY revenue DESC
LIMIT 10
The correlated form is the same idea, written as a lookup:
(SELECT COALESCE(SUM(amount), 0)
FROM orders o
WHERE o.customer_id = c.id)
Without that WHERE, the parentheses are just a company total in disguise. This is the accidental version of a window that stamps the grand total on every row. There the OVER () is visible. Here the query looks like it is fetching that customer's orders. Adding the column up multiplies the company by the row count, which is the failure that post is about.
How to catch it
SELECT SUM(amount) AS company_total FROM orders
If the top customers are tied with each other and tied with company_total, none of those figures is a customer. Pick one name, sum that customer's orders by id, and compare. A match means the subquery was correlated. A match to the company total means it was not.
The prompt that heads this off
When I ask for revenue, orders, or counts per customer, the per-customer
number must filter to that customer id. If you use a subquery, it has to
reference the outer customer. If the top rows are tied at the same number,
stop and check that number against the company total before you rank anyone.
The short version
A subquery that does not mention the outer customer returns one number for the whole table. Every customer then shows the company total and they all tie. Filter the subquery on the customer id, or join and GROUP BY that id.
Read-only MCP gateway: mcpserver.design.
Related reading: