Full answer
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);The query as written:
sql
SELECT t.day, t.amount, y.amount AS prev_amount
FROM daily_sales t JOIN daily_sales y ON y.day = date(t.day, '-1 day')
ORDER BY t.day;| day | amount | prev_amount |
|---|---|---|
| 2026-03-02 | 80 | 120 |
| 2026-03-03 | 150 | 80 |
| 2026-03-06 | 60 | 90 |
Only three days appear: the 2nd, 3rd and 6th, each of which has a sale on the calendar day before. The 1st, 5th and 9th vanish without any warning.
A corrected version:
sql
SELECT day, amount, LAG(amount) OVER (ORDER BY day) AS prev_amount, LAG(day) OVER (ORDER BY day) AS prev_day
FROM daily_sales ORDER BY day;| day | amount | prev_amount | prev_day |
|---|---|---|---|
| 2026-03-01 | 120 | NULL | NULL |
| 2026-03-02 | 80 | 120 | 2026-03-01 |
| 2026-03-03 | 150 | 80 | 2026-03-02 |
| 2026-03-05 | 90 | 150 | 2026-03-03 |
| 2026-03-06 | 60 | 90 | 2026-03-05 |
| 2026-03-09 | 200 | 60 | 2026-03-06 |
LAG returns the previous row in date order, so every day appears and prev_day makes the comparison base visible. The first day has no predecessor and shows NULL. Which version is right depends on the business question, and the report should state it.
sql
CREATE TABLE daily_sales (
day TEXT PRIMARY KEY,
amount INTEGER NOT NULL
);
INSERT INTO daily_sales VALUES
('2026-03-01',120),('2026-03-02',80),('2026-03-03',150),
('2026-03-05',90),('2026-03-06',60),('2026-03-09',200);
SELECT t.day, t.amount, y.amount AS prev_amount
FROM daily_sales t JOIN daily_sales y ON y.day = date(t.day, '-1 day')
ORDER BY t.day;
SELECT day, amount, LAG(amount) OVER (ORDER BY day) AS prev_amount, LAG(day) OVER (ORDER BY day) AS prev_day
FROM daily_sales ORDER BY day;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Inner self-joins drop rows without a partner
- LAG gives the previous recorded row
- LEFT JOIN keeps calendar-day comparisons with NULLs
- State which comparison base is used
Common mistakes
- Assuming every day has data
- Mixing 'previous row' and 'previous calendar day'
Follow-ups
- How would you fill missing days with zero?
- How would you compute percentage change?
Tips
- Name both possible intents