By using db<>fiddle, you agree to license everything you submit by Creative Commons CC0.
Help with an interesting Postgres question: Why isn't an Index Only Scan used on a partition accessed via the parent table?.
CREATE TEMPORARY TABLE t1 (StudyIDA VARCHAR, gender VARCHAR, age int);
INSERT INTO t1 VALUES
('a','M', 1),('a','M', 2),('a','M', 3),
('b','F', 4),('b','F', 5),('b','F', 6),
('c','M', 13),('c','M', 14),('c','M', 15);
CREATE TEMPORARY TABLE t2 (StudyIDA VARCHAR, StudyIDB varchar, gender VARCHAR, age int);
INSERT INTO t2 VALUES
('a','z','M', 3), ('a','z','M', 4), ('a','z','M', 5),
(NULL,'y','F', 7),(NULL,'y','F', 8),(NULL,'y','F', 9),
('c','x','M', 10),('c','x','M', 11),('c','x','M', 12),
(NULL,'w','F', 7),(NULL,'w','F', 8),(NULL,'w','F', 9),
(NULL,'u','M', 7),(NULL,'u','M', 8),(NULL,'u','M', 9);
9 rows affected
15 rows affected
SELECT DISTINCT
COALESCE(t1.StudyIDA, t2.StudyIDA) AS StudyIDA
, t2.StudyIDB
, COALESCE(t1.gender, t2.gender) AS gender
, t1.age as ageA
, t2.age as ageB
FROM t1
FULL JOIN t2
ON t2.StudyIDA is not distinct from t1.StudyIDA
AND t2.gender = t1.gender
AND t2.age = t1.age
ORDER BY StudyIDA, gender, ageA, ageB;
studyida | studyidb | gender | agea | ageb |
---|---|---|---|---|
a | null | M | 1 | null |
a | null | M | 2 | null |
a | z | M | 3 | 3 |
a | z | M | null | 4 |
a | z | M | null | 5 |
b | null | F | 4 | null |
b | null | F | 5 | null |
b | null | F | 6 | null |
c | null | M | 13 | null |
c | null | M | 14 | null |
c | null | M | 15 | null |
c | x | M | null | 10 |
c | x | M | null | 11 |
c | x | M | null | 12 |
null | w | F | null | 7 |
null | y | F | null | 7 |
null | w | F | null | 8 |
null | y | F | null | 8 |
null | w | F | null | 9 |
null | y | F | null | 9 |
null | u | M | null | 7 |
null | u | M | null | 8 |
null | u | M | null | 9 |