Hi, I'm trying to count the number of existing users in a small petproject of mine and currently came up with
number_of_users = Repo.all(from u in User, select: u.id) |> Enum.count
Is there a way to use something like
SELECT COUNT(*)
FROM users;
with ecto?
Thanks in advance
from(u in User, select: count(u.id)). You can find all query functions on Ecto.Query.API.
Please ask questions on the mailing list in the future.
I tried that before but it just returns '\b'.
iex(6)> Repo.all(from(u in User, select: count(u.id)))
'\b'
Without the count everything looks ok:
iex(7)> Repo.all(from(u in User, select: u.id))
[1, 2, 3, 4, 5, 6, 7, 8]
[8] is only displayed as '\b'.
inspect [8] # => "'\\b'"
inspect [8], char_lists: :as_list # => "[8]"
Thanks @lexmag :) this now did the trick. Still looks a little complicated, but works.
iex(1)> import Ecto.Query
nil
iex(2)> List.first Repo.all(from u in User, select: count(u.id))
8
Use Repo.one if you want a single result.
Cool, thanks again, works like a charm.
@optikfluffel I like very much to use the Repo.aggregate/3 function. In your case:
count = Repo.aggregate User, :count, :id
# Same as:
count = User |> Repo.aggregate(:count, :id)
merci @hickscorp
Most helpful comment
@optikfluffel I like very much to use the
Repo.aggregate/3function. In your case: