SQLite Custom Aggregates With create_aggregate
Register a Python aggregate with sqlite3 create_aggregate, implement step and finalize, and compute a per-group median in SQL.
Code
import sqlite3
class Median:
def __init__(self) -> None:
self.values: list[float] = []
def step(self, value: float | None) -> None:
if value is not None:
self.values.append(value)
def finalize(self) -> float | None:
if not self.values:
return None
ordered = sorted(self.values)
middle = len(ordered) // 2
if len(ordered) % 2:
return ordered[middle]
return (ordered[middle - 1] + ordered[middle]) / 2
def main() -> None:
connection = sqlite3.connect(':memory:')
connection.create_aggregate('median', 1, Median)
connection.execute('CREATE TABLE samples (group_name TEXT, value REAL)')
connection.executemany(
'INSERT INTO samples VALUES (?, ?)',
[('a', 1.0), ('a', 3.0), ('a', 10.0), ('b', 2.0), ('b', 4.0)],
)
rows = connection.execute(
'SELECT group_name, median(value) FROM samples GROUP BY group_name ORDER BY group_name'
).fetchall()
print(rows)
connection.close()
if __name__ == '__main__':
main()What the code does
SQLite Custom Aggregates With create_aggregate keeps everything in the class Median and the functions __init__, step, finalize and main.
Points of care
- Plan for an install step:
sqlite3is a real dependency, resolved by the package manager.
Applying it
The main signature reads def step(self, value: float | None) -> None
Statements that matter
def step(self, value: float | None) -> None:
if value is not None:
self.values.append(value)
def finalize(self) -> float | None:
if not self.values:
return None
ordered = sorted(self.values)
middle = len(ordered) // 2
if len(ordered) % 2:
return ordered[middle]
return (ordered[middle - 1] + ordered[middle]) / 2
def __init__(self) -> None:
self.values: list[float] = []
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Do I need to install anything before running this?
- Yes: `sqlite3` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.