Klapsa2503 Klapsa2503 - 6 months ago 33
Scala Question

What is the most efficient way to get single result in Slick?

I wonder which of the following two lines is more efficient:

db.run(events (..filter/sort..) .take(1).result.head)


db.run(events (..filter/sort..) .result.head)

as I have discovered the .take comes from slick.lifted.Query

and .head from slick.profile.BasicStreamingAction


Below code which uses take(1) is efficient because take(1) translates to the SQL in sick and then query optimizer of the underlying relation database does the optimization to pick only the first row of the result.

db.run(events (..filter/sort..) .take(1).result.head)

But in case of only .head at the application layer slick does not translate that code to SQL so its not communicated to the underlying relational database. There by no optimization is done. All rows which match criteria are returned and at the app layer we take the first row which is clear not efficient.