Write a SQL query that left joins CLIENT to STATE, then groups by state name and sums revenue.
💡 Model Answer
The LEFT JOIN guarantees that every row from the CLIENT table appears in the result set, even if there is no corresponding state in the STATE table. This is important when you want to report on all clients, including those that might not yet be assigned a state. The query then aggregates revenue per state: SELECT s.state_name, COALESCE(SUM(r.revenue), 0) AS total_revenue FROM client c LEFT JOIN state s ON c.state_id = s.state_id LEFT JOIN revenue r ON c.client_id = r.client_id GROUP BY s.state_name ORDER BY total_revenue DESC;. The COALESCE function replaces NULL sums with 0, ensuring that states with no revenue still appear in the output. GROUP BY collapses all rows that share the same state_name into a single row, and SUM aggregates the revenue values. Ordering by total_revenue DESC shows the highest‑earning states at the top. In practice, you would index the foreign keys (client.state_id, revenue.client_id) to speed up the join and aggregation. This pattern is common in reporting dashboards where you need to display metrics even when some dimensions are missing.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500