Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether sqlalchemy table is empty

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

like image 758
scottmrogowski Avatar asked Apr 22 '14 01:04

scottmrogowski


2 Answers

You can use-

    db.query(Table_Name).first()

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

like image 54
M.A.K. Simanto Avatar answered Sep 24 '22 12:09

M.A.K. Simanto


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.

like image 2
David S Avatar answered Sep 24 '22 12:09

David S