2

In my postgres DB, I Have some tables which their names vary based on the current date.

To be more specific their names are like these:

STATSDATA15_8_2019
STATSDATA14_8_2019
STATSDATA13_8_2019
...

I need an automated query that considering the current date, grabs data from the related table.

For example:

If the date is August 15th, I need:

select * from STATSDATA15_8_2019

And if it is August 14th, I need:

select * from STATSDATA14_8_2019

In fact i need an automated, dynamic query with variables.

1
  • 2
    you should create a partitioned table instead. Commented Aug 15, 2019 at 11:49

1 Answer 1

1

Disclaimer: I really would recommend to follow the advice of @a_horse_with_no_name creating a partitioned table!


In case that you would stay with your design, you could use a function which dynamically creates the query out of a format string.

This, of course, only works if all of your tables have the same structure.

demo:db<>fiddle

CREATE OR REPLACE FUNCTION select_table_by_date(the_date date) RETURNS TABLE(content text)
LANGUAGE plpgsql
AS $$
    BEGIN
        RETURN QUERY 
             EXECUTE format(
                 'SELECT * FROM statsdata%s', 
                 to_char(the_date, 'DD_FMMM_YYYY')
             );
    END;
$$;

SELECT * FROM select_table_by_date('2019-08-15'::date);

SELECT * FROM select_table_by_date(CURRENT_DATE);
Sign up to request clarification or add additional context in comments.

2 Comments

Dear S-Man Really appreciate your helpful answer. But i made a mistake about the tables' naming convention. They are actually like this: STATSDATA8_7_2019 , STATSDATA8_9_2019 , STATSDATA8_10_2019 , STATSDATA8_15_2019 , I'd be extremely grateful if you revise your answer based on this modification to solve my problem. tnx a lot
Just change the date format string to 'FMMM-FMDD-YYYY'

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.