Search code examples
kotlinkotlin-exposed

How does sorting work with limit in kotlin exposed model?


I have following snippet of code:

UserDataModel
                .find {
                    UserDataTable.type eq type and (
                            UserDataTable.userId eq userId
                            )
                }
                .limit(count)
                .sortedByDescending { it.timestamp }

sortedByDescending is a part of kotlin collections API. The my main concern is: how does exposed lib return top (according to timestamp) count rows from table if select query looks like this and does not contain ORDER BY clause?

SELECT USERDATA.ID, USERDATA.USER_ID, USERDATA.TYPE,
USERDATA.PAYLOAD, USERDATA."TIMESTAMP"
FROM USERDATA 
WHERE USERDATA.TYPE = 'testType'
and USERDATA.USER_ID = 'mockUser'
LIMIT 4

And is it possible that sometimes or somehow returned result would be different for the same data?

Really struggled here. Thank you in advance.


Solution

  • You're sorting the results after query has been executed.

    You need to use orderBy method as described in docs

    UserDataModel
      .find {
        UserDataTable.type eq type and (UserDataTable.userId eq userId)
      }
      .limit(count)
      .orderBy(UserDataTable.timestamp to SortOrder.DESC)