Skip to content

for SELECT DISTINCT, ORDER BY expressions must appear in select list #4589

@dvv

Description

@dvv

Elixir version

18.2

Database and Version

PostgreSQL 17.2

Ecto Versions

3.12.5

Database Adapter and Versions (postgrex, myxql, etc)

postgrex 0.19.3

Current behavior

defmodule Foo do
  use Ecto.Schema
  schema "foo" do
    has_one :bar, Bar
  end
end

defmodule Bar do
  use Ecto.Schema
  schema "bar" do
    field :name, :string
  end
end

Repo.all(from foo in Foo, join: bar in assoc(foo, :bar), order_by: [asc: bar.name])
# SELECT f0.id FROM foo AS f0 INNER JOIN bar AS b1 ON b1.foo_id = f0.id ORDER BY b1.name
Repo.all(from foo in Foo, join: bar in assoc(foo, :bar), order_by: [asc: bar.name], distinct: true)
# SELECT DISTINCT f0.id FROM foo AS f0 INNER JOIN bar AS b1 ON b1.foo_id = f0.id ORDER BY b1.name
# ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

Expected behavior

On distinct: true order_by-ed fields to auto-merge select list:

Repo.all(from foo in Foo, join: bar in assoc(foo, :bar), order_by: [asc: bar.name], distinct: true)
# SELECT DISTINCT f0.id, b1.name FROM foo AS f0 INNER JOIN bar AS b1 ON b1.foo_id = f0.id ORDER BY b1.name

Notice that distinct: [asc: bar.name] (which otherwise would do) won't go here.
Notice that one can not select_merge order_by-ed fields manually since they don't belong to the struct.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions