Knex.js Cheatsheet - Knex SQL Query Builder Reference
For Node.js developers who want to write SQL fluently in JavaScript and switch databases without rewriting queries. The value of Knex-transpiled is a chainable API with automatic parameter binding, but you must call .then/await for it to execute and understand when a raw() escape hatch beats the builder. By the end you can build CRUD, joins, and groupBy chains deterministically, wrap multi-statement logic in a transaction with rollback, and confirm the generated SQL with debug/toString.
Query Data 10
knex("users").select("*")knex("users").select("name", "email")knex("users").where("age", ">", 18)knex("users").where({ status: "active" })knex("users").whereNull("deleted_at")knex("users").orderBy("created_at", "desc")knex("users").limit(10).offset(20)knex("users").first()knex("users").pluck("id")knex("users").distinct("country")Insert Data 5
knex("users").insert({ name: "John", email: "john@example.com" })knex("users").insert([{ name: "A" }, { name: "B" }])knex("users").insert(data).returning("id")knex("users").insert(data).onConflict("email").merge()knex("users").insert(data).onConflict("email").ignore()Update & Delete 5
knex("users").where("id", 1).update({ name: "Jane" })knex("users").where("id", 1).update({ views: knex.raw("views + 1") })knex("users").where("id", 1).update({ deleted_at: knex.fn.now() })knex("users").where("id", 1).del()knex("users").truncate()Join 6
knex("users").join("posts", "users.id", "posts.user_id")knex("users").leftJoin("posts", "users.id", "posts.user_id")knex("users").rightJoin("posts", "users.id", "posts.user_id")knex("users").fullOuterJoin("posts", "users.id", "posts.user_id")knex("users").crossJoin("posts")knex("users").join("posts", function() { this.on("users.id", "=", "posts.user_id").andOn("users.active", "=", knex.raw("?", [1])) })Aggregate & Group 8
knex("users").count("id as total")knex("users").count("* as total").first()knex("orders").sum("amount")knex("users").max("age")knex("users").min("age")knex("orders").avg("amount")knex("users").groupBy("status")knex("users").groupBy("status").having(knex.raw("count(*) > ?", [5]))Transactions 4
knex.transaction(async (trx) => { await trx("users").insert(data) })const trx = await knex.transaction(); await trx.commit() / trx.rollback()const sp = await trx.savepoint(async (sp) => { /* ... */ })await knex.transaction(cb, { isolationLevel: "read committed" })Schema Builder 7
knex.schema.createTable("users", (t) => { t.increments("id"); t.string("name") })knex.schema.dropTableIfExists("users")knex.schema.alterTable("users", (t) => { t.string("email") })t.integer("age").unsigned().notNullable().defaultTo(0)t.timestamps(true, true)knex.schema.table("users", (t) => { t.index(["name", "status"]) })knex.schema.table("users", (t) => { t.unique("email") })Raw & Debug 5
knex.raw("SELECT * FROM users WHERE id = ?", [1])knex("users").where("active", true).debug(true)knex("users").where("id", 1).toSQL().toNative()knex("users").where("id", 1).toString()knex("users").columnInfo()Tips
- Knex supports PostgreSQL, MySQL, MariaDB, SQLite, MSSQL — set client on connect.
- The query builder returns a Promise; await or .then() to execute.
- knex.raw("SQL", bindings) runs raw SQL; bound params prevent SQL injection.
- Create migrations with knex.migrate.make() and run them with knex.migrate.latest().
- Connection pooling is on by default; tune with pool: { min: 2, max: 10 }.
Official References
Each command links to its official documentation below, so you can verify the latest usage and read deeper.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Contact Us
Wrong command or description? Send us corrections, business inquiries or product feedback by email.
Contact Us