Select using Query Builder
What is QueryBuilder
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
:
It builds the following SQL query:
and returns you an instance of User
:
How to create and use a QueryBuilder
QueryBuilder
There are several ways how you can create a Query Builder
:
Using connection:
Using entity manager:
Using repository:
There are 5 different QueryBuilder
types available:
SelectQueryBuilder
- used to build and executeSELECT
queries. Example:InsertQueryBuilder
- used to build and executeINSERT
queries. Example:UpdateQueryBuilder
- used to build and executeUPDATE
queries. Example:DeleteQueryBuilder
- used to build and executeDELETE
queries. Example: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
QueryBuilder
To get a single result from the database, for example to get a user by id or name, you must use getOne
:
getOneOrFail
will get a single result from the database, but if no result exists it will throw an EntityNotFoundError
:
To get multiple results from the database, for example, to get all users from the database, use 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:
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:
Which will result in the following sql query:
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:
Which produces the following SQL query:
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" }
.
is a shortcut for:
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 SQL statement, by using the special expansion syntax:
Which becomes:
Adding WHERE
expression
WHERE
expressionAdding a WHERE
expression is as easy as:
Which will produce:
You can add AND
into an existing WHERE
expression:
Which will produce the following SQL query:
You can add OR
into an existing WHERE
expression:
Which will produce the following SQL query:
You can do an IN
query with the WHERE
expression:
Which will produce the following SQL query:
You can add a complex WHERE
expression into an existing WHERE
using Brackets
Which will produce the following SQL query:
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
HAVING
expressionAdding a HAVING
expression is easy as:
Which will produce following SQL query:
You can add AND
into an exist HAVING
expression:
Which will produce the following SQL query:
You can add OR
into a exist HAVING
expression:
Which will produce the following SQL query:
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
ORDER BY
expressionAdding an ORDER BY
expression is easy as:
Which will produce:
You can change the ordering direction from ascending to descending (or versa):
You can add multiple order-by criteria:
You can also use a map of order-by fields:
If you use .orderBy
more than once you'll override all previous ORDER BY
expressions.
Adding DISTINCT ON
expression (Postgres only)
DISTINCT ON
expression (Postgres only)When using both distinct-on with an order-by expression, the distinct-on expression must match the leftmost order-by. The distinct-on expressions are interpreted using the same rules as order-by. Please note that, using distinct-on without an order-by expression means that the first row of each set is unpredictable.
Adding a DISTINCT ON
expression is easy as:
Which will produce:
Adding GROUP BY
expression
GROUP BY
expressionAdding a GROUP BY
expression is easy as:
Which will produce the following SQL query:
To add more group-by criteria use addGroupBy
:
If you use .groupBy
more than once you'll override all previous GROUP BY
expressions.
Adding LIMIT
expression
LIMIT
expressionAdding a LIMIT
expression is easy as:
Which will produce the following SQL query:
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
OFFSET
expressionAdding an SQL OFFSET
expression is easy as:
Which will produce the following SQL query:
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:
Now let's say you want to load user "Timber" with all of his photos:
You'll get the following result:
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.
This will generate following sql query:
You can also add conditions to the join expression instead of using "where":
This will generate the following sql query:
Inner and left joins
If you want to use INNER JOIN
instead of LEFT JOIN
just use innerJoinAndSelect
instead:
This will generate:
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
:
This will generate:
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:
Joining and mapping functionality
Add profilePhoto
to User
entity and you can map any data into that property using QueryBuilder
:
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
:
For debugging purposes you can use printSql
:
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:
Streaming result data
You can use stream
which returns you a stream. Streaming returns you raw data and you must handle entity transformation manually:
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.
This will give you the first 10 users with their photos.
This will give you all except the first 10 users with their photos. You can combine those methods:
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:
To use pessimistic write locking use the following method:
To use dirty read locking use the following method:
To use optimistic locking use the following method:
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:
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:
A more elegant way to do the same:
Alternatively, you can create a separate query builder and use its generated SQL:
You can create subqueries in FROM
like this:
or using more a elegant syntax:
If you want to add a subselect as a "second from" use addFrom
.
You can use subselects in SELECT
statements as well:
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:
Using a standard find
or query, you will not receive the password
property for the model. However, if you do the following:
You will get the property password
in your query.
Last updated
Was this helpful?