Repo.count in Ecto

Enable Repo.count(query) in Ecto

I have often wanted to just do the following but Ecto’s Repo module doesn’t have a count method.

iex> MyApp.Repo.count(MyApp.Account)

It is not too difficult to create a count function that will allow you to count the results of any query.

defmodule MyApp.DBUtils do
  import Ecto.Query, only: [from: 2]

  @doc "Generate a select count(id) on any query"
  def count(query),
    do: from t in clean_query_for_count(query), select: count(

  # Remove the select field from the query if it exists
  defp clean_query_for_count(query),
    do: Ecto.Query.exclude(query, :select)

This will provide a shortcut for counting any query

MyApp.DBUtils.count(MyApp.Account) |>!

Now, to enable Repo.count we can modify the repo module usually found in lib/my_app/repo.ex

defmodule MyApp.Repo do
  use Ecto.Repo, otp_app: :my_app

  def count(query),
    do: MyApp.DBUtils.count(query) |>!

That’s it. This will enable a count on any query including complicated queries and those that have a select expression set.

Sep 20, 2016 elixir, ecto, tip, tech
comments powered by Disqus