← Back to SQL, page 19

sql-0375 · Medium mid

A day-over-day comparison drops some days. Find the problem with the self-join.

The join looks for a row exactly one calendar day earlier, so days after a gap (no sales on the 4th, 7th or 8th) find no partner and the inner join removes them. If the intent is 'compared with the previous recorded day', use LAG over ORDER BY day; if it is 'compared with yesterday', use a LEFT JOIN and show NULL.

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;
dayamountprev_amount
2026-03-0280120
2026-03-0315080
2026-03-066090

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;
dayamountprev_amountprev_day
2026-03-01120NULLNULL
2026-03-02801202026-03-01
2026-03-03150802026-03-02
2026-03-05901502026-03-03
2026-03-0660902026-03-05
2026-03-09200602026-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