WITH
The WITH clause allows you to chain query parts together, passing results from one part to the next. This enables complex query composition and data manipulations.
Use Cases
WITH is useful for:
- Chaining multiple query parts together
- Performing intermediate aggregations
- Filtering or transforming results before the next query part
- Using query modifiers (
DISTINCT,ORDER BY,LIMIT,SKIP) mid-query
Example: Filtering by Aggregated Values
Find all children above the average age of all people:
GRAPH.QUERY DEMO_GRAPH
"MATCH (p:Person) WITH AVG(p.age) AS average_age MATCH (:Person)-[:PARENT_OF]->(child:Person) WHERE child.age > average_age return child"
Example: Using Modifiers Mid-Query
You can use query modifiers with WITH to filter or sort before continuing:
GRAPH.QUERY DEMO_GRAPH
"MATCH (u:User) WITH u AS nonrecent ORDER BY u.lastVisit LIMIT 3 SET nonrecent.should_contact = true"
This query:
- Matches all users
- Orders them by last visit (oldest first)
- Limits to the 3 least recent visitors
- Sets a flag on those users
Key Points
WITHacts like a pipeline between query parts- Variables not included in
WITHare not available in subsequent parts - You can rename variables using
ASin theWITHclause - Aggregations in
WITHcause implicit grouping (likeRETURN) WHEREfilters placed after aWITHboundary are evaluated after any write operations that preceded theWITH. This means the filter sees the post-write graph state — for example, it will not see edges that were deleted earlier in the same query.
Frequently Asked Questions 4
What does the WITH clause do?
WITH acts as a pipeline between query parts, passing results from one section to the next. It enables intermediate aggregations, filtering, sorting, and variable scoping within a single query.
Do variables carry over after WITH?
Only variables explicitly listed in the WITH clause are available in subsequent query parts. Any variable not included is dropped from scope.
Can I use ORDER BY and LIMIT with WITH?
Yes. WITH supports all query modifiers including DISTINCT, ORDER BY, SKIP, and LIMIT. This lets you filter and sort intermediate results before continuing the query.
How does aggregation work in WITH?
Aggregation functions in WITH cause implicit grouping, just like in RETURN. Non-aggregated expressions become grouping keys automatically.