Skip to content
Advertisement

PostgreSQL dynamic query: find most recent timestamp of several unrelated tables

I have a number of tables, and many of them have a timestamp column. I can get a list of every table with a timestamp column:

I can get the hightest timestamp in the sharks table as follows

I would like to get a table like

I’m suspecting this requires dynamic SQL, so I’m trying something like

But it seems like EXECUTE doesn’t work in subqueries.

Performance is not particularly a concern, just producing the desired results.

Advertisement

Answer

Dynamic Queries cannot function outside of PL/pgSQL blocks, so you need to wrap your code in one.

I set up test tables similar to yours, with only the “timestamp” column shared between them:

Wrap a dynamic query in PL/pgSQL function. Inside I build a query to pull the max(timestamp) from each table with the column, then aggregate those into one query with a union all in between, that I later execute.

You can parametrise your function to be applicable to more groups of tables, or to have a predefined output table structure that’ll let you just select * from test_70099803();

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement