简体   繁体   中英

SQLAlchemy approximate count without making query

With PostgresSQL and MySQL databases I can use EXPLAIN in front of query and it will return me a query plan, which contains the approximate number of rows that query result will have. For PostresSql for example:

EXPLAIN SELECT * FROM foo WHERE i = 4;

                         QUERY PLAN
--------------------------------------------------------------
 Index Scan using fi on foo  (cost=0.00..5.98 rows=100 width=4)
   Index Cond: (i = 4)

This plan contains rows=100 which tells me that this query will return approximately 100 rows. For MS SQL Server I can use SET SHOWPLAN_XML ON , create a query and there is a number in the report that tells approximate numbers of rows.

I was looking if there is something similar in SQLAlchemy. I would like somehow get the number of rows (count) for any select query and it should be the same for any database (so writing a raw SQL is not the option). In SQLAlchemy I am using SQL Expression Language, not ORM.

So the question is how to write a Python function which gets the SQL Alchemy query (with type sqlalchemy.sql.selectable.Select ) at the input and returns the approximate number of rows for this query without making an actual query?

This function would look like this:

def count_approx(self, query):  # query type: sqlalchemy.sql.selectable.Select
    # how to get count?
    return count

An easy approach to get the aproximate number of rows of a table is to use the database system's catalogue (As far as I know, EXPLAIN uses the same).

For MySQL this would look like:

SELECT TABLE_ROWS 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'foo'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM