Skip to content

Instantly share code, notes, and snippets.

@djtango
Created January 21, 2019 11:25
Show Gist options
  • Save djtango/73d16bacc144434df7072fd753e583a5 to your computer and use it in GitHub Desktop.
Save djtango/73d16bacc144434df7072fd753e583a5 to your computer and use it in GitHub Desktop.
Full Outer Join Coalesce
-- ARBITRARY COLUMN SELECTION
create table a (x int, y int, z int);
create table b (x int, y int, z int);
create table c (x int, y int, z int);
insert into a values (1, 2, 3);
insert into b values (1, null, 30);
insert into c values (1, 200, null);
select * from a;
/*
x | y | z
---+---+---
1 | 2 | 3
*/
select * from b;
/*
x | y | z
---+---+----
1 | | 30
*/
select * from c;
/*
x | y | z
---+-----+---
1 | 200 |
*/
select
coalesce(a.x, b.x, c.x) as x,
coalesce(b.y, a.y, c.y) as y,
coalesce(c.z, b.z, a.z) as z
from a
full outer join b on a.x = b.x
full outer join c on b.x = c.x;
/*
x | y | z
---+---+----
1 | 2 | 30
*/
delete from a;
delete from b;
delete from c;
-- DATA OUTSIDE INTERSECTIONS PRESERVED
insert into a values (1,2,3);
insert into b values (1,20,30);
insert into c values (1,200,300);
insert into a values (2, null, null);
insert into c values (100, null, null);
select * from a;
/*
x | y | z
---+---+---
1 | 2 | 3
2 | |
*/
select * from b;
/*
x | y | z
---+----+----
1 | 20 | 30
*/
select * from c;
/*
x | y | z
-----+-----+-----
1 | 200 | 300
100 | |
*/
select
coalesce(b.x, c.x, a.x) as x,
coalesce(b.y, c.y, a.y) as y,
coalesce(b.z, c.z, a.z) as z
from a
full outer join b on a.x = b.x
full outer join c on b.x = c.x;
/*
x | y | z
-----+----+----
1 | 20 | 30
2 | |
100 | |
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment