Skip to content
LeetQuant
QD07 Databases, Pipelines and Distributed Systems

QD07 · Databases, Pipelines and Distributed Systems · Lesson 1 of 5

SQL for Time Series

Aggregate, lag, roll and rank market data per symbol with GROUP BY and window functions, join trades to the prevailing quote with an as-of join, and index on (symbol, ts) so those queries seek instead of scan.

18 min

Objective

Quant developer interviews often include a live SQL round on a table of bars, trades or quotes: "daily returns per symbol", "a 20-day moving average", "the latest price for each instrument", "attach the prevailing quote to every trade". By the end of this lesson you should be able to write each of these, say what the database does to execute it, and avoid the three classic bugs: a window without PARTITION BY, a row-count window used as a calendar window, and an as-of join that looks into the future.

Every query below was run with sqlite3 (3.51), and the output shown is the real output. Window functions behave the same way in PostgreSQL, DuckDB, SQL Server and Snowflake.

The table

CREATE TABLE bars (symbol TEXT, d TEXT, close REAL, volume INTEGER);
INSERT INTO bars VALUES
  ('AAA','2024-01-02',100.0,1000), ('AAA','2024-01-03',102.0,1500),
  ('AAA','2024-01-04', 99.0,1200), ('AAA','2024-01-05',101.0, 800),
  ('AAA','2024-01-08',104.0,2000),
  ('BBB','2024-01-02', 50.0,3000), ('BBB','2024-01-03', 51.0,2500),
  ('BBB','2024-01-04', 52.0,2000), ('BBB','2024-01-05', 50.0,4000),
  ('BBB','2024-01-08', 49.0,3500);

Dates are ISO-8601 strings, so string order equals time order. Note the weekend gap between 5 and 8 January.

GROUP BY: one row per group

GROUP BY collapses each group to a single row. A volume-weighted average price (VWAP) is a ratio of two sums, not an average of prices:

SELECT symbol, COUNT(*) AS n, MIN(close) AS lo, MAX(close) AS hi,
       ROUND(SUM(close * volume) / SUM(volume), 4) AS vwap
FROM bars GROUP BY symbol ORDER BY symbol;
symbol  n  lo    hi     vwap
AAA     5  99.0  104.0  101.6308
BBB     5  49.0  52.0   50.2

Check AAA by hand: ∑pivi=660,600\sum p_i v_i = 660{,}600 and ∑vi=6,500\sum v_i = 6{,}500, so the VWAP is 660,600/6,500=101.6308660{,}600 / 6{,}500 = 101.6308. Filters on individual rows go in WHERE (before grouping); filters on aggregates go in HAVING (after).

Window functions: keep every row, add context

A window function computes a value for each row from a set of related rows, without collapsing them. Its anatomy:

f(...) OVER (PARTITION BY <key> ORDER BY <time> [ROWS | RANGE BETWEEN ... AND ...])
  • PARTITION BY restarts the calculation for each key (each symbol). Forgetting it is the most common bug in time-series SQL.
  • ORDER BY inside OVER defines "previous" and "preceding". It is unrelated to the final ORDER BY of the query.
  • The frame (ROWS or RANGE) says which neighbours enter the calculation.

LAG for returns

SELECT symbol, d, close,
       LAG(close) OVER (PARTITION BY symbol ORDER BY d) AS prev_close,
       ROUND(close / LAG(close) OVER (PARTITION BY symbol ORDER BY d) - 1, 4) AS ret
FROM bars ORDER BY symbol, d;
symbol  d           close  prev_close  ret
AAA     2024-01-02  100.0
AAA     2024-01-03  102.0  100.0       0.02
AAA     2024-01-04  99.0   102.0       -0.0294
AAA     2024-01-05  101.0  99.0        0.0202
AAA     2024-01-08  104.0  101.0       0.0297
BBB     2024-01-02  50.0
BBB     2024-01-03  51.0   50.0        0.02
BBB     2024-01-04  52.0   51.0        0.0196
BBB     2024-01-05  50.0   52.0        -0.0385
BBB     2024-01-08  49.0   50.0        -0.02

The first row of each symbol has no predecessor, so LAG returns NULL and so does the return. That is correct: do not fill it with 0. Drop the PARTITION BY (writing OVER (ORDER BY symbol, d)) and the first BBB row gets prev_close = 104.0, AAA's last close, which produces a spurious −51.9%-51.9\% return. LEAD is the mirror image and looks forward, which is exactly what a feature must never do; it is legitimate only for building labels (forward returns).

Rolling averages: ROWS versus RANGE

SELECT d, close,
       ROUND(AVG(close) OVER (PARTITION BY symbol ORDER BY d
             ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 4) AS ma3,
       COUNT(*) OVER (PARTITION BY symbol ORDER BY d
             ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS n
FROM bars WHERE symbol = 'AAA' ORDER BY d;
d           close  ma3       n
2024-01-02  100.0  100.0     1
2024-01-03  102.0  101.0     2
2024-01-04  99.0   100.3333  3
2024-01-05  101.0  100.6667  3
2024-01-08  104.0  101.3333  3

Two details matter. First, the first two rows average fewer than 3 values; return the count alongside and null out rows with n < 3 if a partial window is not acceptable. Second, ROWS counts rows, so "3 rows" is "3 trading days" only if there are no missing bars. If a bar is missing (a halt, a data gap), the window silently stretches further back in time.

RANGE with a numeric offset counts values of the ordering key instead. Ordering by julianday(d) makes the frame "the last 3 calendar days":

AVG(close) OVER (PARTITION BY symbol ORDER BY julianday(d)
                 RANGE BETWEEN 2 PRECEDING AND CURRENT ROW)
d           close  ma_3cal   n
2024-01-05  101.0  100.6667  3
2024-01-08  104.0  104.0     1

Only the last two rows are shown; the first three match the ROWS version. On 8 January the calendar window (6 to 8 January) contains only that day. Neither choice is wrong; you must choose deliberately and say which one you mean.

ROW_NUMBER for latest-per-key

"The latest row for each key" is a ranking problem: number the rows within each key from newest to oldest and keep number 1.

SELECT symbol, d, close FROM (
  SELECT symbol, d, close,
         ROW_NUMBER() OVER (PARTITION BY symbol ORDER BY d DESC) AS rn
  FROM bars
) WHERE rn = 1 ORDER BY symbol;
symbol  d           close
AAA     2024-01-08  104.0
BBB     2024-01-08  49.0

The same pattern deduplicates (keep the newest version of each (symbol, d)) and picks the top kk per group (rn <= k). ROW_NUMBER breaks ties arbitrarily; RANK gives ties the same number and can therefore return several rows per key. Add a tie-breaking column to the ORDER BY when ties are possible, so the result is deterministic.

As-of joins: the prevailing quote

Trades and quotes arrive at different instants, so an equi-join on timestamp almost never matches. On the data below, JOIN quotes q ON q.symbol = t.symbol AND q.ts = t.ts matches 1 of 5 trades. What you want is an as-of join: for each trade, the most recent quote at or before the trade time.

CREATE TABLE quotes (symbol TEXT, ts TEXT, bid REAL, ask REAL);
CREATE TABLE trades (symbol TEXT, ts TEXT, px REAL, qty INTEGER);
INSERT INTO quotes VALUES
  ('AAA','09:30:00.000', 99.98,100.02), ('AAA','09:30:00.400',100.00,100.04),
  ('AAA','09:30:01.100',100.03,100.07), ('BBB','09:30:00.200', 49.99, 50.01),
  ('BBB','09:30:00.900', 50.02, 50.04);
INSERT INTO trades VALUES
  ('AAA','09:30:00.250',100.02,200), ('AAA','09:30:00.400',100.04,100),
  ('AAA','09:30:01.500',100.03,300), ('BBB','09:30:00.100', 50.00,500),
  ('BBB','09:30:01.000', 50.04,400);

SELECT t.symbol, t.ts, t.px, q.ts AS quote_ts, q.bid, q.ask
FROM trades t
LEFT JOIN quotes q
  ON q.rowid = (SELECT q2.rowid FROM quotes q2
                WHERE q2.symbol = t.symbol AND q2.ts <= t.ts
                ORDER BY q2.ts DESC LIMIT 1)
ORDER BY t.symbol, t.ts;
symbol  ts            px      quote_ts      bid     ask
AAA     09:30:00.250  100.02  09:30:00.000  99.98   100.02
AAA     09:30:00.400  100.04  09:30:00.400  100.0   100.04
AAA     09:30:01.500  100.03  09:30:01.100  100.03  100.07
BBB     09:30:00.100  50.0
BBB     09:30:01.000  50.04   09:30:00.900  50.02   50.04

Points an interviewer will probe:

  • LEFT JOIN, not JOIN. The BBB trade at 09:30:00.100 precedes every BBB quote. An inner join would drop it silently; the left join keeps it with NULLs so you can count unmatched trades.
  • <= versus <. The AAA trade at 09:30:00.400 shares its timestamp with a quote. With <= it is matched to that quote, which may have been caused by the trade (the book updates after the fill), making the trade look as if it hit the ask. With strict < it gets the 09:30:00.000 quote instead. Which is right depends on how the feed sequences events; when in doubt, use < or a sequence number, because a join that can see the consequence of an event is look-ahead.
  • One row per trade. Selecting rowid ... LIMIT 1 guarantees one match even if two quotes share a timestamp. Joining on q.ts = (SELECT MAX(q2.ts) ...) would duplicate the trade in that case.
  • Staleness. An as-of join will happily attach a quote from an hour ago. Add a tolerance (AND q2.ts >= t.ts - interval) or return the age of the quote and filter on it.

Specialised engines have this built in: pandas.merge_asof, DuckDB's ASOF JOIN, kdb+'s aj. The semantics above are what they implement.

Indexes on (symbol, ts)

A B-tree index on (symbol, ts) stores entries sorted by symbol and then by time within each symbol. A query of the form WHERE symbol = ? AND ts <= ? ORDER BY ts DESC LIMIT 1 becomes a single descent of the tree to the right leaf: O(log⁡n)O(\log n) instead of reading every row. SQLite's EXPLAIN QUERY PLAN for the as-of join shows the difference:

-- without the index
|--SCAN t
|--SEARCH q USING INTEGER PRIMARY KEY (rowid=?) LEFT-JOIN
`--CORRELATED SCALAR SUBQUERY 1
   |--SCAN q2
   `--USE TEMP B-TREE FOR ORDER BY

-- after CREATE INDEX idx_quotes_symbol_ts ON quotes(symbol, ts)
|--SCAN t
|--SEARCH q USING INTEGER PRIMARY KEY (rowid=?) LEFT-JOIN
`--CORRELATED SCALAR SUBQUERY 1
   `--SEARCH q2 USING COVERING INDEX idx_quotes_symbol_ts (symbol=? AND ts<?)

Without the index, every trade scans the whole quote table and sorts it: O(T⋅Qlog⁡Q)O(T \cdot Q \log Q). With it, each trade costs O(log⁡Q)O(\log Q). "Covering" means the index alone holds every column the subquery needs (symbol, ts and the rowid), so the table itself is not touched.

Column order matters. The rule is equality columns first, then the range column. An index on (ts, symbol) can only use the ts range (SQLite reports USING INDEX i (ts>? AND ts<?)), so it reads every symbol's rows in the interval and filters symbol afterwards. An index on ts alone cannot help WHERE symbol = ? at all.

Indexes are not free: each one is updated on every insert, which matters for a tick table taking millions of rows per hour. Columnar warehouses usually replace secondary indexes with physical sort order and partitioning on the same keys, covered in Distributed Processing.

Worked example

20-day volatility per symbol in one query

Given bars(symbol, d, close), write a query that returns, for each symbol and day, the rolling 20-day standard deviation of daily simple returns, null whenever fewer than 20 returns are available. SQLite has no STDDEV; build it from window sums.

Show solution

Step 1: returns, partitioned by symbol. Compute them in a common table expression so the rolling step can refer to them.

Step 2: rolling moments. For a window of nn returns, the sample variance is

s2=∑r2−(∑r)2/nn−1.s^2 = \frac{\sum r^2 - (\sum r)^2 / n}{n - 1}.

Both sums are window aggregates over the same frame.

Step 3: enforce a full window. COUNT(ret) over the frame ignores the leading NULL return, so it is exactly the number of returns in the window.

WITH r AS (
  SELECT symbol, d,
         close / LAG(close) OVER (PARTITION BY symbol ORDER BY d) - 1 AS ret
  FROM bars
),
w AS (
  SELECT symbol, d, ret,
         COUNT(ret)     OVER win AS n,
         SUM(ret)       OVER win AS s1,
         SUM(ret * ret) OVER win AS s2
  FROM r
  WINDOW win AS (PARTITION BY symbol ORDER BY d
                 ROWS BETWEEN 19 PRECEDING AND CURRENT ROW)
)
SELECT symbol, d,
       CASE WHEN n = 20 THEN sqrt((s2 - s1 * s1 / n) / (n - 1)) END AS vol20
FROM w ORDER BY symbol, d;

The WINDOW clause names the frame once so the three aggregates cannot drift apart. On the five-row sample table every vol20 is NULL, as it should be; set the frame to 2 PRECEDING and n = 3 to see numbers (for BBB on 8 January the three returns are 0.0196, −0.0385 and −0.02, giving 0.0297). sqrt needs SQLite 3.35 or later. Say aloud that the one-pass formula can lose precision when the mean is large relative to the spread; for daily returns it is fine, but for raw prices you would subtract a reference value first.

Worked example

spread paid on each trade

Using the trades and quotes above, compute each trade's price relative to the prevailing mid, in basis points, using strict < for the as-of match. Which trades get a different quote from the <= version, and what is the AAA 09:30:00.400 trade's cost under each?

Show solution

The cost in basis points is 104×(p−m)/m10^4 \times (p - m)/m with mid m=(bid+ask)/2m = (\text{bid} + \text{ask})/2. Changing <= to < in the subquery only affects trades whose timestamp equals a quote's, which here is the AAA trade at 09:30:00.400. Running the strict version:

symbol  ts            quote_ts      bid     ask
AAA     09:30:00.250  09:30:00.000  99.98   100.02
AAA     09:30:00.400  09:30:00.000  99.98   100.02
AAA     09:30:01.500  09:30:01.100  100.03  100.07
  • With <=: mid =100.02= 100.02, so the cost is 104×0.02/100.02≈2.010^4 \times 0.02 / 100.02 \approx 2.0 bps, a trade at the ask.
  • With <: mid =100.00= 100.00, so the cost is 104×0.04/100.00=4.010^4 \times 0.04 / 100.00 = 4.0 bps, a trade 2 cents through the old ask.

The second reading says a buyer swept the offer and the book then moved up, which is consistent with the new quote appearing at the same millisecond. The choice of comparison doubles the measured cost, so it must be decided from how the feed orders same-timestamp events, not by default.

Knowledge check

A query computes returns with LAG(close) OVER (ORDER BY symbol, d) on a table holding many symbols. What goes wrong?

Knowledge check

The most frequent query on a tick table is WHERE symbol = ? AND ts BETWEEN ? AND ?. Which index serves it best?

Knowledge check

A daily bar table is missing three days for one stock because of a trading halt. What does AVG(close) OVER (PARTITION BY symbol ORDER BY d ROWS BETWEEN 19 PRECEDING AND CURRENT ROW) compute for that stock just after the halt?

Key takeaways

  • GROUP BY collapses rows; window functions keep every row and add context. VWAP is SUM(p * v) / SUM(v).
  • Every time-series window needs PARTITION BY symbol ORDER BY ts. Without the partition the query runs and is wrong.
  • ROWS frames count rows; RANGE frames count values of the ordering key. Missing bars make the two differ.
  • ROW_NUMBER() ... = 1 gives latest-per-key, deduplication and top-kk; add a tie-breaker for determinism.
  • An as-of join attaches the most recent row at or before each timestamp. Use a left join, decide < versus <= deliberately, guarantee one match and bound staleness.
  • Index (symbol, ts): equality column first, range column second. Read EXPLAIN to confirm a seek rather than a scan.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).