TypeORM: How to Execute Raw SQL Queries
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' ); console.log(users);
const manager = myDataSource.manager; const result = await manager.query('DELETE FROM "users" WHERE id = $1', [ 1, ]); console.log(result);
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).
- TypeORM Upsert: Update If Exists, Create If Not Exists
- TypeORM: ORDER BY Multiple Columns
- TypeORM: Get Raw SQL Query from QueryBuilder
- Pagination in TypeORM (Find Options & QueryBuilder)
- TypeORM: AND & OR operators
You can also check out our database topic page for the latest tutorials and examples.
View all comments