Ecto distinct only on values not nil

Hey there

def group_repeat_ids(query, filters) do
    from(e in query,
      distinct: e.event_repeat_id 
    )
  end

is it possible to apply distinct only on lines that are not nil in given field?
the goal is to apply distinct on lines that have a value in given filed and keep all with nil

  def group_repeat_ids(query, filters) do
    distinct_repeat_events =
      from(e in query,
        where: not is_nil(e.event_repeat_id),
        distinct: e.event_repeat_id
      )

    nil_repeat_events =
      from(e in query,
        where: is_nil(e.event_repeat_id)
      )

    union_all(distinct_repeat_events, ^nil_repeat_events)
  end

this seems to do the trick.

I could use union/2 as well, but I am certain that there can be no duplicates between the 2, and that mentions a performance penalty.

https://hexdocs.pm/ecto/Ecto.Query.html#union/2

I am trying to insert this piece into existing code, so it messes up my filters:

(Ecto.QueryError) cannot use bindings in order_by when using union_all.

if i pass this there is a new error:

the following exception happened when compiling a subquery.
** (Ecto.QueryError) cannot preload associations in subquery in query:

union might not be then what i need hah, i would need a “normal” query from it or just not split it at all

For this problem in particular I usually do this:

query = YourApp.Record # or any other Ecto.Query.
sort_clause = [{:name, :asc}]
from(record in query, order_by: ^sort_clause)

And it fixes that particular problem.