Sub topic 13
Combining Tables with Joins
Assume you know Dart classes, Future, Stream, and the basic ideas of tables, rows, and primary keys. This chapter uses a TodoItems table and a Categories table. Each to-do can have one category, but a category is optional.
A join combines rows from two or more tables. In drift, you describe the relationship with a join expression and convert each result row back into typed Dart objects.
Why use a join?
Suppose TodoItems stores only a categoryId. To display the category name, the app must also read Categories. A join lets SQLite match those rows in one query.
| Join type | Result |
|---|---|
| Inner join | Only to-dos with a matching category |
| Left outer join | Every to-do, including to-dos without a category |
Use a left outer join when the related record is optional. Use an inner join when rows without a match have no meaning for the screen.
Defining the relationship
The nullable categoryId column allows a to-do to exist without a category. The references declaration also tells drift which column is related.
import 'package:drift/drift.dart';
import 'package:drift_flutter/drift_flutter.dart';
part 'database.g.dart';
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)();
IntColumn get categoryId =>
integer().nullable().references(Categories, #id)();
}
@DriftDatabase(tables: [TodoItems, Categories])
class AppDatabase extends _$AppDatabase {
AppDatabase([QueryExecutor? executor])
: super(executor ?? driftDatabase(name: 'app'));
@override
int get schemaVersion => 1;
Stream<List<(TodoItem, Category?)>> watchTodosWithCategory() {
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(),
);
}
}The leftOuterJoin call compares categories.id with todoItems.categoryId. Each result is a record containing a TodoItem and a nullable Category. readTable reads the required table. readTableOrNull is necessary because a left join can produce no matching category.
Choosing the correct join
An inner join excludes uncategorized items:
final query = select(todoItems).join([
innerJoin(
categories,
categories.id.equalsExp(todoItems.categoryId),
),
]);Use an inner join for a screen that should show only categorized items. Use a left outer join for a complete to-do list where the category is extra information.
Joins can also be filtered and ordered. Add where conditions to the joined query, then call watch() or get() as you would for a single table. Keep the join in a database method or DAO so widgets receive a useful typed result instead of raw query rows.
Exercise
Which join should you use to display every to-do, including to-dos whose category was deleted or never assigned?
Show answer
Use a left outer join, and read the category with readTableOrNull.