JOIN on TRUE
In 015-sql-joins - sometimes tables should be joined just to give results from multiple tables in the same output without any joining key.
Explanation:
-
FULL OUTER JOIN
:- Combines all rows from both
hire_gaps
andfire_gaps
. - If a row from
hire_gaps
has no matching row infire_gaps
, the result will include the row fromhire_gaps
withNULL
values for thefire_gaps
columns, and vice versa. - Ensures all data from both
hire_gaps
andfire_gaps
is considered, even if one of the CTEs (Common Table Expressions) is empty (e.g., no hires or no terminations).
- Combines all rows from both
-
ON TRUE
:- A join condition that is always true. This means every row from
hire_gaps
is paired with every row fromfire_gaps
(a Cartesian product), but since we’re only aggregating (MAX()
), no duplication occurs. - This approach avoids filtering or matching specific rows because the gaps are independent metrics.
- A join condition that is always true. This means every row from
-
Why Use
FULL OUTER JOIN ON TRUE
?:- To ensure that both
hire_gaps
andfire_gaps
contribute to the final result, even if one of them is empty. - For example:
- If no employees were fired (
fire_gaps
is empty), we still want to return the maximum hiring gap (hire_gaps
). - If no employees were hired (
hire_gaps
is empty), we still want to return the maximum firing gap (fire_gaps
).
- If no employees were fired (
- To ensure that both
-
Effect in the Query:
- The
FULL OUTER JOIN ON TRUE
effectively combines bothhire_gaps
andfire_gaps
, ensuring we computeMAX()
for both gaps even if one CTE has no rows.
- The