100

how do i convert the following mysql query to sqlalchemy?

SELECT * FROM `table_a` ta, `table_b` tb where 1
AND ta.id = tb.id
AND ta.id not in (select id from `table_c`)

so far i have this for sqlalchemy:

query = session.query(table_a, table_b)
query = query.filter(table_a.id == table_b.id)
3
  • I had some weird issue using in_(1,2,3).. I got: 'ColumnOperators.in_() takes 2 positional arguments but 4 were given', so I changed to between(1,3) instead and it worked.. In my scenario I had two in_ clauses within an and_ clause too - not sure if that combo causes odd message in SQLAlchemy 1.4.41. Commented Feb 29, 2024 at 14:07
  • @JGFMK, in your case you just missed the parentheses (or brackets, etc.). in_ requires an iterable, e.g. in_([1,2,3]) Commented Nov 30, 2024 at 10:18
  • @foske - ah that makes sense - a Python list syntax. Commented Dec 2, 2024 at 9:50

3 Answers 3

129

The ORM internals describe the not_in() operator (previously notin_()), so you can say:

query = query.filter(table_a.id.not_in(subquery))
#                               ^^^^^^

From the docs:

inherited from the ColumnOperators.not_in() method of ColumnOperators

implement the NOT IN operator.

This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

Note that version 1.4 states:

The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

So you may find notin_() in some cases.

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

3 Comments

This also works with a simple list in place of subquery. I.e. notin_([42, 43, 44, 45])
Renamed to not_in() in 1.4. docs.sqlalchemy.org/en/14/core/…
Version 1.3.6 notin_() works!!
81

Try this:

subquery = session.query(table_c.id)
query = query.filter(~table_a.id.in_(subquery))

Note: table_a, table_b and table_c should be mapped classes, not Table instances.

5 Comments

hello. how do i join table_a and table_b in this example?
I assume, that query is query object that you showed above.
ohh ok now i get it. initially i was lost because i thought the example was not for join table.
this also works query = query.filter(table_a.id.notin_(subquery))
What if the element is None ?
19

here is the full code:

#join table_a and table_b
query = session.query(table_a, table_b)
query = query.filter(table_a.id == table_b.id)

# create subquery
subquery = session.query(table_c.id)
# select all from table_a not in subquery
query = query.filter(~table_a.id.in_(subquery))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.