What if you could break free from framework limits and write exactly the database commands you want?
Why Raw queries when needed in Express? - Purpose & Use Cases
Imagine you have a complex database task that your usual tools can't handle easily, like a very specific search or a custom report.
You try to build it using only the built-in helpers of your framework, but it feels like forcing a square peg into a round hole.
Using only high-level helpers can be slow and limiting.
You might end up writing lots of code just to work around what the helpers don't support.
This makes your app harder to maintain and can cause bugs.
Raw queries let you write exactly the database commands you need.
This gives you full control and flexibility to handle special cases easily.
You can still use your framework but step outside it when necessary.
Model.findAll({ where: { name: { [Op.like]: '%John%' } } })sequelize.query('SELECT * FROM users WHERE name LIKE :search', { replacements: { search: '%John%' }, type: sequelize.QueryTypes.SELECT })
You can solve tricky database problems without waiting for framework updates or hacks.
When you need a report that joins many tables with custom filters and grouping, raw queries let you write the exact SQL to get the data fast and correctly.
High-level helpers are great but sometimes limiting.
Raw queries give you full control over database commands.
Use raw queries to solve complex or special cases easily.
Practice
Solution
Step 1: Understand raw queries purpose
Raw queries allow writing direct SQL commands for complex or special cases.Step 2: Compare with other options
Options A, B, and C are incorrect because raw queries do not skip database calls, auto-generate SQL, or avoid SQL.Final Answer:
To write direct SQL commands when query builders are insufficient -> Option AQuick Check:
Raw queries = direct SQL use [OK]
- Thinking raw queries auto-generate SQL
- Believing raw queries avoid SQL entirely
- Assuming raw queries skip database calls
Solution
Step 1: Identify parameterized query syntax
Using '?' with an array of parameters is the standard safe way to pass values.Step 2: Check other options
db.query('SELECT * FROM users WHERE id = ' + userId) concatenates strings (unsafe). Options C and D use placeholders not standard in many Express SQL libraries.Final Answer:
db.query('SELECT * FROM users WHERE id = ?', [userId]) -> Option BQuick Check:
Use '?' + params array for safe raw queries [OK]
- Concatenating variables directly into query strings
- Using unsupported placeholder syntax
- Not passing parameters as an array
const result = await db.query('SELECT * FROM products WHERE price > ?', [100]);
console.log(result.rows.length);What will be logged if there are 5 products priced over 100?
Solution
Step 1: Understand the query and parameters
The raw query selects products with price greater than 100, passing 100 safely as a parameter.Step 2: Interpret the result object
Assuming the database library returns an object with a 'rows' array, its length will be the number of matching products, which is 5.Final Answer:
5 -> Option AQuick Check:
Rows length = number of matching products [OK]
- Expecting result directly as array without .rows
- Confusing parameter placement
- Assuming query returns undefined or error
const userId = 10;
const result = await db.query('SELECT * FROM users WHERE id = ' + userId);Solution
Step 1: Analyze query construction
The query concatenates userId directly into the string, which is unsafe and can cause SQL injection.Step 2: Understand best practice
Parameters should be passed separately using placeholders to avoid injection risks.Final Answer:
It risks SQL injection by concatenating variables directly -> Option CQuick Check:
Never concatenate variables directly in raw queries [OK]
- Ignoring SQL injection risks
- Thinking concatenation is safe for numbers
- Not using parameterized queries
Solution
Step 1: Consider safety and flexibility
Using a loop with parameterized queries ensures each update is safe and avoids SQL injection.Step 2: Evaluate other options
Concatenating all updates risks injection and syntax errors; skipping parameters is unsafe; direct concatenation is insecure.Final Answer:
Use a loop with parameterized raw queries for each user update -> Option DQuick Check:
Loop + parameters = safe batch updates [OK]
- Trying to build one big concatenated query
- Ignoring parameterization for speed
- Concatenating user data directly
Ready to prove it?
Pass the test and this pattern moves unknown
