0

I have two raw Postgresql statements.

q1 = "SELECT name FROM table_a"
q2 = "SELECT name FROM table_b"

How can I query the intersection of them using SQLAlchemy.

1 Answer 1

1

This is more or less what you could do:

from sqlalchemy import create_engine, text
engine = create_engine('postgresql://user:password@localhost/somedb')
q1 = "SELECT name FROM table_a intersect SELECT name FROM table_b"
q1res = engine.execute(text(q1)).fetchall()
# or
q2res = engine.execute(text(q1)).fetchone()

Depending on your needs. Ditch fetchone and fetchall if you intend to make inserts or updates.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd like to be able to generate the SQL statement that includes the INTERSECT inside the query, and execute it that way, rather than fetching all the results from both and having python deal with intersects.
Well since you are performing raw queries, simply add an intersection. I've updated the answer. Also you could have a look at sqlalchemy's orm which is extremely powerful: here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.