SQL 50, decoded
0 of 50 solved/50

602. Friend Requests II: Who Has the Most Friends

SQL 50 · Subqueries (day 6). Decode it with the hints, solve it on LeetCode, then compare with the reference solution in MySQLPostgreSQL.

MediumSolve it on LeetCode ↗

Your work

Hints

Open one at a time. Try to finish with as few as you can.

1. What does one output row represent?
One person.
2. Approach
UNION ALL requester_id and accepter_id into one column, GROUP BY id, ORDER BY count DESC LIMIT 1.
3. The trap
UNION without ALL would merge duplicates and undercount.

Reference solution

Tested on MySQL 8.0 and PostgreSQL 16. Switch dialect at the top of the page.

Show the MySQLPostgreSQL solution
WITH ids AS (
  SELECT requester_id AS id FROM RequestAccepted
  UNION ALL
  SELECT accepter_id FROM RequestAccepted
)
SELECT id, COUNT(*) AS num
FROM ids
GROUP BY id
ORDER BY num DESC
LIMIT 1;

Patterns used

Phrase finder