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
League Match GenerationTeams Tableteam_nameArsenalChelseaLiverpoolCROSSJOINAll Matcheshome_teamaway_teamArsenalChelseaArsenalLiverpoolChelseaArsenal... 3 more matchesFormula: n teams → n×(n-1) matchesEach team plays every other team twice
Understanding the Visualization
1
Input
List of team names
2
Self-Join
Cartesian product with filter
3
Output
All home/away match pairs
Key Takeaway
🎯 Key Insight: Self-join with inequality filter generates all pairwise combinations for tournament scheduling
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