← Back to SQL, page 15

sql-0297 · Easy fresher

Show each day's sales as a percentage change from the first day of the series.

Divide by FIRST_VALUE(amount) OVER (ORDER BY day) and subtract 1: 100.0 * (amount - first) / first. This indexes the series to its starting point, which makes several series comparable on one chart. Partition by series key to give each its own baseline.

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);
sql
SELECT day, amount,
       ROUND(100.0 * (amount - FIRST_VALUE(amount) OVER (ORDER BY day)) / NULLIF(FIRST_VALUE(amount) OVER (ORDER BY day), 0), 1) AS pct_vs_first
FROM daily_sales ORDER BY day;
dayamountpct_vs_first
2026-03-011200.0
2026-03-0280-33.3
2026-03-0315025.0
2026-03-0590-25.0
2026-03-0660-50.0
2026-03-0920066.7

Every row is compared with 1 March's 120. A value of -33.3 means a third below the starting level; 66.7 means two thirds above.

For several stores, PARTITION BY store_id gives each store its own first day as the baseline. Guard against a zero baseline with NULLIF, or the division will fail on PostgreSQL and return NULL on SQLite.

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 day, amount,
       ROUND(100.0 * (amount - FIRST_VALUE(amount) OVER (ORDER BY day)) / NULLIF(FIRST_VALUE(amount) OVER (ORDER BY day), 0), 1) AS pct_vs_first
FROM daily_sales ORDER BY day;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • FIRST_VALUE gives the baseline
  • Percentage change = (value - baseline) / baseline
  • Partition to give each series its own baseline
  • Guard a zero baseline with NULLIF

Common mistakes

  • Integer division producing 0
  • Using the global first value for every store

Follow-ups

  • How would you index to a fixed date instead of the first row?
  • How would you chart several stores together?

Tips

  • Mention the partitioned version