How does this work - Multiple MATCH/OPTIONAL MATCH statements with WHERE

Hello fellow Neo4jers/ians!
Going through the lessons under Querying with Cypher and a question -

Related note from the Cypher Manual page -

In the case of multiple MATCH / OPTIONAL MATCH clauses, the predicate in WHERE is always a part of the patterns in the directly preceding MATCH / OPTIONAL MATCH . Both results and performance may be impacted if the WHERE is put inside the wrong MATCH clause.

Query -
MATCH (valKilmer:Person)-[:ACTED_IN]->(m:Movie)
MATCH (actor:Person)-[:ACTED_IN]->(m)
WHERE = 'Val Kilmer'
RETURN m.title as movie ,

How is this block processed? I understand MATCH 1 produces a list of Person nodes who acted in a movie. At this point, the MATCH 2 produces a list of Person nodes who acted in the Movie nodes identified in MATCH 1.

Now when the WHERE is applied to MATCH 2, how is does the condition work on the nodes identified in MATCH 2? I do not see a clear connection between them.

In the OPTIONAL MATCH case, it is a little more intuitive since the WHERE is directly placed after the MATCH statement to which it applies. (at least in the examples I have come across).

Your help is appreciated!

Hello @poornima ,

The Cypher query processor does parse the query to apply the WHERE clause to the first MATCH clause. The only time that the placement of the WHERE clause is significant is when an OPTIONAL MATCH is specified.

If you were to profile the above query vs:
MATCH (valKilmer:Person {name: 'Val Kilmer'})-[:ACTED_IN]->(m:Movie)
MATCH (actor:Person)-[:ACTED_IN]->(m)
RETURN m.title as movie ,

You would see that they are identical in execution.

I will let the documentation team know that the docs should be modified.


@elaine.rosenberg Thank you, it's clear now.