Sitemap
Better Programming

Advice for programmers.

Member-only story

How to Execute Plain SQL Queries With SQLAlchemy in Python

Learn a standard way to run SQL queries in Python

10 min readJan 22, 2022

--

Press enter or click to view image in full size
Image by WilliamsCreativity (Server Data) from Pixabay

There can be many cases where you don’t want to use the advanced Object Relational Mapper (ORM) features of SQLAlchemy and just want to execute plain SQL queries. This is common for legacy systems where plain queries are used everywhere. Besides, for data analysis-oriented projects, it’s also more common and more convenient to use plain SQL queries. For SQL queries with a lot of JOIN clauses and subqueries, it is much more straightforward to execute them directly than to translate them into complex ORM model-based code. Besides, we can store SQL queries in a file and then execute them with sqlparse and SQLAlchemy.

There are many tools that can be used to execute plain SQL queries in Python, such as PyMySQL, mysql-connector-python, MySQL-python, etc. However, it’s recommended to use SQLAlchemy to execute plain SQL queries. This is because SQLAlchemy is very versatile and can be used for all kinds of databases. Besides, even if you are reluctant to learn and use ORM models in your application now, you will very likely have the chance to read or write ORM code one day. Once you have learned how to use SQLAlchemy to execute plain SQL queries, it will be more straightforward for you to explore other features of SQLAlchemy, including the ORM…

--

--

Lynn G. Kwong
Lynn G. Kwong

Written by Lynn G. Kwong

I’m a Software Developer (https://lynn-kwong.medium.com/) keen on sharing thoughts, tutorials, and solutions for the best practice of software development.