Skip to content

Using an ecto fragment to search by a PostgreSQL function

Joel Meador edited this page Jun 8, 2026 · 1 revision

I have a set of orders that is filtered by user_id, and I want to filter by when they were ordered, which is a DateTime field.

How do I filter by date in the database?

Instead of using Enum to filter like this:

def filter_by_date(orders, date) do
  Enum.filter(orders, fn order ->
    DateTime.to_date(order.inserted_at) == date
  end)
end

Push the filter into the database like this:

def on_date(user, date) do
  Order
  |> where([o], o.user_id == ^user_id)
  |> where([o], fragment(“date(?) = ?”, o.inserted_at, ^date))
  |> Repo.all()
end

Home

TODO: can we recreate the tag system here roughly with sections about certain subjects?

Clone this wiki locally