Skip to content

Instantly share code, notes, and snippets.

@grant-humphries
Last active August 1, 2023 08:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grant-humphries/d419b75e3f1c54799f09d8b855568818 to your computer and use it in GitHub Desktop.
Save grant-humphries/d419b75e3f1c54799f09d8b855568818 to your computer and use it in GitHub Desktop.
SQLAlchemy where exists example

This python:

lg = LocationGroup
lgl1 = LocationGroupLocation
lgl2 = aliased(LocationGroupLocation)

sub_q1 = (
    self.db_session.query(lg).
    filter(lg.location_group_type_id == 2,
           lg.location_group_id == lgl1.location_group_id)
)

q1 = (
    self.db_session.query(
        lgl1.location_id,
        lgl2.location_id.label('sister_station')).
    join(lgl2, lgl1.location_group_id == lgl2.location_group_id).
    filter(
        lgl1.location_id != lgl2.location_id,
        sub_q1.exists())
)

Is equivalent to this SQL:

select lgl1.location_id, lgl2.location_id as sister_station
from location_group_location lgl1, location_group_location lgl2
where lgl1.location_group_id = lgl2.location_group_id
    and lgl1.location_id != lgl2.location_id
    and exists (
        select null
        from location_group lg
        where lg.location_group_id = lgl1.location_group_id
            and lg.location_group_type_id = 2)
order by lgl1.location_id;
@ansarisufiyan777
Copy link

Thanks worked like a charm.

@rafa761
Copy link

rafa761 commented May 13, 2021

Thanks, it helped a lot

@onlyCh
Copy link

onlyCh commented Aug 5, 2022

3Q

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment