Skip to content
Advertisement

Optimising filtering multiple SQL count sub queries with SQLAlchemy

I’m trying to convert raw postgres-SQL into sqlalchemy which uses a count and filter

This works great and is very fast (sub 100ms – even when filtering 20 fields)

I’ve written the sqlalchemy as (simplified)

This produces the following SQL

This works but is quite slow (+1 second). I’m not sure why it’s so slow or how to do a filter query on the sub queries.

I suspect the COUNT is being performed on each sub query where the SQL uses the filtered results from the final WHERE condition, but I’m not totally sure and I can’t find any reference to filter (which I think it shorthand for CASE?) in the sqlalchemy docs. I’ve tried adding .filter(user_model.uuid==uuid) to the COUNT SQL but it is still slow.

Would anyone be able to offer an insight into what I’m missing?

Advertisement

Answer

I eventually did this using CASE

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement