SQLAlchemy 2.0:

with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # do something with the result..

SQLAlchemy 1.x:

from sqlalchemy import text

sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names

Note that db.engine.execute() is "connectionless", which is deprecated in SQLAlchemy 2.0.

Answer from Miguel Grinberg on Stack Overflow
🌐
Atlassian
atlassian.com › data › notebook › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy | Atlassian
One method for executing raw SQL is to use the text module, or Textual SQL. The most readable way to use text is to import the module, then after connecting to the engine, define the text SQL statement string before using .execute to run it: 1from sqlalchemy.sql import text 2with engine.connect() ...
Top answer
1 of 10
439

SQLAlchemy 2.0:

with engine.connect() as connection:
    result = connection.execute(text('SELECT * FROM your_table'))
    # do something with the result..

SQLAlchemy 1.x:

from sqlalchemy import text

sql = text('select name from penguins')
result = db.engine.execute(sql)
names = [row[0] for row in result]
print names

Note that db.engine.execute() is "connectionless", which is deprecated in SQLAlchemy 2.0.

2 of 10
293

SQL Alchemy session objects have their own execute method:

result = db.session.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})

All your application queries should be going through a session object, whether they're raw SQL or not. This ensures that the queries are properly managed by a transaction, which allows multiple queries in the same request to be committed or rolled back as a single unit. Going outside the transaction using the engine or the connection puts you at much greater risk of subtle, possibly hard to detect bugs that can leave you with corrupted data. Each request should be associated with only one transaction, and using db.session will ensure this is the case for your application.

Also take note that execute is designed for parameterized queries. Use parameters, like :val in the example, for any inputs to the query to protect yourself from SQL injection attacks. You can provide the value for these parameters by passing a dict as the second argument, where each key is the name of the parameter as it appears in the query. The exact syntax of the parameter itself may be different depending on your database, but all of the major relational databases support them in some form.

Assuming it's a SELECT query, this will return an iterable of RowProxy objects.

You can access individual columns with a variety of techniques:

for r in result:
    print(r[0]) # Access by positional index
    print(r['my_column']) # Access by column name as a string
    r_dict = dict(r.items()) # convert to dict keyed by column names

Personally, I prefer to convert the results into namedtuples:

from collections import namedtuple

Record = namedtuple('Record', result.keys())
records = [Record(*r) for r in result.fetchall()]
for r in records:
    print(r.my_column)
    print(r)

If you're not using the Flask-SQLAlchemy extension, you can still easily use a session:

import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session

engine = sqlalchemy.create_engine('my connection string')
Session = scoped_session(sessionmaker(bind=engine))

s = Session()
result = s.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
Discussions

How to execute raw SQL statements in a connection without using auto-commit mode?
Hi all, I am using mysql+aiomysql engine to manage my connection pool instead of aiomysql's native one. SQLAlchemy is much more powerful in this regard obviously, and I really like it. There ar... More on github.com
🌐 github.com
1
1
May 22, 2022
Is it possible to execute a literal/raw sql statement?
These are out of the control of sqlalchemy. exec_driver_sql as the name implies passes the string to the driver directly, so the same rules as when using the driver directly apply. More on github.com
🌐 github.com
2
1
Is it just me or are the docs for sqlalchemy a f*cking nightmare?
I used to think so as well until I read the Unified Tutorial they wrote for 2.0, which I found quite useful. But you have to actually read it... don't just skim it. More on reddit.com
🌐 r/Python
170
911
April 24, 2023
Raw SQL easier than sqlalchemy?
Personally, I’d rather write straight sql rather than an ORM. You have more control and SQL is more valuable to know. Also, ORM is typically slower to run. If your ORM has issues or is slow, you’re going to be going to SQL anyway to debug / fix the problem, and then you’ll need to reverse engineer your SQL solution back into ORM. The only big savings for ORMs is to save finger typing. I tend to get around this for SQL by using editor macros or writing a little program to generate the SQL and the calls to SQL. More on reddit.com
🌐 r/SQL
7
5
March 14, 2023
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 20 › core › connections.html
Working with Engines and Connections — SQLAlchemy 2.0 Documentation
For the above two SQLite PRAGMA statements, the badge reads [raw sql], which indicates the driver is sending a Python string directly to the database using Connection.exec_driver_sql().
🌐
ZetCode
zetcode.com › db › sqlalchemy › rawsql
Raw SQL in SQLAlchemy
With the connection's execute method, we deliver a simple SELECT SQL statement. ... With the fetchone method, we retrieve a single row. From this row, we get the scalar value. ... The value is printed to the console. ... We execute the script. In the next example, we connect to the PostgreSQL ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-execute-raw-sql-in-sqlalchemy
How to Execute Raw SQL in SQLAlchemy - GeeksforGeeks
February 28, 2022 - from sqlalchemy import text text("YOUR SQL QUERY") Pass the SQL query to the execute() function and get all the results using fetchall() function. Use a for loop to iterate through the results.
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-execute-raw-sql-in-flask-sqlalchemy-app
How to Execute Raw SQL in Flask – SQLAlchemy App | GeeksforGeeks
March 22, 2025 - execute_query API is used to execute raw SQL queries and will return the response message if the query is successfully executed or not. ... from flask import Flask, request from flask_sqlalchemy import SQLAlchemy # CREATE THE FLASK APP app = ...
Find elsewhere
🌐
Hexmos
hexmos.com › freedevtools › c › python › sqlalchemy
SQLAlchemy Text Module - Execute Raw SQL Cheatsheet | python Reference | Online Free DevTools
<sqlalchemy.engine.cursor.LegacyCursorResult object at 0x10106cf50> <sqlalchemy.engine.cursor.LegacyCursorResult object at 0x101ed0c50> Retrieve data from your database using a raw SQL SELECT statement executed via the connection object. >>> with engine.connect() as con: ... rs = con.execute('SELECT * FROM book') ... for row in rs: ... print(row) ... (1, 'Crushing It', 'Gary Vaynerchuck') (2, 'Start with Why', 'Simon Sinek') Explore these resources to deepen your understanding of SQLAlchemy and its capabilities: SQLAlchemy Official Documentation ·
🌐
EDUCBA
educba.com › home › data science › data science tutorials › sql tutorial › sqlalchemy raw sql
SQLAlchemy Raw SQL | How to Use SQLAlchemy Raw SQL?
March 16, 2023 - After that, we can call the connect() method with the help of an engine instance like eng.connect(). It will be called the separate variable called ‘a’, and then we can execute() the method by using the instance, and it will be stored on the separate variable like outs. Finally, we can retrieve and iterate the values using conditional loop statements like iterating them and printing them on the console screen. The sqlalchemy core is the central part and will calculate among the database schema and types. Next, it will be moved to the sql expression language, and then it will go forward to the engine.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
TheLinuxCode
thelinuxcode.com › home › how i execute raw sql in sqlalchemy in 2026: safe, fast, and maintainable patterns
How I Execute Raw SQL in SQLAlchemy in 2026: Safe, Fast, and Maintainable Patterns – TheLinuxCode
February 14, 2026 - In this guide, I show exactly how I run raw SQL with SQLAlchemy against PostgreSQL in a way that still feels clean in 2026 codebases. You will see table setup, parameterized SELECT and INSERT statements, transaction handling, result mapping, and performance habits that keep query latency predictable. I also call out common mistakes I see in reviews, especially around SQLAlchemy 2.0 execution patterns.
🌐
Medium
tomas-svojanovsky.medium.com › unlocking-the-power-of-sqlalchemy-using-raw-sql-queries-f951ade9dea8
Unlocking the Power of SQLAlchemy: Using Raw SQL Queries | by Tomas Svojanovsky | Medium
November 6, 2023 - With raw SQL, you have the flexibility to craft queries your way. Let’s begin with the util file, where we set up the connection. This also includes creating an .env file. from sqlalchemy import create_engine, MetaData from sqlalchemy.ext.declarative import declarative_base from dotenv import dotenv_values metadata = MetaData() Base = declarative_base() def db_connect(): config = dotenv_values(".env") username = config.get("DB_USERNAME") password = config.get("DB_PASSWORD") name = config.get("DB_NAME") port = config.get("DB_PORT") host = config.get("DB_HOST") return create_engine(f"postgresql+psycopg://{username}:{password}@{host}:{port}/{name}", echo=True)
🌐
PlanetScale
planetscale.com › blog › using-mysql-with-sql-alchemy-hands-on-examples
Using MySQL with SQLAlchemy: Hands-on Examples — PlanetScale
Anywhere that you'd use a SQL database along with Python, you can use SQLAlchemy. This tutorial will cover setting up an engine object in Python SQLAlchemy 2.0, which is the first step to using SQLAlchemy. Then, it will cover two specific ways of interacting with a database: with raw SQL statements and by using the object-relational mapper.
🌐
Sentry
sentry.io › sentry answers › flask › execute raw sql in flask-sqlalchemy application
Execute raw SQL in Flask-SQLAlchemy application | Sentry
March 15, 2024 - 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: from sqlalchemy import text query = text("SELECT name, ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-execute-raw-sql-in-flask-sqlalchemy-app
How to Execute Raw SQL in Flask - SQLAlchemy App - GeeksforGeeks
July 23, 2025 - execute_query API is used to execute raw SQL queries and will return the response message if the query is successfully executed or not. ... from flask import Flask, request from flask_sqlalchemy import SQLAlchemy # CREATE THE FLASK APP app = ...
🌐
SQLAlchemy
docs.sqlalchemy.org › en › 14 › core › tutorial.html
SQL Expression Language Tutorial (1.x API) — SQLAlchemy 1.4 Documentation
INSERT INTO addresses (user_id, email_address) VALUES (?, ?) [...] ((1, '[email protected]'), (1, '[email protected]'), (2, '[email protected]'), (2, '[email protected]')) COMMIT <sqlalchemy.engine.cursor.LegacyCursorResult object at 0x...> Above, we again relied upon SQLite’s automatic generation of primary key identifiers for each addresses row. When executing multiple sets of parameters, each dictionary must have the same set of keys; i.e.
🌐
Copdips
copdips.com › 2020 › 06 › compiling-sqlalchemy-query-to-nearly-real-raw-sql-query.html
Compiling SQLAlchemy query to nearly real raw sql query - A code to remember
June 8, 2020 - > render_query(filter1, session) "movies.release_date > '2015-01-01'" > render_query(query1, session) "SELECT movies.id, movies.title, movies.release_date \nFROM movies \nWHERE movies.release_date > '2015-01-01'\n LIMIT 2 OFFSET 0" ... With render_query(), it renders the query with dialect syntax, but please be aware that the values rendered are the ones translated by render_literal_value(), which might not be the ones really passed to SQL database. That's also why I named this post as nearly real raw sql query.