Query Builders
A query builder is an API that assembles SQL from methods (where, join, limit) and binds parameters for you. It sits between raw SQL strings and a full ORM.
Detailed Explanation
Raw SQL is a string. Dynamic filters (if (q) sql += " AND email LIKE ...") become injection bugs and missing spaces. A query builder keeps a structured object and renders SQL at the end:
knex("users").select("id", "email").where({ role: "admin" }).limit(10);
Knex is the classic Node builder (and the base under older Objection). Kysely and Drizzle add TypeScript column types. Prisma is an ORM that also exposes $queryRaw; it is not a general builder for ad-hoc SQL.
Builders shine at composable filters: a function returns a query fragment, another adds a join, a third adds pagination. They still look like SQL, so you can predict the plan. They do not map rows to class instances or manage a unit of work (unless you add that).
You must still know SQL. orWhere grouping, forUpdate, and window functions have builder spellings that are easy to get wrong. When the builder fights you, drop to knex.raw("... ?", [value]) with bindings — never interpolate.
What it costs you: a dialect layer (Postgres vs MySQL identifier quotes) and a second language to learn. For a five-query service, raw pg is less to teach. For a report explorer with 20 optional filters, a builder pays for itself.
Reach for a query builder when SQL is dynamic and you do not want an ORM identity map. Reach for an ORM when models and relations are the app. Reach for raw SQL when the query is a known, tuned statement.
Pagination is where builders earn their keep. A helper that applies limit/offset or a keyset (where("id", ">", cursor)) can sit on every list query without each route reinventing it. Offset pagination is simple and slow on deep pages; keyset pagination needs a stable sort. Put that choice in the builder, not in twelve handlers.
When you log queries in development, log duration too. A builder that looks tidy can still emit a Cartesian join.
Code Examples
function listUsers(knex, { role, q, page = 1 }) {
const query = knex("users").select("id", "email").orderBy("id");
if (role) query.where("role", role);
if (q) query.where("email", "ilike", `%${q.replace(/%/g, "\\%")}%`);
query.limit(20).offset((page - 1) * 20);
return query;
}const sql = knex("orders")
.join("users", "users.id", "orders.user_id")
.where("orders.total", ">", 50)
.select("orders.id", "users.email")
.toString();Bound raw fragment
// Bound raw fragment
knex.raw("created_at > ?", [since]);Common Gotchas
String-concatenating user input into `raw` is injection
pass bindings as the second argument.
`ilike` with `%${q}%` still needs escaping of `%` and `_`
user wildcards can widen the scan.
`toSQL()` / `toString()` is for debugging
log bindings too, not only the text.
Identifier names (`orderBy(userInput)`) can also be injection
allowlist column names.