Write a query to count number of orders placed each day.
Counting Orders Placed Each Day
Explanation
To count the number of orders placed each day, we need to:
- Group the orders by date
- Count the number of orders in each date group
This is a common aggregation query that uses GROUP BY on the date column and COUNT() to get the number of orders per day.
SQL Query
SELECT
order_date,
COUNT(*) AS number_of_orders
FROM
orders
GROUP BY
order_date
ORDER BY
order_date;
Dummy Data Table (orders)
Let's create a sample orders table with some dummy data:
| order_id | customer_id | order_date | amount |
|---|---|---|---|
| 1 | 101 | 2023-01-01 | 100.00 |
| 2 | 102 | 2023-01-01 | 150.00 |
| 3 | 103 | 2023-01-02 | 200.00 |
| 4 | 101 | 2023-01-02 | 75.00 |
| 5 | 104 | 2023-01-02 | 300.00 |
| 6 | 105 | 2023-01-03 | 125.00 |
| 7 | 102 | 2023-01-04 | 250.00 |
| 8 | 103 | 2023-01-04 | 180.00 |
| 9 | 101 | 2023-01-04 | 90.00 |
| 10 | 106 | 2023-01-05 | 400.00 |
Expected Output
After running the query on this dummy data, the output would be:
| order_date | number_of_orders |
|---|---|
| 2023-01-01 | 2 |
| 2023-01-02 | 3 |
| 2023-01-03 | 1 |
| 2023-01-04 | 3 |
| 2023-01-05 | 1 |
Breakdown of the Results
- On 2023-01-01: 2 orders (order_id 1 and 2)
- On 2023-01-02: 3 orders (order_id 3, 4, and 5)
- On 2023-01-03: 1 order (order_id 6)
- On 2023-01-04: 3 orders (order_id 7, 8, and 9)
- On 2023-01-05: 1 order (order_id 10)
Variations
If you want to include days with zero orders, you would need a calendar table and a LEFT JOIN:
WITH date_range AS (
SELECT generate_series(
'2023-01-01'::date,
'2023-01-05'::date,
'1 day'::interval
)::date AS calendar_date
)
SELECT
d.calendar_date AS order_date,
COUNT(o.order_id) AS number_of_orders
FROM
date_range d
LEFT JOIN
orders o ON d.calendar_date = o.order_date
GROUP BY
d.calendar_date
ORDER BY
d.calendar_date;
This would ensure all dates in the range appear in the results, even if no orders were placed on that day.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
