Home > Database > Mysql Tutorial > How to Correctly Find Overlapping Date Ranges in PostgreSQL Queries?

How to Correctly Find Overlapping Date Ranges in PostgreSQL Queries?

Susan Sarandon
Release: 2025-01-05 00:32:39
Original
525 people have browsed it

How to Correctly Find Overlapping Date Ranges in PostgreSQL Queries?

Finding Overlapping Date Ranges in PostgreSQL

Problem:

Your query for finding players on a team in specific years appears to be incorrect. Correct the query and provide the missing details.

Incorrect Query:

SELECT *
FROM contract
JOIN team USING (name_team)
JOIN player USING(name_player)
WHERE name_team = ?
AND DATE_PART('YEAR',date_join) >= ?
AND DATE_PART('YEAR',date_leave) <= ?
Copy after login

Cause:

The query does not find overlapping date ranges because the BETWEEN operator is used incorrectly. The upper bound should be excluded for proper comparison.

Proper Answer:

Basic Query:

SELECT p.*
FROM team AS t
JOIN contract AS c USING (name_team)
JOIN player AS p USING (name_player)
WHERE t.name_team = ?
AND c.date_join < date '2010-01-01'
AND c.date_leave >= date '2009-01-01';
Copy after login

Refined Query with Distinct and NULL Handling:

SELECT DISTINCT p.*
FROM contract AS c
JOIN player AS p USING (name_player)
WHERE c.name_team = ?
AND c.date_join < date '2010-01-01'
AND (c.date_leave >= date '2009-01-01' OR c.date_leave IS NULL);
Copy after login

Using the OVERLAPS Operator:

SELECT DISTINCT name_player
FROM contract
WHERE name_team = ?
AND (date_join, COALESCE(date_leave, CURRENT_DATE)) OVERLAPS
(date '2009-01-01', date '2010-01-01');
Copy after login

Using Range Types and Index Support:

SELECT DISTINCT name_player
FROM contract
WHERE name_team = ?
AND daterange(date_join, date_leave) &&&
daterange '[2009-01-01,2010-01-01)';
Copy after login

Remember to replace the '?' placeholders with the necessary values in your queries.

The above is the detailed content of How to Correctly Find Overlapping Date Ranges in PostgreSQL Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template