Skip to content
Advertisement

SQL selecting date by month and year but select another month/year rows by column relation

I have the following example in my database:

workshop_class_id workshop_session_id workshop_class_date
209 29 2021-06-20
210 29 2021-06-21
213 31 2021-06-30
211 30 2021-06-30
214 31 2021-07-01
212 30 2021-07-03
219 33 2021-07-12

I would like to select by month and year, for example June 2021, but if the rows have relation with workshop_session_id and even if the date it’s not in June 2021, I would like to have these rows.

In the example, I have two rows in July related with dates in June, only the row with the workshop_session_id 33 will be excluded.

I’m using PostgreSQL.

Advertisement

Answer

This way DB can use a possible index on workshop_class_date

SELECT *
FROM yourTable
WHERE workshop_session_id IN (
   SELECT t1.workshop_session_id 
   FROM yourTable t1 
   WHERE t1.workshop_class_date BETWEEN date '2021-06-01' AND date `2021-06-30`) ;
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement