0

I have a set of 4 tables that contain different partitions of some data. I also have a plpgsql function that will take an id and return the name of the table containing that data as a 'character varying'.

However, when I try to use this function to select from the correct table, e.g.

SELECT f.a FROM getTable(someID) AS f;

it doesn't seem to work. It doesn't throw an error on the SELECT, but it doesn't return the fields I'm expecting either (i.e. it says f.a doesn't exist).

How do I select data from a table where the table name is given by the return of a function?

I'm using PostgreSQL 9.1. This is going to be run over millions of records, so I don't want to have to do it as two separate calls.

1 Answer 1

2

I think for the problem described in the topic you should use inheritance with tables.

Answering the question - use execute:

execute "SELECT f.a FROM " || getTable(someID) || " AS f";
Sign up to request clarification or add additional context in comments.

4 Comments

I agree that using inheritance for this would be the way to go. But, when doing that you'll want to turn on the constraint_exclusion setting in postgresql.conf.
@qqx - to be precise, constraint_exclusion should be set to partition
It should be set to at least partition. on would also work, but may cause other queries to be slower. But I now see that partition is the default value for 9.1, that's changed since I last used partitioning.
I used inheritance in the end. I don't think execute would have worked because, and admittedly I didn't mention this, the SELECT was a nested SELECT.

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.