Skip to main content

Connected Components

connected_components(src, dst) groups the ids of a graph into connected components: two ids are in one component when a chain of rows links them. Use it to unify identifiers, for example to give every email and device of one customer the same id.

val links(id, other) = [
['ann@mail', 'device-1'],
['ann@work', 'device-1'],
['ann@work', 'phone-7'],
['bob@mail', 'device-2'],
['carol@mail', 'carol@mail'],
]

from links
| connected_components(id, other)
order by component, node
┌────────────┬────────────┐
│ node │ component │
│ string │ string │
├────────────┼────────────┤
│ ann@mail │ ann@mail │
│ ann@work │ ann@mail │
│ device-1 │ ann@mail │
│ phone-7 │ ann@mail │
│ bob@mail │ bob@mail │
│ device-2 │ bob@mail │
│ carol@mail │ carol@mail │
├────────────┴────────────┤
│ 7 rows │
└─────────────────────────┘

What it returns​

  • One row per id (node), with component: the smallest id of its component, by the sort order of the column type (string order for strings). The same edges give the same component ids on every run and engine.
  • Each row is an undirected edge: (a, b) and (b, a) link the same ids.
  • Rows with a NULL in either column are dropped, so an id appears only through a row that links it. To list an id that has no links, add a self edge (id, id), as for carol@mail above.
  • Both columns must have one type. Cast one of them if they differ, for example connected_components(user_id::string, email).
  • The output has only node and component. Join it back to your rows to attach the component:
from accounts
join {
from links
| connected_components(id, other)
} as c on accounts.email = c.node
select accounts.email, accounts.name, c.component as person_id

Engines​

EngineRuns as
Wvlet engineOne union-find pass over the edges, held in memory.
DuckDBA WITH RECURSIVE ... USING KEY query. Each round moves the smallest id one link further, so long chains of links take many rounds.
Trino, Snowflake, HiveNot supported: compiling the query fails, as these engines can't aggregate inside a recursive query. Run the query on the Wvlet engine, or repeat a pass that gives each id the smallest id of its neighbors in a for ... until loop.

A partial query of your own named connected_components takes precedence over this operator.