8

PostgreSQL have aggregate expressions, e.g. count(*) FILTER (WHERE state = 'success'). How can I generate such expressions using SQLAlchemy?

2
  • @IljaEverilä Completely different topic. That's about aggregate functions, and this is about aggregate expressions. Commented Nov 16, 2017 at 8:16
  • I'd not go so far as to say completely different, but here's a better dupe candidate: stackoverflow.com/questions/46167101/…, also mentioned here. The relevant documentation: funcfilter() and FunctionElement.filter(). Commented Nov 16, 2017 at 8:18

1 Answer 1

15

Suppose I have a model Machine with a boolean field active, and would like to filter the count by active = true

Using func.count(...).filter(...)

from models import db, Machine
from sqlalchemy.sql import func

query = db.session.query(
    func.count(Machine.id).filter(Machine.active == True)
    .label('active_machines')
)

We can look at the generated SQL query:

>>> print(query)
SELECT count(machine.id) FILTER (WHERE machine.active = true) AS active_machines 
FROM machine

This should work the same for the other aggregate functions like func.avg, func.sum, etc

Longer syntax using funcfilter(count(...), filter)

func.count(Machine.id).filter(Machine.active == True) is short hand for:

from sqlalchemy import funcfilter

funcfilter(func.count(Machine.id), Machine.active == True)
Sign up to request clarification or add additional context in comments.

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.