The easiest option is to create a function that:
- Selects all the names of the matching tables;
- Checks how many entries are in the table;
- Deletes empty.
For example:
CREATE OR REPLACE FUNCTION remove_tmp_123() RETURNS integer AS $BODY$ DECLARE check_table varchar; count_rows integer; removed_tables integer; BEGIN removed_tables := 0; FOR check_table IN SELECT table_name FROM information_schema.tables where 1=1 and table_catalog = 'you_db_name' and table_type = 'BASE TABLE' and table_name ilike 'tmp_123%' LOOP execute format('SELECT COUNT(*) from %I ;', check_table) into count_rows; IF (count_rows = 0) then execute format('DROP TABLE %I ;', check_table); removed_tables := removed_tables + 1; end IF; END LOOP; RETURN removed_tables; END; $BODY$ LANGUAGE plpgsql;
Check:
# create table tmp_123 (name varchar); CREATE TABLE Time: 99,390 ms # create table tmp_123534 (name varchar); CREATE TABLE Time: 120,950 ms # create table tmp_12325t343 (name varchar); CREATE TABLE Time: 62,786 ms # insert into tmp_123534(name) values ('1234546'); INSERT 0 1 Time: 21,371 ms =# select remove_tmp_123(); remove_tmp_123 ---------------- 2 (1 row) # SELECT table_name FROM information_schema.tables where 1=1 and table_catalog = 'you_db_name' and table_type = 'BASE TABLE' and table_name ilike 'tmp_123%' ; table_name ------------ tmp_123534 (1 row)