Lukasz Lukasz - 2 months ago 6
SQL Question

Find records with overlapping date range in SQL

I have following table and data:

CREATE TABLE customer_wer(
id_customer NUMBER,
name VARCHAR2(10),
surname VARCHAR2(20),
date_from DATE,
date_to DATE NOT NULL,
CONSTRAINT customer_wer_pk PRIMARY KEY (id_customer, data_from));

INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-JAN-00', '31-MAR-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-APR-00', '30-JUN-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '15-JUN-00', '30-SEP-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-OCT-00', '31-DEC-00');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-JAN-01', '31-MAR-01');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-APR-01', '30-JUN-01');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-JUL-01', '5-OCT-01');
INSERT INTO customer_wer VALUES (4, 'Karolina', 'Komuda', '01-OCT-01', '31-DEC-01');


I need a
SELECT
query to find the records with overlapping dates. It means that in the example above, I should have four records in result

number
2
3
7
8


Thank you in advance.
I am using Oracle DB.

Answer

Try this:

select * from t t1
join t t2 on (t1.datefrom > t2.datefrom and t1.datefrom < t2.dateto)
          or (t1.dateto > t2.datefrom and t1.dateto < t2.dateto)

Thank You for this example. After modification it is working:

SELECT *
FROM customer_wer k
JOIN customer_wer w
ON k.id_customer = w.id_customer
WHERE (k.date_from > w.date_to AND k.date_from < w.date_to)
OR (k.date_to > w.date_from AND k.date_to < w.date_to);