Skip to content

Repository aggregations with joins render ambiguous column references #11797

Closed

Description

@dmurvihill

Issue description

When using e.g. Repository.maximum() with a join, you can get ambiguous column references (in Postgres at least)

Expected Behavior

Instead of SELECT MAX("id"), should SELECT MAX("VoterRecord"."id") and return a number or null.

Actual Behavior

Generates the following query (formatting added):

SELECT MAX("id") AS "MAX" FROM "voter_record" "VoterRecord"
  LEFT JOIN "voter_file_snapshot" "VoterRecord__VoterRecord_fileSnapshot"
    ON "VoterRecord__VoterRecord_fileSnapshot"."id"="VoterRecord"."fileSnapshotId"
  WHERE (((("VoterRecord__VoterRecord_fileSnapshot"."id" = $1))))

And the ORM gives this error because both tables have an id column:

QueryFailedError: column reference "id" is ambiguous

Steps to reproduce

Try this on Postgres:

 @Entity()
@Index('records_by_snapshot', ['fileSnapshot.id', 'stateVoterId'], {
  unique: true,
})
export class VoterRecord {
  @PrimaryGeneratedColumn()
  readonly id: number;

// (data columns)

  @ManyToOne(() => VoterFileSnapshot, (snapshot) => snapshot.voterRecords, {
    nullable: false,
  })
  fileSnapshot?: VoterFileSnapshot;
}

@Entity()
export class VoterFileSnapshot {
  @PrimaryGeneratedColumn()
  readonly id: number;

// (metadata columns)

  @OneToMany(() => VoterRecord, (record) => record.fileSnapshot)
  voterRecords?: VoterRecord[];
}

voters = dataSource.getRepository(VoterRecord);
files = dataSource.getRepository(VoterFileSnapshot);
const liveFile = await files.findOneBy({ status: 'LIVE' });
const maxId = await voters.maximum('id', { fileSnapshot: { id: liveFile.id } })

// maxId should have the highest ID in the current voter file snapshot

My Environment

Dependency Version
Operating System Mac OS 15.6.1 (24G90)
Node.js version 24.11.0
Typescript version 5.8.2
TypeORM version 0.3.27

Additional Context

I assume this happens with all repository aggregation functions, and not just maximum. Likely it impacts every SQL engine as well.

Relevant Database Driver(s)

  • aurora-mysql
  • aurora-postgres
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • spanner
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

Not right now

Activity

  1. added 2 commits that reference this issue on Dec 3, 2025
    418535f
    152d270
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions