Problem 78 · Object & System Design
In-Memory SQL-like Table
01Problem
Implement Table(columns) with insert(row: dict), select(columns, where=None, order_by=None, limit=None) where where is a list of (column, op, value) conjuncts and order_by is a list of (column, 'asc'|'desc'). Optionally create_index(column) for equality lookups.
02Key insight
Separate the plan: pick an access path (hash index on an equality predicate if available, else full scan), filter, sort, project, limit. Multi-key mixed-direction ordering is done with successive stable sorts from the last key to the first.
03Solution
Try it first.
TimeO(n log n) scan+sort; O(k log k) with index hit
SpaceO(n)
tests.py · 3 passing
tests.pypython9 lines
t = Table(["id", "name", "dept", "salary"])
for row in [(1, "ann", "eng", 200), (2, "bob", "eng", 150), (3, "cat", "ops", 150), (4, "dan", "eng", None)]:
t.insert(dict(zip(t.columns, row)))
q = t.select(["name"], where=[("dept", "=", "eng")], order_by=[("salary", "desc")])
assert q == [{"name": "ann"}, {"name": "bob"}, {"name": "dan"}]
q = t.select(["id"], order_by=[("salary", "asc"), ("name", "desc")], limit=2)
assert q == [{"id": 3}, {"id": 2}]
t.create_index("dept")
assert t.select(["id"], where=[("dept", "=", "ops"), ("salary", ">=", 100)]) == [{"id": 3}]04Staff-level follow-up
How do columnar engines (Snowflake, Databricks/Photon) differ? Store columns contiguously, prune with per-micro-partition min/max zone maps, evaluate predicates vectorized over column batches, and late-materialize projected columns.