🚀 Welcome to MDriven Learn –  MDriven is now on Discord!  Don’t miss the latest Release Notes.
OCLOperators orderBy
This page was created by Alexandra on 2017-08-13. Last edited by Wikiadmin on 2026-07-29.

You can use orderBy in OCL to return a collection sorted in ascending order by a value you choose; it is intended for expressions that prepare ordered data for display or further processing.

Syntax

collection->orderby(variable | variable.property)
  • collection is the collection to sort.
  • variable is a temporary name for each object in the collection.
  • property is the attribute, identity, derived attribute, or supported value reached through a single link that supplies the sort value.

orderBy sorts from the lowest value to the highest value. To sort in the opposite direction, use orderDescending.

Sort cars by name

Given a class Car with a Name attribute, this expression returns the Car objects ordered by Name in ascending order:

Car.allinstances->orderby(c | c.Name)

For example, cars named Alfa, Ford, and Volvo are returned in that order. The result is the ordered collection of cars, not a collection containing only their names.

Sort by an identity or derived attribute

The sort expression can use an identity or a derived attribute when that value represents the order you need. For example:

collection1->orderby(t | t.Identity)

The temporary variable name is your choice. In this example, t is equivalent to any other valid iterator name.

Sort using values reached through single links

Since the OCL-PS extensions dated 2021-01-16, OCL-PS supports sort expressions that follow single links to reach the ordering value. This lets you sort a collection by an attribute on a related object, including an attribute reached through multiple single-link steps.

For example, if each object has a single link named Owner, and Owner has a Name attribute, the ordering expression can follow that link:

collection->orderby(x | x.Owner.Name)

Missing linked data excludes the object

Sorting through linked information reduces the result set when the required linked object or value is absent. The navigation behaves as a join, not an outer join.

In the preceding example, an object without an Owner, or without the required linked data, is not included in the result. Check this behavior when you sort optional relationships; an unexpected smaller result is often caused by missing data along the navigation path.

Related operators

  • Use orderDescending when you need descending order.
  • Use sqlLike to select string matches before ordering them. For example, a filtered collection can end with ->orderby(identity).
  • Open the OCL Editor and type in a class to discover available operators; see Documentation:OCL General Operators.

Watch the orderBy walkthrough.

See also