E
E
eldar_web2019-05-23 19:24:24
PostgreSQL
eldar_web, 2019-05-23 19:24:24

How can I set the sort sequence in SQL (postgresql)?

Let's say there is a request with a condition:

SELECT * FROM table WHERE (id, make_name) IN (('1995','TOYOTA'),('5015','FIAT'),('1010','BMW'));

I want a sort sequence that goes in the condition.
How to implement a request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rPman, 2019-05-24
@eldar_web

If you are reluctant to create a temporary table (and ideologically this is the right option for such a case), then instead of using in, use a nested query with values ​​, adding an order field there:

SELECT * FROM
 table t,
 (VALUES (1,'1995','TOYOTA'),(2,'5015','FIAT'),(3,'1010','BMW')) AS v(o,id,make_name)
WHERE t.id=v.id AND t.make_name=v.make_name
ORDER BY v.o

V
Vitsliputsli, 2019-05-23
@Vitsliputsli

It can be twisted like this:

SELECT * 
FROM table 
WHERE (id, make_name) IN (('1995','TOYOTA'),('5015','FIAT'),('1010','BMW'))
ORDER BY CASE 
    WHEN id='1995' THEN 1
    WHEN id='5015' THEN 2
    WHEN id='1010' THEN 3
    END

Or prefetch and join.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question