Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
MySQL conditional filters handling

I am using node.js and trying to query based on multiple filters if only they are true

select * from orders ${isFilter ? 'where' : ''} 
    ${orderId !== undefined && orderId ? `order_id = '${orderId}' or ` : '' }
    ${receiptId !== undefined && receiptId? `receipt_id = '${receiptId}' or `: '' }
    ${driver !== undefined && driver ? `driver_id = '${Number(driver)}'` : '' }

this works fine where there is no filter or when all the filters are true but the OR causes an issue when one filter or more are missing. what would be the best way to handle this ?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

This is a pseudo code to dynamically compose the query

var clause = 'where';
var query = 'select * from orders';
if (isFilter) { // this statement could be removed
    if (orderId !== undefined && orderId) {
        query += clause + ' order_id = `${orderId}`';
        clause = 'or';
    }
    if (receiptId !== undefined && receiptId) {
        query += clause + ' receiptId = `${receiptId}`';
        clause = 'or';
    }
    if (driver !== undefined && driver) {
        query += clause + ' driver = `${driver}`';
        clause = 'or'; // this is not really needed, but it could be useful for further filters in future
    }
}
about 4 years ago · Juan Pablo Isaza Report

0

let whereClause = [];

if(orderId) whereClause.push(`order_id = '${orderId}'`);
if(receiptId) whereClause.push(`receipt_id = '${receiptId}'`);
if(driver) whereClause.push(`driver_id = ${parseInt(driver)}`);

let whereQuery = whereClause.join(' OR ');

let sql = `select * from orders where true ${whereClause.length ? whereQuery : ''}`;

try using join. so that you can add many properties even not in order. Also if you're expecting it to be undefined, then you may remove that as it resulted false on condition statement.

about 4 years ago · Juan Pablo Isaza Report

0

I think it would be reasonable if you can log the query. we can be sure about the query that's being sent. This would be the first step to troubleshoot and may be we can use the way you are trying using ternary operator with few changes.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!