Transactions, concurrency and queries · 4 MIN READ
Window functions and CTEs: running totals, top N per group and recursive queries
Compute running totals, differences and shares with window functions, select the top rows per group with row_number, and walk series and trees with recursive common table expressions.
Reports often need a value that depends on neighbouring rows: a running total, the change since yesterday, the best two days per region. Window functions, in SQLite since 3.25, compute those without collapsing rows the way GROUP BY does. Common table expressions name intermediate results, and WITH RECURSIVE can generate rows, such as every day in a range or every reply in a thread, that are not stored anywhere.
sqlite · A MAP OF THE IDEA
- PARTITION BY the group
- ORDER BY inside OVER
- Filter in an outer query
- Recurse with a stop rule
Useful when
- Per-row results with group context in a single query.
- Generated series and tree walks need no extra tables.
Watch out
- Ties make row_number arbitrary without a tie-breaker.
- Recursive CTEs on cyclic data need a depth bound.
Implementation & operation cost: Sorting per partition; an index matching PARTITION BY and ORDER BY avoids a temporary sort.
OVER, PARTITION BY and ORDER BY
A window function is an aggregate or ranking function followed by OVER. PARTITION BY splits rows into groups that are computed independently, and ORDER BY inside OVER defines the order within each group. With an ORDER BY, an aggregate like sum uses a frame that runs from the start of the partition to the current row and its peers, which is a running total; without one, it covers the whole partition, which gives a group total on every row. lag and lead read a value from the previous or next row and return NULL at the edges, and row_number, rank and dense_rank number rows.
Sales reports and a comment thread
The program uses a :memory: database with SetMaxOpenConns(1), because an in-memory database belongs to the single connection that created it. It computes a running total and day-over-day change per region, the best two days per region, each day's share of its region total, a daily series with zero for missing days, and an indented comment thread. A small helper scans every column as sql.NullString so NULLs print visibly.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"strings"
_ "modernc.org/sqlite"
)
func show(ctx context.Context, db *sql.DB, title, query string) {
rows, err := db.QueryContext(ctx, query)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
cols, _ := rows.Columns()
fmt.Println("--", title)
for rows.Next() {
vals := make([]sql.NullString, len(cols))
ptrs := make([]any, len(cols))
for i := range vals {
ptrs[i] = &vals[i]
}
if err := rows.Scan(ptrs...); err != nil {
log.Fatal(err)
}
out := make([]string, len(cols))
for i, v := range vals {
out[i] = cols[i] + "=" + v.String
if !v.Valid {
out[i] = cols[i] + "=NULL"
}
}
fmt.Println(strings.Join(out, " "))
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}
func main() {
ctx := context.Background()
// One connection: a :memory: database lives only on the connection that created it.
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
db.SetMaxOpenConns(1)
defer db.Close()
if _, err := db.ExecContext(ctx, `
CREATE TABLE sales (day TEXT, region TEXT, amount INTEGER);
INSERT INTO sales VALUES
('2026-11-01', 'eu', 120), ('2026-11-01', 'us', 200),
('2026-11-02', 'eu', 80), ('2026-11-02', 'us', 150),
('2026-11-03', 'eu', 160), ('2026-11-03', 'us', 210),
('2026-11-04', 'eu', 90);
CREATE TABLE comments (id INTEGER PRIMARY KEY, parent INTEGER REFERENCES comments, body TEXT);
INSERT INTO comments VALUES
(1, NULL, 'Ship it?'), (2, 1, 'Tests first'), (3, 2, 'They pass'),
(4, 1, 'Docs too'), (5, NULL, 'Unrelated thread');`); err != nil {
log.Fatal(err)
}
show(ctx, db, "running total and change per region", `
SELECT region, day, amount,
sum(amount) OVER (PARTITION BY region ORDER BY day) AS running,
amount - lag(amount) OVER (PARTITION BY region ORDER BY day) AS change
FROM sales ORDER BY region, day`)
show(ctx, db, "best two days per region", `
SELECT region, day, amount FROM (
SELECT *, row_number() OVER (PARTITION BY region ORDER BY amount DESC) AS rank
FROM sales)
WHERE rank <= 2 ORDER BY region, rank`)
show(ctx, db, "share of the region total", `
SELECT region, day, round(100.0 * amount / sum(amount) OVER (PARTITION BY region), 1) AS pct
FROM sales WHERE region = 'eu' ORDER BY day`)
show(ctx, db, "every day in the range, with zero for gaps", `
WITH RECURSIVE days(day) AS (
SELECT '2026-10-31'
UNION ALL
SELECT date(day, '+1 day') FROM days WHERE day < '2026-11-04')
SELECT days.day, coalesce(sum(s.amount), 0) AS total
FROM days LEFT JOIN sales AS s ON s.day = days.day AND s.region = 'eu'
GROUP BY days.day ORDER BY days.day`)
show(ctx, db, "thread under comment 1", `
WITH RECURSIVE thread(id, depth, path) AS (
SELECT id, 0, printf('%03d', id) FROM comments WHERE id = 1
UNION ALL
SELECT c.id, t.depth + 1, t.path || '/' || printf('%03d', c.id)
FROM comments AS c JOIN thread AS t ON c.parent = t.id)
SELECT printf('%*s', depth * 2, '') || body AS line FROM thread
JOIN comments USING (id) ORDER BY path`)
}For eu the running total grows 120, 200, 360, 450 and change starts as NULL, then -40, 80 and -70. row_number keeps 2026-11-03 and 2026-11-01 for both regions. The eu shares are 26.7, 17.8, 35.6 and 20 percent. The recursive series adds 2026-10-31 with a total of 0 through the LEFT JOIN. The thread lists comment 1, its replies 2 and 4, and reply 3 under 2, indented by depth, while thread 5 is not reached.
Top N per group
Window functions cannot appear in WHERE, because WHERE runs before windows are computed. Compute row_number() OVER (PARTITION BY region ORDER BY amount DESC) in a subquery or CTE, then filter on it outside. row_number breaks ties arbitrarily unless the ORDER BY makes rows unique, so add a tie-breaker such as day; use rank if tied rows should all be kept. The same structure gives latest row per key, first event per user and deduplication by keeping row number 1.
WITH ranked AS (
SELECT *, row_number() OVER (
PARTITION BY region ORDER BY amount DESC, day) AS rn
FROM sales)
SELECT region, day, amount FROM ranked WHERE rn <= 2;The CTE numbers each region's days from the highest amount down, using day to break ties deterministically, and the outer query keeps the first two per region.
WITH RECURSIVE
A recursive CTE has an initial SELECT, UNION ALL, and a recursive SELECT that refers to the CTE itself. SQLite runs the recursive part on each new batch of rows until it produces none, so it needs a terminating condition such as day < '2026-11-04' or a join that runs out of children. Carrying a depth and a path column lets you indent and order a tree; zero-padding the ids in the path, as printf('%03d') does, keeps text ordering correct. Add a LIMIT or a depth bound when data could contain a cycle, because UNION ALL does not stop on repeated rows.
Reading results in Go
Window functions and CTEs are ordinary SQL to database/sql: scan the columns as usual. Columns such as lag that can be NULL need sql.NullInt64 or a pointer, and computed columns have the types SQLite produced, so round(...) returns a REAL and 20.0 prints as 20 through a string scan. Push the computation into SQL when it reduces the rows sent to Go, and keep business rules that need testing and explanation in Go when the SQL would become opaque.
TAKE THIS WITH YOU
Use OVER (PARTITION BY ... ORDER BY ...) for running totals, lag for differences and row_number in a subquery for top N per group, and WITH RECURSIVE with a clear stop condition for series and trees.
Check your understanding
You need the two largest sales per region. Which query shape works in SQLite?
Go to the source
Progress stays in this browser. No account needed.