Documentation for EXISTS

This commit is contained in:
Gwendal Roué committed 2021-03-20 15:47:00 +01:00
1 parent 989a0e82eb
commit 63448fb0bc
1 file changed
+37
+37
View File
@@ -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<Row>("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: