Data-Mapper ORM for TypeScript and ES2021+ supporting MySQL/MariaDB, PostgreSQL, MS SQL Server, Oracle, SAP HANA, SQLite, MongoDB databases.
Powerful query builder providing fluent API for constructing complex SQL queries with type safety and database-agnostic syntax. TypeORM's query builder allows for dynamic query construction while maintaining type safety.
Primary query builder for SELECT operations with full SQL feature support.
/**
* Query builder for SELECT queries with fluent API
* @template Entity - Entity type being queried
*/
class SelectQueryBuilder<Entity> {
/**
* Sets SELECT clause columns
* @param selection - Columns to select
* @returns SelectQueryBuilder for chaining
*/
select(selection?: string | string[]): SelectQueryBuilder<Entity>;
/**
* Adds columns to existing SELECT clause
* @param selection - Additional columns to select
* @returns SelectQueryBuilder for chaining
*/
addSelect(selection: string | string[]): SelectQueryBuilder<Entity>;
/**
* Sets FROM clause
* @param entityTarget - Entity class or table name
* @param alias - Table alias
* @returns SelectQueryBuilder for chaining
*/
from<T>(entityTarget: ObjectType<T> | EntitySchema<T> | string, alias: string): SelectQueryBuilder<T>;
/**
* Adds WHERE condition
* @param where - WHERE condition string or object
* @param parameters - Query parameters
* @returns SelectQueryBuilder for chaining
*/
where(
where: string | ((qb: SelectQueryBuilder<Entity>) => string) | Brackets | ObjectLiteral | ObjectLiteral[],
parameters?: ObjectLiteral
): SelectQueryBuilder<Entity>;
/**
* Adds AND WHERE condition
* @param where - WHERE condition
* @param parameters - Query parameters
* @returns SelectQueryBuilder for chaining
*/
andWhere(
where: string | ((qb: SelectQueryBuilder<Entity>) => string) | Brackets | ObjectLiteral | ObjectLiteral[],
parameters?: ObjectLiteral
): SelectQueryBuilder<Entity>;
/**
* Adds OR WHERE condition
* @param where - WHERE condition
* @param parameters - Query parameters
* @returns SelectQueryBuilder for chaining
*/
orWhere(
where: string | ((qb: SelectQueryBuilder<Entity>) => string) | Brackets | ObjectLiteral | ObjectLiteral[],
parameters?: ObjectLiteral
): SelectQueryBuilder<Entity>;
/**
* Adds INNER JOIN
* @param property - Property to join or table name
* @param alias - Join alias
* @param condition - Join condition
* @param parameters - Parameters for join condition
* @returns SelectQueryBuilder for chaining
*/
innerJoin(property: string, alias: string, condition?: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;
/**
* Adds LEFT JOIN
* @param property - Property to join or table name
* @param alias - Join alias
* @param condition - Join condition
* @param parameters - Parameters for join condition
* @returns SelectQueryBuilder for chaining
*/
leftJoin(property: string, alias: string, condition?: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;
/**
* Adds ORDER BY clause
* @param sort - Column to sort by
* @param order - Sort direction
* @param nulls - NULL value ordering
* @returns SelectQueryBuilder for chaining
*/
orderBy(
sort: string | ((alias: string) => string),
order?: "ASC" | "DESC",
nulls?: "NULLS FIRST" | "NULLS LAST"
): SelectQueryBuilder<Entity>;
/**
* Adds additional ORDER BY clause
* @param sort - Column to sort by
* @param order - Sort direction
* @param nulls - NULL value ordering
* @returns SelectQueryBuilder for chaining
*/
addOrderBy(
sort: string | ((alias: string) => string),
order?: "ASC" | "DESC",
nulls?: "NULLS FIRST" | "NULLS LAST"
): SelectQueryBuilder<Entity>;
/**
* Adds GROUP BY clause
* @param groupBy - Columns to group by
* @returns SelectQueryBuilder for chaining
*/
groupBy(groupBy: string): SelectQueryBuilder<Entity>;
/**
* Adds additional GROUP BY clause
* @param groupBy - Additional columns to group by
* @returns SelectQueryBuilder for chaining
*/
addGroupBy(groupBy: string): SelectQueryBuilder<Entity>;
/**
* Adds HAVING clause
* @param having - HAVING condition
* @param parameters - Condition parameters
* @returns SelectQueryBuilder for chaining
*/
having(having: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;
/**
* Adds AND HAVING condition
* @param having - HAVING condition
* @param parameters - Condition parameters
* @returns SelectQueryBuilder for chaining
*/
andHaving(having: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;
/**
* Adds OR HAVING condition
* @param having - HAVING condition
* @param parameters - Condition parameters
* @returns SelectQueryBuilder for chaining
*/
orHaving(having: string, parameters?: ObjectLiteral): SelectQueryBuilder<Entity>;
/**
* Sets LIMIT clause
* @param limit - Maximum number of results
* @returns SelectQueryBuilder for chaining
*/
limit(limit?: number): SelectQueryBuilder<Entity>;
/**
* Sets OFFSET clause
* @param offset - Number of results to skip
* @returns SelectQueryBuilder for chaining
*/
offset(offset?: number): SelectQueryBuilder<Entity>;
/**
* Executes query and returns single entity
* @returns Promise resolving to entity or null
*/
getOne(): Promise<Entity | null>;
/**
* Executes query and returns entity array
* @returns Promise resolving to entity array
*/
getMany(): Promise<Entity[]>;
/**
* Executes query and returns raw result object
* @returns Promise resolving to raw result or null
*/
getRawOne(): Promise<any>;
/**
* Executes query and returns raw result array
* @returns Promise resolving to raw results array
*/
getRawMany(): Promise<any[]>;
/**
* Executes query and returns entities with raw results
* @returns Promise resolving to entities and raw results
*/
getRawAndEntities(): Promise<{ entities: Entity[]; raw: any[] }>;
/**
* Gets count of matching entities
* @returns Promise resolving to count
*/
getCount(): Promise<number>;
/**
* Gets generated SQL query string
* @returns SQL query string
*/
getSql(): string;
/**
* Creates a subquery
* @returns SelectQueryBuilder for subquery
*/
subQuery(): SelectQueryBuilder<any>;
/**
* Sets query parameters
* @param parameters - Parameters object
* @returns SelectQueryBuilder for chaining
*/
setParameters(parameters: ObjectLiteral): SelectQueryBuilder<Entity>;
/**
* Sets single query parameter
* @param key - Parameter key
* @param value - Parameter value
* @returns SelectQueryBuilder for chaining
*/
setParameter(key: string, value: any): SelectQueryBuilder<Entity>;
}Builder for INSERT operations with support for bulk inserts and conflict resolution.
/**
* Query builder for INSERT operations
* @template Entity - Entity type being inserted
*/
class InsertQueryBuilder<Entity> {
/**
* Sets INTO clause (target table/entity)
* @param target - Entity target
* @returns InsertQueryBuilder for chaining
*/
into<T>(target: ObjectType<T> | EntitySchema<T> | string): InsertQueryBuilder<T>;
/**
* Sets VALUES clause with entity objects
* @param values - Values to insert
* @returns InsertQueryBuilder for chaining
*/
values(values: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]): InsertQueryBuilder<Entity>;
/**
* Sets ON CONFLICT clause for upsert operations
* @param conflictPath - Conflict column(s)
* @returns InsertQueryBuilder for chaining
*/
onConflict(conflictPath: string): InsertQueryBuilder<Entity>;
/**
* Sets RETURNING clause (PostgreSQL)
* @param returning - Columns to return
* @returns InsertQueryBuilder for chaining
*/
returning(returning: string | string[]): InsertQueryBuilder<Entity>;
/**
* Executes INSERT query
* @returns Promise resolving to insert result
*/
execute(): Promise<InsertResult>;
/**
* Gets generated SQL query string
* @returns SQL query string
*/
getSql(): string;
}
/**
* Result of INSERT operation
*/
class InsertResult {
/** Generated ID values */
identifiers: ObjectLiteral[];
/** Number of affected rows */
affected?: number;
/** Raw database result */
raw: any;
}Builder for UPDATE operations with conditional updates and joins.
/**
* Query builder for UPDATE operations
* @template Entity - Entity type being updated
*/
class UpdateQueryBuilder<Entity> {
/**
* Sets UPDATE clause (target table/entity)
* @param target - Entity target
* @returns UpdateQueryBuilder for chaining
*/
update<T>(target: ObjectType<T> | EntitySchema<T> | string): UpdateQueryBuilder<T>;
/**
* Sets SET clause with values to update
* @param values - Values to update
* @returns UpdateQueryBuilder for chaining
*/
set(values: QueryDeepPartialEntity<Entity>): UpdateQueryBuilder<Entity>;
/**
* Adds WHERE condition
* @param where - WHERE condition
* @param parameters - Query parameters
* @returns UpdateQueryBuilder for chaining
*/
where(
where: string | Brackets | ObjectLiteral | ObjectLiteral[],
parameters?: ObjectLiteral
): UpdateQueryBuilder<Entity>;
/**
* Adds AND WHERE condition
* @param where - WHERE condition
* @param parameters - Query parameters
* @returns UpdateQueryBuilder for chaining
*/
andWhere(
where: string | Brackets | ObjectLiteral | ObjectLiteral[],
parameters?: ObjectLiteral
): UpdateQueryBuilder<Entity>;
/**
* Sets RETURNING clause (PostgreSQL)
* @param returning - Columns to return
* @returns UpdateQueryBuilder for chaining
*/
returning(returning: string | string[]): UpdateQueryBuilder<Entity>;
/**
* Executes UPDATE query
* @returns Promise resolving to update result
*/
execute(): Promise<UpdateResult>;
/**
* Gets generated SQL query string
* @returns SQL query string
*/
getSql(): string;
}
/**
* Result of UPDATE operation
*/
class UpdateResult {
/** Number of affected rows */
affected?: number;
/** Raw database result */
raw: any;
/** Updated entities (when using RETURNING) */
entities?: Entity[];
}Builder for DELETE operations with conditional deletes.
/**
* Query builder for DELETE operations
* @template Entity - Entity type being deleted
*/
class DeleteQueryBuilder<Entity> {
/**
* Sets DELETE FROM clause
* @param target - Entity target
* @returns DeleteQueryBuilder for chaining
*/
delete(): DeleteQueryBuilder<Entity>;
/**
* Sets FROM clause
* @param target - Entity target
* @returns DeleteQueryBuilder for chaining
*/
from<T>(target: ObjectType<T> | EntitySchema<T> | string): DeleteQueryBuilder<T>;
/**
* Adds WHERE condition
* @param where - WHERE condition
* @param parameters - Query parameters
* @returns DeleteQueryBuilder for chaining
*/
where(
where: string | Brackets | ObjectLiteral | ObjectLiteral[],
parameters?: ObjectLiteral
): DeleteQueryBuilder<Entity>;
/**
* Sets RETURNING clause (PostgreSQL)
* @param returning - Columns to return
* @returns DeleteQueryBuilder for chaining
*/
returning(returning: string | string[]): DeleteQueryBuilder<Entity>;
/**
* Executes DELETE query
* @returns Promise resolving to delete result
*/
execute(): Promise<DeleteResult>;
/**
* Gets generated SQL query string
* @returns SQL query string
*/
getSql(): string;
}
/**
* Result of DELETE operation
*/
class DeleteResult {
/** Number of affected rows */
affected?: number;
/** Raw database result */
raw: any;
}Helper classes for building complex WHERE conditions.
/**
* Creates grouped WHERE conditions with parentheses
*/
class Brackets {
constructor(whereFactory: (qb: WhereExpressionBuilder) => any);
}
/**
* Creates negated grouped WHERE conditions
*/
class NotBrackets {
constructor(whereFactory: (qb: WhereExpressionBuilder) => any);
}
/**
* Interface for WHERE expression building
*/
interface WhereExpression {
where(where: Function | string | Brackets, parameters?: ObjectLiteral): this;
andWhere(where: Function | string | Brackets, parameters?: ObjectLiteral): this;
orWhere(where: Function | string | Brackets, parameters?: ObjectLiteral): this;
}Query Builder Examples:
import { DataSource, SelectQueryBuilder, Brackets } from "typeorm";
const dataSource = new DataSource(/* options */);
await dataSource.initialize();
// Basic SELECT with joins
const users = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.innerJoinAndSelect("user.posts", "post")
.leftJoinAndSelect("user.profile", "profile")
.where("user.active = :active", { active: true })
.orderBy("user.createdAt", "DESC")
.limit(10)
.getMany();
// Complex WHERE conditions with brackets
const results = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where(new Brackets(qb => {
qb.where("user.firstName = :firstName", { firstName: "John" })
.orWhere("user.lastName = :lastName", { lastName: "Doe" });
}))
.andWhere("user.active = :active", { active: true })
.getMany();
// Subquery
const averageAge = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.select("AVG(user.age)", "avg")
.getRawOne();
const olderUsers = await dataSource
.getRepository(User)
.createQueryBuilder("user")
.where(`user.age > (${averageAge.avg})`)
.getMany();
// INSERT with query builder
await dataSource
.createQueryBuilder()
.insert()
.into(User)
.values([
{ firstName: "John", lastName: "Doe" },
{ firstName: "Jane", lastName: "Smith" }
])
.execute();
// UPDATE with query builder
await dataSource
.createQueryBuilder()
.update(User)
.set({ active: false })
.where("lastLoginAt < :date", { date: thirtyDaysAgo })
.execute();
// DELETE with query builder
await dataSource
.createQueryBuilder()
.delete()
.from(User)
.where("active = :active", { active: false })
.execute();Install with Tessl CLI
npx tessl i tessl/npm-typeorm