Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to execute a raw SQL query using Express with a database client.
Express
db.query([1], (err, result) => { if (err) throw err; res.send(result.rows); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the SQL query inside quotes.
Using incorrect method names like execute or query without context.
✗ Incorrect
The raw SQL query must be a string passed to the query method. Option C correctly provides the SQL string.
2fill in blank
mediumComplete the code to safely insert a user name using parameterized raw query to avoid SQL injection.
Express
const sql = 'INSERT INTO users(name) VALUES($1)'; db.query(sql, [[1]], (err, res) => { if (err) throw err; console.log('User added'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing variable names that are undefined in the context.
Not using parameterized queries and inserting values directly.
✗ Incorrect
The user name comes from the request body, so req.body.name is the correct value to pass as parameter.
3fill in blank
hardFix the error in the raw query callback by completing the missing parameter to handle the result.
Express
db.query('SELECT * FROM products', (err, [1]) => { if (err) { console.error(err); return; } res.json([1].rows); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect parameter names that do not match the result object.
Forgetting to use the result parameter to access rows.
✗ Incorrect
The second parameter in the callback is commonly named result and contains the query result including rows.
4fill in blank
hardFill both blanks to create a raw query that updates a user's email by id using parameters.
Express
const sql = 'UPDATE users SET email = $1 WHERE id = $2'; db.query(sql, [[1], [2]], (err, res) => { if (err) throw err; res.send('Email updated'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up the order of parameters.
Using undefined variables instead of request data.
✗ Incorrect
The email comes from req.body.email and the user id from req.params.id to safely update the record.
5fill in blank
hardFill all three blanks to write a raw query that deletes a user by id and logs the affected row count.
Express
const sql = 'DELETE FROM users WHERE id = $1'; db.query(sql, [[1]], (err, [2]) => { if (err) throw err; console.log('Deleted rows:', [3].rowCount); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using request body instead of URL params for id.
Not using the correct result parameter to get rowCount.
✗ Incorrect
The id to delete is from req.params.userId, the callback result parameter is named result, and result.rowCount gives the number of deleted rows.