Kinda Code
Home/Flutter/TypeORM: How to Execute Raw SQL Queries

TypeORM: How to Execute Raw SQL Queries

Last updated: September 20, 2022

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.