0Pricing
Neo4j Graph Database Fundamentals · Lezione

Combinare query con WITH e UNION

Imparate a concatenare le fasi delle query usando WITH e a unire i set di risultati con UNION per scrivere query Cypher avanzate.

Combinare query con WITH e UNION è una lezione Neo4j Graph Database Fundamentals gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Neo4j Graph Database Fundamentals, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Neo4j Graph Database Fundamentals include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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

Domande Frequenti

La lezione «Combinare query con WITH e UNION» è gratuita?

Sì — il testo completo di «Combinare query con WITH e UNION» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Neo4j Graph Database Fundamentals, passa a CoddyKit PRO. Il corso Neo4j Graph Database Fundamentals include 4 lezioni in totale.

Cosa imparerò in «Combinare query con WITH e UNION»?

Imparate a concatenare le fasi delle query usando WITH e a unire i set di risultati con UNION per scrivere query Cypher avanzate. Eserciti Neo4j Graph Database Fundamentals con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Neo4j Graph Database Fundamentals?

Non è richiesta alcuna esperienza precedente. Neo4j Graph Database Fundamentals su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Combinare query con WITH e UNION»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Neo4j Graph Database Fundamentals?

Sì. Ogni lezione Neo4j Graph Database Fundamentals include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Filtraggio e ordinamento dei risultati
  2. Aggregazioni e proiezioni
  3. Aggiornamento ed eliminazione dei dati del grafo
  4. Combinare query con WITH e UNION
← Torna a Neo4j Graph Database Fundamentals