HomeInterview QuestionsWrite a SELECT query to retrieve each customer ID …

Write a SELECT query to retrieve each customer ID and the total number of orders from the orders table.

🟡 Medium Coding Junior level
1Times asked
May 2026Last seen
May 2026First seen

💡 Model Answer

To get the total number of orders per customer you can use the COUNT aggregate function and GROUP BY. The query assumes the orders table has a column named customer_id that references the customer.

SELECT customer_id, COUNT(*) AS total_orders

FROM orders

GROUP BY customer_id;

Explanation: COUNT(*) counts all rows for each customer_id. GROUP BY groups the rows by customer_id so the count is calculated per customer. If you only want to count distinct orders you could use COUNT(DISTINCT order_id). The result will list each customer_id once with the number of orders they have placed. Complexity is O(n) where n is the number of rows in orders, as the database scans the table once and aggregates by key.

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 — invisible to screen sharing.

Get Assisting AI — Starts at ₹500