I have a PostgreSQL table with id_1, id_2, starttime and endtime, and I want to know the amount of entries, however, entries in a chain where the last entry is reachable by comparing starttime to endtime should be counted as one. Do you know how I could query that?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! This is a classic graph traversal problem that can be solved very elegantly in SQL.
Your description of a "chain" implies a directed graph where each row (id_1, id_2) represents a link from node id_1 to node id_2. You want to count the number of separate chains, which is equivalent to counting the starting points of these chains.
A row represents the start of a chain if its id_1 does not appear as an id_2 in any other row. If it did, it would be a continuation of another chain, not the beginning of one.
Here are a few ways to write this query in PostgreSQL, from most recommended to alternatives.
Sample Data
Let's imagine your table, which we'll call entry_chains, looks like this:
id_1
id_2
starttime
endtime
A
B
2023-01-01
2023-01-02
B
C
2023-01-03
2023-01-04
D
E
2023-02-10
2023-02-11
F
G
2023-03-15
2023-03-16
G
H
2023-03-17
2023-03-18
X
Y
2023-04-01
2023-04-02
In this data, we have three distinct chains:
A -> B -> C
D -> E
F -> G -> H
X -> Y
The starting points are A, D, F, and X. The query should return a count of 4.
Solution 1: Using NOT EXISTS (Recommended)
This is generally the most performant and robust method. It checks for the non-existence of a parent link for each id_1.
sql
SELECT COUNT(DISTINCT t1.id_1)
FROM entry_chains AS t1
WHERE NOT EXISTS (
SELECT 1
FROM entry_chains AS t2
WHERE t2.id_2 = t1.id_1
);
How it works:
FROM entry_chains AS t1: It iterates through each row in your table, aliased as t1.
WHERE NOT EXISTS (...): This is the crucial filter. For each row t1, it runs the subquery.
SELECT 1 FROM entry_chains AS t2 WHERE t2.id_2 = t1.id_1: The subquery looks for any row (t2) whose id_2 matches the current row's id_1.
If the subquery finds a match, it means t1.id_1 is an endpoint of another chain link, so it's not a starting point. EXISTS would be true, and NOT EXISTS becomes false, so this row is filtered out.
If the subquery finds no match, t1.id_1 is a true starting point. EXISTS is false, NOT EXISTS is true, and the row is kept.
COUNT(DISTINCT t1.id_1): Finally, it counts the unique starting IDs found. DISTINCT is important in case you have multiple rows starting from the same ID (e.g., (A, B) and (A, Z)).
Solution 2: Using a LEFT JOIN
This is another very common and intuitive way to solve the problem. It tries to join the table to itself to find "parent" entries.
sql
SELECT COUNT(DISTINCT t1.id_1)
FROM entry_chains AS t1
LEFT JOIN entry_chains AS t2 ON t1.id_1 = t2.id_2
WHERE t2.id_1 IS NULL;
How it works:
FROM entry_chains AS t1 LEFT JOIN entry_chains AS t2 ON t1.id_1 = t2.id_2: This attempts to find a "parent" (t2) for every "child" (t1) by matching the child's start (t1.id_1) with the parent's end (t2.id_2).
The LEFT JOIN ensures that all rows from t1 are kept, even if no matching parent is found in t2.
WHERE t2.id_1 IS NULL: If a row in t1 represents a true starting point, it has no parent. In this case, the LEFT JOIN will fail to find a match in t2, and all columns for t2 (including t2.id_1) will be NULL. This WHERE clause filters for exactly those rows.
COUNT(DISTINCT t1.id_1): As before, this counts the unique starting points.
Solution 3: Using NOT IN (Use with Caution)
This approach is often the most readable but has a major caveat.
sql
SELECT COUNT(DISTINCT id_1)
FROM entry_chains
WHERE id_1 NOT IN (
SELECT id_2 FROM entry_chains WHERE id_2 IS NOT NULL
);
How it works:
It first creates a set of all values that appear in the id_2 column (i.e., all endpoints).
Then, it counts the id_1 values that are not present in that set of endpoints.
⚠️ Important Caveat: Standard SQL's NOT IN behaves unexpectedly if the subquery returns any NULL values. If your id_2 column could contain NULL, the entire WHERE clause might evaluate to "unknown" and return zero rows. The WHERE id_2 IS NOT NULL in the subquery is a critical guard against this behavior. For this reason, NOT EXISTS or LEFT JOIN are generally safer and preferred.
What about Cycles?
The solutions above assume your chains have clear starting points. If your data can contain cycles (e.g., A -> B -> C -> A), none of the nodes in the cycle will be identified as a "start," and the entire cycle will not be counted.
If you need to count each cycle as a single entity, the problem becomes much more complex and requires a recursive query using a Common Table Expression (CTE) to traverse the graph and identify its connected components. If this is a possibility in your data, let me know, and I can provide a more advanced solution.