clayschick
How to use Distinct, Select, and Where in Ecto query?
I’m trying to create a simple query to select distinct values from a column. If I only use select and distinct I get back a list of unique values.
Users
|> select([u], u.group_id)
|> distinct(true)
|> Repo.all()
Which gives me back a list of ids as expected:
[42, 43, nil]
However, when I add a where clause to exclude the nil value I get back a different result.
Users
|> where([u], not is_nil(u.group_id))
|> select([u], u.group_id)
|> distinct(true)
|> Repo.all()
This returns the value:
'*+'
I would have expected the query to return of a list of integers without a nil value. When I run the generated raw SQL in psql I get back the list as expected.
How can I get back a list of distinct group_ids that does not include the nil value?
Marked As Solved
gregvaughn
You’ve hit the charlist problem. Print your result with:
IO.inspect(result, charlists: :as_lists)
What you’re getting is a list of 2 integers. But they both happen to be printable ascii characters, which is how erlang represents strings. The single quotes are one hint.
Also Liked
rvirding
You wait till you get burned with strange binaries.
They are both the case of not really having strings and using other datatypes to implement them.
sorentwo
Don’t worry, this happens to everybody at some point. Erlang has been around quite a while and charlists will keep rearing their bizarre head.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance










