Question

I need to know whether any given sqlalchemy table (sqlalchemy.schema.Table) has exactly 0 rows. I have a lot of tables with a lot of rows in each and this has to run for all of them at startup so I am looking for the most efficient way to do this from a runtime perspective. So, just doing a count is not what I am looking for. The database is PostgreSQL if that changes anything

Was it helpful?

Solution 2

SQLAlchemy will allow you to do a "raw" query. In PostgreSQL, you can query the meta data for n_live_tup to get the record count:

SELECT 
  schemaname as schema_name,
  relname as table_name, 
  n_live_tup as record_count 
FROM pg_stat_user_tables WHERE n_live_tup > 0;

obviously, this gives you all of the tables with live records. If you only want the ones without, change the to WHERE n_live_tup = 0 and if you want to limit it to only a certain table add table_name = <<your_table_name>> to the where clause.

If you don't have a role with permissions, and you just want to see if the table is empty, then you can alway do this:

SELECT True FROM <<your_table_name>> LIMIT 1;

This will return True if the table has records or NULL if it doesn't.

OTHER TIPS

You can use-

    db.query(Table_Name).first()

where db is sessionmaker() object. Thanks @David S

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top