how to get paginated select on slick + postgresql

2020-03-01 23:50发布

问题:

In a postgresql database, with slick 3, what's the best way to have pagination?

  • get all rows and do pagination with scala (seems not very efficient) ?
  • static query with limit and offset?
  • is there any other way?

回答1:

You can use take and drop methods on TableQuery objects. They will be translated to limit and offset in the resulting SQL query:

val users: TableQuery[UsersTable] = UsersTable.query

val firstPartOfUsers  = users.drop(0).take(25).result
val secondPartOfUsers = users.drop(25).take(25).result

Those two actions will be translated to the following SQL queries:

select "name", "email", "id" from "users" limit 25 offset 0
select "name", "email", "id" from "users" limit 25 offset 25