Dynamic SQL Query Builder
Difficulty: Medium · Topics: String Building, SQL, Builder Pattern · Acceptance: 0.0% of 1 submissions
Difficulty: Medium | Tags: SQL, Builder Pattern, String Building
Description
Build SQL SELECT queries dynamically from a configuration object that specifies table, columns, conditions, ordering, and pagination.
Implement a builder:
QueryBuilder
.select("name", "age")
.from("users")
.where("age", ">", 25)
.and("status", "=", "active")
.orderBy("name", "ASC")
.limit(10)
.offset(20)
.build() → String
Examples
Example 1:
QueryBuilder.select("*").from("users").build()
Output: "SELECT * FROM users"
Example 2:
QueryBuilder
.select("name", "email")
.from("users")
.where("age", ">", 18)
.and("active", "=", true)
.orderBy("name", "ASC")
.limit(10)
.build()
Output: "SELECT name, email FROM users WHERE age > 18 AND active = true ORDER BY name ASC LIMIT 10"
Example 3 — With JOIN:
QueryBuilder
.select("u.name", "o.total")
.from("users u")
.join("orders o", "u.id = o.user_id")
.where("o.total", ">", 100)
.build()
Output: "SELECT u.name, o.total FROM users u JOIN orders o ON u.id = o.user_id WHERE o.total > 100"
Constraints
- Column names and table names are non-empty.
- String values in WHERE clauses should be quoted.
- Support
AND,ORconditions. - Support
JOIN,LEFT JOIN,RIGHT JOIN. - Support
GROUP BYandHAVING.
---
## Database