Skip to content
Java project #21Advanced

Mini SQL Engine

An in-memory database with a hand-written lexer and recursive-descent parser for CREATE, INSERT, SELECT (WHERE, GROUP BY, aggregates, ORDER BY, LIMIT), UPDATE, DELETE and more.

Estimated time
~12 hours to build
Files
9 files · 857 lines
Technologies
Java 21, Sealed interfaces, Records, Pattern matching for switch, java.util.function.Predicate

Introduction

Databases feel magical until you build a small one. This engine follows the same pipeline as real ones: text is tokenised, parsed into an abstract syntax tree of records, and executed against tables. Sealed interfaces and pattern-matching switches make each stage clear and complete.

Problem statement

Implement an interactive SQL subset over in-memory tables with INT, REAL and TEXT columns: CREATE TABLE, multi-row INSERT with type checking, SELECT with *, columns or COUNT/SUM/AVG/MIN/MAX, WHERE conditions combining comparisons and LIKE with AND, OR, NOT and parentheses, GROUP BY, ORDER BY (ASC/DESC), LIMIT, UPDATE, DELETE, DROP TABLE and SHOW TABLES. Statements may span lines and end with ;. Every error — syntax, unknown table or column, type mismatch, invalid grouping — must be reported without ending the session.

Objectives

  • Write a lexer and a recursive-descent parser for a real grammar
  • Model an AST with sealed interfaces and records
  • Evaluate conditions by compiling them into Predicates
  • Implement grouping and aggregation

Features

  • CREATE, INSERT, SELECT, UPDATE, DELETE, DROP, SHOW TABLES
  • WHERE with AND/OR/NOT, parentheses and LIKE
  • GROUP BY with five aggregates; ORDER BY and LIMIT
  • Typed columns, NULL values and escaped quotes
  • Formatted result tables and precise error messages

Concepts demonstrated

  • Lexing
  • Recursive-descent parsing
  • Abstract syntax trees
  • Query execution
  • Aggregation

System architecture

Lexer produces WORD, NUMBER, STRING and SYMBOL tokens (handling '' escapes and negative numbers). Parser has one method per grammar rule; conditions use condition → andTerm (OR andTerm)*, andTerm → factor (AND factor)*, giving AND higher precedence than OR. Ast defines the statements and conditions as sealed hierarchies of records. Database.execute switches over the statement type; WHERE trees become composed Predicates; SELECT filters, groups (LinkedHashMap keeps first-seen order), aggregates, sorts with a stable comparator and limits. Main buffers lines until a ; and prints results as tables.

TextArchitecture diagram
"SELECT name FROM t WHERE a > 1;"
--Lexer--> [SELECT][name][FROM][t][WHERE][a][>][1][;]
--Parser--> Select(items=[name], table=t, where=Compare(a, >, 1))
--Database--> filter rows with a Predicate -> project -> sort -> limit -> table

Folder structure

TextProject tree
mini-sql-engine/
├── README.md
├── src/Ast.java
├── src/Database.java
├── src/Lexer.java
├── src/Main.java
├── src/Parser.java
├── src/SqlException.java
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

src/Ast.java

36 lines
Javasrc/Ast.java
import java.util.List;
/** The parsed form of statements and WHERE conditions (an abstract syntax tree of records). */
public final class Ast {
private Ast() { }
public enum ColType { INT, REAL, TEXT }
public record Column(String name, ColType type) { }
public sealed interface Statement permits Create, Insert, Select, Update, Delete, Drop, ShowTables { }
public record Create(String table, List<Column> columns) implements Statement { }
public record Insert(String table, List<List<Object>> rows) implements Statement { }
public record Update(String table, List<Assignment> sets, Condition where) implements Statement { }
public record Delete(String table, Condition where) implements Statement { }
public record Drop(String table) implements Statement { }
public record ShowTables() implements Statement { }
/** A selected item: a column, *, or an aggregate such as COUNT(*) or AVG(marks). */
public record SelectItem(String aggregate, String column) {
String label() { return aggregate == null ? column : aggregate + "(" + column + ")"; }
}
public record Select(List<SelectItem> items, String table, Condition where, String groupBy, String orderBy, boolean descending, Integer limit) implements Statement { }
public record Assignment(String column, Object value) { }
/** WHERE trees: comparisons combined with AND / OR / NOT. */
public sealed interface Condition permits Compare, And, Or, Not { }
public record Compare(String column, String op, Object value) implements Condition { }
public record And(Condition left, Condition right) implements Condition { }
public record Or(Condition left, Condition right) implements Condition { }
public record Not(Condition inner) implements Condition { }
}

What each file does

src/Lexer.java
Tokenisation of SQL text, including string escapes and negative numbers.
src/SqlException.java
The single exception type for syntax and execution errors.
src/Ast.java
Sealed records for statements, select items and WHERE conditions.
src/Parser.java
The recursive-descent parser for the supported grammar.
src/Database.java
Tables, type checking, predicate compilation, grouping, aggregates, sorting and limits.
src/Main.java
Multi-line statement input and table formatting.

How to run it

Compile

Terminal
javac -d out $(find src -name "*.java")
# Windows PowerShell: javac -d out (Get-ChildItem -Recurse src -Filter *.java).FullName

Run

Terminal
java -cp out Main

Test against the expected output

Terminal
java -cp out Main < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | java -cp out Main > 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 - end each statement with ;
sql> CREATE TABLE students (roll INT, name TEXT, branch TEXT, marks INT, cgpa REAL);
Table students created with 5 column(s)
sql> INSERT INTO students VALUES (101, 'Asha', 'CSE', 91, 9.1), (102, 'Ravi', 'ECE', 74, 7.4), (103, 'Meera', 'CSE', 85, 8.6), (104, 'John', 'MECH', 58, 6.2), (105, 'Priya', 'ECE', 88, 8.8), (106, 'O''Brien', 'CSE', 67, NULL);
6 row(s) inserted
sql> SELECT * FROM students;
+------+---------+--------+-------+------+
| roll | name | branch | marks | cgpa |
+------+---------+--------+-------+------+
| 101 | Asha | CSE | 91 | 9.10 |
| 102 | Ravi | ECE | 74 | 7.40 |
| 103 | Meera | CSE | 85 | 8.60 |
| 104 | John | MECH | 58 | 6.20 |
| 105 | Priya | ECE | 88 | 8.80 |
| 106 | O'Brien | CSE | 67 | NULL |
+------+---------+--------+-------+------+
6 row(s)
sql> SELECT name, marks FROM students WHERE branch = 'CSE' AND marks >= 80 ORDER BY marks DESC;
+-------+-------+
| name | marks |
+-------+-------+
| Asha | 91 |
| Meera | 85 |
+-------+-------+
2 row(s)
sql> SELECT name FROM students WHERE NOT (branch = 'CSE' OR marks < 60);
+-------+
| name |
+-------+
| Ravi |
| Priya |
+-------+
2 row(s)
sql> SELECT name, branch FROM students WHERE name LIKE '%a' ORDER BY name;
+-------+--------+
| name | branch |
+-------+--------+
| Asha | CSE |
| Meera | CSE |
| Priya | ECE |
+-------+--------+
3 row(s)
sql> SELECT branch, COUNT(*), AVG(marks), MAX(cgpa) FROM students GROUP BY branch ORDER BY branch;
+--------+----------+------------+-----------+
| branch | COUNT(*) | AVG(marks) | MAX(cgpa) |
+--------+----------+------------+-----------+
| CSE | 3 | 81.0 | 9.10 |
| ECE | 2 | 81.0 | 8.80 |
| MECH | 1 | 58.0 | 6.20 |
+--------+----------+------------+-----------+
3 row(s)
sql> SELECT COUNT(cgpa), SUM(marks), MIN(name) FROM students;
+-------------+------------+-----------+
| COUNT(cgpa) | SUM(marks) | MIN(name) |
+-------------+------------+-----------+
| 5 | 463 | Asha |
+-------------+------------+-----------+
1 row(s)
sql> UPDATE students SET marks = 70, cgpa = 7.0 WHERE roll = 106;
1 row(s) updated
sql> DELETE FROM students WHERE marks < 60;
1 row(s) deleted
sql> SELECT roll, name, marks FROM students ORDER BY marks LIMIT 3;
+------+---------+-------+
| roll | name | marks |
+------+---------+-------+
| 106 | O'Brien | 70 |
| 102 | Ravi | 74 |
| 103 | Meera | 85 |
+------+---------+-------+
3 row(s)
sql> INSERT INTO students VALUES (107, 'Kiran', 'IT', 'ninety', 8.0);
ERROR: column marks needs an INT, got 'ninety'
sql> INSERT INTO students VALUES (108, 'Lina');
ERROR: expected 5 values but got 2
sql> SELECT age FROM students;
ERROR: no column 'age'
sql> SELECT name, COUNT(*) FROM students;
ERROR: column name must be aggregated or in GROUP BY
sql> SELEC * FROM students;
ERROR: unknown statement starting with 'SELEC'
sql> SELECT * FROM teachers;
ERROR: no table teachers
sql> SELECT * FROM students WHERE name = Asha;
ERROR: expected a value but found 'Asha' (strings need 'quotes')
sql> CREATE TABLE students (x INT);
ERROR: table students already exists
sql> SHOW TABLES;
+----------+---------+------+
| table | columns | rows |
+----------+---------+------+
| students | 5 | 5 |
+----------+---------+------+
1 row(s)
sql> SELECT * FROM students WHERE name = 'unterminated;
ERROR: unterminated string literal
21 statement(s), 9 error(s)
Input
-- create and fill a table
CREATE TABLE students (roll INT, name TEXT, branch TEXT, marks INT, cgpa REAL);
INSERT INTO students VALUES
  (101, 'Asha', 'CSE', 91, 9.1),
  (102, 'Ravi', 'ECE', 74, 7.4),
  (103, 'Meera', 'CSE', 85, 8.6),
  (104, 'John', 'MECH', 58, 6.2),
  (105, 'Priya', 'ECE', 88, 8.8),
  (106, 'O''Brien', 'CSE', 67, NULL);

SELECT * FROM students;
SELECT name, marks FROM students WHERE branch = 'CSE' AND marks >= 80 ORDER BY marks DESC;
SELECT name FROM students WHERE NOT (branch = 'CSE' OR marks < 60);
SELECT name, branch FROM students WHERE name LIKE '%a' ORDER BY name;
SELECT branch, COUNT(*), AVG(marks), MAX(cgpa) FROM students GROUP BY branch ORDER BY branch;
SELECT COUNT(cgpa), SUM(marks), MIN(name) FROM students;
UPDATE students SET marks = 70, cgpa = 7.0 WHERE roll = 106;
DELETE FROM students WHERE marks < 60;
SELECT roll, name, marks FROM students ORDER BY marks LIMIT 3;

-- errors
INSERT INTO students VALUES (107, 'Kiran', 'IT', 'ninety', 8.0);
INSERT INTO students VALUES (108, 'Lina');
SELECT age FROM students;
SELECT name, COUNT(*) FROM students;
SELEC * FROM students;
SELECT * FROM teachers;
SELECT * FROM students WHERE name = Asha;
CREATE TABLE students (x INT);
SHOW TABLES;
SELECT * FROM students WHERE name = 'unterminated;

Testing

  • Run with tests/sample-input.txt and compare with tests/expected-output.txt.
  • GROUP BY branch gives CSE and ECE averages of 81.0 and MECH 58.0; COUNT(cgpa) ignores the NULL.
  • WHERE NOT (branch = 'CSE' OR marks < 60) returns exactly Ravi and Priya.
  • Nine deliberate errors are each reported with a specific message, and the session continues.

Common errors

a OR b AND c is evaluated as (a OR b) AND c

Parse AND at a lower level than OR so it binds more tightly.

Some rows are inserted before a later row fails

Validate and convert every row first, then add them all — the INSERT is all-or-nothing.

Possible improvements

  • Add JOIN between two tables
  • Support indexes with a TreeMap for fast WHERE on one column
  • Save and load tables to CSV files

Additional challenges

  1. 1Add HAVING after GROUP BY.
  2. 2Support expressions in SELECT such as marks * 2.
  3. 3Add transactions with BEGIN, COMMIT and ROLLBACK.

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