Design PatternsL3 · Medium
Builder Pattern: SQL Query Builder
Problem
Building a SQL query string by concatenating strings leads to bugs and unreadable code. Design a QueryBuilder using the Builder pattern that lets you construct SELECT queries step-by-step with a fluent interface, then call .build() to get the final SQL string.
Requirements
- QueryBuilder.select(...columns) — which columns to fetch
- QueryBuilder.from(table) — source table
- QueryBuilder.where(condition) — optional filter (multiple calls = AND)
- QueryBuilder.orderBy(column, direction) — optional sort
- QueryBuilder.limit(n) — optional row limit
- QueryBuilder.build() — returns the final SQL string
- Method chaining (fluent interface): each method returns `this`
Constraints
- –from() is mandatory — build() throws if no table set
- –select() defaults to '*' if not called
- –Multiple where() calls are joined with AND
✓ Saved