Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8865929
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T16:39:03+00:00 2026-06-14T16:39:03+00:00

Select from great answer in How to find first free time in reservations table

  • 0

Select from great answer in How to find first free time in reservations table in PostgreSql

create table reservation (during tsrange,
 EXCLUDE USING gist (during WITH &&)
 );

is used to find gaps in schedule starting at given date and hour (2012-11-17 8: in sample below)
It finds saturday, sunday and public holidays also.
Public holidays are defined in table

create table pyha ( pyha date primary key)

How to exclude weekends and public holidays also?

Hard-coding free time as reserved to query like

with gaps as (
  select
    upper(during) as start,
    lead(lower(during),1,upper(during)) over (ORDER BY during) - upper(during) as gap
  from (
    select during
    from reservation
   union all values
     ('(,2012-11-17 8:)'::tsrange), -- given date and hour from which to find free work time
     ('[2012-11-17 0:,2012-11-18 24:)'::tsrange), -- exclude saturday
     ('[2012-11-18 0:,2012-11-19 8:)'::tsrange),  -- exclude sunday
     ('[2012-11-19 18:,2012-11-20 8:)'::tsrange),
     ('[2012-11-20 18:,2012-11-21 8:)'::tsrange),
     ('[2012-11-21 18:,2012-11-22 8:)'::tsrange),
     ('[2012-11-22 18:,2012-11-23 8:)'::tsrange),
     ('[2012-11-23 18:,2012-11-24 24:)'::tsrange),
     ('[2012-11-24 0:,2012-11-25 24:)'::tsrange), -- exclude saturday
     ('[2012-11-25 0:,2012-11-26 8:)'::tsrange)  -- exclude sunday
 ) as x
)
select *
  from gaps
where gap > '0'::interval
order by start

requires separate row in union for every free time range.

Which is best way to return free time in work days and work hours ( 8:00 .. 18:00 ) starting from given date and hour ?

Update

Select in answer returns free time at 8:00 always.
How to return free time not before specified start hour in specified start date, for example not before 2012-11-19 9:00 if start hour is 9 ?
Start hour may have only values 8,9,10,11,12,13,14,15,16 or 17

Even if 2012-11-19 8:00 if free it should return 2012-11-19 9:00.
It should return 8:00 only if there is no free time in 2012-11-19 at 9:00 and 8:00 is first free in succeeding work days.

I tried to fix this by adding 2012-11-19 9: to two places as shown in query below but this query still returns free time at 2012-11-19 8:00.
How to fix this so it returns free time at 2012-11-19 9:00 ?

create table reservation (during tsrange,
 EXCLUDE USING gist (during WITH &&)
 );
create table pyha ( pyha date primary key);
with gaps as (
    select
        upper(during) as start,
        lead(lower(during),1,upper(during)) over (ORDER BY during) - upper(during) as gap
    from (
        select during
          from reservation
             where upper(during)>= '2012-11-19 9:'
       union all values
         ('(,2012-11-19 9:)'::tsrange)
        union all
        select
            unnest(case
                when pyha is not null then array[tsrange(d, d + interval '1 day')]
                when date_part('dow', d) in (0, 6) then array[tsrange(d, d + interval '1 day')]
                else array[tsrange(d, d + interval '8 hours'),
                           tsrange(d + interval '18 hours', d + interval '1 day')]
            end)
        from generate_series(
            '2012-11-19'::timestamp without time zone,
            '2012-11-19'::timestamp without time zone+ interval '3 month',
            interval '1 day'
        ) as s(d)
        left join pyha on pyha = d::date
    ) as x
)

select start,
   date_part('epoch', gap) / (60*60) as hours
  from gaps
where gap > '0'::interval
order by start

Update2

I tried updated answer but it returns wrong data. Complete testcase is:

create temp table reservation  ( during tsrange ) on commit drop;
insert into reservation values(
'[2012-11-19 11:00:00,2012-11-19 11:30:00)'::tsrange );

with gaps as (
    select
        upper(during) as start,
        lead(lower(during),1,upper(during)) over (ORDER BY during) - upper(during) as gap
    from (
        select during
          from reservation
        union all
        select
            unnest(case
                when pyha is not null then array[tsrange(d, d + interval '1 day')]
                when date_part('dow', d) in (0, 6) then array[tsrange(d, d + interval '1 day')]
                when d::date =  DATE'2012-11-19' then array[
                            tsrange(d, '2012-11-19 12:'),  -- must return starting at 12:00
                            tsrange(d + interval '18 hours', d + interval '1 day')]
                else array[tsrange(d, d + interval '8 hours'), 
                           tsrange(d + interval '18 hours', d + interval '1 day')]
            end)
        from generate_series(
            DATE'2012-11-19'::timestamp without time zone,
            DATE'2012-11-19'::timestamp without time zone+ interval '3 month',
            interval '1 day'
        ) as s(d) 
        left join pyha on pyha = d::date
    ) as x 
)

select start,
   date_part('epoch', gap) / (60*60) as tunde
  from gaps 
where gap > '0'::interval
order by start

Observed first row:

"2012-11-19 11:30:00"

Expected :

"2012-11-19 12:00:00"

how to fix ?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T16:39:05+00:00Added an answer on June 14, 2026 at 4:39 pm

    You can use generate_series() function in order to mask-out non business hours:

    with gaps as (
        select
            upper(during) as start,
            lead(lower(during),1,upper(during)) over (ORDER BY during) - upper(during) as gap
        from (
            select during
            from reservation
            union all
            select
                unnest(case
                    when pyha is not null then array[tsrange(d, d + interval '1 day')]
                    when date_part('dow', d) in (0, 6) then array[tsrange(d, d + interval '1 day')]
                    when d::date = '2012-11-14' then array[tsrange(d, d + interval '9 hours'), tsrange(d + interval '18 hours', d + interval '1 day')]
                    else array[tsrange(d, d + interval '8 hours'), tsrange(d + interval '18 hours', d + interval '1 day')]
                end)
            from generate_series(
                '2012-11-14'::timestamp without time zone, 
                '2012-11-14'::timestamp without time zone + interval '2 week', 
                interval '1 day'
            ) as s(d) 
            left join pyha on pyha = d::date
        ) as x 
    )
    select *
        from gaps
    where gap > '0'::interval
    order by start
    

    Let me explain some tricky parts:

    • you dont have to insert dates for sat/sun into pyha table because you can use date_part('dow', d) function. Use pyha table for public holidays only. ‘dow’ returns 0 or 6 for Sun or Sat respectively.
    • public holidays and sat/sun can be represented as single interval (0..24). Weekdays have to be represented by two intervals (0..8) and (18..24) hence unnest() and array[]
    • you can specify start date and length in generate_series() function

    Based on your update to the question I added another when to case:

    when d::date = '2012-11-14' then array[tsrange(d, d + interval '9 hours'), tsrange(d + interval '18 hours', d + interval '1 day')]
    

    The idea is to produce different interval(s) for starting date (d::date = '2012-11-14'): (0..9) and (18..24)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

select * from FOO.MBR_DETAILS where BAR= 'BAZ' and MBR_No = '123' execution time =
I want to select a bunch of data from a table using a GROUP
I am trying to create T-SQL function from Northwind to return new table, that
SELECT * From `users` AS `User` LEFT JOIN `selections` AS `Selections` ON (`Selections`.`user_id` =
SELECT * FROM list WHERE list_item LIKE %_1375_% returns results it should not. For
SELECT * FROM tbl_transaction t LEFT JOIN tbl_transaction_hsbc ht ON t.transactionid = ht.transactionid transactionid
SELECT * FROM menu WHERE item_id = 1 OR item_id = 2 OR item_id
SELECT * FROM myTable WHERE field1 LIKE 'match0' AND myfunc(t1.hardwareConfig) LIKE 'match1' Here is
SELECT * FROM ExternalQuestionKeyword INNER JOIN ExternalKeywords ON ExternalKeywords.ID=ExternalQuestionKeyword.KeywordID WHERE QuestionID = 17
SELECT * FROM tbl_group_join tgj LEFT JOIN tbl_groups tg ON tg.group_id = tgj.group_id LEFT

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.