File tree Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Expand file tree Collapse file tree 2 files changed +42
-1
lines changed Original file line number Diff line number Diff line change @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really
7
7
warrant a full blog post. These are mostly things I learn by pairing with
8
8
smart people at [ Hashrocket] ( http://hashrocket.com/ ) .
9
9
10
- _ 500 TILs and counting..._
10
+ _ 501 TILs and counting..._
11
11
12
12
---
13
13
@@ -87,6 +87,7 @@ _500 TILs and counting..._
87
87
- [ Assert An Exception Is Raised] ( elixir/assert-an-exception-is-raised.md )
88
88
- [ Binary Representation Of A String] ( elixir/binary-representation-of-a-string.md )
89
89
- [ Check For A Substring Match] ( elixir/check-for-a-substring-match.md )
90
+ - [ Counting Records With Ecto] ( elixir/counting-records-with-ecto.md )
90
91
- [ Create A Date With The Date Sigil] ( elixir/create-a-date-with-the-date-sigil.md )
91
92
- [ Creating Indexes With Ecto] ( elixir/creating-indexes-with-ecto.md )
92
93
- [ Determine The Latest Release Of A Hex Package] ( elixir/determine-the-latest-release-of-a-hex-package.md )
Original file line number Diff line number Diff line change
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
+ ```
You can’t perform that action at this time.
0 commit comments