liveBook · Manning

Optional match clause

As explained in Graph Algorithms for Data Science

An OPTIONAL MATCH clause is a Cypher query clause that preserves rows when a pattern is absent by binding the unmatched elements to null.

An OPTIONAL MATCH clause finds a graph pattern without discarding rows when that pattern is absent. Existing variables remain available, while unmatched elements are bound to null. section 3.4

Use OPTIONAL MATCH when a query should retain its primary results even if related data may not exist:

  • Begin with MATCH for the required pattern, then use OPTIONAL MATCH for an uncertain related pattern. section 3.4
  • Attach a WHERE clause directly after the relevant MATCH or OPTIONAL MATCH; each WHERE filters the preceding clause. section 3.1.2
  • Use WITH between successive matches or aggregations when intermediate rows could multiply and distort counts. section 4.5

Keep Satish when a book is missing

MATCH (p:Person) WHERE p.name = 'Satish' OPTIONAL MATCH (b:Book) WHERE b.title = 'Catcher in the rye' RETURN * The Person row for Satish remains in the result even when no matching Book exists; the book variable is null. section 3.4

Optional relationship analysis

A social-network query can count several kinds of mentions with successive OPTIONAL MATCH clauses. WITH carries earlier counts forward so each later match does not multiply previous rows. section 4.5

How Graph Algorithms for Data Science covers it

How deep it goes
Explains row preservation, null bindings, clause-local filtering, and cardinality control through WITH, without covering execution internals.
Examples
Uses Satish and a possibly absent book, friendship patterns, and social-media mention counts.
What it assumes
Assumes basic Cypher patterns, MATCH, WHERE, and RETURN while teaching how missing patterns differ from required matches.
What you can do after
Apply it via Cypher to retain entities lacking optional relationships and structure multi-stage counts.
How it connects
Connects OPTIONAL MATCH to MATCH, WHERE, WITH, aggregation, and query cardinality.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Graph Algorithms for Data Science. The section links point to the parts of the book it draws on.