0

I have a timescale db with multiple tables having the same structure.

I want to retrieve the recent row from each table where a value is true.

My logic is to

  1. retrieve all the tablenames for the tables where this condition can be true
  2. loop over list of tablenames and select the rows where the condition is met

I get an syntax error on the FOR loop but I expect that I do more things wrong.

Can someone suggest a solution please? Thank you in advance.

DECLARE
tablename text;
BEGIN
    FOR tablename IN
    SELECT table_name FROM information_schema.tables
    WHERE table_name LIKE 'ohlc%'
    LOOP
      SELECT WHERE tablename.is_active is TRUE
      ORDER BY time_stamp DESC
      Limit 1
    END LOOP;
END;
timmy
  • 468
  • 1
  • 6
  • 21
  • Hello, I don't have a direct answer for you but wanted to share this stream which might help you dig into the challenge you have, it's about getting the most recent value from tables https://youtu.be/HwJrmYJoIw4 *transparency: I work for Timescale* – greenweeds Mar 08 '22 at 10:47

1 Answers1

2

translate your problem

  1. find table that have specific column name in schema. How to find a table having a specific column in postgresql
  2. first condition meet then loop. Function to loop through and select data from multiple tables
  3. most tricky issue is quote_ident.

create or replace function test0()
returns table (_is_active boolean, id int) as
$$
declare tbl text;
begin
for tbl in
    select quote_ident( table_name)
    from information_schema.columns
    where table_schema = 'public'
    and table_name ilike 'ohlc%'
    and column_name = 'is_active'
    loop
        return query EXECUTE
        'select ' || quote_ident('is_active') || ' , ' || quote_ident('id') || ' from ' || tbl || ' where '|| quote_ident('is_active') ||' is true';
    end loop;
end
$$ language plpgsql;
jian
  • 4,119
  • 1
  • 17
  • 32
  • thank you, how do I get the results from this function? – timmy Mar 08 '22 at 12:36
  • got it, select * from test0(); – timmy Mar 08 '22 at 12:40
  • Please, could you edit your answer so the result table includes a column with name of the table that has is_active true – timmy Mar 08 '22 at 13:33
  • @timmy another column added. Hope it can help you. – jian Mar 08 '22 at 13:48
  • this throws an error: Number of returned columns (2) does not match expected column count (1). If I try to add a like this: returns table (symbol text, _is_active boolean) I get another error: Returned type boolean does not match expected type text in column 1. – timmy Mar 08 '22 at 14:07
  • my mistake. I edited it. let' say, all the table have two column is_active and id. Also id and is_active data type is consistent. – jian Mar 08 '22 at 14:09
  • @timmy. I add another column id. – jian Mar 08 '22 at 14:10