-1

I have a requirement where I need to get rows using a list of string if it matches any value in the specified column.

SELECT * FROM assets WHERE name IN (:names)

But I also need to order some of its items that are guaranteed to exist from the above query. These are the names that should be in order, after that the rest can be in any order.

'BG123', 'AR234', 'QR45', 'DO456'

How can I order it based on these given value. I cannot use the PK since it is a random string. It should also work when the table is empty at first. Thanks

Additional sample:

I need to order these names as long as they exist, while the rest can be in any order and matching the names list at the same time.

  1. Bon app
  2. Consolidated Holdings
  3. Around the horn

enter image description here

forpas
  • 160,666
  • 10
  • 38
  • 76
Bitwise DEVS
  • 2,858
  • 4
  • 24
  • 67

2 Answers2

1

you can try this as well :

SELECT * FROM(
SELECT *,
CASE WHEN name = 'DO456' then 4
     WHEN name ='QR45' then 3
     WHEN name = 'AR234' then 2
     WHEN name = 'BG123' then 1
     else 0
     end as name_temp 
 FROM assets WHERE name IN (:names)
) a
order by name_temp desc;
from assets ) a;
DB08
  • 151
  • 6
0

You would need to use a CASE statement that produced values in the order you want and then ORDER BY that CASE statement e.g.

ORDER BY
CASE WHEN name = 'BG123' then 1
     WHEN name = 'AR234' then 2
     WHEN name = 'QR45' then 3
     WHEN name = 'DO456' then 4
else 5 end
NickW
  • 8,430
  • 2
  • 6
  • 19