Skip to content

Commit 8ef1b1e

Browse files
committed
Add Counting Records With Ecto as an elixir til
1 parent c58d374 commit 8ef1b1e

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
77
warrant a full blog post. These are mostly things I learn by pairing with
88
smart people at [Hashrocket](http://hashrocket.com/).
99

10-
_500 TILs and counting..._
10+
_501 TILs and counting..._
1111

1212
---
1313

@@ -87,6 +87,7 @@ _500 TILs and counting..._
8787
- [Assert An Exception Is Raised](elixir/assert-an-exception-is-raised.md)
8888
- [Binary Representation Of A String](elixir/binary-representation-of-a-string.md)
8989
- [Check For A Substring Match](elixir/check-for-a-substring-match.md)
90+
- [Counting Records With Ecto](elixir/counting-records-with-ecto.md)
9091
- [Create A Date With The Date Sigil](elixir/create-a-date-with-the-date-sigil.md)
9192
- [Creating Indexes With Ecto](elixir/creating-indexes-with-ecto.md)
9293
- [Determine The Latest Release Of A Hex Package](elixir/determine-the-latest-release-of-a-hex-package.md)

elixir/counting-records-with-ecto.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Counting Records With Ecto
2+
3+
Sometimes you want to know how many records there are in a table. Ecto gives
4+
us a couple ways to approach this.
5+
6+
We can use the
7+
[`count\1`](https://hexdocs.pm/ecto/Ecto.Query.API.html#count/1) function
8+
that the Ecto query API provides.
9+
10+
```elixir
11+
> Repo.one(from p in "people", select: count(p.id))
12+
13+
16:09:52.759 [debug] QUERY OK source="people" db=1.6ms
14+
SELECT count(p0."id") FROM "people" AS p0 []
15+
168
16+
```
17+
18+
Alternatively, we can use the
19+
[`fragment/1`](https://hexdocs.pm/ecto/Ecto.Query.API.html#fragment/1)
20+
function to use PostgreSQL's `count` function.
21+
22+
```elixir
23+
> Repo.one(from p in "people", select: fragment("count(*)"))
24+
25+
16:11:19.818 [debug] QUERY OK source="people" db=1.5ms
26+
SELECT count(*) FROM "people" AS p0 []
27+
168
28+
```
29+
30+
Lastly, `Ecto.Repo` has the
31+
[`aggregate/4`](https://hexdocs.pm/ecto/Ecto.Repo.html#c:aggregate/4)
32+
function which provides a `:count` option.
33+
34+
```elixir
35+
> Repo.aggregate(from(p in "people"), :count, :id)
36+
37+
16:11:23.786 [debug] QUERY OK source="people" db=1.7ms
38+
SELECT count(p0."id") FROM "people" AS p0 []
39+
168
40+
```

0 commit comments

Comments
 (0)