Bird
Raised Fist0
Expressframework~20 mins

Knex as query builder alternative in Express - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Knex Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Knex query?
Consider this Knex query to select users with age over 30. What will be the resulting SQL query string?
Express
const query = knex('users').select('id', 'name').where('age', '>', 30).toString();
console.log(query);
ASELECT `id`, `name` FROM `users` WHERE `age` > 30
BSELECT id, name FROM users WHERE age > 30
Cselect `id`, `name` from `users` where `age` > 30
Dselect id, name from users where age > 30
Attempts:
2 left
💡 Hint
Knex outputs SQL with backticks and lowercase keywords by default.
component_behavior
intermediate
2:00remaining
What happens when you chain .insert() and .returning() in Knex?
Given this Knex code inserting a new user, what will be the value of 'result' after execution?
Express
const result = await knex('users').insert({name: 'Alice', age: 25}).returning('id');
A[{ id: 1 }]
B[1]
C1
Dundefined
Attempts:
2 left
💡 Hint
The returning method returns an array of inserted ids.
🔧 Debug
advanced
2:00remaining
Why does this Knex query throw an error?
This code throws an error. What is the cause?
Express
knex('users').select('name').where({age: '> 30'}).then(console.log);
AThe where clause uses an object with a string '> 30' instead of a comparison operator.
BThe then method is not awaited.
CThe select method is missing parentheses.
DThe table name 'users' is invalid.
Attempts:
2 left
💡 Hint
Check how the where clause expects conditions.
📝 Syntax
advanced
2:00remaining
Which option correctly updates a user's age using Knex?
Choose the correct Knex syntax to update the age of user with id 5 to 40.
Aknex('users').where('id', 5).update({age: 40});
Bknex('users').set({age: 40}).where('id', 5);
Cknex.update('users').set({age: 40}).where('id', 5);
Dknex('users').update({age: 40}).where('id', 5);
Attempts:
2 left
💡 Hint
Knex update queries start with the table, then where, then update.
state_output
expert
3:00remaining
What is the final state of the database after this transaction?
Given this Knex transaction code, what rows remain in the 'products' table after commit?
Express
await knex.transaction(async trx => {
  await trx('products').where('stock', '<', 5).del();
  await trx('products').insert({name: 'New Product', stock: 10});
});
AAll original products including those with stock < 5 plus the new product
BOnly the new product with stock 10
CNo products remain
DAll products with stock >= 5 plus the new product with stock 10
Attempts:
2 left
💡 Hint
The transaction deletes low stock products then adds one new product.

Practice

(1/5)
1. What is the main advantage of using Knex as a query builder in an Express app?
easy
A. It allows writing database queries using JavaScript instead of raw SQL.
B. It automatically creates database tables without any code.
C. It replaces Express middleware for handling requests.
D. It compiles JavaScript into SQL code for faster execution.

Solution

  1. Step 1: Understand Knex's purpose

    Knex is designed to let developers write database queries in JavaScript instead of SQL.
  2. 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.
  3. Final Answer:

    It allows writing database queries using JavaScript instead of raw SQL. -> Option A
  4. Quick 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
A. knex.tables('users').select('*')
B. knex.from('users').selects()
C. knex.query('SELECT * FROM users')
D. knex.select('*').from('users')

Solution

  1. Step 1: Review Knex select syntax

    The common pattern is knex.select('*').from('tableName') to get all rows.
  2. 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.
  3. Final Answer:

    knex.select('*').from('users') -> Option D
  4. Quick 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
A. All products with price less than or equal to 100, showing id and name.
B. All products with price greater than 100, showing all columns.
C. All products with price greater than 100, showing id and name.
D. Syntax error due to incorrect method chaining.

Solution

  1. Step 1: Analyze the where clause

    The query filters products where price is greater than 100.
  2. Step 2: Analyze the select clause

    It selects only the 'id' and 'name' columns to return.
  3. Final Answer:

    All products with price greater than 100, showing id and name. -> Option C
  4. Quick 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
A. Missing table name in knex call.
B. Using '=' instead of ',' inside where method.
C. select() requires column names as arguments.
D. where method cannot be chained after knex call.

Solution

  1. Step 1: Check where method syntax

    The where method expects arguments separated by commas, e.g., where('status', 'pending').
  2. Step 2: Identify the error

    The query uses '=' inside where which is invalid syntax in JavaScript function calls.
  3. Final Answer:

    Using '=' instead of ',' inside where method. -> Option B
  4. Quick 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
A. knex('users').where('id', 5).update({ email: 'new@example.com' })
B. knex('users').set('email', 'new@example.com').where('id', 5)
C. knex.update('users').set('email', 'new@example.com').where('id', 5)
D. knex('users').update({ email: 'new@example.com' }).where('id' = 5)

Solution

  1. Step 1: Recall correct update syntax

    Knex updates usually chain where() before update() to specify which rows to change.
  2. 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.
  3. Final Answer:

    knex('users').where('id', 5).update({ email: 'new@example.com' }) -> Option A
  4. Quick 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