title: Neo4j: using 'order by' and 'limit' with subqueries
body: <p>I have a data model that's a tree structure with a max depth of 3. For example:</p>
  
  <pre><code>          (a)       ... first level root node
          /  |  \
         /   |   \
       (b)  (b)  (b)  ... [0..n] number of second depth nodes
      / |         |
     /  |         |
   (c) (c)       (c)  ... [0..n] number of third depth nodes per (b) node
  </code></pre>
  
  <p>The relationships between the nodes are: <code>(c)-[:in]-&gt;(b)-[:in]-&gt;(a)</code></p>
  
  <p>Given a root node (a), I want to create a query that will return the 10 most recent (b) nodes, along with the 3 most recent (c) nodes on each (b) node.</p>
  
  <p>I start here with a query to get the 10 most recent (b) nodes:</p>
  
  <pre><code>match (a) where id(a) = {root_id}
  match (a)&lt;-[:in]-(b) where b is not null
  return b order by id(b) desc limit 10
  </code></pre>
  
  <p>This gets the 10 most recent b nodes as expected. However, I can't find a way to get the 3 most recent (c) nodes per (b). This is what I have:</p>
  
  <pre><code>match (a) where id(a) = {root_id}
  match (a)&lt;-[:in]-(b) where b is not null
  with b order by id(b) desc limit 10
  optional match (b)&lt;-[:in]-(c)
  return b, c order by id(c) desc limit 3;
  </code></pre>
  
  <p>However, the <code>limit 3</code> is applying to the entire return, not just the <code>c</code> subquery.</p>
  
  <p>Is there a way to roll up the (c) subquery such that the <code>limit 3</code> is applied once for each (b) node?</p>
  
  <p>(I know node ids are not the best to use due to their volatility. I'm just using id() as a quick way to order things in this example)</p>