diff --git a/README.md b/README.md index 6dd6e2672..ad7b7389c 100644 --- a/README.md +++ b/README.md @@ -4589,6 +4589,43 @@ GRDB comes with a Swift version of many SQLite [built-in operators](https://sqli > :point_up: **Note**: SQLite string comparison, by default, is case-sensitive and not Unicode-aware. See [string comparison](#string-comparison) if you need more control. +- `EXISTS`, `NOT EXISTS` + + To check if a subquery would return rows, call the `exists` method: + + ```swift + let alias = TableAlias(name: "coach") + + // Players who coach at least one other player + // + // SELECT coach.* FROM player coach + // WHERE EXISTS (SELECT * FROM player WHERE coachId = coach.id) + Player + .aliased(alias) + .filter(Player.filter(Column("coachId") == alias[Column("id")]).exists()) + + // Players who do not coach any other player + // + // SELECT coach.* FROM player coach + // WHERE NOT EXISTS (SELECT * FROM player WHERE coachId = coach.id) + Player + .aliased(alias) + .filter(!Player.filter(Column("coachId") == alias[Column("id")]).exists()) + ``` + + See how you use `TableAlias` in order to let a subquery refer to a column from another table. + + Since the above example involves the same table twice, it requires an explicit disambiguation with `TableAlias(name:)`. A future GRDB version may automatically perform this disambiguation. + + Subqueries can also be expressed as SQL, with [SQL Interpolation]: + + ```swift + // SELECT coach.* FROM player coach + // WHERE EXISTS (SELECT * FROM player WHERE coachId = coach.id) + let subquery = SQLRequest("SELECT * FROM player WHERE coachId = \(alias[Column("id")])") + Player.aliased(alias).filter(subquery.exists()) + ``` + - `LIKE` The SQLite LIKE operator is available as the `like` method: