Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two columns in postgres database

I am somewhat stumped on a seemingly simple problem. I have a table set up such as,

CREATE TABLE cities (
     column_1 TEXT,
     column_2 TEXT);

Where the contents of these tables look like

column_1  |  column_2
---------------------
Atlanta   |  Atlanta
Boston    |  Chicago
Chicago   |  Los Angeles
Seattle   |  Tacoma
NULL      |  Seattle

What query could I run that would look at both of these columns, and despite their order, return where the two columns matchup?

The result I am looking for would be:

column_1  |  column_2
---------------------
Atlanta   |  Atlanta
Chicago   |  Chicago
Seattle   |  Seattle

I have tried:

SELECT *
FROM cities
WHERE column_1 = column_2;

But this only returns the EXACT matches:

column_1  |  column_2
---------------------
Atlanta   |  Atlanta
like image 988
Ben_S Avatar asked Nov 07 '18 14:11

Ben_S


1 Answers

You just need a self join:

SELECT c1.column_1, c2.column_2
FROM cities c1
JOIN cities c2
    ON c1.column_1 = c2.column_2
like image 73
404 Avatar answered Oct 21 '22 06:10

404