Distinct with order by clause not giving correct results

I am using distinct and order by clause in my query. The code is below:

    Table
     |> distinct([i], [i.id])
     |> order_by([i], desc: i.id)

It always returns records with ids in ascending order. By looking at the query it generates, it sets distinct to asc like this.

                           distinct: [asc: i0.id]

I can’t use distinct: true because I am not using select.
I don’t want to specify ASC or desc in the distinct query because the query is building dynamically. Sometimes order_by will be asc and sometimes desc.
So, is there any other way for this to work.
And why it always sets distinct in asc order?

Any help will be much appreciated.

Thanks

:wave:

I can’t use distinct: true because I am not using select.

Unless I’m missing something, what exactly stops you from

Table
|> distinct(true)
|> order_by([i], desc: i.id)

?

1 Like

Hi, thanks for your reply.
distinct: true is used when we have select query expression. By using it without select raises an error about the select statement.

Are you showing us the full query?

User |> distinct(true) |> order_by(desc: :id) |> Repo.all

Works fine for me.

1 Like