J
J
John2022-04-21 13:35:33
SQLite
John, 2022-04-21 13:35:33

SQLite how to sort by multiple columns at once?

There is a table:
name | v1 | v2 | v3
----------------------
Vova | 2 | 0 | 0
Vanya | 0 | 0 | 0
Grisha| 0 | 4 | 0
Vasya | 0 | 0 | 10
Petya | 1 | 20 | 40

The task is to display the names by sorting by columns v1 v2 v3, and take into account when sorting sequentially the fields starting from v1 with the condition that the field is greater than zero.
Result: Vasya (10), Grisha (4), Vova (2), Petya (1), Vanya (0)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2022-04-21
@ioangrozniy

In this case you can use case statement with where statement

select * from users
order by case 
  when v1 > 0 then v1 
  when v2 > 0 then v2
  else v3
end desc;

SQLite online sandbox

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question