Skip to content

ORDER BY clause

Marijn van Wezel edited this page Dec 13, 2022 · 2 revisions

The ORDER BY sub-clause following RETURN or WITH specifies that the output should be sorted and how.

Query::orderBy(Property|Property[] $properties, bool $descending = false): Query

Parameters

  • $properties : A single property to order by, or a non-empty list of properties to order by.
  • $descending : Whether to order in descending order.

Relevant methods

  • addProperty(Property ...$property): self : Add one or more properties to order by.
  • setDescending(bool $descending = true): self : Set whether to sort in a DESCENDING order.

Examples

Order nodes by property

$n = node();
$query = query()
    ->match($n)
    ->returning([$n->property('name'), $n->property('age')])
    ->orderBy($n->property('name'))
    ->build();

$this->assertStringMatchesFormat("MATCH (%s) RETURN %s.name, %s.age ORDER BY %s.name", $query);

Order nodes by multiple properties

$n = node();
$query = query()
    ->match($n)
    ->returning([$n->property('name'), $n->property('age')])
    ->orderBy([$n->property('age'), $n->property('name')])
    ->build();

$this->assertStringMatchesFormat("MATCH (%s) RETURN %s.name, %s.age ORDER BY %s.age, %s.name", $query);

Order nodes in descending order

$n = node();
$query = query()
    ->match($n)
    ->returning([$n->property('name'), $n->property('age')])
    ->orderBy([$n->property('name')], true)
    ->build();

$this->assertStringMatchesFormat("MATCH (%s) RETURN %s.name, %s.age ORDER BY %s.name DESCENDING", $query);

External links