Combinando Consultas com WITH e UNION
Aprenda a encadear etapas de consultas usando WITH e combinar conjuntos de resultados usando UNION para realizar consultas avançadas em Cypher.
Combinando Consultas com WITH e UNION é uma aula grátis de Neo4j Graph Database Fundamentals no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Neo4j Graph Database Fundamentals, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Neo4j Graph Database Fundamentals inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Why Chain Query Stages
Complex questions often need several steps: filter, aggregate, then filter again. Cypher uses WITH to pass results from one stage to the next.
Introducing WITH
WITH works like RETURN but feeds its output into the next part of the query instead of ending it.
MATCH (p:Person)-[:FRIEND]->(f)
WITH p, count(f) AS friendCount
WHERE friendCount > 3
RETURN p.name, friendCount;Filtering After Aggregation
You cannot put aggregate functions in a WHERE directly. Instead, aggregate with WITH, then filter the aggregated value in the following WHERE.
This is the Cypher equivalent of SQL's HAVING.
MATCH (c:City)<-[:LIVES_IN]-(p:Person)
WITH c, count(p) AS population
WHERE population > 1000
RETURN c.name, population;Carrying Variables Forward
Only variables listed in WITH stay in scope afterward. Anything omitted is dropped, so list everything you still need.
MATCH (p:Person)-[:BOUGHT]->(prod)
WITH p, collect(prod.name) AS products
RETURN p.name, products;Ordering and Limiting Mid-Query
WITH can include ORDER BY, SKIP, and LIMIT to shape intermediate results before the next stage.
MATCH (p:Person)
WITH p ORDER BY p.age DESC LIMIT 5
MATCH (p)-[:FRIEND]->(f)
RETURN p.name, f.name;Introducing UNION
UNION combines the results of two queries into one result set. Both sides must return the same column names.
MATCH (p:Person) RETURN p.name AS name
UNION
MATCH (c:Company) RETURN c.name AS name;UNION vs UNION ALL
UNION removes duplicate rows. UNION ALL keeps every row, including duplicates, and is faster when you know there are none.
MATCH (p:Person) RETURN p.name AS name
UNION ALL
MATCH (c:Company) RETURN c.name AS name;Combining WITH and UNION
You can aggregate within each side of a UNION using WITH, then merge the summaries. This builds powerful reporting queries.
MATCH (o:Order) WITH 'orders' AS kind, count(o) AS n RETURN kind, n
UNION
MATCH (u:User) WITH 'users' AS kind, count(u) AS n RETURN kind, n;Multiple WITH Stages
You can chain many WITH clauses to build a pipeline: each stage refines the data further.
MATCH (p:Person)-[:RATED]->(m:Movie)
WITH m, avg(p.rating) AS avgRating
WITH m, avgRating WHERE avgRating > 4
RETURN m.title, avgRating;Common Pitfalls
Watch out for:
- Forgetting to carry a needed variable through WITH
- Mismatched column names across UNION branches
- Using WITH when a simple WHERE would do
When to Use Each
Use WITH for multi-step pipelines and post-aggregation filtering. Use UNION to stack results from structurally different queries.
Quick Check
Check your understanding of query composition.
Recap
You learned to compose advanced queries:
- WITH pipes results between stages
- Filter aggregates after WITH (like HAVING)
- Only variables in WITH stay in scope
- UNION merges result sets; UNION ALL keeps duplicates
Perguntas Frequentes
A aula “Combinando Consultas com WITH e UNION” é grátis?
Sim — o texto completo de “Combinando Consultas com WITH e UNION” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Neo4j Graph Database Fundamentals, atualize para CoddyKit PRO. O curso de Neo4j Graph Database Fundamentals inclui 4 aulas no total.
O que vou aprender em “Combinando Consultas com WITH e UNION”?
Aprenda a encadear etapas de consultas usando WITH e combinar conjuntos de resultados usando UNION para realizar consultas avançadas em Cypher. Você pratica Neo4j Graph Database Fundamentals com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Neo4j Graph Database Fundamentals?
Nenhuma experiência prévia é necessária. Neo4j Graph Database Fundamentals no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Combinando Consultas com WITH e UNION”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Neo4j Graph Database Fundamentals?
Sim. Cada aula de Neo4j Graph Database Fundamentals inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Filtrando e Ordenando Resultados
- Agregação e Projeções
- Atualizando e Excluindo Dados de Grafos
- Combinando Consultas com WITH e UNION