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;| day | amount | pct_vs_first |
|---|---|---|
| 2026-03-01 | 120 | 0.0 |
| 2026-03-02 | 80 | -33.3 |
| 2026-03-03 | 150 | 25.0 |
| 2026-03-05 | 90 | -25.0 |
| 2026-03-06 | 60 | -50.0 |
| 2026-03-09 | 200 | 66.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