Sub topic 8
Filtering, Sorting, and Limiting Results
This chapter assumes that you know basic Dart, async and await, Drift table definitions, and the difference between a Future and a Stream. It also assumes that AppDatabase and the generated TodoItem and TodoItems classes already exist.
A Drift query is built by starting with a table and adding conditions. Filtering reduces the rows returned. Sorting controls their order. Limiting controls how many rows the database returns.
Filtering rows with `where`
Use a column expression inside where. The expression is converted into a SQL condition.
// Inside AppDatabase
Future<List<TodoItem>> openItems({String? search}) {
Expression<bool> filter = todoItems.isDone.equals(false);
final text = search?.trim();
if (text != null && text.isNotEmpty) {
filter = filter & todoItems.title.like('%$text%');
}
final query = select(todoItems)
..where((item) => filter)
..orderBy([
(item) => OrderingTerm.desc(item.createdAt),
]);
return query.get();
}The first condition selects unfinished items. If the caller supplies search text, & combines the conditions with AND. The like expression finds titles containing the supplied text.
Common expressions include:
| Goal | Drift expression |
|---|---|
| Equal to a value | `column.equals(value)` |
| Greater than a value | `column.isBiggerThanValue(value)` |
| Contains text | `column.like('%text%')` |
| Is null | `column.isNull()` |
| Is not null | `column.isNotNull()` |
Avoid building raw SQL strings from untrusted input. Drift expressions keep the query typed and let the database handle values safely.
Sorting and limiting results
Use orderBy with one or more OrderingTerm values. Drift applies the terms in sequence. The second term breaks ties from the first term.
Future<List<TodoItem>> newestItems(int maximum) {
final query = select(todoItems)
..orderBy([
(item) => OrderingTerm.desc(item.createdAt),
(item) => OrderingTerm.asc(item.id),
])
..limit(maximum);
return query.get();
}This query returns at most maximum rows. Newest items appear first. When two items have the same creation time, the smaller ID appears first.
Always provide an ordering when using limit. Without an explicit order, SQLite may return any matching rows. The result can change after an index change or database update.
For pagination, combine limit with an offset:
Future<List<TodoItem>> pageOfItems({
required int page,
int pageSize = 20,
}) {
final query = select(todoItems)
..orderBy([(item) => OrderingTerm.desc(item.createdAt)])
..limit(pageSize, offset: page * pageSize);
return query.get();
}Offset pagination is simple, but rows inserted between requests can shift later pages. For large or frequently changing datasets, keyset pagination is more stable. It requests rows after the last seen ID or timestamp.
How the query is evaluated
Exercise
Why should a query use orderBy before applying limit?
Show answer
Without an explicit order, SQLite does not guarantee which matching rows it returns, so the limited result can change between executions.