Select using Query Builder

What is QueryBuilder

QueryBuilder is one of the most powerful features of TypeORM -it allows you to build SQL queries using elegant and convenient syntax,execute them and get automatically transformed entities.

Simple example of QueryBuilder:

  1. const firstUser = await connection
  2. .getRepository(User)
  3. .createQueryBuilder("user")
  4. .where("user.id = :id", { id: 1 })
  5. .getOne();

It builds the following SQL query:

  1. SELECT
  2. user.id as userId,
  3. user.firstName as userFirstName,
  4. user.lastName as userLastName
  5. FROM users user
  6. WHERE user.id = 1

and returns you an instance of User:

  1. User {
  2. id: 1,
  3. firstName: "Timber",
  4. lastName: "Saw"
  5. }

How to create and use a QueryBuilder

There are several ways how you can create a Query Builder:

  • Using connection:

    1. import {getConnection} from "typeorm";
    2. const user = await getConnection()
    3. .createQueryBuilder()
    4. .select("user")
    5. .from(User, "user")
    6. .where("user.id = :id", { id: 1 })
    7. .getOne();
  • Using entity manager:

    1. import {getManager} from "typeorm";
    2. const user = await getManager()
    3. .createQueryBuilder(User, "user")
    4. .where("user.id = :id", { id: 1 })
    5. .getOne();
  • Using repository:

    1. import {getRepository} from "typeorm";
    2. const user = await getRepository(User)
    3. .createQueryBuilder("user")
    4. .where("user.id = :id", { id: 1 })
    5. .getOne();

There are 5 different QueryBuilder types available:

  • SelectQueryBuilder - used to build and execute SELECT queries. Example:

    1. import {getConnection} from "typeorm";
    2. const user = await getConnection()
    3. .createQueryBuilder()
    4. .select("user")
    5. .from(User, "user")
    6. .where("user.id = :id", { id: 1 })
    7. .getOne();
  • InsertQueryBuilder - used to build and execute INSERT queries. Example:

    1. import {getConnection} from "typeorm";
    2. await getConnection()
    3. .createQueryBuilder()
    4. .insert()
    5. .into(User)
    6. .values([
    7. { firstName: "Timber", lastName: "Saw" },
    8. { firstName: "Phantom", lastName: "Lancer" }
    9. ])
    10. .execute();
  • UpdateQueryBuilder - used to build and execute UPDATE queries. Example:

    1. import {getConnection} from "typeorm";
    2. await getConnection()
    3. .createQueryBuilder()
    4. .update(User)
    5. .set({ firstName: "Timber", lastName: "Saw" })
    6. .where("id = :id", { id: 1 })
    7. .execute();
  • DeleteQueryBuilder - used to build and execute DELETE queries. Example:

    1. import {getConnection} from "typeorm";
    2. await getConnection()
    3. .createQueryBuilder()
    4. .delete()
    5. .from(User)
    6. .where("id = :id", { id: 1 })
    7. .execute();
  • RelationQueryBuilder - used to build and execute relation-specific operations [TBD].

You can switch between different types of query builder within any of them,once you do, you will get a new instance of query builder (unlike all other methods).

Getting values using QueryBuilder

To get a single result from the database,for example to get a user by id or name, you must use getOne:

  1. const timber = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
  4. .getOne();

To get multiple results from the database,for example, to get all users from the database, use getMany:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .getMany();

There are two types of results you can get using select query builder: entities or raw results.Most of the time, you need to select real entities from your database, for example, users.For this purpose, you use getOne and getMany.But sometimes you need to select some specific data, let’s say the sum of all user photos.This data is not an entity, it’s called raw data.To get raw data, you use getRawOne and getRawMany.Examples:

  1. const { sum } = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .select("SUM(user.photosCount)", "sum")
  4. .where("user.id = :id", { id: 1 })
  5. .getRawOne();
  1. const photosSums = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .select("user.id")
  4. .addSelect("SUM(user.photosCount)", "sum")
  5. .where("user.id = :id", { id: 1 })
  6. .getRawMany();
  7. // result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]

What are aliases for?

We used createQueryBuilder("user"). But what is “user”?It’s just a regular SQL alias.We use aliases everywhere, except when we work with selected data.

createQueryBuilder("user") is equivalent to:

  1. createQueryBuilder()
  2. .select("user")
  3. .from(User, "user")

Which will result in the following sql query:

  1. SELECT ... FROM users user

In this SQL query, users is the table name, and user is an alias we assign to this table.Later we use this alias to access the table:

  1. createQueryBuilder()
  2. .select("user")
  3. .from(User, "user")
  4. .where("user.name = :name", { name: "Timber" })

Which produces the following SQL query:

  1. SELECT ... FROM users user WHERE user.name = 'Timber'

See, we used the users table by using the user alias we assigned when we created a query builder.

One query builder is not limited to one alias, they can have multiple aliases.Each select can have its own alias,you can select from multiple tables each with its own alias,you can join multiple tables each with its own alias.You can use those aliases to access tables are you selecting (or data you are selecting).

Using parameters to escape data

We used where("user.name = :name", { name: "Timber" }).What does { name: "Timber" } stand for? It’s a parameter we used to prevent SQL injection.We could have written: where("user.name = '" + name + "'),however this is not safe, as it opens the code to SQL injections.The safe way is to use this special syntax: where("user.name = :name", { name: "Timber" }),where :name is a parameter name and the value is specified in an object: { name: "Timber" }.

  1. .where("user.name = :name", { name: "Timber" })

is a shortcut for:

  1. .where("user.name = :name")
  2. .setParameter("name", "Timber")

Note: do not use the same parameter name for different values across the query builder. Values will be overridden if you set them multiple times.

You can also supply an array of values, and have them transformed into a list of values in the SQLstatement, by using the special expansion syntax:

  1. .where("user.name IN (:...names)", { names: [ "Timber", "Cristal", "Lina" ] })

Which becomes:

  1. WHERE user.name IN ('Timber', 'Cristal', 'Lina')

Adding WHERE expression

Adding a WHERE expression is as easy as:

  1. createQueryBuilder("user")
  2. .where("user.name = :name", { name: "Timber" })

Which will produce:

  1. SELECT ... FROM users user WHERE user.name = 'Timber'

You can add AND into an existing WHERE expression:

  1. createQueryBuilder("user")
  2. .where("user.firstName = :firstName", { firstName: "Timber" })
  3. .andWhere("user.lastName = :lastName", { lastName: "Saw" });

Which will produce the following SQL query:

  1. SELECT ... FROM users user WHERE user.firstName = 'Timber' AND user.lastName = 'Saw'

You can add OR into an existing WHERE expression:

  1. createQueryBuilder("user")
  2. .where("user.firstName = :firstName", { firstName: "Timber" })
  3. .orWhere("user.lastName = :lastName", { lastName: "Saw" });

Which will produce the following SQL query:

  1. SELECT ... FROM users user WHERE user.firstName = 'Timber' OR user.lastName = 'Saw'

You can add a complex WHERE expression into an existing WHERE using Brackets

  1. createQueryBuilder("user")
  2. .where("user.registered = :registered", { registered: true })
  3. .andWhere(new Brackets(qb => {
  4. qb.where("user.firstName = :firstName", { firstName: "Timber" })
  5. .orWhere("user.lastName = :lastName", { lastName: "Saw" })
  6. }))

Which will produce the following SQL query:

  1. SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')

You can combine as many AND and OR expressions as you need.If you use .where more than once you’ll override all previous WHERE expressions.

Note: be careful with orWhere - if you use complex expressions with both AND and OR expressions,keep in mind that they are stacked without any pretences.Sometimes you’ll need to create a where string instead, and avoid using orWhere.

Adding HAVING expression

Adding a HAVING expression is easy as:

  1. createQueryBuilder("user")
  2. .having("user.name = :name", { name: "Timber" })

Which will produce following SQL query:

  1. SELECT ... FROM users user HAVING user.name = 'Timber'

You can add AND into an exist HAVING expression:

  1. createQueryBuilder("user")
  2. .having("user.firstName = :firstName", { firstName: "Timber" })
  3. .andHaving("user.lastName = :lastName", { lastName: "Saw" });

Which will produce the following SQL query:

  1. SELECT ... FROM users user HAVING user.firstName = 'Timber' AND user.lastName = 'Saw'

You can add OR into a exist HAVING expression:

  1. createQueryBuilder("user")
  2. .having("user.firstName = :firstName", { firstName: "Timber" })
  3. .orHaving("user.lastName = :lastName", { lastName: "Saw" });

Which will produce the following SQL query:

  1. SELECT ... FROM users user HAVING user.firstName = 'Timber' OR user.lastName = 'Saw'

You can combine as many AND and OR expressions as you need.If you use .having more than once you’ll override all previous HAVING expressions.

Adding ORDER BY expression

Adding an ORDER BY expression is easy as:

  1. createQueryBuilder("user")
  2. .orderBy("user.id")

Which will produce:

  1. SELECT ... FROM users user ORDER BY user.id

You can change the ordering direction from ascending to descending (or versa):

  1. createQueryBuilder("user")
  2. .orderBy("user.id", "DESC")
  3. createQueryBuilder("user")
  4. .orderBy("user.id", "ASC")

You can add multiple order-by criteria:

  1. createQueryBuilder("user")
  2. .orderBy("user.name")
  3. .addOrderBy("user.id");

You can also use a map of order-by fields:

  1. createQueryBuilder("user")
  2. .orderBy({
  3. "user.name": "ASC",
  4. "user.id": "DESC"
  5. });

If you use .orderBy more than once you’ll override all previous ORDER BY expressions.

Adding GROUP BY expression

Adding a GROUP BY expression is easy as:

  1. createQueryBuilder("user")
  2. .groupBy("user.id")

Which will produce the following SQL query:

  1. SELECT ... FROM users user GROUP BY user.id

To add more group-by criteria use addGroupBy:

  1. createQueryBuilder("user")
  2. .groupBy("user.name")
  3. .addGroupBy("user.id");

If you use .groupBy more than once you’ll override all previous GROUP BY expressions.

Adding LIMIT expression

Adding a LIMIT expression is easy as:

  1. createQueryBuilder("user")
  2. .limit(10)

Which will produce the following SQL query:

  1. SELECT ... FROM users user LIMIT 10

The resulting SQL query depends on the type of database (SQL, mySQL, Postgres, etc).Note: LIMIT may not work as you may expect if you are using complex queries with joins or subqueries.If you are using pagination, it’s recommended to use take instead.

Adding OFFSET expression

Adding an SQL OFFSET expression is easy as:

  1. createQueryBuilder("user")
  2. .offset(10)

Which will produce the following SQL query:

  1. SELECT ... FROM users user OFFSET 10

The resulting SQL query depends on the type of database (SQL, mySQL, Postgres, etc).Note: OFFSET may not work as you may expect if you are using complex queries with joins or subqueries.If you are using pagination, it’s recommended to use skip instead.

Joining relations

Let’s say you have the following entities:

  1. import {Entity, PrimaryGeneratedColumn, Column, OneToMany} from "typeorm";
  2. import {Photo} from "./Photo";
  3. @Entity()
  4. export class User {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. name: string;
  9. @OneToMany(type => Photo, photo => photo.user)
  10. photos: Photo[];
  11. }
  1. import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm";
  2. import {User} from "./User";
  3. @Entity()
  4. export class Photo {
  5. @PrimaryGeneratedColumn()
  6. id: number;
  7. @Column()
  8. url: string;
  9. @ManyToOne(type => User, user => user.photos)
  10. user: User;
  11. }

Now let’s say you want to load user “Timber” with all of his photos:

  1. const user = await createQueryBuilder("user")
  2. .leftJoinAndSelect("user.photos", "photo")
  3. .where("user.name = :name", { name: "Timber" })
  4. .getOne();

You’ll get the following result:

  1. {
  2. id: 1,
  3. name: "Timber",
  4. photos: [{
  5. id: 1,
  6. url: "me-with-chakram.jpg"
  7. }, {
  8. id: 2,
  9. url: "me-with-trees.jpg"
  10. }]
  11. }

As you can see leftJoinAndSelect automatically loaded all of Timber’s photos.The first argument is the relation you want to load and the second argument is an alias you assign to this relation’s table.You can use this alias anywhere in query builder.For example, let’s take all Timber’s photos which aren’t removed.

  1. const user = await createQueryBuilder("user")
  2. .leftJoinAndSelect("user.photos", "photo")
  3. .where("user.name = :name", { name: "Timber" })
  4. .andWhere("photo.isRemoved = :isRemoved", { isRemoved: false })
  5. .getOne();

This will generate following sql query:

  1. SELECT user.*, photo.* FROM users user
  2. LEFT JOIN photos photo ON photo.user = user.id
  3. WHERE user.name = 'Timber' AND photo.isRemoved = FALSE

You can also add conditions to the join expression instead of using “where”:

  1. const user = await createQueryBuilder("user")
  2. .leftJoinAndSelect("user.photos", "photo", "photo.isRemoved = :isRemoved", { isRemoved: false })
  3. .where("user.name = :name", { name: "Timber" })
  4. .getOne();

This will generate the following sql query:

  1. SELECT user.*, photo.* FROM users user
  2. LEFT JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
  3. WHERE user.name = 'Timber'

Inner and left joins

If you want to use INNER JOIN instead of LEFT JOIN just use innerJoinAndSelect instead:

  1. const user = await createQueryBuilder("user")
  2. .innerJoinAndSelect("user.photos", "photo", "photo.isRemoved = :isRemoved", { isRemoved: false })
  3. .where("user.name = :name", { name: "Timber" })
  4. .getOne();

This will generate:

  1. SELECT user.*, photo.* FROM users user
  2. INNER JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
  3. WHERE user.name = 'Timber'

The difference between LEFT JOIN and INNER JOIN is that INNER JOIN won’t return a user if it does not have any photos.LEFT JOIN will return you the user even if it doesn’t have photos.To learn more about different join types, refer to the SQL documentation.

Join without selection

You can join data without its selection.To do that, use leftJoin or innerJoin:

  1. const user = await createQueryBuilder("user")
  2. .innerJoin("user.photos", "photo")
  3. .where("user.name = :name", { name: "Timber" })
  4. .getOne();

This will generate:

  1. SELECT user.* FROM users user
  2. INNER JOIN photos photo ON photo.user = user.id
  3. WHERE user.name = 'Timber'

This will select Timber if he has photos, but won’t return his photos.

Joining any entity or table

You can join not only relations, but also other unrelated entities or tables.Examples:

  1. const user = await createQueryBuilder("user")
  2. .leftJoinAndSelect(Photo, "photo", "photo.userId = user.id")
  3. .getMany();
  1. const user = await createQueryBuilder("user")
  2. .leftJoinAndSelect("photos", "photo", "photo.userId = user.id")
  3. .getMany();

Joining and mapping functionality

Add profilePhoto to User entity and you can map any data into that property using QueryBuilder:

  1. export class User {
  2. /// ...
  3. profilePhoto: Photo;
  4. }
  1. const user = await createQueryBuilder("user")
  2. .leftJoinAndMapOne("user.profilePhoto", "user.photos", "photo", "photo.isForProfile = TRUE")
  3. .where("user.name = :name", { name: "Timber" })
  4. .getOne();

This will load Timber’s profile photo and set it to user.profilePhoto.If you want to load and map a single entity use leftJoinAndMapOne.If you want to load and map multiple entities use leftJoinAndMapMany.

Getting the generated query

Sometimes you may want to get the SQL query generated by QueryBuilder.To do so, use getSql:

  1. const sql = createQueryBuilder("user")
  2. .where("user.firstName = :firstName", { firstName: "Timber" })
  3. .orWhere("user.lastName = :lastName", { lastName: "Saw" })
  4. .getSql();

For debugging purposes you can use printSql:

  1. const users = await createQueryBuilder("user")
  2. .where("user.firstName = :firstName", { firstName: "Timber" })
  3. .orWhere("user.lastName = :lastName", { lastName: "Saw" })
  4. .printSql()
  5. .getMany();

This query will return users and print the used sql statement to the console.

Getting raw results

There are two types of results you can get using select query builder: entities and raw results.Most of the time, you need to select real entities from your database, for example, users.For this purpose, you use getOne and getMany.However, sometimes you need to select specific data, like the sum of all user photos.Such data is not a entity, it’s called raw data.To get raw data, you use getRawOne and getRawMany.Examples:

  1. const { sum } = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .select("SUM(user.photosCount)", "sum")
  4. .where("user.id = :id", { id: 1 })
  5. .getRawOne();
  1. const photosSums = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .select("user.id")
  4. .addSelect("SUM(user.photosCount)", "sum")
  5. .where("user.id = :id", { id: 1 })
  6. .getRawMany();
  7. // result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]

Streaming result data

You can use stream which returns you a stream.Streaming returns you raw data and you must handle entity transformation manually:

  1. const stream = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .where("user.id = :id", { id: 1 })
  4. .stream();

Using pagination

Most of the time when you develop an application, you need pagination functionality.This is used if you have pagination, page slider, or infinite scroll components in your application.

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .leftJoinAndSelect("user.photos", "photo")
  4. .take(10)
  5. .getMany();

This will give you the first 10 users with their photos.

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .leftJoinAndSelect("user.photos", "photo")
  4. .skip(10)
  5. .getMany();

This will give you all except the first 10 users with their photos.You can combine those methods:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .leftJoinAndSelect("user.photos", "photo")
  4. .skip(5)
  5. .take(10)
  6. .getMany();

This will skip the first 5 users and take 10 users after them.

take and skip may look like we are using limit and offset, but they aren’t.limit and offset may not work as you expect once you have more complicated queries with joins or subqueries.Using take and skip will prevent those issues.

Set locking

QueryBuilder supports both optimistic and pessimistic locking.To use pessimistic read locking use the following method:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .setLock("pessimistic_read")
  4. .getMany();

To use pessimistic write locking use the following method:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .setLock("pessimistic_write")
  4. .getMany();

To use dirty read locking use the following method:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .setLock("dirty_read")
  4. .getMany();

To use optimistic locking use the following method:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .setLock("optimistic", existUser.version)
  4. .getMany();

Optimistic locking works in conjunction with both @Version and @UpdatedDate decorators.

Partial selection

If you want to select only some entity properties, you can use the following syntax:

  1. const users = await getRepository(User)
  2. .createQueryBuilder("user")
  3. .select([
  4. "user.id",
  5. "user.name"
  6. ])
  7. .getMany();

This will only select the id and name of User.

Using subqueries

You can easily create subqueries. Subqueries are supported in FROM, WHERE and JOIN expressions.Example:

  1. const qb = await getRepository(Post).createQueryBuilder("post");
  2. const posts = qb
  3. .where("post.title IN " + qb.subQuery().select("user.name").from(User, "user").where("user.registered = :registered").getQuery())
  4. .setParameter("registered", true)
  5. .getMany();

A more elegant way to do the same:

  1. const posts = await connection.getRepository(Post)
  2. .createQueryBuilder("post")
  3. .where(qb => {
  4. const subQuery = qb.subQuery()
  5. .select("user.name")
  6. .from(User, "user")
  7. .where("user.registered = :registered")
  8. .getQuery();
  9. return "post.title IN " + subQuery;
  10. })
  11. .setParameter("registered", true)
  12. .getMany();

Alternatively, you can create a separate query builder and use its generated SQL:

  1. const userQb = await connection.getRepository(User)
  2. .createQueryBuilder("user")
  3. .select("user.name")
  4. .where("user.registered = :registered", { registered: true });
  5. const posts = await connection.getRepository(Post)
  6. .createQueryBuilder("post")
  7. .where("post.title IN (" + userQb.getQuery() + ")")
  8. .setParameters(userQb.getParameters())
  9. .getMany();

You can create subqueries in FROM like this:

  1. const userQb = await connection.getRepository(User)
  2. .createQueryBuilder("user")
  3. .select("user.name", "name")
  4. .where("user.registered = :registered", { registered: true });
  5. const posts = await connection
  6. .createQueryBuilder()
  7. .select("user.name", "name")
  8. .from("(" + userQb.getQuery() + ")", "user")
  9. .setParameters(userQb.getParameters())
  10. .getRawMany();

or using more a elegant syntax:

  1. const posts = await connection
  2. .createQueryBuilder()
  3. .select("user.name", "name")
  4. .from(subQuery => {
  5. return subQuery
  6. .select("user.name", "name")
  7. .from(User, "user")
  8. .where("user.registered = :registered", { registered: true });
  9. }, "user")
  10. .getRawMany();

If you want to add a subselect as a “second from” use addFrom.

You can use subselects in SELECT statements as well:

  1. const posts = await connection
  2. .createQueryBuilder()
  3. .select("post.id", "id")
  4. .addSelect(subQuery => {
  5. return subQuery
  6. .select("user.name", "name")
  7. .from(User, "user")
  8. .limit(1);
  9. }, "name")
  10. .from(Post, "post")
  11. .getRawMany();

Hidden Columns

If the model you are querying has a column with a select: false column, you must use the addSelect function in order to retrieve the information from the column.

Let’s say you have the following entity:

  1. import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. name: string;
  8. @Column({select: false})
  9. password: string;
  10. }

Using a standard find or query, you will not receive the password property for the model. However, if you do the following:

  1. const users = await connection.getRepository(User)
  2. .createQueryBuilder()
  3. .select("user.id", "id")
  4. .addSelect("user.password")
  5. .getMany();

You will get the property password in your query.