HackerRank MySQL - Symmetric Pairs




You are given a table, Functions, containing two columns: X and Y.

Two pairs (X1, Y1) and (X2, Y2) are said to be symmetric pairs if X1 = Y2 and X2 = Y1.

Write a query to output all such symmetric pairs in ascending order by the value of X.



  1. SELECT X,
  2. Y
  3. FROM FUNCTIONS F1
  4. WHERE EXISTS
  5. (SELECT *
  6. FROM FUNCTIONS F2
  7. WHERE F2.Y = F1.X
  8. AND F2.X = F1.Y
  9. AND F2.X > F1.X)
  10. AND (X != Y)
  11. UNION
  12. SELECT X,
  13. Y
  14. FROM FUNCTIONS F1
  15. WHERE X = Y
  16. AND (
  17. (SELECT COUNT(*)
  18. FROM FUNCTIONS
  19. WHERE X = F1.X
  20. AND Y = F1.X) > 1)
  21. ORDER BY X;
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube