<a id="compose-statements"></a>

# Compose statements

A statement is a sequence of clauses, and `WITH` ends one query part and starts the next. Unions combine whole statements, and a statement built once can be stored, shared and rendered repeatedly.

<a id="end-a-query-part-with-with"></a>

## End a query part with WITH

Only the names a `WITH` projects are available to the clauses after it. A structured projection item needs an alias, because the next part needs a name for the value:

```python
from cypher_dsl import Configuration, Renderer, match, name, node, param

person = node("Person", name="p")
statement = (
    match(person)
    .with_(person["uid"].alias("uid"))
    .where(person["rating"] > param("min_rating"))
    .returning(name("uid"))
)

renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
```

```cypher
MATCH (p:Person) WITH p.uid AS uid WHERE p.rating > $min_rating RETURN uid
```

Only `uid` is available after this `WITH`. A later `returning(person)` is rejected. An ordinary `WITH` filter can use both incoming variables and projected aliases, even when the incoming variable is not passed on. A `DISTINCT` projection restricts its own filter to the names it outputs: an incoming name the structured projection omits is masked. An aggregation alone does not mask, so `WITH count(p) AS n WHERE p.x > 1` renders and the server rejects it. That is Neo4j’s check, not the library’s.

Passing a plain variable through needs no alias:

```python
from cypher_dsl import Configuration, Renderer, desc, match, node

person = node("Person", name="p")
statement = (
    match(person)
    .with_(person)
    .order_by(desc(person["rating"]))
    .limit(1)
    .returning(person["display_name"])
)

renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
```

```cypher
MATCH (p:Person) WITH p ORDER BY p.rating DESC LIMIT 1 RETURN p.display_name
```

`WITH` carries the same `distinct`, `order_by`, `skip` and `limit` modifiers as `RETURN`, so a query part can cut its rows before the next part reads them.

<a id="combine-statements-with-union"></a>

## Combine statements with UNION

`union` returns a draft that holds the branches. `build()` finalises it, and `render` accepts the draft directly. `UNION` removes duplicates, `UNION ALL` keeps them, and the branches must agree on the shape: either every branch ends in its own `RETURN` or none does. A standalone union needs `RETURN` in every branch.

```python
from cypher_dsl import Configuration, Renderer, match, node, param, union

person = node("Person", name="p")
movie = node("Movie", name="m")
statement = union(
    match(person)
    .where(person["rating"] > param("min_rating", 4))
    .returning(person["display_name"].alias("who")),
    match(movie)
    .where(movie["released"] > param("since", 2000))
    .returning(movie["title"].alias("who")),
    all=True,
)

renderer = Renderer.get(Configuration(server_version="5.26", pretty_print=True))
print(renderer.render(statement).cypher)
```

```cypher
MATCH (p:Person) WHERE p.rating > $min_rating RETURN p.display_name AS who
UNION ALL
MATCH (m:Movie) WHERE m.released > $since RETURN m.title AS who
```

Each branch is written under the same incoming scope, and a branch scope stays isolated from the others. The library does not compare the branches, so column agreement across them is Neo4j’s check. A union whose branches project different numbers of columns renders and the server rejects it. An empty branch is rejected when `union()` receives it.

<a id="reuse-and-compare-statements"></a>

## Reuse and compare statements

Every builder call returns a new immutable value, so a statement built once can be kept and rendered many times, including concurrently. `build()` completes the clauses explicitly, and `render` accepts a `Builder`, a `Statement`, a `UnionDraft` or a `UnionStatement`:

```python
from cypher_dsl import Configuration, Renderer, match, node, param

person = node("Person", name="p")
statement = (
    match(person)
    .where(person["rating"] > param("min_rating"))
    .returning(person["display_name"])
    .build()
)

renderer = Renderer.get(Configuration(server_version="5.26"))
first = renderer.render(statement)
second = renderer.render(statement)

print(first.cypher == second.cypher)
print(first.parameters is second.parameters)
```

```text
True
False
```

Expressions deliberately have no structural `==`, because `==` builds a Cypher comparison. To compare two statements, compare their rendered text:

```python
from cypher_dsl import Configuration, Renderer, match, node

left_person = node("Person", name="p")
right_person = node("Person", name="p")
renderer = Renderer.get(Configuration(server_version="5.26"))

left = match(left_person).returning(left_person["display_name"]).build()
right = match(right_person).returning(right_person["display_name"]).build()

print(renderer.render(left).cypher == renderer.render(right).cypher)
```

```text
True
```

Comparing `cypher` compares Cypher text, not bindings.

<a id="optional-filters"></a>

<a id="build-a-statement-from-optional-filters"></a>

## Build a statement from optional filters

A search form sends only the filters the user filled in. The text box is always present and matches a name or an email, and every other input adds a filter when the request carries one:

```python
from cypher_dsl import (
    Configuration,
    Renderer,
    contains,
    exists,
    match,
    node,
    param,
)

person = node("Person", name="p")
request = {
    "q": "ann",
    "age": 30,
    "city": "Berlin",
    "department": "R&D",
}

query = param("q", request["q"])
age = request.get("age")
city_name = request.get("city")
department_name = request.get("department")

statement = match(person).where(
    contains(person["name"], query) | contains(person["email"], query)
)
if age is not None:
    statement = statement.where(person["age"] >= param("age", age))
if city_name is not None:
    city = node("City", name="c")
    lives_in = match(node(name="p").relationship_to(city, "LIVES_IN")).where(
        city["name"] == param("city_name", city_name)
    )
    statement = statement.where(exists(lives_in))
if department_name is not None:
    department = node("Department", name="d")
    works_in = (
        match(node(name="p").relationship_to(department, "WORKS_IN"))
        .where(
            department["name"]
            == param("department_name", department_name)
        )
    )
    statement = statement.where(exists(works_in))
statement = statement.returning(person["display_name"])

renderer = Renderer.get(Configuration(server_version="5.26", pretty_print=True))
print(renderer.render(statement).cypher)
```

```cypher
MATCH (p:Person)
  WHERE (p.`name` CONTAINS $q OR p.email CONTAINS $q) AND p.age >= $age
    AND EXISTS {
      MATCH (p)-[:LIVES_IN]->(c:City) WHERE c.`name` = $city_name
    }
    AND EXISTS {
      MATCH (p)-[:WORKS_IN]->(d:Department)
        WHERE d.`name` = $department_name
    }
RETURN p.display_name
```

The last `EXISTS` is wrapped here to fit the page. The renderer writes that clause on one line when it fits the 120-column layout width. That width is the reason the first `EXISTS` broke and the second did not: the first group no longer fitted the remaining columns.

The text box is one condition over two properties, joined with `|` because Python’s `or` cannot be overloaded. Every optional input adds one `where` to the outer statement. The related patterns are built as statements of their own, so their `where` calls attach to their own `match`, and `exists` turns the finished statement into a predicate. [Call subqueries](subqueries.md) documents `exists` and the other subquery expressions.
