Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
SQLAlchemy ORM conversion to Pandas DataFrame
Next article icon

SQLAlchemy ORM conversion to Pandas DataFrame

Last Updated : 22 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to convert an SQLAlchemy ORM to Pandas DataFrame using Python.

We need to have the sqlalchemy as well as the pandas library installed in the python environment -

$ pip install sqlalchemy $ pip install pandas

For our example, we will make use of the MySQL database where we have already created a table named students. You are free to use any database but you need to accordingly create its connection string. The raw SQL script for reference for this example is provided below:

CREATE DATABASE Geeks4Geeks; USE Geeks4Geeks;  CREATE TABLE students (     first_name VARCHAR(50),     last_name VARCHAR(50),     course VARCHAR(50),     score FLOAT );  INSERT INTO students VALUES ('Ashish', 'Mysterio', 'Statistics', 96), ('Rahul', 'Kumar', 'Statistics', 83), ('Irfan', 'Malik', 'Statistics', 66), ('Irfan', 'Ahmed', 'Statistics', 81), ('John', 'Wick', 'Statistics', 77), ('Mayon', 'Irani', 'Statistics', 55), ('Ashish', 'Mysterio', 'Sociology', 85), ('Rahul', 'Kumar', 'Sociology', 78), ('Irfan', 'Malik', 'Biology', 92), ('Irfan', 'Ahmed', 'Chemistry', 45), ('John', 'Wick', 'Biology', 78), ('Mayon', 'Irani', 'Physics', 78);  SELECT * FROM students;

The syntax for converting the SQLAlchemy ORM to a pandas dataframe is the same as you would do for a raw SQL query, given below -

Syntax: pandas.read_sql(sql, con, **kwargs)

Where:

  • sql: The SELECT SQL statement to be executed
  • con: SQLAlchemy engine object to establish a connection to the database

Please note that you can also use pandas.read_sql_query() instead of pandas.read_sql()

Example 1:

In the above example, we can see that the sql parameter of the pandas.read_sql() method takes in the SQLAlchemy ORM query as we may have defined it without the pandas dataframe conversion. The db.select() will get converted to raw SQL query when read by the read_sql() method. In the output, we have also printed the type of the response object. The output is a pandas DataFrame object where we have fetched all the records present in the student's table.

Python3
import pandas import sqlalchemy as db from sqlalchemy.ext.declarative import declarative_base  Base = declarative_base()  # DEFINE THE ENGINE (CONNECTION OBJECT) engine = db.create_engine("mysql+pymysql:\ //root:password@localhost/Geeks4Geeks")  # CREATE THE TABLE MODEL TO USE IT FOR QUERYING class Students(Base):      __tablename__ = 'students'      first_name = db.Column(db.String(50),                            primary_key=True)     last_name  = db.Column(db.String(50),                            primary_key=True)     course     = db.Column(db.String(50))     score      = db.Column(db.Float)  # SQLAlCHEMY ORM QUERY TO FETCH ALL RECORDS df = pandas.read_sql_query(     sql = db.select([Students.first_name,                      Students.last_name,                       Students.course,                      Students.score]),     con = engine )  print("Type:", type(df)) print() print(df) 

Output:

Example 2:

In this example, we have used the session object to bind the connection engine. We have also applied a filter() method which is equivalent to the WHERE clause in SQL. It consists of the condition that the picked records should contain the first name and the last name of those students who have a score of greater than 80. One thing worth noting here is that, for the queries build using the session object, we need to use the statement attribute to explicitly convert into a raw SQL query. This is required because without the statement attribute, it will be a sqlalchemy.orm.query.Query object which cannot be executed by the pandas.read_sql() method and you will get a sqlalchemy.exc.ObjectNotExecutableError error. The above output shows the type of object which is a pandas DataFrame along with the response.

Python3
import pandas import sqlalchemy as db from sqlalchemy.ext.declarative import declarative_base  Base = declarative_base()  # DEFINE THE ENGINE (CONNECTION OBJECT) engine = db.create_engine("mysql+pymysql:\ //root:password@localhost/Geeks4Geeks")  # CREATE THE TABLE MODEL TO USE IT FOR QUERYING class Students(Base):      __tablename__ = 'students'      first_name = db.Column(db.String(50),                             primary_key=True)     last_name  = db.Column(db.String(50),                            primary_key=True)     course     = db.Column(db.String(50))     score      = db.Column(db.Float)  # CREATE A SESSION OBJECT TO INITIATE QUERY IN DATABASE from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) session = Session()  # SQLAlCHEMY ORM QUERY TO FETCH ALL RECORDS df = pandas.read_sql_query(     sql = session.query(Students.first_name,                          Students.last_name).filter(       Students.score > 80).statement,     con = engine )  print("Type:", type(df)) print() print(df) 

Output:


Next Article
SQLAlchemy ORM conversion to Pandas DataFrame

A

apathak092
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    Converting Django QuerySet to Pandas DataFrame
    Django's ORM provides a powerful way to query databases and retrieve data using QuerySet objects. However, there are times when you may need to manipulate, analyze, or visualize this data in a more sophisticated way than what Django alone can offer. In such cases, pandas, a popular data manipulation
    5 min read
    Connecting Pandas to a Database with SQLAlchemy
    In this article, we will discuss how to connect pandas to a database and perform database operations using SQLAlchemy. The first step is to establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = crea
    3 min read
    How to Convert Pandas to PySpark DataFrame ?
    In this article, we will learn How to Convert Pandas to PySpark DataFrame. Sometimes we will get csv, xlsx, etc. format data, and we have to store it in PySpark DataFrame and that can be done by loading data in Pandas then converted PySpark DataFrame. For conversion, we pass the Pandas dataframe int
    3 min read
    Create a SQL table from Pandas dataframe using SQLAlchemy
    In this article, we will discuss how to create a SQL table from Pandas dataframe using SQLAlchemy. As the first steps establish a connection with your existing database, using the create_engine() function of SQLAlchemy. Syntax: from sqlalchemy import create_engine engine = create_engine(dialect+driv
    3 min read
    Converting Pandas Dataframe To Dask Dataframe
    In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences