Sql select without sorting

I think this is a long snapshot, but is there a way to list the sql query without sorting ...

eg. I have

select * from items 
where manufacID = 2 
or manufacID = 1
or manufacID = 4

and I don’t want them to be listed in asc or decs order, but when I entered ... so 2,1,4.

So can I do this?

+3
source share
5 answers

You can add an additional column as a sort column, and then arrange it as follows:

SELECT 
  *,
  CASE manufacID
    WHEN 2 THEN 1
    WHEN 1 THEN 2
    WHEN 4 THEN 3
  END AS sortOrder
FROM
  items
ORDER BY
  sortOrder
+7
source

Yes, use this:

SELECT * FROM items
WHERE manufacID IN (2, 1, 4)
ORDER BY (manufacID = 2) ASC,
         (manufacID = 1) ASC,
         (manufacID = 4) ASC

Results are sorted in the order that matches the conditions. Change ASC to DESC to reverse the order. This only works in databases that allow conditions in sort clauses.

(Side note: why do you want to do this?)

+6

, , . SQL Server, , undefined.

You can create a value for an order from the values:

select * from items 
where manufacID in (2, 1, 4)
order by case manufacID
  when 2 then 1
  when 1 then 2
  when 4 then 3
end
+5
source
SELECT * FROM
(
select 1 as sort, * from items 
where manufacID = 2 

union all

select 2 as sort, * from items 
where manufacID = 1

union all

select 3 as sort, * from items 
where manufacID = 4
)
order by sort
+1
source
select * from items where manufacID = 2 
union all
select * from items where manufacID = 1
union all
select * from items where manufacID = 4
0
source

Source: https://habr.com/ru/post/1767344/


All Articles