What's the difference in performance between Repo.one and Repo.all?

Hello, what’s the difference in performance between Repo.one and Repo.all?

please see my following code

Repo.one

defp fetch_posts_by_alias(post_alias, "admin") do
		query = from p in Post,
						 join: c in assoc(p, :cms_post_category),
						 where: p.seo_alias_link == ^post_alias,
						 order_by: p.inserted_at

		query = admin_fields(query)
		Repo.one(query)
	end

Repo.all

	defp fetch_posts_by_alias(post_alias, "admin") do
		query = from p in Post,
						 join: c in assoc(p, :cms_post_category),
						 where: p.seo_alias_link == ^post_alias,
						 order_by: p.inserted_at

		query = admin_fields(query)
		Repo.all(query)
	end

both of them load one result from database.

Thanks.

It is not about performance, its about guarantees.

all/2 will always return a list which has either no elements, one element or many.

one/2 though will raise if the query returns more than one item.

one/2 could be implemented like this:

def one(queryable, opts) do
  case all(queryable, opts) do
    [] -> nil
    [item] -> item
    _ -> raise Ecto.MultipleResultsError
  end
end
10 Likes

That also happens to be exactly how one/2 is implemented :wink:

10 Likes