← Questions
In-memory SQL table with filtering and multi-key sorting
0
I was asked this
No reports yet. Sign in to say where you were asked it.
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]) -> Nonecreates an empty table with a fixed list of column names. Table names are unique. -
insert(name: str, values: list[str]) -> Noneappends 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.Nonereturns every column. -
where: a list of(column, op, value)conditions that must all hold.opis 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 noorder_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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
Write and test your solution herePython in your browser, the question's tests level by level, saved for you.Sign in to start coding


