7

How can I do the following SQL query using SQLAlchemy?

SELECT COUNT (*)
FROM det_factura
WHERE company = 31
  AND date::text LIKE '2011-05% ';
1
  • What SQL backend are you using? Commented Jan 15, 2012 at 21:54

1 Answer 1

8

If det_factura is also a mapped object, then this query should do it:

qry = (session.query(func.count(det_factura.id))
        .filter(det_factura.company==31)
        .filter(det_factura.date.like('2010-05%'))
        )

If it is a table instance, the one below should work:

qry = select([func.count(det_factura.id)],
        and_(det_factura.company==31,
             det_factura.date.like('2010-05%')
            )
        )
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. SQLSoup I'm working with, as I adapt this code to sqlsoup.
hmm.. but what if you don't have an id field? how do you simply get "count(*)", possibly in the presence of other things in select list (so you cant use sqlalchemy .count())?
@shaunc: You can always do func.count('*') to get a COUNT(*) SQL expression.

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.