Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 14

    SQL Joins Explained: INNER, LEFT, RIGHT, FULL, CROSS and Self Joins

    What this lesson teaches

    INNER JOIN returns matching pairs of rows. LEFT JOIN also keeps unmatched left rows, filling the missing right side with NULLs.

    You will learn how to choose between these joins, why joins can repeat rows, and when RIGHT, FULL, CROSS and self joins help. You will also learn how a filter can accidentally remove the rows you meant to keep.

    The examples use one small help-desk dataset. One agent has no team, and one team has no agents. Those gaps make the differences visible.

    Start with rows, not circles

    A join combines rows from two tables (or other sets of rows) into one result. A join condition describes which pairs match. For example, an agent's TeamId can match a team's Id.

    Our tables contain these rows:

    Agents

    IdNameTeamIdLeadId
    1Ada10NULL
    2Ben101
    3Cy201
    4DiNULLNULL

    Teams

    IdNameNote
    10SupportNULL
    20BillingPayments
    30OperationsInternal

    Here, SQL NULL represents missing or unknown data. Di has no assigned team. Operations has no agents. Support exists, but its note is missing.

    An alias is a short name used for a table or column within a query. We will use a for Agents and t for Teams. The ON clause gives the matching condition.

    flowchart LR
        A["Ada"] -->|"matches TeamId 10"| S["Support"]
        B["Ben"] -->|"matches TeamId 10"| S
        C["Cy"] -->|"matches TeamId 20"| T["Billing"]
        D["Di"] -->|"has"| N["No match"]
        O["Operations"] -->|"has"| N

    Ada and Ben form separate pairs with Support; Di and Operations have no matching row.

    This is a one-to-many relationship: one team can have several agents. Consequently, a join can repeat a team's columns. A Venn diagram is only a rough picture because it does not show those separate row pairs.

    All SQL below runs on SQLite in the console example near the end. SQLite supports RIGHT and FULL joins only from version 3.39.0 (2022). The SQLite bundled with Microsoft.Data.Sqlite 10 is newer, so they run here.

    T-SQL is SQL Server's version of SQL. These queries are written the same way in T-SQL, so they would also run on SQL Server (not run here).

    INNER JOIN versus LEFT JOIN

    Use INNER JOIN when you want only matching pairs. Use LEFT JOIN when every row from the left table must survive, even without a match.

    The left table is the one written before JOIN. Here, that is Agents.

    SQL
    SELECT a.Id, a.Name AS Agent, t.Name AS Team
    FROM Agents AS a
    INNER JOIN Teams AS t ON a.TeamId = t.Id
    ORDER BY a.Id;
    IdAgentTeam
    1AdaSupport
    2BenSupport
    3CyBilling

    For each agent, the condition checks for a team with the matching ID. Ada and Ben each match Support. Cy matches Billing. An equality comparison with SQL NULL is never true, even for NULL = NULL, so Di's NULL TeamId finds no match in ON a.TeamId = t.Id. The result contains three rows.

    Now change only the join type:

    SQL
    SELECT a.Id, a.Name AS Agent, t.Name AS Team
    FROM Agents AS a
    LEFT JOIN Teams AS t ON a.TeamId = t.Id
    ORDER BY a.Id;
    IdAgentTeam
    1AdaSupport
    2BenSupport
    3CyBilling
    4DiNULL

    The three matching pairs remain. The join also adds a row for Di, with NULL in Team. It does not create a team or update either table.

    In the Teams-first LEFT JOIN below, Support appears twice: once for Ada and once for Ben. A left row that matches five right rows produces five pairs, not one result row.

    JOIN without a join type means INNER JOIN. Writing INNER explicitly can make an interview answer easier to follow.

    An outer join (LEFT, RIGHT or FULL) is a join that can also keep rows that have no match. LEFT OUTER JOIN and LEFT JOIN mean the same thing; OUTER is optional.

    The mistake to avoid. Do not describe LEFT JOIN as “one row for every left row.” It keeps every left row, but multiple matches can increase the count.

    In an interview, say: “INNER JOIN returns matching row pairs. LEFT JOIN also keeps every unmatched left row, with NULLs for the right columns. Both can repeat rows when one row has several matches.”

    RIGHT JOIN: keep the other side

    RIGHT JOIN keeps every row from the right table, even rows with no match. Here, that means every team, including Operations.

    SQL
    SELECT a.Id, a.Name AS Agent, t.Name AS Team
    FROM Agents AS a
    RIGHT JOIN Teams AS t ON a.TeamId = t.Id
    ORDER BY t.Id, a.Id;
    IdAgentTeam
    1AdaSupport
    2BenSupport
    3CyBilling
    NULLNULLOperations

    Support appears twice, Billing once, and Operations once. The Operations row has NULL for the agent columns. Di is absent because Di matches no team.

    For this query, swapping the tables and using LEFT JOIN gives the same result:

    SQL
    SELECT a.Id, a.Name AS Agent, t.Name AS Team
    FROM Teams AS t
    LEFT JOIN Agents AS a ON a.TeamId = t.Id
    ORDER BY t.Id, a.Id;
    IdAgentTeam
    1AdaSupport
    2BenSupport
    3CyBilling
    NULLNULLOperations

    Both queries select the same columns and produce the same ordered rows. Many development teams prefer the second style because the table whose rows must survive appears first. Follow your team's convention rather than changing styles halfway through a query.

    The mistake to avoid. Do not replace RIGHT with LEFT without swapping the table sources. That changes which unmatched rows survive.

    In an interview, say: “RIGHT JOIN keeps every row of the right table, even rows with no match. Swapping the tables lets me express the same join with LEFT JOIN, which often reads more clearly.”

    FULL OUTER JOIN: keep both sides

    FULL OUTER JOIN returns matching pairs and unmatched rows from either side. Missing columns from the opposite side become NULL.

    A common use is reconciliation: comparing two lists to find what is only in the first, only in the second, or in both.

    SQL
    SELECT COALESCE(a.TeamId, t.Id) AS TeamKey,
           a.Name AS Agent, t.Name AS Team,
           CASE WHEN a.Id IS NULL THEN 'only in Teams'
                WHEN t.Id IS NULL THEN 'only in Agents'
                ELSE 'in both' END AS Presence
    FROM Agents AS a
    FULL OUTER JOIN Teams AS t ON a.TeamId = t.Id
    ORDER BY CASE WHEN a.Id IS NULL THEN 1 ELSE 0 END, a.Id, t.Id;
    TeamKeyAgentTeamPresence
    10AdaSupportin both
    10BenSupportin both
    20CyBillingin both
    NULLDiNULLonly in Agents
    30NULLOperationsonly in Teams

    COALESCE returns its first non-NULL argument. It gives us one displayed team key from whichever side supplies it. Di's TeamKey remains NULL because Di has no assigned team. See Microsoft's COALESCE reference for more examples.

    CASE chooses a result according to conditions. IS NULL tests whether something is NULL; do not use = NULL for that test.

    The result contains five rows: three matched pairs, Di without a team, and Operations without an agent. The Presence column identifies those categories.

    When reconciling two lists of the same kind, join their corresponding keys, display COALESCE(leftKey, rightKey), and flag which side is missing. Multiple rows with the same matching key can still produce multiple pairs.

    The mistake to avoid. Do not assume FULL JOIN removes repeated matches. It preserves unmatched rows in addition to the matching pairs; it does not collapse those pairs.

    In an interview, say: “I use FULL OUTER JOIN to reconcile two lists. It keeps both sides, so I can coalesce their keys and flag rows found only in A, only in B, or in both.”

    CROSS JOIN: every combination

    A CROSS JOIN returns every possible pair, without an ON condition. Its row count multiplies: three teams times four agents gives twelve rows.

    SQL
    SELECT t.Name AS Team, a.Name AS Agent
    FROM Teams AS t
    CROSS JOIN Agents AS a
    ORDER BY t.Id, a.Id;
    TeamAgent
    SupportAda
    SupportBen
    SupportCy
    SupportDi
    BillingAda
    BillingBen
    BillingCy
    BillingDi
    OperationsAda
    OperationsBen
    OperationsCy
    OperationsDi

    Support pairs with all four agents. Billing does the same, followed by Operations. These combinations do not mean that every agent belongs to every team.

    This is useful when you deliberately need a complete grid. For example, cross join teams with calendar days, then LEFT JOIN recorded work onto that grid. Days without work can remain visible. Test combinations are another use.

    The trade-off is size. A useful small grid can become an expensive result when both inputs are large.

    The mistake to avoid. Do not use CROSS JOIN to discover existing relationships. It generates combinations whether or not those relationships exist.

    In an interview, say: “CROSS JOIN returns the Cartesian product: every row of one table paired with every row of the other. It has no ON condition. I use it for calendar grids or test combinations, but check the size because the row counts multiply.”

    Self joins: use one table in two roles

    A self join joins a table to itself. Different aliases give the same table different roles.

    Here, a means the agent being reported and lead means that agent's lead:

    SQL
    SELECT a.Name AS Agent, lead.Name AS Lead
    FROM Agents AS a
    LEFT JOIN Agents AS lead ON a.LeadId = lead.Id
    ORDER BY a.Id;
    AgentLead
    AdaNULL
    BenAda
    CyAda
    DiNULL

    Ben and Cy match Ada through LeadId = 1. Ada and Di remain in the result with NULL for Lead. LEFT JOIN matters because agents without a lead must stay.

    A second use is finding pairs within the same team:

    SQL
    SELECT a.Name AS AgentA, b.Name AS AgentB
    FROM Agents AS a
    INNER JOIN Agents AS b ON a.TeamId = b.TeamId AND a.Id < b.Id
    ORDER BY a.Id, b.Id;
    AgentAAgentB
    AdaBen

    The matching team IDs find colleagues. a.Id < b.Id excludes an agent paired with themselves and keeps only one direction of each pair. The result is Ada paired with Ben, not a second Ben–Ada row.

    The mistake to avoid. Do not match only on TeamId when you want unique colleague pairs. That also produces self-pairs and reversed pairs.

    In an interview, say: “A self join uses one table in two roles, such as an agent and their lead. For unique pairs within a team, I also require a.Id < b.Id.”

    Missing rows and filters

    Filter placement can change which rows an outer join keeps.

    First, distinguish a missing team from a missing note:

    SQL
    SELECT a.Name AS Agent
    FROM Agents AS a
    LEFT JOIN Teams AS t ON a.TeamId = t.Id
    WHERE t.Id IS NULL
    ORDER BY a.Id;
    Agent
    Di

    This finds Di. In the CREATE TABLE below, Teams.Id is the primary key (the column identifying each team) and is declared NOT NULL. A real team row can never have a NULL Id, so a NULL in t.Id here means no team matched.

    Testing t.Note IS NULL would also find Ada and Ben. Their team exists; its Note happens to be NULL.

    On an INNER JOIN, a filter on Teams returns the same rows in ON or in WHERE. On a LEFT JOIN it does not:

    SQL
    SELECT a.Name AS Agent, t.Name AS Team
    FROM Agents AS a
    LEFT JOIN Teams AS t ON a.TeamId = t.Id
    WHERE t.Name = 'Support'
    ORDER BY a.Id;
    AgentTeam
    AdaSupport
    BenSupport

    This keeps only Ada and Ben. WHERE runs on the joined rows, so it removes Cy (Billing) and Di (no team) again: the LEFT JOIN now behaves like an INNER JOIN. Put t.Name = 'Support' in ON to keep all four agents:

    AgentTeam
    AdaSupport
    BenSupport
    CyNULL
    DiNULL

    See Microsoft's FROM and JOIN reference for join rules and the SELECT reference for query processing order. Filter traps receive a fuller treatment later in the course.

    The mistake to avoid. Do not test a nullable description column to detect a missing row, or put a right-side equality filter in WHERE while expecting unmatched rows to survive.

    In an interview, say: “I test the right table's non-null key to find missing matches. With LEFT JOIN, ON controls matching, but WHERE can remove the unmatched rows afterwards.”

    Run the examples and inspect the grids

    This is one .NET 10 console program using Microsoft.Data.Sqlite 10.0.12. It creates an in-memory database, which exists for this connection rather than in a database file. No server or network is needed.

    The program prints a separate labelled grid for every query above, showing NULLs and repeated rows. It also runs the INNER JOIN filter both ways. Every query has ORDER BY to make its output order explicit.

    C#
    using Microsoft.Data.Sqlite;
    
    using var connection = new SqliteConnection("Data Source=:memory:");
    connection.Open();
    using (var setup = connection.CreateCommand())
    {
        setup.CommandText = """
            CREATE TABLE Teams (
                Id INTEGER NOT NULL PRIMARY KEY,
                Name TEXT NOT NULL,
                Note TEXT NULL
            );
            CREATE TABLE Agents (
                Id INTEGER NOT NULL PRIMARY KEY,
                Name TEXT NOT NULL,
                TeamId INTEGER NULL,
                LeadId INTEGER NULL
            );
            INSERT INTO Teams VALUES
                (10, 'Support', NULL),
                (20, 'Billing', 'Payments'),
                (30, 'Operations', 'Internal');
            INSERT INTO Agents VALUES
                (1, 'Ada', 10, NULL),
                (2, 'Ben', 10, 1),
                (3, 'Cy', 20, 1),
                (4, 'Di', NULL, NULL);
            """;
        setup.ExecuteNonQuery();
    }
    
    var queries = new (string Label, string Sql)[]
    {
        ("INNER", """
            SELECT a.Id, a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            INNER JOIN Teams AS t ON a.TeamId = t.Id
            ORDER BY a.Id;
            """),
        ("LEFT", """
            SELECT a.Id, a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            LEFT JOIN Teams AS t ON a.TeamId = t.Id
            ORDER BY a.Id;
            """),
        ("RIGHT", """
            SELECT a.Id, a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            RIGHT JOIN Teams AS t ON a.TeamId = t.Id
            ORDER BY t.Id, a.Id;
            """),
        ("RIGHT rewritten as LEFT", """
            SELECT a.Id, a.Name AS Agent, t.Name AS Team
            FROM Teams AS t
            LEFT JOIN Agents AS a ON a.TeamId = t.Id
            ORDER BY t.Id, a.Id;
            """),
        ("FULL", """
            SELECT COALESCE(a.TeamId, t.Id) AS TeamKey,
                   a.Name AS Agent, t.Name AS Team,
                   CASE WHEN a.Id IS NULL THEN 'only in Teams'
                        WHEN t.Id IS NULL THEN 'only in Agents'
                        ELSE 'in both' END AS Presence
            FROM Agents AS a
            FULL OUTER JOIN Teams AS t ON a.TeamId = t.Id
            ORDER BY CASE WHEN a.Id IS NULL THEN 1 ELSE 0 END, a.Id, t.Id;
            """),
        ("CROSS", """
            SELECT t.Name AS Team, a.Name AS Agent
            FROM Teams AS t
            CROSS JOIN Agents AS a
            ORDER BY t.Id, a.Id;
            """),
        ("Agent and lead", """
            SELECT a.Name AS Agent, lead.Name AS Lead
            FROM Agents AS a
            LEFT JOIN Agents AS lead ON a.LeadId = lead.Id
            ORDER BY a.Id;
            """),
        ("Colleague pairs", """
            SELECT a.Name AS AgentA, b.Name AS AgentB
            FROM Agents AS a
            INNER JOIN Agents AS b ON a.TeamId = b.TeamId AND a.Id < b.Id
            ORDER BY a.Id, b.Id;
            """),
        ("No matching team", """
            SELECT a.Name AS Agent
            FROM Agents AS a
            LEFT JOIN Teams AS t ON a.TeamId = t.Id
            WHERE t.Id IS NULL
            ORDER BY a.Id;
            """),
        ("INNER filter in ON", """
            SELECT a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            INNER JOIN Teams AS t ON a.TeamId = t.Id AND t.Name = 'Support'
            ORDER BY a.Id;
            """),
        ("INNER filter in WHERE", """
            SELECT a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            INNER JOIN Teams AS t ON a.TeamId = t.Id
            WHERE t.Name = 'Support'
            ORDER BY a.Id;
            """),
        ("Filter in ON", """
            SELECT a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            LEFT JOIN Teams AS t ON a.TeamId = t.Id AND t.Name = 'Support'
            ORDER BY a.Id;
            """),
        ("Filter in WHERE", """
            SELECT a.Name AS Agent, t.Name AS Team
            FROM Agents AS a
            LEFT JOIN Teams AS t ON a.TeamId = t.Id
            WHERE t.Name = 'Support'
            ORDER BY a.Id;
            """),
    };
    
    foreach (var (label, sql) in queries)
    {
        Console.WriteLine($"\n{label}");
        using var command = connection.CreateCommand();
        command.CommandText = sql;
        using var reader = command.ExecuteReader();
        Console.WriteLine(string.Join(" | ",
            Enumerable.Range(0, reader.FieldCount).Select(reader.GetName)));
        while (reader.Read())
        {
            Console.WriteLine(string.Join(" | ",
                Enumerable.Range(0, reader.FieldCount)
                    .Select(i => reader.IsDBNull(i)
                        ? "NULL" : reader.GetValue(i).ToString())));
        }
    }

    Needs the package Microsoft.Data.Sqlite 10.0.12. Built and run with it: the result grid under each query in this lesson is what it printed.

    Check yourself

    Which join keeps Di even though Di has no assigned team?

    A Agents LEFT JOIN Teams
    B Agents INNER JOIN Teams
    C Agents RIGHT JOIN Teams
    D Teams LEFT JOIN Agents
    Show answer

    Correct answer: A

    Agents is the left table, so LEFT JOIN keeps Di and supplies NULLs for the missing team columns. Teams LEFT JOIN Agents keeps every team instead, and Di matches no team.

    You need each pair of colleagues once, without pairing anyone with themselves. Which condition works?

    A a.TeamId = b.TeamId
    B a.TeamId = b.TeamId AND a.Id <> b.Id
    C a.TeamId = b.TeamId AND a.Id < b.Id
    D a.Id = b.Id
    Show answer

    Correct answer: C

    The team comparison finds colleagues. The strict ID ordering removes self-pairs and keeps only one direction of each pair.

    Going deeper

    In SQL Server, APPLY lets a right-side table expression use values from each left row. It is covered in Window Functions and Pagination and in question 73 of SQL query patterns: set operations, grouping and ranking, rather than run in this SQLite example.

    For C# practice, try Name the customer on each order and Order lines, even with unknown products. They exercise the same choices: require a matching related row, or retain the original row when related data is missing.

    Sources

    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·