Skip to content

Instantly share code, notes, and snippets.

@Nathan-Wall
Last active February 15, 2017 02:06
Show Gist options
  • Save Nathan-Wall/a6c6fcd49d0bf3940ff03be91e269eb2 to your computer and use it in GitHub Desktop.
Save Nathan-Wall/a6c6fcd49d0bf3940ff03be91e269eb2 to your computer and use it in GitHub Desktop.
Combine two SQL columns into one, selecting distinct results
CREATE TABLE _test_1 (
a varchar(64));
CREATE TABLE _test_2 (
b varchar(64));
INSERT INTO _test_1 (a)
VALUES ('john'),
('sue'),
('bob'),
('john'),
('sally'),
('kevin'),
('alex'),
('john'),
('kevin');
INSERT INTO _test_2 (b)
VALUES ('john'),
('mike'),
('alex'),
('eric'),
('john'),
('carla'),
('carla');
SELECT DISTINCT ON (t1.a, t2.b) coalesce(t1.a, t2.b) AS out
FROM _test_1 t1
FULL JOIN _test_2 t2 ON t1.a = t2.b;
DROP TABLE _test_2;
DROP TABLE _test_1;
@Nathan-Wall
Copy link
Author

Output is:

  out  
-------
 alex
 bob
 john
 kevin
 sally
 sue
 carla
 eric
 mike
(9 rows)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment