Sub topic 13
Combining tables with joins
This chapter assumes you have finished the chapters on defining tables, writing CRUD queries, and watching queries as streams. You should be comfortable with foreign keys and with select(...).get() and .watch(). Here you will read from two tables in one query and get typed objects back.
Why joins
Storing a category name on every to-do row duplicates data. Renaming a category then means updating many rows. The normal fix is a second table, with each to-do holding a categoryId that points at a category row.
Reading both back needs a join. A join is a query that combines rows from two tables according to a condition. Drift builds joins in Dart, so column names and result types are checked at compile time.
The schema
The examples use two tables. categoryId is nullable because a to-do does not have to belong to a category.
class Categories extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get name => text().withLength(min: 1, max: 50)();
}
class TodoItems extends Table {
IntColumn get id => integer().autoIncrement()();
TextColumn get title => text().withLength(min: 1, max: 100)();
BoolColumn get isDone => boolean().withDefault(const Constant(false))();
IntColumn get categoryId =>
integer().nullable().references(Categories, #id)();
}The references(Categories, #id) call declares a foreign key. SQLite enforces foreign keys only when the foreign_keys pragma is on. Drift does not turn it on for you. You can enable it in the beforeOpen callback of your migration strategy:
@override
MigrationStrategy get migration => MigrationStrategy(
beforeOpen: (details) async {
await customStatement('PRAGMA foreign_keys = ON');
},
);Adding categoryId to an existing app changes the schema. Raise schemaVersion and add the column in onUpgrade with m.addColumn, as covered in the migrations chapter.
Join types
Drift offers three join constructors.
| Constructor | Rows in the result | Typical use |
|---|---|---|
| `innerJoin` | Only rows with a match on both sides | Show to-dos that have a category |
| `leftOuterJoin` | Every row from the first table, with `null` for a missing match | Show all to-dos, categorized or not |
| `crossJoin` | Every pairing of rows from both tables | Rare. Generating combinations |
select(todoItems).join([...]) makes todoItems the left table. A leftOuterJoin therefore keeps every to-do even when categoryId is null.
Writing a join query
A join starts from a normal select statement and calls .join with a list of joins. The join condition is an expression. Use equalsExp to compare two columns. Plain equals compares a column with a Dart value.
Stream<List<(TodoItem, Category?)>> watchWithCategory() {
final query = select(todoItems).join([
leftOuterJoin(categories, categories.id.equalsExp(todoItems.categoryId)),
]);
return query.watch().map((rows) => rows
.map((row) => (row.readTable(todoItems), row.readTableOrNull(categories)))
.toList());
}A joined query returns TypedResult objects, not row classes. Each one holds columns from both tables, and you pick them out by table:
row.readTable(todoItems)returns aTodoItem. It throws if the table's columns are allnull.row.readTableOrNull(categories)returns aCategory?. It isnullwhen the outer join found no match.
Use readTable on the side that always exists. Use readTableOrNull on the optional side of an outer join. Calling readTable(categories) on an unmatched row throws at runtime, and the compiler cannot warn you.
The return type uses Dart records, which need Dart 3. On older SDKs, return a small class instead.
Filtering and ordering joined queries
The ..where((t) => ...) callback form works only on a plain select. On a joined query you call where and orderBy on the query itself, and you refer to columns through the table objects.
Stream<List<(TodoItem, Category?)>> watchOpenByCategoryName(String name) {
final query = select(todoItems).join([
innerJoin(categories, categories.id.equalsExp(todoItems.categoryId)),
])
..where(todoItems.isDone.equals(false) & categories.name.equals(name))
..orderBy([OrderingTerm.asc(todoItems.title)])
..limit(50);
return query.watch().map((rows) => rows
.map((row) => (row.readTable(todoItems), row.readTableOrNull(categories)))
.toList());
}The & operator combines two boolean expressions with SQL AND. Use | for OR. Because this query uses innerJoin, every result has a category, so readTable(categories) would also be safe here.
Aggregates with groupBy
A join often feeds an aggregate, such as the number of to-dos per category. Add an aggregate expression with addColumns and group with groupBy:
Stream<List<(Category, int)>> watchCategoryCounts() {
final count = todoItems.id.count();
final query = select(categories).join([
leftOuterJoin(todoItems, todoItems.categoryId.equalsExp(categories.id)),
])
..addColumns([count])
..groupBy([categories.id]);
return query.watch().map((rows) => [
for (final row in rows) (row.readTable(categories), row.read(count) ?? 0),
]);
}Here categories is the left table, so a category with no to-dos still appears. count() on todoItems.id counts only non-null values. An empty category therefore reports 0, not 1. You read the aggregate with row.read(count), using the same expression object you added.
If you need only aggregate values and no full rows, use selectOnly(table). It selects no columns by default, and you add the ones you want with addColumns.
Streams and joins
A joined watch() re-runs when any table it reads from changes. Inserting a category refreshes watchWithCategory, and so does updating a to-do. You do not need to list the tables yourself, because drift takes them from the query.
StreamBuilder<List<(TodoItem, Category?)>>(
stream: db.watchWithCategory(),
builder: (context, snapshot) {
final rows = snapshot.data ?? const [];
return ListView(
children: [
for (final (item, category) in rows)
ListTile(
title: Text(item.title),
subtitle: Text(category?.name ?? 'No category'),
),
],
);
},
)Common errors
- Using
readTableon the optional side. It throws aStateErroron rows without a match. UsereadTableOrNull. - Using
equalsinstead ofequalsExp.equalsexpects a Dart value, so passing a column does not compile. UseequalsExpto compare two columns. - Forgetting that the left table decides what an outer join keeps.
select(categories).join([leftOuterJoin(todoItems, ...)])andselect(todoItems).join([leftOuterJoin(categories, ...)])return different rows. - Ambiguous column names in custom SQL. Both tables have an
idcolumn. In raw SQL, qualify them astodo_items.id. The typed API avoids this problem. - Duplicate rows from one-to-many joins. Joining a category to many to-dos returns one row per to-do. Group the results in Dart or use
groupByif you expected one row per category.
Testing a join
Joins are easy to test with the in-memory database from the previous testing chapter. Insert a category and two to-dos, one with a category and one without, then check both result shapes.
import 'package:drift/drift.dart';
import 'package:drift/native.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('left join keeps to-dos without a category', () async {
final db = AppDatabase(NativeDatabase.memory());
addTearDown(db.close);
final homeId = await db
.into(db.categories)
.insert(CategoriesCompanion.insert(name: 'Home'));
await db.into(db.todoItems).insert(
TodoItemsCompanion.insert(title: 'Buy milk', categoryId: Value(homeId)));
await db
.into(db.todoItems)
.insert(TodoItemsCompanion.insert(title: 'Call Sam'));
final rows = await db.watchWithCategory().first;
final byTitle = {for (final (i, c) in rows) i.title: c?.name};
expect(byTitle, {'Buy milk': 'Home', 'Call Sam': null});
});
}Exercise
You want a screen that lists every category with its number of open (not done) to-dos, including categories that have none. Which join type and starting table do you use, and where does the isDone condition go so empty categories still appear?
Show answer
Start from categories and use leftOuterJoin to todoItems. Put the isDone condition in the join's on expression, as todoItems.categoryId.equalsExp(categories.id) & todoItems.isDone.equals(false), not in where. A where on todoItems.isDone removes the null-filled rows for empty categories and turns the query into an inner join. Then add todoItems.id.count() with addColumns and group by categories.id.