1

I have select query and I want to add filter and search values to select query. The user can perform a search and filter separately and together as well. Following are the scenario:

when I applied only search (Success)

select name, id from master.contact where name ilike 'sal%' or name ilike 'man%';

when I applied only first filter (Success)

select name, id from master.contact where isActive=true;

when I applied both filters (Success)

select name, id from master.contact where isActive=true and pan='abcd';

when I applied only the second filter (Fail)

select name, id from master.contact and pan='abcd';

when I applied search and both filters (Fail)

select * from master.contact where name ilike 'sal%' or name ilike 'man%' where master.contact.is_active = true and pan='abcd';

when I applied search and first filter (Fail)

select * from master.contact where name ilike 'sal%' or name ilike 'man%' where master.contact.is_active = true;

nodejs

const query = {
    text: `
      select master.contact.id,
      master.contact.name
      from
      master.contact
       `
  };
  if (input.search) {
    query.text += ` where
    (master.contact.pan ILIKE '${input.search}%' or master.contact.ira ILIKE '${input.search}%')`;
  }

  if (input.filters) {
    const {
      isActive,
      pan
    } = input.filters;
    if (isActive !== undefined) {
      query.text += ` where master.contact.isActive = ${isActive}`;
    }

    if (pan) {
      query.text += `and master.contact.pan = ${pan}`;
    }
0

1 Answer 1

2

How about collect the criteria in an array then join and append it, like so:

const query = {
    text: `
      select master.contact.id,
      master.contact.name
      from
      master.contact
       `
  };

// Create an array to store any criteria
var where = [];

  if (input.search) {
    where.push(`(master.contact.pan ILIKE '${input.search}%' or master.contact.ira ILIKE '${input.search}%')`);
  }

  if (input.filters) {
    const {
      isActive,
      pan
    } = input.filters;
    if (isActive !== undefined) {
      where.push(`master.contact.isActive = ${isActive}`);
    }

    if (pan) {
      where.push(`master.contact.pan = ${pan}`);
    }

// If criteria were added, append to query text
if (where.length > 0) {
   query.text += ' where ' + where.join(' and ');
}
Sign up to request clarification or add additional context in comments.

1 Comment

I end up using where 1=1. but this is nice

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.