Pg-promise: Support for ordering by IN clause

Created on 20 Jun 2016  路  7Comments  路  Source: vitaly-t/pg-promise

Hey,

I have the following query:

  const data = await db.any(`SELECT * ... WHERE id IN ($1^)`, pgp.as.csv(ids.map(i => i.id)));

It would be great if the lib supported a corresponding ORDER BY statement so that I could order by the order of ids in the IN clause. I am not sure if it is easily possible so this is just a topic for discussion.

P.S. I have not found anything related to it in the WIKI

question

Most helpful comment

By the way, in your original example you are using the old syntax. Here's the new one:

const data = await db.any(`SELECT * ... WHERE id IN ($1:csv)`, [ids.map(i => i.id)]);

All 7 comments

I'm not quite clear on this. ORDER BY is part of your query string, so what stops you from using it there?

Ok, but in that example it is static, right? Which means you can just specify it in the query string.

Or are you asking about some sort of a dynamic ORDER BY? If so, then please provide an example for that.

Yes, it would be great if the library provided a shortcut for this:

    ORDER BY
     CASE id
      ${ids.map((item, i) => 'WHEN \'' + item.id + '\' THEN ' + i).join('\n')}
     END

This kind of ORDER BY clause is always based on what is passed as $1^.

I am not sure how this could look like in the library though.

By the way, in your original example you are using the old syntax. Here's the new one:

const data = await db.any(`SELECT * ... WHERE id IN ($1:csv)`, [ids.map(i => i.id)]);

Perhaps?

const data = await db.any(`SELECT * ... WHERE id IN ($1:csv) ORDER BY $1:orderBy`, [ids.map(i => i.id)]);

According to the general syntax, there can be anything for the ORDER BY, it is impossible to generalize.

For your task you should just generate a string that will contain the list of all the WHEN/THEN statements, and then insert it.

There are many ways to do it, and they are all simple.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ForbesLindesay picture ForbesLindesay  路  3Comments

jabooth picture jabooth  路  4Comments

Juanflugel picture Juanflugel  路  3Comments

realcarbonneau picture realcarbonneau  路  4Comments

dzaman picture dzaman  路  3Comments