A Green Weevil bug

Debugging SQL Query With SQLAlchemy

SQLAlchemy provides ORM-like querying to any database. But knowing what is the final SQL executed can help us.

To view the SQL executed by SQLAlchemy, you need to import the driver from sqlalchemy.dialects. Adjust it to your needs.

The final code is the following:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from sqlalchemy.dialects import sqlite

query = session.query(Entity).filter(
    and_(
        Entity.status.in_(target_statuses),
        Entity.confirmed_at == None,
        Entity.created_at <= cutoff_datetime
    )
).order_by(func.coalesce(
    Entity.in_progress_at,
    Entity.created_at)
)

# This prints out the SQL code generated and executed by SQLAlchemy
print(query.statement.compile(dialect=sqlite.dialect()))

Follow me

Thanks for reading this article. Make sure to follow me on X, subscribe to my Substack publication and bookmark my blog to read more in the future.

Photo by Pixabay.

License GPLv3 | Terms
Built with Hugo
Theme Stack designed by Jimmy