← Questions

In-memory SQL table with filtering and multi-key sorting

0
OpenAIMetaAirbnb+1CodingLast asked May 2026

Build a small in-memory SQL-like database. You do not need to parse SQL text. Queries arrive as structured arguments.

Implement SQLManager:

  • create_table(name: str, columns: list[str]) -> None creates an empty table with a fixed list of column names. Table names are unique.
  • insert(name: str, values: list[str]) -> None appends one row. It has one value per column, in column order. Every value arrives as a string, and you infer its type: a value that is an optional sign followed by digits ("42", "-7") is an integer, and anything else ("3.5", "bob") is a string. A column's type is fixed by the first value it receives. A later value of the other type is an error, and the failed insert must leave the table unchanged.
  • select(name, columns=None, where=None, order_by=None) -> list[list] returns the matching rows.
    • columns: the column names to return, in that order. None returns every column.
    • where: a list of (column, op, value) conditions that must all hold. op is one of =, !=, <, <=, >, >=. The comparison uses the column's type, so integers compare numerically.
    • order_by: a list of (column, "ASC" | "DESC") pairs. The first pair is the primary key. Rows that tie on every key keep insertion order. With no order_by, rows come back in insertion order.
    • A query may filter or sort on columns that it does not return.

Raise an error for an unknown table or column, a wrong number of values, or a filter value whose type does not match the column.

Example

create_table("users", ["id", "name", "age"])
insert("users", ["1", "ann", "30"])
insert("users", ["2", "bob", "25"])
insert("users", ["3", "cat", "30"])

select("users", ["name"], [("age", ">=", "30")])
  -> [["ann"], ["cat"]]

select("users", ["name", "age"], order_by=[("age", "DESC"), ("name", "ASC")])
  -> [["ann", 30], ["cat", 30], ["bob", 25]]

insert("users", ["x", "dan", "20"])   # error: column id holds integers

Expect follow-up parts, such as OR conditions, indexes, or UPDATE/DELETE.

Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding