When working with customer purchase data, looking at individual orders doesn't always tell us the full story.
Sometimes, we need to compare a customer's current purchase with their previous purchase to understand whether their spending is increasing or decreasing.
For example:
Did the customer spend more on their latest order?
Has their purchase amount increased compared to the previous order?
Which customers are spending more over time?
We can solve this using the SQL window function "LAG()".
In this tutorial, let's see how to use "LAG()" with "PARTITION BY" and "ORDER BY" to compare customer purchases in Oracle SQL.
The Problem
Suppose we have a table called "customer_orders" containing customer IDs, order dates, and purchase amounts.
Sample Table: customer_orders
customer_id| order_date| amount
C101| 01-Nov-2026| 1000
C101| 05-Nov-2026| 1500
C101| 10-Nov-2026| 1200
C102| 02-Nov-2026| 500
C102| 08-Nov-2026| 800
C102| 12-Nov-2026| 1000
Your Challenge
Write an SQL query to:
Display…