Sub topic 8
Filtering, sorting, and limiting results
This chapter assumes you have a working AppDatabase with the TodoItems table from the earlier chapters. You should also know how select(...).get() returns rows. Here you will narrow a query with where, order it with orderBy, and cap it with limit. All three work the same for get() and watch().
How a select statement is built
select(todoItems) returns a SimpleSelectStatement. It is a mutable builder object. You add clauses to it, then run it with get(), getSingle(), getSingleOrNull(), or watch(). The cascade operator (..) is the usual way to chain clauses, because each clause method returns void rather than the statement.
Nothing touches the database until the last step. The order in which you add clauses does not matter. SQL always applies them as filter, then sort, then limit.
Filtering with where
where takes a function that receives the table and returns an Expression<bool>. Drift builds these expressions from the typed columns, so a typo in a column name is a compile error rather than a runtime SQL error.
// Inside AppDatabase
Future<List<TodoItem>> openItems() =>
(select(todoItems)..where((t) => t.isDone.equals(false))).get();
Future<List<TodoItem>> searchByTitle(String text) =>
(select(todoItems)..where((t) => t.title.contains(text))).get();
Future<List<TodoItem>> recentItems(DateTime since) =>
(select(todoItems)
..where((t) => t.createdAt.isBiggerOrEqualValue(since)))
.get();Common comparison methods:
| Method | SQL meaning |
|---|---|
| `equals(x)` | `= x` |
| `isBiggerThanValue(x)`, `isSmallerThanValue(x)` | `>` and `<` |
| `isBiggerOrEqualValue(x)`, `isSmallerOrEqualValue(x)` | `>=` and `<=` |
| `isBetweenValues(a, b)` | `BETWEEN a AND b` |
| `isIn([a, b])`, `isNotIn([a, b])` | `IN (...)` |
| `like('%x%')`, `contains(x)` | pattern matching on text |
| `isNull()`, `isNotNull()` | `IS NULL` and `IS NOT NULL` |
Combining conditions
Use & for AND, | for OR, and .not() for negation. Dart operator precedence is different from SQL, so wrap each side in parentheses.
// Inside AppDatabase
Future<List<TodoItem>> openOrRecent(DateTime since) {
return (select(todoItems)
..where((t) =>
t.isDone.equals(false) |
t.createdAt.isBiggerOrEqualValue(since)))
.get();
}Calling where more than once on the same statement combines the conditions with AND. This makes optional filters easy to write, as the search example below shows.
Edge cases in filtering
- Null checks. A comparison with
NULLis never true in SQL, sot.note.equals('x')skips rows wherenoteis null. UseisNull()when you want those rows. - Case sensitivity. SQLite's
LIKEignores case for ASCII letters only. Non-ASCII letters such asÉandéare treated as different. - Wildcards in user input. Drift sends your values as bound variables, so text such as
'; DROP TABLEcannot inject SQL. The characters%and_still act as wildcards inside alikepattern. A search for100%will match more rows than you expect. - Empty lists.
isIn([])is valid and matches no rows, so you do not need a special case.
Sorting with orderBy
orderBy takes a list of functions. Each function returns an OrderingTerm. Terms are applied in list order, so later terms only break ties among earlier ones.
// Inside AppDatabase
Future<List<TodoItem>> sorted() {
return (select(todoItems)
..orderBy([
(t) => OrderingTerm.asc(t.isDone),
(t) => OrderingTerm.desc(t.createdAt),
(t) => OrderingTerm.asc(t.id),
]))
.get();
}This puts open items first, newest first within each group. The last term sorts by id, which is unique, so the order is the same on every run. Without a unique tie-breaker, SQLite may return rows with equal sort values in any order. That matters for pagination, covered below.
Without an orderBy, SQL gives no guarantee about row order. Even if rows look like they come back in insertion order today, do not depend on it.
Limiting results
limit(count, offset: n) caps the number of rows and optionally skips some first.
// Inside AppDatabase
Future<List<TodoItem>> latestFive() {
return (select(todoItems)
..orderBy([(t) => OrderingTerm.desc(t.createdAt)])
..limit(5))
.get();
}A limit without an order returns an arbitrary set of rows, so pair the two. For a single row, getSingleOrNull() returns null when nothing matches. It throws if more than one row matches. getSingle() throws on zero rows as well. When you want the first of many, use limit(1) and getSingleOrNull().
Putting it together: an optional-filter search
A search screen often has several optional filters. Because where calls combine with AND, you can add each filter only when the caller supplies it.
// Inside AppDatabase
Future<List<TodoItem>> search({
String? text,
bool? isDone,
int limit = 20,
int offset = 0,
}) {
final query = select(todoItems);
if (text != null && text.isNotEmpty) {
query.where((t) => t.title.contains(text));
}
if (isDone != null) {
query.where((t) => t.isDone.equals(isDone));
}
query
..orderBy([
(t) => OrderingTerm.desc(t.createdAt),
(t) => OrderingTerm.asc(t.id),
])
..limit(limit, offset: offset);
return query.get();
}To make this live, replace the final get() with watch(). The method then returns a Stream<List<TodoItem>>. The next chapter covers how those streams work.
Pagination: offset versus keyset
Offset pagination is simple, but it has two weaknesses. SQLite still walks past the skipped rows, so deep pages get slower. And if a row is inserted or deleted between page loads, items shift and you can see duplicates or miss rows.
Keyset pagination avoids both by remembering the last row seen and asking for rows after it.
// Inside AppDatabase
Future<List<TodoItem>> pageAfter(DateTime? lastCreatedAt, {int size = 20}) {
final query = select(todoItems);
if (lastCreatedAt != null) {
query.where((t) => t.createdAt.isSmallerThanValue(lastCreatedAt));
}
query
..orderBy([(t) => OrderingTerm.desc(t.createdAt)])
..limit(size);
return query.get();
}This version assumes createdAt values are distinct. If two rows can share a timestamp, a page boundary could skip one of them. In that case compare on (createdAt, id) together, or use the autoincrement id as the cursor.
Common mistakes
- Forgetting parentheses around the cascade. Write
(select(todoItems)..where(...)).get(). Without the outer parentheses,get()is called on the result ofwhere, which returnsvoid, and Dart reports an error. - Using Dart
&&and||. These do not work on drift expressions. Use&and|. - Filtering in Dart after loading everything.
items.where(...)on a full list works, but it loads every row first. Push filters, sorting, and limits into the query so SQLite does the work.
Exercise
Write a method topOpen(int n) on AppDatabase that returns the n most recently created items that are not done, with id as the tie-breaker.
Show answer
Future<List<TodoItem>> topOpen(int n) => (select(todoItems)..where((t) => t.isDone.equals(false))..orderBy([(t) => OrderingTerm.desc(t.createdAt), (t) => OrderingTerm.asc(t.id)])..limit(n)).get();
Exercise
A query uses limit(10, offset: 20) with no orderBy. Give two reasons it can return unreliable pages.
Show answer
Without orderBy, SQL does not guarantee row order, so the 10 rows can differ between runs or after a write. Even with an order, inserting or deleting rows between page loads shifts the offset, causing duplicates or skipped rows. Add a unique tie-breaker to orderBy, or switch to keyset pagination.