'Filter rows from table 1 with table 2 info

I have 2 tables. One table listing results of a run and a 2nd table with timestamps.

table1 (not sure how to add another column to the table but table 1 has an end time also that will need to be filtered out):

Tenant start
x 2022-05-01 23:00:00
x 2022-05-02 02:00:00
x 2022-05-02 06:00:00

table 2:

start end
2022-05-01 23:00:00 2022-05-02 03:00:00

The goal is to filter out/ exlude rows from table 1 that fall in between start/end time from table 2.

The results should be :

Tenant start
x 2022-05-02 06:00:00

I tried doing below:

select *
from table 1
where start not in (select start from table 2)

But does not seem to work correctly.



Solution 1:[1]

Using exists logic we can try:

SELECT t1.*
FROM table1 t1
WHERE NOT EXISTS (
    SELECT 1
    FROM table2 t2
    WHERE t1.start BETWEEN t2.start AND t2.end
);

For your updated requirement, we could select an exists boolean expression:

SELECT t1.*, NOT EXISTS (
    SELECT 1
    FROM table2 t2
    WHERE t1.start BETWEEN t2.start AND t2.end
) AS mw
FROM table1 t1;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1