I have the following table
drop table names;
create table names(
name varchar(200),
surname varchar(200),
primary key(name, surname)
);
insert into names values ('john', 'doe');
insert into names values ('john', 'richards');
I’d like to list the surnames where the name is the same.
i.e. I want this result
----------+----------
doe | richards
doe | doe
richards | richards
(this is only an example, the real problem is quite different)
The followig query returns duplicates
select n1.surname, n2.surname
from names n1 join names n2
on n1.name = n2.name;
surname | surname
----------+----------
doe | richards
doe | doe
richards | richards
richards | doe
So, I used the least and greatest postgresql functions, and got my result. But: least and greatest are not standard SQL, and I was wondering whether a more efficient solution exists, as using a join condition I cannot imagine now.
select distinct least(n1.surname, n2.surname), greatest(n1.surname,
n2.surname)
from names n1 join names n2
on n1.name = n2.name;
least | greatest
----------+----------
doe | richards
doe | doe
richards | richards
If you only want a tie-breaker, use < of > or >= or <=