Getting all entries from DB when parameter is null

Viewed 21

I have a column named Category in postgres db table. I am using a node api to fetch data from that db. The api takes a parameter of category to filter the categories by name. Now, that parameter can be a string or a null value. If the parameter is null, I want the api to fetch all the records. If it is a string, I want it to filter. So far, I have tried this:

SELECT * FROM dextrades WHERE chain_id = '1' AND txn_value > (50000 * 2) AND category LIKE Coalesce('Whale', '%') ORDER BY trade_time DESC LIMIT 100;

Now when a string is passed it works great. But when null is passed, it also takes it as a string and returns nothing.

This is my Node api route:

dexRouter.get("/:trades/:chain/:txn/:wallet", async (req, res) => {
  let trades = await db.query(
    `SELECT * FROM dextrades WHERE chain_id = ${req.params.chain} AND txn_value > (50000 * ${req.params.txn}) AND category LIKE Coalesce('${req.params.wallet}', '%') ORDER BY trade_time DESC LIMIT ${req.params.trades};`
  );
  trades = trades.rows;
  res.status(200).json(trades);
});

How do I make sure that null goes as a null value and not as a string?

0 Answers
Related