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
*, 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.
Folder structure
Complete source code
src/Ast.java
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
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
-- 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.txtand compare withtests/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
- 1Add HAVING after GROUP BY.
- 2Support expressions in SELECT such as marks * 2.
- 3Add transactions with BEGIN, COMMIT and ROLLBACK.
Built and tested it yourself? Mark it to update your dashboard.