'ORDER BY is not working when I try to use this psql query
I have a psql database storing reviews for a certain product.
When the client requests data from the api, it sends in a request with a product_id, count, and a sort as query parameters.
I have this snippit of code below that should query the database and bring back the correct data.
async (query) => {
const sort = {
relevance: 'helpfulness DESC, date DESC',
helpfulness: 'helpfulness DESC',
newest: 'date DESC'
};
const sql = 'SELECT id, product_id, rating, to_timestamp(date / 1000) AS date, summary, body, recommend, reviewer_name, reviewer_email, response, helpfulness, photos FROM reviews WHERE product_id=$1 AND reported=false ORDER BY $2 LIMIT $3'
try {
const result = await pool.query(sql ,[query.product_id, sort[query.sort] || sort.relevance, query.count || 5]);
return result;
} catch (error) {
throw new Error(error);
}}
My issue is that the sort does not apply at all during the query. It will grab the right product_id and also limit the rows that are returned properly but the sort just won't apply.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
