01What is SQL to Knex?
Moving a Node.js codebase from raw SQL strings to Knex.js means rewriting each query as a chain of builder calls. This converter does the first pass for you. Paste one statement, press Convert, and you get a Knex chain with your literal values passed as arguments or bindings instead of baked into SQL text. It does not use regex tricks. The statement is parsed into a syntax tree first, and the chain is generated from that tree. One SELECT, INSERT, UPDATE or DELETE is accepted at a time. The method names follow the official Knex query builder documentation at knexjs.org. For SELECT, the table and alias become knex("users as u"). Plain columns go into .select() or .distinct(). COUNT, SUM, AVG, MIN and MAX become .count(), .sum() and friends, and an alias turns into the object form, such as .count({ "orders": "o.id" }). JOINs map to .join(), .leftJoin(), .rightJoin(), .fullOuterJoin() and .crossJoin(). A single column-to-column condition uses the short form. Multi-part ON clauses get a callback with .on() and .andOnVal(). WHERE is handled predicate by predicate. Comparisons become .where(), column pairs become .whereColumn(), and IN, BETWEEN and IS NULL get their own methods. ILIKE becomes .whereILike(). OR becomes .orWhere(), and parenthesised groups become nested callbacks. HAVING is emitted as .havingRaw() with ?? for identifiers and ? for values. Anything Knex has no method for, like price * 2, falls back to knex.raw() with the same placeholders. A real example. Paste SELECT u.name, COUNT(o.id) AS orders FROM users u LEFT JOIN orders o ON o.user_id = u.id AND o.status = 'paid' GROUP BY u.name HAVING COUNT(o.id) > 5. You get a leftJoin callback with .andOnVal("o.status", "=", "paid") and .havingRaw("COUNT(??) > ?", ["o.id",5]). INSERT turns each VALUES row into an object, and NOW() or CURRENT_TIMESTAMP becomes knex.fn.now(). UPDATE puts its where calls before .update(). DELETE ends in .del(). An UPDATE or DELETE with no WHERE gets a comment warning that it touches every row. The converter says no rather than guessing. Subqueries, UNION, CTEs, window functions, comma joins and bind placeholders produce an error message. The parsing runs inside your browser tab, so the queries you paste, with their table names and sample values, are not uploaded. You still need to swap the sample literals for your real variables.
Node.js backend developers rewriting raw SQL into Knex.js chains who want parameter binding handled correctly from the start. The tool runs entirely in your browser, so your data never leaves your device.
02How to use SQL to Knex
- Paste one statement into the SQL Query box, or pick the Simple SELECT, JOIN query or INSERT statement example.
- Click Convert.
- Read the Knex.js Code panel, or the red error message if the statement uses syntax the converter rejects.
- Click Copy and paste the chain into your code.
- Replace the sample literals with your variables, and use Reset to clear both panes for the next query.
03Worked examples
- Input:
SELECT id, name, email FROM users WHERE active = true ORDER BY name ASC LIMIT 10; - Result:
knex("users") .select("id", "name", "email") .where("active", true) .orderBy("name", "asc") .limit(10); - An = comparison uses the two-argument .where() form.
- Input:
SELECT * FROM orders WHERE status = 'paid' AND (total > 100 OR coupon IS NOT NULL) - Result:
knex("orders") .where("status", "paid") .where((qb) => { qb.where("total", ">", 100) .orWhereNotNull("coupon") }); - The parenthesised OR group becomes a nested callback, so precedence is kept. SELECT * adds no .select() call.
- Input:
SELECT u.name, COUNT(o.id) AS orders FROM users u LEFT JOIN orders o ON o.user_id = u.id AND o.status = 'paid' GROUP BY u.name HAVING COUNT(o.id) > 5 - Result:
knex("users as u") .select("u.name") .count({ "orders": "o.id" }) .leftJoin("orders as o", function () { this.on("o.user_id", "=", "u.id") .andOnVal("o.status", "=", "paid"); }) .groupBy("u.name") .havingRaw("COUNT(??) > ?", ["o.id",5]); - Input:
INSERT INTO users (name, email, created_at) VALUES ('Alice', '[email protected]', NOW()), ('Bob', '[email protected]', NOW()) - Result:
knex("users") .insert([ { "name": "Alice", "email": "[email protected]", "created_at": knex.fn.now() }, { "name": "Bob", "email": "[email protected]", "created_at": knex.fn.now() }, ]); - Input:
DELETE FROM sessions - Result:
// No WHERE clause: this deletes every row knex("sessions") .del(); - Input:
SELECT * FROM users WHERE id IN (SELECT user_id FROM orders) - Result:
Subqueries are not supported - Shown as an error instead of a half-correct conversion.
04Common use cases
- Porting the raw SQL strings in a legacy Express app's data layer to Knex one query at a time
- Finding out which Knex method matches ILIKE, BETWEEN or a NOT group without digging through the docs
- Turning a multi-row INSERT from a SQL dump into a Knex seed file with knex.fn.now() timestamps
- Converting a report query from a database GUI into a Node.js service, LEFT JOIN conditions included
- Catching an UPDATE or DELETE without WHERE before it lands in a migration
- Showing a bootcamp class how each SQL clause maps to a query builder call
05Tips
- Keep user input as method arguments or raw() bindings when you swap in variables. Never rebuild the SQL string by concatenation.
- Quoted identifiers like "user" or `order` are accepted and passed to Knex bare, because Knex quotes identifiers itself.
- If you get "Subqueries are not supported", split the query in two or rewrite the IN (SELECT ...) as a join.
- Call .toString() on the generated builder in a Node REPL and compare the SQL with your original before you commit.
- A WHERE with mixed AND and OR comes out as a nested .where((qb) => ...) callback, which keeps the precedence of your original.
06Related concepts
Knex.js, Query builder, SQL injection, whereRaw, Node.js.
Frequently Asked Questions
What is SQL to Knex?
SQL to Knex is a free, browser-based developer tool on AIDToolStack. Convert SQL to Knex.js query builder It requires no installation or sign-up and works entirely in your browser.
Is SQL to Knex free to use?
Yes. No sign-up, no fees and no usage cap.
Does SQL to Knex store my data?
No. It runs in your browser; nothing is uploaded.