Check whether sqlalchemy table is empty

前端 未结 2 1472
长发绾君心
长发绾君心 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:29

    You can use-

        db.query(Table_Name).first()
    

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

    0 讨论(0)
  • 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 = <<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.

    0 讨论(0)
提交回复
热议问题