Ecto.Query.order_by
order_by
, go back to Ecto.Query module for more information.
An order by query expression.
Orders the fields based on one or more fields. It accepts a single field
or a list of fields. The default direction is ascending (:asc
) and can be
customized in a keyword list as one of the following:
:asc
:asc_nulls_last
:asc_nulls_first
:desc
:desc_nulls_last
:desc_nulls_first
The *_nulls_first
and *_nulls_last
variants are not supported by all
databases. While all databases default to ascending order, the choice of
"nulls first" or "nulls last" is specific to each database implementation.
order_by
may be invoked or listed in a query many times. New expressions
are always appended to the previous ones.
order_by
also accepts a list of atoms where each atom refers to a field in
source or a keyword list where the direction is given as key and the field
to order as value.
Keywords examples
from(c in City, order_by: c.name, order_by: c.population)
from(c in City, order_by: [c.name, c.population])
from(c in City, order_by: [asc: c.name, desc: c.population])
from(c in City, order_by: [:name, :population])
from(c in City, order_by: [asc: :name, desc_nulls_first: :population])
A keyword list can also be interpolated:
values = [asc: :name, desc_nulls_first: :population]
from(c in City, order_by: ^values)
A fragment can also be used:
from c in City, order_by: [
# A deterministic shuffled order
fragment("? % ? DESC", c.id, ^modulus),
desc: c.id,
]
Expressions examples
City |> order_by([c], asc: c.name, desc: c.population)
City |> order_by(asc: :name) # Sorts by the cities name