0
0
Expressframework~20 mins

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

Choose your learning style9 modes available
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.