SQLAlchemy optimization count () ...

Source: Internet
Author: User

A. Count () in SQLAlchemy

COUNT () Statistics are particularly slow:

Session.query (CLS). Count () 8W data cost nearly 50s

However, query directly in the database: SELECT COUNT (*) from TABLE_NAME. Spents only 0.738s

This difference makes people really strange.

Later in "1" saw the reason: The count() method is used to determine how many rows are returned in the result set, let us look at the resulting SQL statement, SQLAlchemy First Take out all the rows that meet the criteria , and then count the number of SELECT count(*) rows.

This is after iterating through all the database records, then select COUNT (*). It's scary, when the data is large, less than 100W is not big. Of course time is all spent on traversing the top.

We can func.count() use the Count function directly from an expression. -----This is the equivalent of the direct count () in the database

Session.query (Func.count (cls.id)). Scalar ()---Direct statistics primary key ID

Second, other optimization

-------2016-6-28 11:40:23---

Source: "1" sqlalchemy query

SQLAlchemy optimization count () ...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.