Skip to content

Emitted SQL has selected columns in wrong order #8466

Closed

Description

@dustin-rcg

Issue Description

In some cases, the order of selected columns in the emitted SQL is different than the order than they were added to the SelectQueryBuilder with select and addSelect. This is a problem when using getQuery etc. to insert one sql query into another where the order matters, such as UNION ALL.

Expected Behavior

When I add selected columns to the SelectQueryBuilder with select and addSelect functions, the emitted SQL query should preserve the order.

Actual Behavior

The emitted SQL reorders the columns.

Steps to Reproduce

  1. Create the entity
import { Column, Entity, PrimaryColumn } from "typeorm";

@Entity({ database: "Risk", name: "RMEconomicExposures" })
export class RMEconomicExposure {
  @PrimaryColumn({ name: "ManagerId", type: "int" })
  investmentId: number;

  @PrimaryColumn({ name: "ReportDate", type: "datetime" })
  reportDate: Date;

  @PrimaryColumn({ name: "TierLevel", type: "varchar" })
  tierLevel: string;

  @Column({ name: "Measure", type: "float" })
  measure: number;

  @Column({ name: "AppCode", type: "int", nullable: true })
  appCode: number | null;

  @Column({ name: "CreateDate", type: "datetime", nullable: true })
  createDate: Date | null;

  @Column({ name: "CreateUser", type: "varchar", nullable: true })
  createUser: string | null;

  @Column({ name: "UpdateDate", type: "datetime", nullable: true })
  modifyDate: Date | null;

  @Column({ name: "UpdateUser", type: "varchar", nullable: true })
  modifyUser: string | null;
}
  1. Write the query with typeorm.
await getConnection("Foo").transaction(async manager => {
      console.log(manager
        .createQueryBuilder()
        .subQuery()
        .from(RMEconomicExposure, "m")
        .where(`m.investmentId in (${investmentIds})`)
        .select("m.investmentId", "investmentId")
        .addSelect("m.reportDate", "reportDate")
        .addSelect("m.tierLevel", "tierLevel")
        .addSelect("''", "categoryLevel")
        .addSelect("cast(null as float)", "rcg")
        .addSelect("cast(null as float)", "rcgEst")
        .addSelect("m.measure", "rm")
        .getQuery());
})
  1. The output reorders the columns:
(SELECT "m"."ManagerId" AS "investmentId", "m"."ReportDate" AS "reportDate", "m"."TierLevel" AS "tierLevel", 
"m"."Measure" AS "rm", '' AS "categoryLevel", cast(null as float) AS "rcg", cast(null as float) AS "rcgEst" 
FROM "Risk".."RMEconomicExposures" "m" WHERE "m"."ManagerId" in (...))

Notice the column "rm" was moved from last place to between "tierLevel" and "categoryLevel".

My Environment

Dependency Version
Operating System MacOS Monterrey 12.0.1
Node.js version 16.13.0
Typescript version 4.5.2
TypeORM version 0.2.41

Additional Context

Relevant Database Driver(s)

DB Type Reproducible
aurora-data-api no
aurora-data-api-pg no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql no
nativescript no
oracle no
postgres no
react-native no
sap no
sqlite no
sqlite-abstract no
sqljs no
sqlserver yes

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

  • ✖️ Yes, I have the time, and I know how to start.
  • ✖️ Yes, I have the time, but I don't know how to start. I would need guidance.
  • ✖️ No, I don’t have the time, but I can support (using donations) development.
  • ✅ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

Activity

  1. mrfoster commented on Mar 17, 2023

    @mrfoster

    It looks like queryBuilder.expressionMap.selects is still in the correct order. The following hack may help to correct the resultant key order until a fix is available.

        const results = await queryBuilder.getRawMany()
    
        // https://github.com/typeorm/typeorm/issues/8466
        // HACK: Fix column ordering
        const correctedResults = results.map((result) =>
          queryBuilder.expressionMap.selects
            .map((select) => select.aliasName)
            .reduce((p, c) => {
              p[c] = result[c]
              return p
            }, {}),
        )
    
        return correctedResults
  2. pcnova commented on Nov 9, 2023

    @pcnova

    I ran into this and realized that if everything is double-quoted properly when handing it to TypeORM, then it won't reorder the selects. That is, instead of this:

    builder.select("m.investmentId", "investmentId");

    ...do this:

    builder.select('"m"."investmentId"', 'investmentId');

    It seems like this way, TypeORM sees that it doesn't need to try and fix quotes, so it doesn't touch the select statement when you call getQuery().


    Note 1: In my case, I am even quoting things that technically don't need it, like "m"."id" - not sure whether this is needed to avoid the issue.

    Note 2: The 'investmentId' alias in the example above does not need double quotes - this is because TypeORM insists on adding double-quotes to this itself, so if you add them, you'll end up with invalid SQL. 😬

  3. dberardo-com commented on Jun 25, 2025

    @dberardo-com

    i am not sure if it is related, but i would like to override the value of a virtual column using addSelect in the querybuilder, but it seems like virtual columns get added after the query builder select statements.

  4. dberardo-com commented on Feb 2, 2026

    @dberardo-com

    @gioboa do you believe my comment from above is related ?

  5. gioboa commented on Feb 2, 2026

    @gioboa
    Collaborator

    Thanks @mrfoster Do you have a specific issue with this change?

  6. added
    good first issue
    and removed on Apr 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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