HomeInterview QuestionsTo contain all 10 teams, each must play every othe…

To contain all 10 teams, each must play every other team at home and away. Can you write a query to do this?

🟡 Medium Coding Junior level
1Times asked
Jun 2026Last seen
Jun 2026First seen

💡 Model Answer

Assuming you have a table teams with a column team_id, you can generate all home‑away pairings with a self‑join and then union the reverse pairs. Example:

sql
-- List of teams
SELECT team_id FROM teams;

-- Generate home‑away pairs
SELECT t1.team_id AS home_team, t2.team_id AS away_team
FROM teams t1
JOIN teams t2 ON t1.team_id <> t2.team_id
ORDER BY t1.team_id, t2.team_id;

This produces 10 × 9 = 90 rows. If you also need the reverse (away‑home) for each match, you can simply add the same query again or use a UNION ALL:

sql
SELECT t1.team_id AS home_team, t2.team_id AS away_team
FROM teams t1
JOIN teams t2 ON t1.team_id <> t2.team_id
UNION ALL
SELECT t2.team_id AS home_team, t1.team_id AS away_team
FROM teams t1
JOIN teams t2 ON t1.team_id <> t2.team_id;

Complexity is O(n²) where n is the number of teams. The query is straightforward and works in most SQL dialects.

This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.

🎤 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.

Get Assisting AI — Starts at ₹500