Challenge - 5 Problems
Knex Query Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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);
Attempts:
2 left
💡 Hint
Knex outputs SQL with backticks and lowercase keywords by default.
✗ Incorrect
Knex generates SQL with backticks around identifiers and lowercase SQL keywords when calling toString().
❓ component_behavior
intermediate2: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');
Attempts:
2 left
💡 Hint
The returning method returns an array of inserted ids.
✗ Incorrect
Knex returns an array of inserted ids when using .returning('id') with insert.
🔧 Debug
advanced2: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);
Attempts:
2 left
💡 Hint
Check how the where clause expects conditions.
✗ Incorrect
Knex expects the where object values to be exact values, not comparison strings. Use .where('age', '>', 30) instead.
📝 Syntax
advanced2: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.
Attempts:
2 left
💡 Hint
Knex update queries start with the table, then where, then update.
✗ Incorrect
The correct order is knex('table').where(...).update(...). Options A, B, and C use invalid methods or incorrect order.
❓ state_output
expert3: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}); });
Attempts:
2 left
💡 Hint
The transaction deletes low stock products then adds one new product.
✗ Incorrect
The transaction deletes products with stock less than 5, then inserts a new product with stock 10. So remaining are products with stock >= 5 plus the new one.