Skip to content
Python project #21Advanced

Mini SQL Engine

A tiny relational database with a tokenizer, a recursive-descent parser and an executor for CREATE, INSERT, SELECT with WHERE/GROUP BY/ORDER BY/LIMIT, UPDATE and DELETE.

Estimated time
~7 hours to build
Files
6 files · 683 lines
Technologies
Python 3, re, operator, Modules

Introduction

Databases can seem like magic until you build one. This project implements a meaningful subset of SQL in three modules — a lexer, a parser and executor, and an interactive shell — and shows how real systems handle types, NULLs and aggregates.

Problem statement

Provide a shell that reads statements ending in ';' (possibly over several lines). Support CREATE TABLE with INT, REAL and TEXT columns; INSERT with optional column lists and several rows (all-or-nothing); SELECT of columns, * or COUNT/SUM/AVG/MIN/MAX with WHERE conditions (= != < > <= >= LIKE, AND binding tighter than OR), GROUP BY, ORDER BY [DESC] and LIMIT; UPDATE … SET … WHERE; DELETE … WHERE; DROP TABLE; SHOW TABLES; DESCRIBE. Report syntax errors, unknown tables and columns and type mismatches.

Objectives

  • Write a tokenizer with regular expressions
  • Write a recursive-descent parser
  • Execute queries over in-memory rows
  • Organise a program into modules

Features

  • Multi-line statements with an interactive prompt
  • Typed columns with validation and NULLs
  • WHERE with AND/OR and LIKE wildcards
  • Aggregates with GROUP BY, ORDER BY and LIMIT
  • UPDATE, DELETE, DROP, SHOW TABLES and DESCRIBE

Concepts demonstrated

  • Lexing and parsing
  • Query execution
  • NULL semantics
  • Modular design

System architecture

sql_lexer.tokenize turns text into typed tokens (numbers, quoted strings with '' escapes, operators, keywords and names). sql_engine.Parser offers accept/expect helpers, and Database.execute dispatches on the first keyword to a method per statement that parses and executes it. WHERE clauses become a list of AND-groups combined with OR. Aggregates skip NULLs, except COUNT(*). main.py reads statements, echoes them when input is redirected and renders results as bordered tables.

Folder structure

TextProject tree
mini-sql-engine/
├── README.md
├── main.py
├── sql_engine.py
├── sql_lexer.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

75 lines
Pythonmain.py
"""Mini SQL Engine: an interactive shell for a small subset of SQL on in-memory tables.
Supported: CREATE TABLE, INSERT INTO ... VALUES, SELECT (columns, *, COUNT/SUM/AVG/MIN/MAX,
WHERE with = != < > <= >= LIKE combined with AND/OR, GROUP BY, ORDER BY [DESC], LIMIT),
UPDATE ... SET ... WHERE, DELETE FROM ... WHERE, DROP TABLE, SHOW TABLES, DESCRIBE.
Statements end with ';' and may span several lines.
"""
import sys
from sql_engine import Database
from sql_lexer import SQLError
def render(headers: list[str], rows: list[list]) -> str:
def cell(value) -> str:
if value is None:
return "NULL"
if isinstance(value, float):
return f"{value:.2f}"
return str(value)
text = [[cell(v) for v in row] for row in rows]
widths = [max(len(h), *(len(r[i]) for r in text)) if text else len(h) for i, h in enumerate(headers)]
numeric = [all(isinstance(r[i], (int, float)) for r in rows if r[i] is not None) and rows for i in range(len(headers))]
line = "+" + "+".join("-" * (w + 2) for w in widths) + "+"
out = [line, "| " + " | ".join(h.ljust(w) for h, w in zip(headers, widths)) + " |", line]
for row in text:
out.append("| " + " | ".join(v.rjust(w) if numeric[i] else v.ljust(w) for i, (v, w) in enumerate(zip(row, widths))) + " |")
out.append(line)
out.append(f"{len(rows)} row{'s' if len(rows) != 1 else ''}")
return "\n".join(out)
def statements(stream):
"""Yield complete statements (ending with ';'), echoing them when input is redirected."""
buffer = []
echo = not stream.isatty()
prompt = "sql> "
while True:
if not echo:
print(prompt, end="", flush=True)
line = stream.readline()
if not line:
if "".join(buffer).strip():
yield " ".join(buffer)
return
if echo and line.strip():
print(f"{prompt}{line.rstrip()}")
stripped = line.strip()
if not buffer and stripped.lower() in ("quit", "exit", ".quit"):
return
if stripped and not stripped.startswith("--"):
buffer.append(stripped)
prompt = "...> " if buffer else "sql> "
if stripped.endswith(";"):
yield " ".join(buffer)
buffer = []
prompt = "sql> "
def main() -> None:
db = Database()
print("Mini SQL Engine - end statements with ';', type quit to exit")
for sql in statements(sys.stdin):
try:
result = db.execute(sql)
except SQLError as error:
print(f"Error: {error}")
continue
print(result if isinstance(result, str) else render(*result))
if __name__ == "__main__":
main()

What each file does

main.py
The interactive shell: reads statements ending in ';', renders result tables and prints errors.
sql_lexer.py
The tokenizer and the SQLError exception shared by the other modules.
sql_engine.py
The Table and Parser classes and the Database executor for every statement type.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Mini SQL Engine - end statements with ';', type quit to exit
sql> CREATE TABLE students (roll INT, name TEXT, city TEXT, marks REAL);
Table students created with 4 columns.
sql> INSERT INTO students VALUES
...> (1, 'Asha', 'Pune', 91.5),
...> (2, 'Ravi', 'Delhi', 78),
...> (3, 'Meera', 'Pune', 85),
...> (4, 'Kiran', 'Chennai', 66.25),
...> (5, 'Arjun', 'Delhi', 72);
5 row(s) inserted.
sql> INSERT INTO students (roll, name) VALUES (6, 'O''Brien');
1 row(s) inserted.
sql> SELECT * FROM students;
+------+---------+---------+-------+
| roll | name | city | marks |
+------+---------+---------+-------+
| 1 | Asha | Pune | 91.50 |
| 2 | Ravi | Delhi | 78.00 |
| 3 | Meera | Pune | 85.00 |
| 4 | Kiran | Chennai | 66.25 |
| 5 | Arjun | Delhi | 72.00 |
| 6 | O'Brien | NULL | NULL |
+------+---------+---------+-------+
6 rows
sql> SELECT name, marks FROM students WHERE marks >= 75 ORDER BY marks DESC;
+-------+-------+
| name | marks |
+-------+-------+
| Asha | 91.50 |
| Meera | 85.00 |
| Ravi | 78.00 |
+-------+-------+
3 rows
sql> SELECT name FROM students WHERE city = 'Delhi' OR city = 'Chennai' AND marks > 70;
+-------+
| name |
+-------+
| Ravi |
| Arjun |
+-------+
2 rows
sql> SELECT name, city FROM students WHERE name LIKE 'a%';
+-------+-------+
| name | city |
+-------+-------+
| Asha | Pune |
| Arjun | Delhi |
+-------+-------+
2 rows
sql> SELECT city, COUNT(*), AVG(marks), MAX(marks) FROM students GROUP BY city ORDER BY city;
+---------+----------+------------+------------+
| city | count(*) | avg(marks) | max(marks) |
+---------+----------+------------+------------+
| Chennai | 1 | 66.25 | 66.25 |
| Delhi | 2 | 75.00 | 78.00 |
| Pune | 2 | 88.25 | 91.50 |
| NULL | 1 | NULL | NULL |
+---------+----------+------------+------------+
4 rows
sql> SELECT COUNT(*), COUNT(marks), SUM(marks) FROM students;
+----------+--------------+------------+
| count(*) | count(marks) | sum(marks) |
+----------+--------------+------------+
| 6 | 5 | 392.75 |
+----------+--------------+------------+
1 row
sql> UPDATE students SET city = 'Mumbai', marks = 70 WHERE roll = 6;
1 row(s) updated.
sql> DELETE FROM students WHERE marks < 70;
1 row(s) deleted.
sql> SELECT roll, name, city FROM students ORDER BY name LIMIT 3;
+------+-------+-------+
| roll | name | city |
+------+-------+-------+
| 5 | Arjun | Delhi |
| 1 | Asha | Pune |
| 3 | Meera | Pune |
+------+-------+-------+
3 rows
sql> INSERT INTO students VALUES (7, 'Sana', 'Goa', 'high');
Error: value 'high' doesn't fit column marks (REAL)
sql> SELECT grade FROM students;
Error: table students has no column 'grade'
sql> SELECT * FROM teachers;
Error: no such table 'teachers'
sql> SELEC * FROM students;
Error: unknown statement 'selec'
sql> SHOW TABLES;
+----------+------+
| table | rows |
+----------+------+
| students | 5 |
+----------+------+
1 row
sql> DESCRIBE students;
+--------+------+
| column | type |
+--------+------+
| roll | INT |
| name | TEXT |
| city | TEXT |
| marks | REAL |
+--------+------+
4 rows
sql> quit
Input
CREATE TABLE students (roll INT, name TEXT, city TEXT, marks REAL);
INSERT INTO students VALUES
  (1, 'Asha', 'Pune', 91.5),
  (2, 'Ravi', 'Delhi', 78),
  (3, 'Meera', 'Pune', 85),
  (4, 'Kiran', 'Chennai', 66.25),
  (5, 'Arjun', 'Delhi', 72);
INSERT INTO students (roll, name) VALUES (6, 'O''Brien');
SELECT * FROM students;
SELECT name, marks FROM students WHERE marks >= 75 ORDER BY marks DESC;
SELECT name FROM students WHERE city = 'Delhi' OR city = 'Chennai' AND marks > 70;
SELECT name, city FROM students WHERE name LIKE 'a%';
SELECT city, COUNT(*), AVG(marks), MAX(marks) FROM students GROUP BY city ORDER BY city;
SELECT COUNT(*), COUNT(marks), SUM(marks) FROM students;
UPDATE students SET city = 'Mumbai', marks = 70 WHERE roll = 6;
DELETE FROM students WHERE marks < 70;
SELECT roll, name, city FROM students ORDER BY name LIMIT 3;
INSERT INTO students VALUES (7, 'Sana', 'Goa', 'high');
SELECT grade FROM students;
SELECT * FROM teachers;
SELEC * FROM students;
SHOW TABLES;
DESCRIBE students;
quit

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • The O''Brien row is inserted with NULL city and marks, which aggregates ignore: COUNT(*) is 6 but COUNT(marks) is 5.
  • city = 'Delhi' OR city = 'Chennai' AND marks > 70 returns Ravi and Arjun, because AND binds tighter than OR.
  • Inserting 'high' into a REAL column, an unknown column, an unknown table and the typo SELEC all produce errors.

Common errors

Strings containing quotes break the tokenizer

Match '...' with '' as an escaped quote, then replace '' with ' in the value.

A bad row in a multi-row INSERT leaves the others inserted

Validate every row first and extend the table only at the end.

Possible improvements

  • Add parentheses in WHERE expressions
  • Support JOIN between two tables
  • Persist tables to JSON or CSV files

Additional challenges

  1. 1Add an index (a dictionary from value to rows) and use it for = conditions.
  2. 2Implement HAVING after GROUP BY.
  3. 3Add transactions with BEGIN, COMMIT and ROLLBACK.

Built and tested it yourself? Mark it to update your dashboard.