> ## Documentation Index
> Fetch the complete documentation index at: https://docs.helix-db.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Branch, repeat, and condition queries

> Compose sub-traversals and gate named entries without leaving one transaction

Guide

`sub()` starts an inline traversal that consumes the current stream. Use it for
branching operations; use `g()` only for a top-level traversal entry.

## Branching operations

| Operation | Behavior |
| - | - |
| `optional(sub)` | Keep the input when the branch has no result |
| `union(subs)` | Concatenate results from every branch |
| `choose(predicate, then, else)` | Select one branch |
| `coalesce(subs)` | Use the first non-empty branch |
| `repeat(sub, config)` | Apply a traversal with an explicit bound |

## Retain row-local values

Combine branches with [bindings](https://docs.helix-db.com/database/helix-db/query-guides/traversals.md#preserve-correlated-values)
to keep one stable row shape across alternative paths. Bind the starting service, use
`optional` and `union` sub-traversals to bind each candidate workload path, then
project with `projectDistinctBindings` and `coalesce`. See
[Project correlated bindings](https://docs.helix-db.com/database/helix-db/query-guides/projections.md#project-correlated-bindings).

## Gate later entries

A batch condition runs an entry only when an earlier entry's result meets a test.
Add the entry with `varAsIf` / `var_as_if` instead of `varAs`. This request returns a
user's posts only when the user exists:

```rust Rust theme={"languages":{"custom":["languages/helixql.json"]}}
read_batch()
    .var_as(
        "user",
        g().n_with_label("User")
            .where_(Predicate::eq("username", "alice")),
    )
    .var_as_if(
        "posts",
        BatchCondition::VarNotEmpty("user".to_string()),
        g().n(NodeRef::var("user"))
            .out(Some("AUTHORED"))
            .value_map(Some(vec!["$id", "title"])),
    )
    .returning(["posts"]);
```

```ts TypeScript theme={"languages":{"custom":["languages/helixql.json"]}}
readBatch()
  .varAs("user", g().nWithLabel("User").where(Predicate.eq("username", "alice")))
  .varAsIf(
    "posts",
    BatchCondition.varNotEmpty("user"),
    g().n(NodeRef.var("user")).out("AUTHORED").valueMap(["$id", "title"]),
  )
  .returning(["posts"]);
```

```go Go theme={"languages":{"custom":["languages/helixql.json"]}}
helix.ReadQuery("user_posts").
	VarAs("user", helix.G().NWithLabel("User").Where(helix.PredEq("username", "alice"))).
	VarAsIf(
		"posts",
		helix.VarNotEmpty("user"),
		helix.G().N(helix.NodeVar("user")).Out("AUTHORED").ValueMap("$id", "title"),
	).
	Returning("posts")
```

```python Python theme={"languages":{"custom":["languages/helixql.json"]}}
(
    read_batch()
    .var_as(
        "user",
        g().n_with_label("User").where(Predicate.eq("username", "alice")),
    )
    .var_as_if(
        "posts",
        BatchCondition.var_not_empty("user"),
        g().n(NodeRef.var("user")).out("AUTHORED").value_map(["$id", "title"]),
    )
    .returning(["posts"])
)
```

```json JSON theme={"languages":{"custom":["languages/helixql.json"]}}
{
  "request_type": "read",
  "query_name": "user_posts",
  "query": {
    "read": {
      "entries": [
        {
          "query": {
            "name": "user",
            "root": {
              "where": {
                "input": {
                  "nodes_where": {
                    "predicate": {
                      "eq": {
                        "left": { "property": "$label" },
                        "right": { "constant": { "string": "User" } }
                      }
                    }
                  }
                },
                "predicate": {
                  "eq": {
                    "left": { "property": "username" },
                    "right": { "constant": { "string": "alice" } }
                  }
                }
              }
            }
          }
        },
        {
          "query": {
            "name": "posts",
            "root": {
              "value_map": {
                "input": {
                  "out": {
                    "input": { "nodes": { "reference": { "var": "user" } } },
                    "label": "AUTHORED"
                  }
                },
                "properties": ["$id", "title"]
              }
            },
            "condition": { "var_not_empty": "user" }
          }
        }
      ],
      "returns": ["posts"]
    }
  }
}
```

```cypher Cypher theme={"languages":{"custom":["languages/helixql.json"]}}
MATCH (user:User)
WHERE user.username = 'alice'
MATCH (user)-[:AUTHORED]->(post)
RETURN id(post) AS id, post.title AS title
```

The condition serializes inside the named entry, not as a separate step. Other
conditions test for an empty result (`varEmpty`), a minimum size (`varMinSize`), or
the previous entry (`prevNotEmpty`). The first entry in a batch cannot depend on a
previous result.

Cypher has no batch conditions. In the Cypher tab, the second `MATCH` runs once for
each user the first one finds, so the statement returns no rows when the user does
not exist.

## Bound recursive work

Recursive and fan-out operations must have application-level bounds. Prefer explicit
depth, candidate, and response limits. A response `limit` does not necessarily bound
all work performed before that operation.

## Next steps

> [card] [Projection and bindings](https://docs.helix-db.com/database/helix-db/query-guides/projections.md)
>
> Emit stable rows from correlated paths.

> [card] [Parameters](https://docs.helix-db.com/database/helix-db/query-guides/parameters.md)
>
> Bind values and bounds at request time.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.