Get index of result in query

Hi,
I’m wondering if we have

def function do
    query = from(l in Lang, order_by: [desc: l.priority])
    Repo.all(query)
end

we will get list of all languages, ordered. If we have this table as example

id ---+---name----+priority
1        Elixir     100
3        Ruby       50
2        C#         40                 

and we want to get index of lang Ruby with id of 3 in this ordered_by priority table how we should do it?

id = 3
query1 = from(l in Lang, order_by: [desc: l.priority} # All languages, ordered
repo1 = Repo.all(query)
query2 = from(l in query1 (?), where: l.id == ^id, select: l.index (?)
Repo.one(query2

You should take a look at row_number/0.

You could add a row_number to your first query and than use it as a subquery for the second one, where you filter for the wanted language.

3 Likes