7.9.13. SQL-12b — Set operations

Set operations stack two SELECT queries with compatible projections and dedupe / intersect / subtract their result rows. Under _sql(...) the existing daslib/linq.das array/iterator functions union, intersect, and except are recognized by the emitter and lowered to the matching SQL set-op:

Source shape

Emitted SQL

lhs |> union(rhs)

<lhs-sql> UNION <rhs-sql>

lhs |> intersect(rhs)

<lhs-sql> INTERSECT <rhs-sql>

lhs |> except(rhs)

<lhs-sql> EXCEPT <rhs-sql>

Both sides must project the same column shape (same column count and types). Use _select(_.Col) to pin the shape explicitly when the sources have different schemas.

7.9.13.1. Distinct tags from either table

let all_tiers <- _sql((db |> select_from(type<Customer>) |> _select(_.Tier))
                      |> union(db |> select_from(type<Prospect>) |> _select(_.Tier)))
// SELECT "Tier" FROM "Customers" UNION SELECT "Tier" FROM "Prospects"

7.9.13.2. Tags present in both tables

let shared <- _sql((db |> select_from(type<Customer>) |> _select(_.Tier))
                   |> intersect(db |> select_from(type<Prospect>) |> _select(_.Tier)))

7.9.13.3. Tags present only on the LHS

let exclusive <- _sql((db |> select_from(type<Customer>) |> _select(_.Tier))
                      |> except(db |> select_from(type<Prospect>) |> _select(_.Tier)))

See also

Full source: tutorials/sql/12b-set_ops.das

Previous tutorial: SQL-12 — distinct

Next tutorial: SQL-13 — Aggregates: sum/avg/…