Demo: building the monthly sales report in SQL
On This Lesson 3 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
build the monthly report as one query that uses CTEs, windows, and FILTER.
Draft outline details
Step by step
- Show the Java version that loads all orders and aggregates in memory; note its row count and time.
- Write a CTE
monthlythat groups paid orders bydate_trunc('month', created_at)and category. - Add
rank() OVER (PARTITION BY month ORDER BY revenue DESC)and keep the top 3. - Add
lag(revenue)for month-over-month change andFILTERfor refunded counts. - Planned mistake: put the
rank()condition inWHERE; PostgreSQL rejects it. Fix: wrap in a CTE and filter outside. - Compare time and data transferred with the Java version.
Prepares MID-011-LAB1.
Check your understanding
Why is aggregating in SQL usually better than in Java?
Show answer
Less data crosses the network and the database is built for it.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.