Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Is it possible to select from all tables inside the schema? I got all the table names from

select table_name from information_schema.tables

but I am unable to use it to do my query.

share|improve this question

1 Answer 1

You can't do it directly as one can not write a query where the table names are not known (ie. coming from some variable or subquery). But you can build and execute a dynamic SQL for this. For example, if you need the column 'name' from every table, you can do the following:

FOR i IN SELECT table_name FROM information_schema.tables
LOOP
    sql_string := sql_string || $$
        UNION
        SELECT name FROM i.table_name
    $$;
END LOOP;

EXECUTE sql_string;

In this form it won't work however, since you cannot SELECT in plpqsql unless you do it into a variable. You can either create a temporary table for this or loop over the results, depending on your needs.

Also a WHERE clause is needed in the FOR to determine which schema do you want to select from.

And, of course, this presumes that you want to select a single (or multiple, but always with the same name) columns from all the tables. If you simply need all the data from every table, then the tables must have the same structure (the same column types in the same order).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.