salamey salamey - 3 months ago 20
Python Question

sqlalchemy IS NOT NULL select

How can I add the filter as in SQL to select values that are NOT NULL from a certain column ?

SELECT *
FROM table
WHERE YourColumn IS NOT NULL;


How can I do the same with SQLAlchemy filters?

select = select(table).select_from(table).where(all_filters)

Answer

column_obj != None will produce a IS NOT NULL constraint:

In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

Demo:

>>> from sqlalchemy.sql import column
>>> column('YourColumn') != None
<sqlalchemy.sql.elements.BinaryExpression object at 0x10c8d8b90>
>>> str(column('YourColumn') != None)
'"YourColumn" IS NOT NULL'