Day-over-Day Change in Sales

SQL coding challenge · Difficulty: easy · Topic: Window Functions · +50 XP

Problem

An analyst wants each day's sales next to the previous day's, and the difference between them. The first day has no previous day, so its columns are NULL.

Schema — `daily_sales`

| Column | Type |
| --- | --- |
| order_date | DATE |
| sales | INT |

Example Input — `daily_sales`

| order_date | sales |
| --- | --- |
| 2024-06-01 | 100 |
| 2024-06-02 | 150 |
| 2024-06-03 | 120 |
| 2024-06-04 | 180 |
| 2024-06-05 | 200 |

Expected Output

| order_date | sales | prev_day_sales | dod_change |
| --- | --- | --- | --- |
| 2024-06-01 | 100 | NULL | NULL |
| 2024-06-02 | 150 | 100 | 50 |
| 2024-06-03 | 120 | 150 | -30 |
| 2024-06-04 | 180 | 120 | 60 |
| 2024-06-05 | 200 | 180 | 20 |

Explanation

The first day has no day before it, so both prev_day_sales and dod_change are NULL — not 0. Nothing was sold on the previous day because there was no previous day, and those are different statements.

2024-06-02 sold 150 against the previous day's 100, so the change is +50. 2024-06-03 sold 120 against 150, so the change is -30 — a fall shows as a negative number, which is correct.

Notes

What this SQL challenge teaches you

“Day-over-Day Change in Sales” is a easy-level SQL challenge focused on Window Functions. Working through it gives you hands-on practice with LAG, OVER, Window Functions — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.

Concepts covered

How to approach it

If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:

  1. LAG(sales) OVER (ORDER BY order_date) reads the previous row.
  2. The first row has no previous row, so LAG returns NULL.
  3. Subtract to get the change: sales - LAG(sales) OVER (...).

How to practise it on PySpark.in

Open the challenge, write your SQL query in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.

Related SQL challenges

Frequently asked questions

Do I need to install Spark or a database to solve this?

No. The SQL environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.

Is this challenge free?

Yes - the problem, the sample dataset, the hints and unlimited test runs are free.

What level is it?

It is rated easy and covers Window Functions.

Solve this challenge free on PySpark.in