TypeORM: How to Execute Raw SQL Queries

Last updated on September 20, 2022 Snowball Loading... Post a comment

In TypeORM, you can execute raw SQL queries by calling the query() method (you can access this method via your data source or the entity manager). You can do everything from CRUD data (create, read, update, and delete) to other complex operations.


const users = await myDataSource.query(
      'SELECT * FROM users ORDER BY id DESC LIMIT 100'


Another example:

const manager = myDataSource.manager;
const result = await manager.query('DELETE FROM "users" WHERE id = $1', [

Running raw SQL queries will give you maximum flexibility but will be a bit difficult for those with little experience working with MySQL, PostgreSQL, SQLite, MS SQL, etc. In addition, errors are also easier to make (typing errors in SQL statements are harder to detect).

Further reading:

You can also check out our database topic page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

You May Also Like