cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

CALL subquery statements

I am using two sub queries with CALL statements. There are different matches and conditions applied in each sub query. if first sub query not producing any results then am not getting the result in the second call statement.
My syntax is like below.

MATCH (n:Person) WHERE n.id = 'CID0001'
CALL 
{
    WITH n
    MATCH (n) - [: .....] -> ()
    WHERE ..... 
    MATCH (n) - [: ....] -> (p)
    RETURN p
    LIMIT 1
}
CALL 
{
    WITH n
    MATCH (n) <- [: .....] - ()
    WHERE ..... 
    MATCH (n) <- [: ....] - (c)
    RETURN c
    LIMIT 1
}
WITH n, coalesce(p,c) as subvalue 
RETURN n, subvalue 
LIMIT 20

If first call statement fails then i am not getting the result in second call. I know the sub query will works like this. I changed the MATCH as OPTIONAL MATCH in each sub query like below.

MATCH (n:Person) WHERE n.id = 'CID0001'
CALL 
{
    WITH n
    OPTIONAL MATCH (n) - [: .....] -> ()
    WHERE ..... 
    OPTIONAL MATCH (n) - [: ....] -> (p)
    RETURN p
    LIMIT 1
}
CALL 
{
    WITH n
    OPTIONAL MATCH (n) <- [: .....] - ()
    WHERE ..... 
    OPTIONAL MATCH (n) <- [: ....] - (c)
    RETURN c
    LIMIT 1
}
WITH n, coalesce(p,c) as subvalue 
where (p is not null or c is not null)
RETURN n, subvalue 
LIMIT 20

I am getting results but am facing another issue. When using OPTIONAL MATCH, I am getting null values from sub queries. Since we are limiting the results to one record inside sub query, NULL is returned even though subsequent records having not null values. Is there any alternative way to achieve this without using OPTIONAL MATCH statements.

1 REPLY 1

If you want both sub queries to execute and contribute their results to the final result, try a Union of the two.

Chaining subqueries make the second sub query dependent on the results of the first.