Check whether sqlalchemy table is empty

前端 未结 2 1471
长发绾君心
长发绾君心 2021-01-13 05:12

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 al

2条回答
  •  囚心锁ツ
    2021-01-13 05:45

    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 = <> 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 <> LIMIT 1;
    

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

提交回复
热议问题