Sort operator

The sort operator sorts the input stream based on the variables and their sort order.

Sorting requires the server to fetch all results, sort them, then proceed in the pipeline. This may have significant query performance impact.

Syntax

The sort direction may be specified explicitly to be ascending (asc) or descending (desc). The default sort direction when not specified is ascending.

sort <var> [asc|desc] [ , <var> [asc|desc] ... ];

Example

Schema for the following examples
#!test[schema, commit]
define
  entity content owns id;
  entity page sub content,
    owns page-id,
    owns name;
  entity profile sub page,
    owns username;
  entity user sub profile,
    owns phone,
    owns karma;

  attribute id value string;
  attribute page-id sub id;
  attribute username sub page-id;
  attribute name value string;
  attribute phone value string;
  attribute karma value double;
attribute start-date, value date;
relation friendship relates friend @card(0..2), owns start-date;
user plays friendship:friend;

Retrieve all friends of a user, sorted by the time they became friends from latest to earliest.

#!test[read]
match
  $user isa user, has name "<name>";
  friendship (friend: $user, friend: $friend),
    has start-date $start;
sort $start desc;

Multiple variables may be given. Rows are sorted by the first variable, and ties are broken by each subsequent one in turn.

#!test[read]
match
  $user isa user, has karma $karma, has username $username;
sort $karma desc, $username asc;