9

I wanted to write a Postgres function to loop through a bunch of tables and perform the same procedure on them. The tables are selected by the table name, starts with dmt_. The procedure I want to do on each table is pretty simple, just get the number of latest records in last few days. The problem how to get the tables with matching table name.

1
  • See here or here Commented Dec 10, 2017 at 20:07

4 Answers 4

12

You can query information_schema for this.

SELECT table_schema, table_name 
FROM information_schema.tables 
WHERE table_name ~ '^dmt_'`

Once you have the schema & name, you can manipulate them as required in plpgsql or other procedural languages.

Sign up to request clarification or add additional context in comments.

1 Comment

I have for tb in SELECT * FROM information_schema.tables WHERE table_name ~ '^dmt_mas' loop in my function and got the error loop variable of loop over rows must be a record or row variable or list of scalar variables at tb, tried like dmt%` and same error
1

You can also feed the output of table names to the grep if you are using linux:

psql -d database_name -c "\d" | grep "some_pattern"

Comments

0

This works for me

psql -Uyourusername  yourdb -h yourhost -p 5432 -c '\dt dmt_*'

ie. the command

\dt dmt_*

Comments

-1
SELECT
     relname as table_name, n_live_tup as row_count
FROM
    pg_stat_user_tables
ORDER BY
    n_live_tup DESC;

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.