TypeORM: How to Execute Raw SQL Queries

Updated: September 20, 2022 By: Snowball 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.

Example:

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

console.log(users);

Another example:

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).

Further reading:

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

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles