1

I have a series of tables partitioned by dates and named in the following format:

public.schedule_20121018

Is there a way to generate a sequence of dates in the above 20121018 pattern so that I can do a for loop SELECT through information_schema.tables?

For now I've got

SELECT * FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema = 'public'
AND table_name like 'schedule_%'
ORDER BY table_name;

But for instance I need the last 7 days' record so that a date sequence shall be starting from 20121012 to 20121018. Thanks!

2 Answers 2

3
SELECT *
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
    AND table_schema = 'public'
    AND table_name in (
        select 'schedule_' || to_char(d, 'YYYYMMDD')
        from 
        generate_series(current_date - 7, current_date - 1, '1 day') s(d)
        )
ORDER BY table_name;

Older Postgresql versions:

SELECT *
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
    AND table_schema = 'public'
    AND table_name in (
        select 'schedule_' || to_char(current_date - d, 'YYYYMMDD')
        from 
        generate_series(7, 1, -1) s(d)
        )
ORDER BY table_name;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Clodoaldo. I tried to_char but it gives ERROR: multiple decimal points for function "to_char". Have you tried it on your machine or should I use some other functions? I suspect it's I'm using a lower Postgresql version 8.2? Thanks!
@Rock Added a version for older postgresql versions.
Thanks a lot Clodoaldo. I figured it out in another way select regexp_replace((current_date + s.a), '-', '', 'g') as dates from generate_series(-7,-1,1) as s(a); but yours is much cleaner. Thanks!
2

Use generate_series, possibly with to_char for formatting.

regress=# select generate_series(DATE '20121012', DATE '20121018', interval '1' day);
    generate_series     
------------------------
 2012-10-12 00:00:00+08
 2012-10-13 00:00:00+08
 2012-10-14 00:00:00+08
 2012-10-15 00:00:00+08
 2012-10-16 00:00:00+08
 2012-10-17 00:00:00+08
 2012-10-18 00:00:00+08
(7 rows)

Comments

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.