Skip to content

fix: disable global order for aggregate functions - #11925

Merged
alumni merged 3 commits into
typeorm:masterfrom
Cprakhar:fix/aggregate-disable-global-order
Feb 17, 2026
Merged

alumni merged 3 commits into
typeorm:masterfrom
Cprakhar:fix/aggregate-disable-global-order

Conversation

@Cprakhar

@Cprakhar Cprakhar commented Jan 19, 2026 •

Copy link
Copy Markdown
Collaborator

Description of Change

This pull request addresses an issue where an incorrect SQL query is generated when using aggregate functions on the entity repository, such as repo.max().

Closes #11213

-- Before
SELECT MAX("Post"."counter") AS "MAX" FROM "post" "Post" ORDER BY "Post"."counter"
-- QueryFailedError: Use GROUP BY "Post"."counter"

-- After
SELECT MAX("Post"."counter") AS "MAX" FROM "post" "Post"

Note: When using an aggregate function on a single column, the ORDER BY clause is redundant.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #11213
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md) (N/A)

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

User description

Description of Change

This pull request addresses an issue where an incorrect SQL query is generated when using aggregate functions on the entity repository, such as repo.max().

Closes #11213

-- Before
SELECT MAX("Post"."counter") AS "MAX" FROM "post" "Post" ORDER BY "Post"."counter"
-- QueryFailedError: Use GROUP BY "Post"."counter"

-- After
SELECT MAX("Post"."counter") AS "MAX" FROM "post" "Post"

Note: When using an aggregate function on a single column, the ORDER BY clause is redundant.

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #11213
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

PR Type

Bug fix, Tests


Description

  • Disable global ORDER BY clause for aggregate functions

  • Add setOption("disable-global-order") to aggregate query builder

  • Update Post entity test fixture with orderBy configuration

  • Prevents QueryFailedError when using aggregate functions like max()


Diagram Walkthrough

flowchart LR
  A["Aggregate Function Query"] -->|setOption disable-global-order| B["Query Builder"]
  B -->|generates SQL| C["SELECT without ORDER BY"]
  C -->|executes successfully| D["Result"]
Loading

File Walkthrough

Relevant files
Bug fix
EntityManager.ts
Add disable-global-order option to aggregate queries         

src/entity-manager/EntityManager.ts

  • Added .setOption("disable-global-order") to aggregate function query
    builder
  • Prevents redundant ORDER BY clause in aggregate queries
  • Resolves QueryFailedError when using aggregate functions on
    repositories
+1/-0     
Tests
Post.ts
Configure Post entity with global order by                             

test/functional/repository/aggregate-methods/entity/Post.ts

  • Updated Post entity decorator with orderBy: { counter: "DESC" }
    configuration
  • Enables testing of aggregate functions with global order settings
  • Validates that aggregate queries work correctly despite entity-level
    ordering
+1/-1     

@pkg-pr-new

pkg-pr-new Bot commented Jan 19, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11925
    

commit: 4846be7

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 19, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 4846be7

CategorySuggestion                                                                                                                                    Impact
Possible issue
Set option before applying options

Move the .setOption("disable-global-order") call to before qb.setFindOptions({
where }) to ensure the entity-level orderBy is not applied to the aggregate
query.

src/entity-manager/EntityManager.ts [1179-1180]

 const qb = this.createQueryBuilder(entityClass, metadata.name)
+qb.setOption("disable-global-order")
 qb.setFindOptions({ where })

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out a potential logic error where the disable-global-order option is set too late, making the PR's fix potentially ineffective.

Medium
Clear ordering on aggregate queries

Add a .orderBy() call without arguments before .select() to explicitly clear any
ordering clauses from the query builder for the aggregate query.

src/entity-manager/EntityManager.ts [1184-1192]

 const result = await qb
+    .orderBy()
     .select(
         `${fnName}(${this.connection.driver.escape(
             alias,
         )}.${this.connection.driver.escape(column.databaseName)})`,
         fnName,
     )
     .setOption("disable-global-order")
     .getRawOne()

[To ensure code accuracy, apply this suggestion manually]

Suggestion importance[1-10]: 6

__

Why: The suggestion offers a valid alternative to fix the issue by explicitly clearing any ordering with .orderBy(), which is a more direct approach than relying on an option.

Low
  • More

Previous suggestions

Suggestions up to commit 0366bee
CategorySuggestion                                                                                                                                    Impact
General
Set option before select method

Reorder the query builder methods by placing the .setOption() call before the
.select() call to improve code readability and adhere to common conventions.

src/entity-manager/EntityManager.ts [1184-1192]

 const result = await qb
+    .setOption("disable-global-order")
     .select(
         `${fnName}(${this.connection.driver.escape(
             alias,
         )}.${this.connection.driver.escape(column.databaseName)})`,
         fnName,
     )
-    .setOption("disable-global-order")
     .getRawOne()
Suggestion importance[1-10]: 3

__

Why: The suggestion proposes a stylistic change to reorder query builder methods for better readability, which is a valid but low-impact improvement as it does not affect functionality.

Low
Suggestions up to commit 159d248
CategorySuggestion                                                                                                                                    Impact
General
Use dedicated method for disabling order

Replace the setOption call, which uses a string literal, with a more type-safe
alternative like a dedicated method or a constant to avoid potential typos and
improve code clarity.

src/entity-manager/EntityManager.ts [1184-1192]

 const result = await qb
     .select(
         `${fnName}(${this.connection.driver.escape(
             alias,
         )}.${this.connection.driver.escape(column.databaseName)})`,
         fnName,
     )
-    .setOption("disable-global-order")
+    .disableGlobalOrder()
     .getRawOne()
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly identifies the use of a "magic string" and proposes a more robust and maintainable approach, which is a valid code quality improvement.

Low
Suggestions up to commit 8085a5e
CategorySuggestion                                                                                                                                    Impact
General
Use dedicated method for disabling order

Replace the magic string "disable-global-order" in setOption with a more robust
solution like a dedicated method or a constant to improve type safety and
prevent typos.

src/entity-manager/EntityManager.ts [1119-1127]

 const result = await qb
     .select(
         `${fnName}(${this.connection.driver.escape(
             alias,
         )}.${this.connection.driver.escape(column.databaseName)})`,
         fnName,
     )
-    .setOption("disable-global-order")
+    .disableGlobalOrder()
     .getRawOne()
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly identifies the use of a 'magic string' which is a code smell, but the proposed improved_code uses a disableGlobalOrder() method that does not exist on the SelectQueryBuilder, making the specific improvement invalid.

Low
Suggestions up to commit d98884d
CategorySuggestion                                                                                                                                    Impact
General
Set option before select method

Reorder the query builder calls by moving .setOption("disable-global-order")
before the .select() method call for improved code structure and readability.

src/entity-manager/EntityManager.ts [1119-1127]

 const result = await qb
+    .setOption("disable-global-order")
     .select(
         `${fnName}(${this.connection.driver.escape(
             alias,
         )}.${this.connection.driver.escape(column.databaseName)})`,
         fnName,
     )
-    .setOption("disable-global-order")
     .getRawOne()
Suggestion importance[1-10]: 4

__

Why: The suggestion correctly points out that for better code structure and readability, configuration methods like setOption should precede action methods like select in a query builder chain, even if it doesn't affect functionality.

Low
Suggestions up to commit babb830
CategorySuggestion                                                                                                                                    Impact
Possible issue
Prevent precision loss for large numbers

Replace parseFloat with Number() and add a check using Number.isSafeInteger to
prevent potential precision loss for large aggregate values, throwing an error
if the number is unsafe.

src/entity-manager/EntityManager.ts [1119-1128]

 const result = await qb
     .select(
         `${fnName}(${this.connection.driver.escape(
             alias,
         )}.${this.connection.driver.escape(column.databaseName)})`,
         fnName,
     )
     .setOption("disable-global-order")
     .getRawOne()
-return result[fnName] === null ? null : parseFloat(result[fnName])
 
+if (!result || result[fnName] === null) {
+    return null
+}
+
+const num = Number(result[fnName])
+
+if (Number.isInteger(num) && !Number.isSafeInteger(num)) {
+    throw new TypeORMError(
+        `Precision loss in ${fnName} calculation. The result ${result[fnName]} is larger than Number.MAX_SAFE_INTEGER.`,
+    )
+}
+
+return num
+
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a potential silent data corruption issue due to precision loss when parseFloat is used on large numbers from aggregate functions. The proposed fix to check for safe integers and throw an error is a robust way to prevent incorrect results.

Medium

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jan 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (2) 📎 Requirement gaps (0)

Grey Divider


Remediation recommended

1. repository.maximum() ordering change undocumented 📘 Rule violation ✧ Quality ⭐ New
Description
Aggregate methods now disable entity/global orderBy, changing generated SQL for users relying on
entity orderBy. Documentation for repository aggregate methods and @Entity({ orderBy }) does not
mention this behavior, so users may be surprised by the change.
Code

src/entity-manager/EntityManager.ts[1191]

+            .setOption("disable-global-order")
Evidence
Compliance ID 2 requires docs updates for user-facing behavior changes. The PR explicitly changes
SQL generation for aggregate methods by disabling global ordering, but the repository API docs list
aggregate methods without clarifying that orderBy is ignored, and the decorator docs describe
orderBy broadly without noting aggregates are excluded.

Rule 2: Docs updated for user-facing changes
src/entity-manager/EntityManager.ts[1184-1192]
docs/docs/working-with-entity-manager/6-repository-api.md[336-358]
docs/docs/help/3-decorator-reference.md[17-25]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Repository aggregate methods (e.g., `maximum`, `minimum`, `sum`, `average`) now ignore entity/global `orderBy` by disabling global ordering, which is a user-visible SQL generation change. Docs should explicitly state that aggregate methods do not apply `orderBy` (including `@Entity({ orderBy })`).

## Issue Context
The PR fixes issue #11213 by removing redundant/incorrect `ORDER BY` from aggregate queries via `.setOption("disable-global-order")`. Current docs describe aggregate methods but do not mention ordering behavior, and `@Entity({ orderBy })` docs describe default ordering broadly.

## Fix Focus Areas
- docs/docs/working-with-entity-manager/6-repository-api.md[336-358]
- docs/docs/help/3-decorator-reference.md[17-25]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Missing issue reference in test 📘 Rule violation ✓ Correctness
Description
• The PR fixes issue #11213 but the test file does not include a comment referencing this issue. •
Per compliance rule 3, issue fixes should include an issue reference in the test comment when
applicable. • This makes it harder to trace the test back to the original issue for future
maintenance.
Code

test/functional/repository/aggregate-methods/entity/Post.ts[5]

+@Entity({ orderBy: { counter: "DESC" } })
Evidence
The PR description states 'Closes #11213' and the test was modified to add orderBy configuration to
verify the fix works. However, there is no comment in the test file referencing issue #11213. The
compliance rule states that 'issue fixes add or update tests in test/functional, with an issue
reference in the test comment when applicable.' Since this is an issue fix with a test update, a
comment reference would help trace the test to the original issue.

Rule 3: Prefer functional tests over per-issue tests
test/functional/repository/aggregate-methods/entity/Post.ts[5-5]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test file is missing a comment that references issue #11213, which this PR fixes. Adding this reference helps with traceability and future maintenance.
## Issue Context
The PR fixes issue #11213 where aggregate functions incorrectly generated SQL with ORDER BY clauses. The test was updated to add `orderBy` configuration to the Post entity to verify that aggregate functions now properly disable the global order.
## Fix Focus Areas
- test/functional/repository/aggregate-methods/entity/Post.ts[5-5]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Grey Divider

Previous review results

Review updated until commit 4846be7

Results up to commit 0366bee


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review


ⓘ The new review experience is currently in Beta. Learn more

Results up to commit 159d248


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review
Results up to commit 8085a5e


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review
Results up to commit d98884d


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider

Great, no issues found!

Qodo reviewed your code and found no material issues that require review
Results up to commit babb830


🐞 Bugs (0) 📘 Rule violations (1) 📎 Requirement gaps (0)

Grey Divider
Remediation recommended
1. Missing issue reference in test 📘 Rule violation ✧ Quality
Description
• The PR fixes issue #11213 but the test file does not include a comment referencing this issue.
• Per compliance rule 3, issue fixes should include an issue reference in the test comment when
  applicable.
• This makes it harder to trace the test back to the original issue for future maintenance.
Code

test/functional/repository/aggregate-methods/entity/Post.ts[5]

+@Entity({ orderBy: { counter: "DESC" } })
Evidence
The PR description states 'Closes #11213' and the test was modified to add orderBy configuration to
verify the fix works. However, there is no comment in the test file referencing issue #11213. The
compliance rule states that 'issue fixes add or update tests in test/functional, with an issue
reference in the test comment when applicable.' Since this is an issue fix with a test update, a
comment reference would help trace the test to the original issue.

Rule 3: Prefer functional tests over per-issue tests
test/functional/repository/aggregate-methods/entity/Post.ts[5-5]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The test file is missing a comment that references issue #11213, which this PR fixes. Adding this reference helps with traceability and future maintenance.

## Issue Context
The PR fixes issue #11213 where aggregate functions incorrectly generated SQL with ORDER BY clauses. The test was updated to add `orderBy` configuration to the Post entity to verify that aggregate functions now properly disable the global order.

## Fix Focus Areas
- test/functional/repository/aggregate-methods/entity/Post.ts[5-5]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit d98884d

@coveralls

coveralls commented Jan 19, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 81.16%. remained the same
when pulling 4846be7 on Cprakhar:fix/aggregate-disable-global-order
into 960a59f on typeorm:master.

@Cprakhar
Cprakhar force-pushed the fix/aggregate-disable-global-order branch from d98884d to 8085a5e Compare January 19, 2026 21:34
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 8085a5e

@Cprakhar

Copy link
Copy Markdown
Collaborator Author

Could you please re-run the workflow and review the changes, @gioboa?

@Cprakhar
Cprakhar force-pushed the fix/aggregate-disable-global-order branch from 8085a5e to 159d248 Compare January 24, 2026 10:42
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 159d248

@Cprakhar
Cprakhar force-pushed the fix/aggregate-disable-global-order branch from 159d248 to 0366bee Compare January 27, 2026 09:51
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 0366bee

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it looks great to me 👏
Thanks @Cprakhar

@gioboa
gioboa requested review from G0maa and alumni February 17, 2026 15:59
@qodo-free-for-open-source-projects

Copy link
Copy Markdown

Persistent review updated to latest commit 4846be7

@alumni
alumni merged commit 2efb2a1 into typeorm:master Feb 17, 2026
38 checks passed
@Cprakhar
Cprakhar deleted the fix/aggregate-disable-global-order branch February 17, 2026 17:52
@pkuczynski pkuczynski added this to the 1.0 milestone Mar 8, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Broken maximum\minimum queries when default orderBy is defined

5 participants