1

I have a table like

create table appointments
(
    id                  serial   not null constraint appointments_pkey           primary key,
    patient_id          varchar(255)                                   not null,
    date                timestamp(0)  not null 
);

I want to get date of next appointment and previous appointment in single query.

I created query as

 SELECT
        (
                    SELECT MIN(ap.date) FROM appointments ap
                    WHERE ap.date >= NOW() AND ap.patient_id = '1'
        ) AS next,
        (
                    SELECT MAX(ap.date) FROM appointments ap
                    WHERE ap.date < NOW() AND ap.patient_id = '1'
        ) AS last

which works as expected, but I think it is not optimized because two subqueries. Can you help me to optimize me such query,please?

2 Answers 2

4

you can use case when expression

select 
    min(case when ap.date >= NOW() then ap.date end) next,
    max(case when ap.date < NOW() then ap.date end) last
from appointments ap
where ap.patient_id = '1'
0

Your method is probably fine. I would more likely use union all for the purpose, though:

(SELECT ap.*
 FROM appointments ap
 WHERE ap.patient_id = 1 AND ap.date >= NOW()
 ORDER BY ap.date DESC
 FETCH FIRST 1 ROW ONLY
) UNION ALL
(SELECT ap.*
 FROM appointments ap
 WHERE ap.patient_id = 1 AND ap.date < NOW()
 ORDER BY ap.date ASC
 FETCH FIRST 1 ROW ONLY
) ;

This returns the entire rows, not just the dates.

Both this query and your can take advantage of an index on appointments(patient_id, date). Other solutions such as conditional aggregation and window functions probably are not going to take advantage of indexes so the entire table would need to be scanned.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.