close

How to make a subquery in sqlalchemy

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to make a subquery in sqlalchemy in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to make a subquery in sqlalchemy?

  1. How to make a subquery in sqlalchemy?

    I just wanted to add, that if you are using this method to update your DB, make sure you add the synchronize_session='fetch' kwarg.

  2. make a subquery in sqlalchemy

    I just wanted to add, that if you are using this method to update your DB, make sure you add the synchronize_session='fetch' kwarg.

Method 1

You can create subquery with subquery method

subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).filter(Residents.apartment_id.in_(subquery))

Method 2

I just wanted to add, that if you are using this method to update your DB, make sure you add the synchronize_session='fetch' kwarg. So it will look something like:

subquery = session.query(Apartments.id).filter(Apartments.postcode==2000).subquery()
query = session.query(Residents).\
          filter(Residents.apartment_id.in_(subquery)).\
          update({"key": value}, synchronize_session='fetch')

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read