All the Matches of the League - Problem

You are given a table Teams that contains the names of teams in a league.

Write a SQL query to report all the possible matches of the league.

Note: Every two teams play two matches with each other - one match where team A is the home team and team B is the away team, and another match where team B is the home team and team A is the away team.

Return the result table in any order.

Table Schema

Teams
Column Name Type Description
team_name PK varchar The name of the team (unique)
Primary Key: team_name
Note: Each row represents one team in the league

Input & Output

Example 1 — Basic League Matches
Input Table:
team_name
Arsenal
Chelsea
Liverpool
Output:
home_team away_team
Arsenal Chelsea
Arsenal Liverpool
Chelsea Arsenal
Chelsea Liverpool
Liverpool Arsenal
Liverpool Chelsea
💡 Note:

With 3 teams, each team plays against the other 2 teams twice (once at home, once away). Arsenal vs Chelsea, Arsenal vs Liverpool, Chelsea vs Arsenal, Chelsea vs Liverpool, Liverpool vs Arsenal, and Liverpool vs Chelsea - totaling 6 matches.

Example 2 — Two Teams Only
Input Table:
team_name
TeamA
TeamB
Output:
home_team away_team
TeamA TeamB
TeamB TeamA
💡 Note:

With only 2 teams, there are exactly 2 matches: TeamA hosts TeamB, and TeamB hosts TeamA. Each team plays once at home and once away.

Constraints

  • 1 ≤ number of teams ≤ 100
  • team_name contains only letters and spaces
  • All team names are unique

Visualization

Tap to expand
All the Matches of the League INPUT Teams Table team_name Real Madrid Barcelona Atletico Madrid 3 Teams Total Team A Team B Team C Each team plays every other team twice (home + away) ALGORITHM STEPS 1 CROSS JOIN Join Teams with itself Teams t1, Teams t2 2 Filter Self-Match Exclude same team pairs t1.name <> t2.name 3 Generate Pairs All permutations created home_team, away_team 4 Return Result n*(n-1) total matches 3*(3-1) = 6 matches SQL Query: SELECT t1.team_name AS home_team, t2.team_name AS away_team FINAL RESULT home_team away_team Real Madrid Barcelona Real Madrid Atletico Barcelona Real Madrid Barcelona Atletico Atletico Real Madrid Atletico Barcelona 6 Matches OK - All pairs generated Each team hosts every other team once Formula: n x (n-1) Key Insight: CROSS JOIN (Cartesian Product) generates all possible team combinations. By filtering out rows where home_team equals away_team, we get all valid match pairs. No DISTINCT needed since permutations (A vs B) and (B vs A) represent different matches - home and away games respectively. TutorialsPoint - All the Matches of the League | Optimal Solution (Cross Join)
Asked in
Meta 12 Amazon 8 Google 6
23.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen