Order and Group

Learn about ordering and grouping in Ecto.

SQL allows us to be specific about how our results are ordered. We can also group result rows, which comes in handy when getting counts in our results. The order by and group by expressions in SQL are available in Ecto via the order_by and group_by keywords. Let’s see how those work.

The order_by expression

If we wanted a list of all of the artists in alphabetical order, we could use order_by, like this:

Press + to interact
q = from a in "artists", select: [a.name], order_by: a.name
Repo.all(q)
widget

The order_by expression returns the results in ascending order by default, but we can change this with the desc: keyword.

Press + to interact
q = from a in "artists", select: [a.name], order_by: [desc: a.name]
Repo.all(q)
widget

The order_by expression with multiple columns

We can also order ...