LIMIT

LIMIT constrains the number of returned rows.

LIMIT accepts any expression that evaluates to a positive INTEGER and does not refer to nodes or relationships.

Neo4j does not guarantee the results generated by LIMIT. The only clause that guarantees a specific row order is ORDER BY.

Example graph

The following graph is used for the examples below:

graph limit clause

To recreate it, run the following query against an empty Neo4j database:

CREATE
  (andy: Person {name: 'Andy'}),
  (bernard: Person {name: 'Bernard'}),
  (charlotte: Person {name: 'Charlotte'}),
  (david: Person {name: 'David'}),
  (erika: Person {name: 'Erika'}),
  (andy)-[:KNOWS]->(bernard),
  (andy)-[:KNOWS]->(charlotte),
  (andy)-[:KNOWS]->(david),
  (andy)-[:KNOWS]->(erika)

Examples

Example 1. Return a limited subset of the rows

To return a limited subset of the rows, use this syntax:

Query
MATCH (n)
RETURN n.name
ORDER BY n.name
LIMIT 3

Limit to 3 rows by the example query.

Table 1. Result
n.name

"Andy"

"Bernard"

"Charlotte"

Rows: 3

Example 2. Using an expression with LIMIT to return a subset of the rows

LIMIT accepts any expression that evaluates to a positive integer, as long as it can be statically calculated (i.e. calculated before the query is run).

Query
MATCH (n)
RETURN n.name
ORDER BY n.name
LIMIT 1 + toInteger(3 * rand())

Limit 1 row plus randomly 0, 1, or 2. So randomly limit to 1, 2, or 3 rows.

Table 2. Result
n.name

"Andy"

"Bernard"

"Charlotte"

Rows: 3

LIMIT and side effects

The use of LIMIT in a query will not stop side effects, like CREATE, DELETE, or SET, from happening if the limit is in the same query part as the side effect.

Query
CREATE (n)
RETURN n
LIMIT 0

This query returns nothing, but creates one node:

Table 3. Result

(empty result)

Rows: 0
Nodes created: 1

Query
MATCH (n {name: 'A'})
SET n.age = 60
RETURN n
LIMIT 0

This query returns nothing, but writes one property:

Table 4. Result

(empty result)

Rows: 0
Properties set: 1

If we want to limit the number of updates we can split the query using the WITH clause:

Query
MATCH (n)
WITH n ORDER BY n.name LIMIT 1
SET n.locked = true
RETURN n

Writes locked property on one node and return that node:

Table 5. Result
n

{locked:true,name:"Andy",age:60}

Rows: 1
Properties set: 1

Using LIMIT as a standalone clause

LIMIT can be used as a standalone clause, or in conjunction with ORDER BY or SKIP/OFFSET.

Standalone use of LIMIT
MATCH (n)
LIMIT 2
RETURN collect(n.name) AS names
Table 6. Result
names

["Andy", "Bernard"]

Rows: 1

The following query orders all nodes by name descending, skips the two first rows and limits the results to two rows. It then collects the results in a list.

LIMIT used in conjunction with ORDER BY and SKIP
MATCH (n)
ORDER BY n.name DESC
SKIP 2
LIMIT 2
RETURN collect(n.name) AS names
Table 7. Result
names

["David", "Charlotte"]

Rows: 1