# Flask: How to Execute Raw SQL with SQLAlchemy

> Execute raw SQL in a Flask-SQLAlchemy app using SQLAlchemy's text() function with a Connection, including parameter binding to prevent SQL injection

**URL:** https://sentry.io/answers/execute-raw-sql-in-flask-sqlalchemy-application/

---

## The Problem

When using Flask with SQLAlchemy, how can we execute a raw SQL statement?

## The Solution

SQLAlchemy provides powerful object-relational mapping (ORM) that allows one to use data from SQL databases as Python objects. Most common operations can be accomplished without needing to use custom SQL statements, and avoiding custom SQL makes our code more readable and reduces the chances that [SQL injection vulnerabilities](https://owasp.org/www-community/attacks/SQL_Injection) will be introduced.

However, the ORM may still be insufficient for representing particularly complex SQL queries. For this reason, SQLAlchemy provides a mechanism for executing raw SQL queries: the [`TextClause`](https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.TextClause) object, created using the [`text()`](https://docs.sqlalchemy.org/en/14/core/sqlelement.html#sqlalchemy.sql.expression.text) function. Instances of this object contain SQL statements and can be passed to the `execute()` method in the same way as normal ORM operations. Example code:

```python
from sqlalchemy import text

query = text("SELECT name, price FROM products")
with db.engine.connect() as conn:
    result = conn.execute(query)
```

**Note:** `Engine.execute()` was deprecated in SQLAlchemy 1.4 and removed entirely in SQLAlchemy 2.0. Statements must now be executed through a `Connection` (as shown above) or, in the ORM, through `Session.execute()`.

It is possible to achieve the same result by providing a raw string as a parameter for `execute()`, but the `TextClause` object provides some additional functionality, such as parameter binding:

```python
from sqlalchemy import text

query = text("SELECT name, price FROM products WHERE category=:product_category")
with db.engine.connect() as conn:
    result = conn.execute(query, {"product_category": "Fruit"})
```

Parameter binding allows us to reuse the same SQL query with different values and mitigates the risks of SQL injection when working with untrusted data.

---

*Source: [sentry.io/answers/execute-raw-sql-in-flask-sqlalchemy-application/](https://sentry.io/answers/execute-raw-sql-in-flask-sqlalchemy-application/)*
