Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room user configurable order by queries

I am migrating an app to use Room from normal Sqlite and one part that I am having trouble with is that there are several queries that have an order by statement that are user configurable, meaning they can change how they want to view the list order.

What it seems is the Room does not allow for dynamic order by statements so I would have to make individual queries specific for each order by statement.

Has anyone found a better way around this issue so I can have 1 query statement where the only thing that changes is the order by clause vs having to write what in my case would be about 15 extra query statements all basically the same?

like image 594
tyczj Avatar asked Apr 30 '18 16:04

tyczj


People also ask

How to ORDER BY condition in SQL?

SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.

What is the default Ordering of data using the ORDER BY clause?

The SQL ORDER BY Keyword The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

What annotation is used to build your SQL query at runtime dynamically?

The @Query annotation allows you to write SQL statements and expose them as DAO methods.


1 Answers

I'm facing the same problem right now. The thing that can be done is to use CASE:

SELECT * FROM Table
ORDER BY 
CASE WHEN :parameter = 1 THEN Column END ASC,
CASE WHEN :parameter = 2 THEN Column2 END DESC

But I'm assuming you are using a ViewModel as well, so you will probably have to reinitialise it every time. I think this way is a little bit better than writing 15 queries, maybe not as compact though.

This answer also has a nice example, but the logic is reversed I believe.

like image 141
Suleyman Avatar answered Oct 01 '22 15:10

Suleyman