self-join: table joined with itself. If need to compare rows to other rows in the same table. i.e. for each row, compare it to all others in the same table for a match. or form all pairs of rows for some processing. (primary to foreign key not used). need table alias[es]. #"Cartesian product": M*M rows select * from pet as p1,pet as p2; # Must have table aliases. select p1.name,p2.name from pet as p1,pet as p2; #name "pairs": xy but not yx, xx, yy "M choose 2"=(M^2-M)/2=M*(M-1)/2 pairs #i.e. all pairs of rows, but each pair only once and no "self-pairs". #use primary key or other unique orderable column Select p1.name,p2.name From pet as p1,pet as p2 Where p1.name=p2.name group by p1.name; #in order by weight with rank shown too Select p1.name,count(*) as 'weight rank' From pet as p1,pet as p2 Where p1.weight>=p2.weight Group by p1.name Order by `weight rank`; #Or, to include a derived column that is the ordered ranking: set @c=0; select name,weight,@c:=@c+1 as rank from pet order by weight; #Or, to find a particular's rank: set @fluffyweight=(select weight from pet where name='fluffy'); select count(*) from pet where weight<=@fluffyweight; #pairs per owner: select p1.owner,p1.name,p2.name from pet as p1,pet as p2 where p2.name=c2.SurfaceArea and c1.Continent='South America' order by SurfaceArea;