diff --git a/README.md b/README.md index 8843268..d0fc5d8 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_500 TILs and counting..._ +_501 TILs and counting..._ --- @@ -87,6 +87,7 @@ _500 TILs and counting..._ - [Assert An Exception Is Raised](elixir/assert-an-exception-is-raised.md) - [Binary Representation Of A String](elixir/binary-representation-of-a-string.md) - [Check For A Substring Match](elixir/check-for-a-substring-match.md) +- [Counting Records With Ecto](elixir/counting-records-with-ecto.md) - [Create A Date With The Date Sigil](elixir/create-a-date-with-the-date-sigil.md) - [Creating Indexes With Ecto](elixir/creating-indexes-with-ecto.md) - [Determine The Latest Release Of A Hex Package](elixir/determine-the-latest-release-of-a-hex-package.md) diff --git a/elixir/counting-records-with-ecto.md b/elixir/counting-records-with-ecto.md new file mode 100644 index 0000000..671eb57 --- /dev/null +++ b/elixir/counting-records-with-ecto.md @@ -0,0 +1,40 @@ +# Counting Records With Ecto + +Sometimes you want to know how many records there are in a table. Ecto gives +us a couple ways to approach this. + +We can use the +[`count\1`](https://hexdocs.pm/ecto/Ecto.Query.API.html#count/1) function +that the Ecto query API provides. + +```elixir +> Repo.one(from p in "people", select: count(p.id)) + +16:09:52.759 [debug] QUERY OK source="people" db=1.6ms +SELECT count(p0."id") FROM "people" AS p0 [] +168 +``` + +Alternatively, we can use the +[`fragment/1`](https://hexdocs.pm/ecto/Ecto.Query.API.html#fragment/1) +function to use PostgreSQL's `count` function. + +```elixir +> Repo.one(from p in "people", select: fragment("count(*)")) + +16:11:19.818 [debug] QUERY OK source="people" db=1.5ms +SELECT count(*) FROM "people" AS p0 [] +168 +``` + +Lastly, `Ecto.Repo` has the +[`aggregate/4`](https://hexdocs.pm/ecto/Ecto.Repo.html#c:aggregate/4) +function which provides a `:count` option. + +```elixir +> Repo.aggregate(from(p in "people"), :count, :id) + +16:11:23.786 [debug] QUERY OK source="people" db=1.7ms +SELECT count(p0."id") FROM "people" AS p0 [] +168 +```