Query Operations

Sorting

ORDER BY with sortedBy and sortedByDescending

The kotlin collections sortedBy and sortedByDescending functions are also available on SqlQuery instances.

val q = sql {
  Table<Person>().sortedBy { p -> p.name }
}
//> SELECT p.id, p.name, p.age FROM Person p ORDER BY p.name

val q = sql {
  Table<Person>().sortedByDescending { p -> p.name }
}
//> SELECT p.id, p.name, p.age FROM Person p ORDER BY p.name DESC

Advanced Sorting

When you want to do advanced sorting (e.g. different sorting for different columns) use a select block and the sortBy function inside.

val q = sql.select {
  val p = from(Table<Person>())
  sortBy(p.name to Ord.Asc, p.age to Ord.Desc)
}
//> SELECT p.id, p.name, p.age FROM Person p ORDER BY p.name ASC, p.age DESC

Note, that if you want to use Asc and Desc directly then just import them!

import io.exoquery.Ord.Asc
import io.exoquery.Ord.Desc

val q = sql.select {
  val p = from(Table<Person>())
  sortBy(p.name to Asc, p.age to Desc)
}
//> SELECT p.id, p.name, p.age FROM Person p ORDER BY p.name ASC, p.age DESC

Also available are Ord.AscNullsFirst, Ord.AscNullsLast, Ord.DescNullsFirst, and Ord.DescNullsLast for databases that support those options.