RETURN¶
The RETURN clause specifies what data to return from a query.
Basic Returns¶
Return Nodes¶
Return Properties¶
Return All Properties¶
Aliases¶
Use aliases for clarity:
Expressions¶
Arithmetic¶
String Operations¶
Conditional Expressions¶
MATCH (u:User)
RETURN u.name,
CASE
WHEN u.age < 18 THEN 'Minor'
WHEN u.age < 65 THEN 'Adult'
ELSE 'Senior'
END AS ageGroup
Aggregations¶
COUNT¶
SUM, AVG, MIN, MAX¶
COLLECT¶
COUNT DISTINCT¶
Grouping¶
Aggregations automatically group by non-aggregated fields:
Multiple grouping fields:
DISTINCT¶
Return unique results:
Relationships¶
Return Relationships¶
Relationship Properties¶
Relationship Type¶
Paths¶
Return Paths¶
Path Length¶
MATCH path = (u:User {name: 'Alice'})-[:KNOWS*]->(f:User {name: 'Bob'})
RETURN length(path) AS pathLength
Nodes in Path¶
Computed Values¶
Counts and Sizes¶
String Functions¶
MATCH (u:User)
RETURN toLower(u.name) AS lowerName,
toUpper(u.email) AS upperEmail,
substring(u.name, 0, 1) AS initial
Date/Time Functions¶
Limiting Results¶
Combine with LIMIT:
Maps and Objects¶
Return as Map¶
Collect Maps¶
Pattern Comprehensions¶
MATCH (u:User)
RETURN u.name,
[(u)-[:KNOWS]->(f) | f.name] AS friendNames,
[(u)-[:POSTED]->(p) | {title: p.title, date: p.created}] AS posts
Conditional Returns¶
CASE Expression¶
MATCH (u:User)
RETURN u.name,
CASE u.subscription
WHEN 'premium' THEN 'Premium User'
WHEN 'basic' THEN 'Basic User'
ELSE 'Free User'
END AS userType
CASE with Conditions¶
MATCH (u:User)
RETURN u.name,
CASE
WHEN u.age < 18 THEN 'Youth discount'
WHEN u.age >= 65 THEN 'Senior discount'
ELSE 'Regular price'
END AS pricing
Complex Aggregations¶
Multiple Aggregations¶
MATCH (u:User)-[:POSTED]->(p:Post)
RETURN u.name,
count(p) AS posts,
avg(p.likes) AS avgLikes,
max(p.created) AS lastPost
Nested Aggregations¶
MATCH (u:User)-[:POSTED]->(p:Post)
WITH u, count(p) AS postCount
WHERE postCount > 10
RETURN u.name, postCount
ORDER BY postCount DESC
Performance Tips¶
-
Return Only What You Need
-
Use DISTINCT Wisely
-
Limit Early
-
Project Early with WITH
Common Patterns¶
Top N per Group¶
MATCH (u:User)-[:POSTED]->(p:Post)
WITH u, p
ORDER BY p.created DESC
RETURN u.name, collect(p.title)[0..5] AS recentPosts
Pivot Data¶
MATCH (u:User)-[:LIVES_IN]->(c:City)
RETURN c.name AS city,
count(u) AS population
ORDER BY population DESC
Running Totals¶
MATCH (p:Post)
WITH p
ORDER BY p.created
RETURN p.title,
p.created,
sum(p.views) OVER (ORDER BY p.created) AS cumulativeViews
Next Steps¶
- Match patterns with MATCH
- Filter results with WHERE
- Sort results with ORDER BY
- Limit results with LIMIT
- Read Cypher Introduction