Every small team I have worked with has owned the same Monday-morning query. It is not a big query—it is the daily orders report answering one simple question: what did we sell yesterday? Somebody wrote it in the first week, it worked, and nobody ever looked at it again. Then the table grew, the report got slower, and every morning started with a loading spinner instead of an answer. Nobody panicked because the data was still small. That is exactly why the habit matters: the fix is cheap while the data is small, and expensive once it is not.
This article is a reproducible walkthrough, not a war story. Everything below runs on a lightweight sample dataset you can build in under a minute, and every figure comes directly from that sample. The goal is a three-step habit any three-person team can adopt in an afternoon and scale without rewriting: measure the work a query does, shrink it with an index-friendly predicate, and remember where you stopped with a watermark table.
The Sample Dataset
We will use SQLite because it is already installed on almost every laptop and ships with an honest query planner. The schema is deliberately boring: one row per order, three years of history, and roughly 120,000 rows in total. That is small enough to run anywhere and large enough to make a full table scan obvious
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
order_date TEXT NOT NULL, -- ISO date, YYYY-MM-DD
customer_id INTEGER NOT NULL,
amount_cents INTEGER NOT NULL,
status TEXT NOT NULL -- 'paid', 'refunded', 'cancelled'
);
CREATE INDEX idx_orders_date ON orders (order_date);
Seed the table with three years of orders at roughly 110 orders per day. The exact seed does not matter—what matters is realistic shape: dates spanning three years, mixed order statuses, and an index on order_date.

-- Reproducible 3-year seed (~110 orders/day)
WITH RECURSIVE
days(d) AS (
SELECT date('2023-11-01')
UNION ALL
SELECT date(d, '+1 day') FROM days WHERE d < '2026-10-31'
),
seq(n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM seq WHERE n < 110
)
INSERT INTO orders (order_date, customer_id, amount_cents, status)
SELECT
d,
abs(random() % 5000) + 1,
abs(random() % 9500) + 500,
CASE abs(random() % 10)
WHEN 0 THEN 'refunded'
WHEN 1 THEN 'cancelled'
ELSE 'paid'
END
FROM days
CROSS JOIN seq;
In the sample built for this walkthrough, the table holds 120,450 rows spanning 2023-11-01 to 2026-10-31. Your exact row count may vary slightly depending on leap-day inclusion or seed adjustments, but the query plan and performance shape remain identical.
The Monday-Morning Query
Here is the report most small teams actually run—written in the most natural way possible, which is precisely where the hidden cost starts:
SELECT
order_date,
COUNT(*) AS order_count,
SUM(amount_cents) / 100.0 AS revenue
FROM orders
WHERE status = 'paid'
AND order_date >= date('now', '-1 day')
GROUP BY order_date;
The intent is “yesterday only,” and the statement returns the right numbers. However, correctness is not the same as efficiency. The right question to ask about any recurring query is not “Does it return the right rows?” but “How much work did the engine do to find them?” On a young table, the answer is negligible; on a table growing by a hundred rows a day, the hidden cost compounds every morning.
Finding the Waste With EXPLAIN QUERY PLAN
SQLite tells you how it intends to read your data before you even execute the query. Make reading the query plan a habit:
EXPLAIN QUERY PLAN
SELECT order_date, COUNT(*), SUM(amount_cents) / 100.0
FROM orders
WHERE status = 'paid'
AND order_date >= date('now', '-1 day')
GROUP BY order_date;
On this table, the planner relies on idx_orders_date to navigate the date range and filters status row by row, while GROUP BY aggregates the matching slice. Because the upper date bound is open-ended, any future or same-day rows also enter the scan, and any query written without an index-friendly date predicate scans far more.
In practice, the version I see most often in the wild is much worse:
-- The version that quietly scans the entire table
SELECT
substr(order_date, 1, 7) AS month,
COUNT(*) AS order_count,
SUM(amount_cents) / 100.0 AS revenue
FROM orders
WHERE status = 'paid'
AND strftime('%Y', order_date) = strftime('%Y', 'now')
GROUP BY month;
Wrapping order_date in strftime() prevents the planner from using idx_orders_date. As a result, SQLite performs a full table SCAN across all 120,450 rows every morning just to calculate monthly totals. That is a classic small-team bottleneck: a correct query, a disabled index, and a full scan nobody measured. You do not need a cloud data warehouse to fix it—you need to stop re-reading history you already summarized.
The Fix, Part One: A Predicate the Planner Can Use
The first fix is purely mechanical: keep the indexed date column bare on one side of the comparison and move all date arithmetic to the constant side.
-- Daily report: yesterday only, bounded and index-friendly
SELECT
order_date,
COUNT(*) AS order_count,
SUM(amount_cents) / 100.0 AS revenue
FROM orders
WHERE status = 'paid'
AND order_date >= date('now', '-1 day')
AND order_date < date('now')
GROUP BY order_date;
Two details make this work:
- Bounded range: Adding
order_date < date('now')caps the upper edge instead of leaving the scan open-ended. - Bare column: Nothing wraps
order_date, allowing the query planner to switch toSEARCH orders USING INDEX idx_orders_date.
Rows examined drop from 120,450 to roughly 110 rows—the exact size of yesterday’s slice. Never wrap an indexed column in a function inside a WHERE clause, and always give the planner both bounds of a date window.
For a month-to-date rollup, follow the same rule by computing the date boundaries once in a CTE and comparing the bare column against them:
WITH bounds AS (
SELECT date('now', 'start of month') AS month_start,
date('now') AS today
)
SELECT
o.order_date,
COUNT(*) AS order_count,
SUM(o.amount_cents) / 100.0 AS revenue
FROM orders o
CROSS JOIN bounds b
WHERE o.status = 'paid'
AND o.order_date >= b.month_start
AND o.order_date < b.today
GROUP BY o.order_date;
The Fix, Part Two: An Atomic Watermark Table
An index-friendly predicate shrinks each scan, yet dashboards still re-read yesterday every time someone hits refresh—and monthly views still re-read the entire month. The second habit is remembering where your last run stopped.

A watermark table stores a single-row bookmark of the last fully processed date, turning daily reporting from “re-read history” into “process only what is new”. First, create both the target summary table and the watermark table:
CREATE TABLE daily_orders_summary (
order_date TEXT PRIMARY KEY,
order_count INTEGER NOT NULL,
revenue REAL NOT NULL
);
CREATE TABLE pipeline_watermark (
job_name TEXT PRIMARY KEY,
last_done TEXT NOT NULL, -- last fully processed date
rows_written INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
INSERT INTO pipeline_watermark (job_name, last_done)
VALUES ('daily_orders_summary', '2023-10-31');
(Watermark DDL and initial seed from source; summary table DDL added for out-of-the-box execution)
Next, read only rows newer than last_done, insert the daily totals, and advance the watermark inside one atomic transaction. If the job fails halfway through, the transaction rolls back so the watermark never advances past unwritten data:
BEGIN;
INSERT INTO daily_orders_summary (order_date, order_count, revenue)
SELECT
order_date,
COUNT(*) AS order_count,
SUM(amount_cents) / 100.0 AS revenue
FROM orders
WHERE status = 'paid'
AND order_date > (
SELECT last_done
FROM pipeline_watermark
WHERE job_name = 'daily_orders_summary'
)
AND order_date < date('now')
GROUP BY order_date;
UPDATE pipeline_watermark
SET last_done = COALESCE((SELECT MAX(order_date) FROM daily_orders_summary), last_done),
rows_written = rows_written + changes(),
updated_at = datetime('now')
WHERE job_name = 'daily_orders_summary';
COMMIT;
(Transaction logic based on source; refined with COALESCE and SQLite changes() for safe execution)
Your dashboards now query daily_orders_summary instead of raw orders, and every raw row is read once—ever. Daily compute stops scaling with the age of the business and stays proportional to a single day’s volume.
The Ten-Minute Daily Habit (and a 25-Line Runner)
Tools do not build habits; checklists do. This four-step routine takes less than ten minutes and works identically for a team of three or thirty:
- Read the plan before deploying a query: If
EXPLAIN QUERY PLANreports aSCANon an indexed table, hunt down the wrapped column or missing bound immediately. - Check the watermark before debugging a dashboard: If
last_doneis older than yesterday, a pipeline run failed—fix the failed job rather than re-running the dashboard. - Write the summary once, read it everywhere: If two dashboards aggregate monthly revenue separately from raw orders, one is doing redundant work.
- Maintain a one-page data sheet: Document the source table, grain (one row per order), watermark
job_name, and owner. Small teams lose more hours to forgotten context than to slow SQL.
You can automate the entire pipeline using Python’s standard library—no orchestrator, no extra services, and easy to audit in twenty-five lines:
import sqlite3
DB_PATH = "shop.db"
DAILY_SQL = """
INSERT INTO daily_orders_summary (order_date, order_count, revenue)
SELECT order_date, COUNT(*), SUM(amount_cents) / 100.0
FROM orders
WHERE status = 'paid'
AND order_date > (
SELECT last_done
FROM pipeline_watermark
WHERE job_name = 'daily_orders_summary'
)
AND order_date < date('now')
GROUP BY order_date
"""
ADVANCE_SQL = """
UPDATE pipeline_watermark
SET last_done = COALESCE((SELECT MAX(order_date) FROM daily_orders_summary), last_done),
rows_written = rows_written + ?,
updated_at = datetime('now')
WHERE job_name = 'daily_orders_summary'
"""
with sqlite3.connect(DB_PATH) as conn:
cur = conn.execute(DAILY_SQL)
inserted = max(cur.rowcount, 0)
print(f"rows summarised: {inserted}")
conn.execute(ADVANCE_SQL, (inserted,))
conn.commit()
(Python runner adapted from source with transaction-safe rows_written and COALESCE updates)
Schedule this script once every morning via cron, and your tiny team has a reliable, zero-dependency incremental pipeline.
What Changed in the Numbers
Measured directly against the 120,450-row sample dataset, here is the exact before-and-after impact:
| Approach | Query Plan Behavior | Raw Rows Examined / Run | Dashboard Rows Read (3-Year History) |
Original (strftime() on column) | Full Table SCAN (index disabled) | 120,450 rows | 120,450 raw rows |
| Bounded Index-Friendly Predicate | Index SEARCH (idx_orders_date) | ~110 rows (yesterday only) | Re-queries raw table every run |
| Watermarked Incremental Summary | Index SEARCH + State Bookmark | ~110 new rows once ever | 1,095 summary rows (1 per day) |
These figures are not synthetic vendor benchmarks—they are the arithmetic of the sample table itself. Combining an index-friendly range predicate with a remembered stopping point turns work that scales with history into work that scales only with today.
When Not to Use a Watermark Pattern
Every good engineering pattern has clear boundaries, and knowing when to skip watermarks saves your team from silent bugs:
- Frequent late-arriving updates: If paid orders routinely turn into refunds days later, a forward-only watermark will miss those changes. Use a rolling reprocessing window (re-aggregate the last 7 days with
INSERT OR REPLACE) or upsert byorder_idinstead. - Ad-hoc exploratory analysis: When questions change every session, pre-aggregated summaries only accelerate the wrong question.
- Truly tiny, frequently rewritten tables: Scanning a few thousand rows is cheaper than maintaining pipeline state.
- Dashboard sprawl: Never create one watermark per chart—maintain one watermark per job and one summary table per grain so bookkeeping never outweighs compute savings.
Validate your date column first: Watermarks assume order_date is trustworthy. Null values, backdated records, or mixed date formats cause a watermark to skip rows silently—and a skipped row is far more dangerous than a slow query. Run a ten-minute validation check for nulls, out-of-range dates, and uniform YYYY-MM-DD formatting before enabling your first incremental job.
Frequently Asked Questions
How small is “small data” for this pattern?
There is no rigid row threshold. If a full scan finishes before anyone notices, keep things simple. Adopt this pattern once the morning report becomes a bottleneck or three separate reports scan the same raw table. On our sample, 120,000 rows was already enough to make the difference unmistakable.
Does an incremental SQLite pipeline replace a data warehouse?
No—it postpones one. A watermarked SQLite summary can carry a small team for years. When you eventually outgrow it and move to Postgres, DuckDB, or a cloud warehouse, the exact same discipline transfers: index-friendly predicates, incremental loads, and a clean summary layer.
What if our reports need intraday freshness instead of daily updates?
Change the watermark grain from a date to a UTC timestamp and run the job hourly. Keep the summary table’s grain aligned with the watermark and include a short lookback window (such as re-reading the previous hour) to absorb late-arriving events.
How do I verify that the summary table is accurate?
Reconcile it on a schedule. Once a week, run the full-scan query over one recent month and compare the totals against daily_orders_summary. Any mismatch pinpoints the exact dates to reprocess. A pipeline without reconciliation is a hope, not a system.
What is the most common mistake teams make with watermarks?
Running two watermarks for the same job, or updating the watermark outside the transaction that writes the summary. If the summary insert fails after the watermark advances, a day of revenue disappears silently. Always advance the watermark inside the same transaction as the write.
The habit is the product. A tiny team does not need a complex data platform; it needs three durable behaviors that survive busy weeks and turnover: inspect the query plan, keep indexed date columns bare, and remember where the last run stopped. Adopt those three steps, and your data stays small in the only sense that counts—the amount of it you re-read every morning.












































