Knex helps you write database queries using JavaScript instead of raw SQL. It makes working with databases easier and safer.
Knex as query builder alternative in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
knex('tableName').select('column1', 'column2').where('column', 'value')
Use knex('tableName') to start a query on a specific table.
Chain methods like select(), where(), insert(), update() to build your query.
Examples
Express
knex('users').select('*')
Express
knex('users').where('id', 1).select('name', 'email')
Express
knex('products').insert({ name: 'Book', price: 10 })
Express
knex('orders').where('status', 'pending').update({ status: 'shipped' })
Sample Program
This Express app uses Knex to create a 'users' table in an in-memory SQLite database. It inserts two users and provides a GET endpoint to fetch all users. Knex builds the SQL queries behind the scenes.
Express
import express from 'express'; import knex from 'knex'; const app = express(); app.use(express.json()); const db = knex({ client: 'sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); (async () => { // Create a simple table and insert data await db.schema.createTable('users', table => { table.increments('id'); table.string('name'); table.string('email'); }); await db('users').insert([{ name: 'Alice', email: 'alice@example.com' }, { name: 'Bob', email: 'bob@example.com' }]); app.get('/users', async (req, res) => { const users = await db('users').select('id', 'name', 'email'); res.json(users); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); })();
Important Notes
Knex supports many databases like SQLite, PostgreSQL, MySQL, and more.
Always handle errors when running queries in real apps.
Knex queries return promises, so use async/await or .then() to get results.
Summary
Knex lets you write database queries in JavaScript instead of SQL.
It helps keep your code clean, safe, and easy to read.
You can use it with many databases and chain query methods for clarity.
Practice
1. What is the main advantage of using
Knex as a query builder in an Express app?easy
Solution
Step 1: Understand Knex's purpose
Knex is designed to let developers write database queries in JavaScript instead of SQL.Step 2: Compare options
Options B, C, and D describe features Knex does not provide. It does not create tables automatically, replace Express middleware, or compile JS into SQL.Final Answer:
It allows writing database queries using JavaScript instead of raw SQL. -> Option AQuick Check:
Knex = JS query builder [OK]
Hint: Knex lets you write queries in JS, not raw SQL [OK]
Common Mistakes:
- Thinking Knex creates tables automatically
- Confusing Knex with Express middleware
- Believing Knex compiles JS to SQL code
2. Which of the following is the correct way to select all rows from a table named
users using Knex?easy
Solution
Step 1: Review Knex select syntax
The common pattern is knex.select('*').from('tableName') to get all rows.Step 2: Check each option
knex.select('*').from('users') matches the correct syntax. knex.from('users').selects() uses invalid selects() method. knex.tables('users').select('*') uses knex.tables which is not standard Knex syntax. knex.query('SELECT * FROM users') uses raw SQL string which is not the Knex query builder method.Final Answer:
knex.select('*').from('users') -> Option DQuick Check:
Correct select syntax = knex.select('*').from('users') [OK]
Hint: Use knex.select('*').from('table') to get all rows [OK]
Common Mistakes:
- Using knex.tables() instead of knex.select().from()
- Using selects() instead of select()
- Trying to pass raw SQL string to knex
3. What will the following Knex query return?
knex('products').where('price', '>', 100).select('id', 'name')medium
Solution
Step 1: Analyze the where clause
The query filters products where price is greater than 100.Step 2: Analyze the select clause
It selects only the 'id' and 'name' columns to return.Final Answer:
All products with price greater than 100, showing id and name. -> Option CQuick Check:
where('price', '>', 100) + select('id', 'name') = All products with price greater than 100, showing id and name. [OK]
Hint: where filters rows; select chooses columns [OK]
Common Mistakes:
- Confusing > with < in where clause
- Assuming all columns are returned
- Thinking method chaining causes syntax error
4. Identify the error in this Knex query:
knex('orders').where('status' = 'pending').select()medium
Solution
Step 1: Check where method syntax
The where method expects arguments separated by commas, e.g., where('status', 'pending').Step 2: Identify the error
The query uses '=' inside where which is invalid syntax in JavaScript function calls.Final Answer:
Using '=' instead of ',' inside where method. -> Option BQuick Check:
where('status' = 'pending') is invalid [OK]
Hint: Use commas, not '=' inside where() arguments [OK]
Common Mistakes:
- Using '=' instead of ',' in method arguments
- Thinking select() must have columns
- Believing where cannot be chained
5. You want to update the
email of a user with id = 5 using Knex. Which query correctly performs this update?hard
Solution
Step 1: Recall correct update syntax
Knex updates usually chain where() before update() to specify which rows to change.Step 2: Evaluate each option
knex('users').where('id', 5).update({ email: 'new@example.com' }) correctly chains where('id', 5) before update({ email: ... }). knex('users').update({ email: 'new@example.com' }).where('id' = 5) uses '=' instead of ',' causing syntax error. knex('users').set('email', 'new@example.com').where('id', 5) uses invalid set() method. knex.update('users').set('email', 'new@example.com').where('id', 5) uses invalid syntax.Final Answer:
knex('users').where('id', 5).update({ email: 'new@example.com' }) -> Option AQuick Check:
where() before update() is correct pattern [OK]
Hint: Chain where() before update() to target rows [OK]
Common Mistakes:
- Using '=' instead of ',' in where arguments
- Using non-existent set() method
- Using invalid knex.update('users') syntax
