SQL:SQL INNER JOIN and LEFT JOIN: Combining Relational Tables
SQL•Joins

SQL INNER JOIN and LEFT JOIN: Combining Relational Tables

Relational databases normalize data across tables. Joins connect records using primary and foreign keys.

Syntax

SELECT * FROM tableA INNER JOIN tableB ON tableA.id = tableB.a_id;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
INNER JOINJoin TypeReturns only rows with matching keys in both tables.
LEFT JOINJoin TypeReturns all rows from left table, and matched rows from right table (or NULL).

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT
);

CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    user_id INTEGER,
    amount REAL
);

INSERT INTO users VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');
INSERT INTO orders VALUES (101, 1, 99.00), (102, 1, 45.00), (103, 2, 250.00);

-- LEFT JOIN shows all users, even Charlie who has 0 orders
SELECT 
    u.name,
    COALESCE(SUM(o.amount), 0.0) AS total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name;
Expected Output:
name     total_spent
-------  -----------
Alice    144.0      
Bob      250.0      
Charlie  0.0        

How It Works: Step-by-Step

  • Lines 1-11: Sets up relational schema where orders reference user_id.
  • Lines 14-19: LEFT JOIN retains Charlie; COALESCE converts NULL order sums to 0.0.

Key Concepts

  • INNER JOIN excludes unmatched rows; LEFT JOIN preserves all left-table rows.
  • COALESCE(val, fallback) returns the first non-null argument.

Common Mistake: Filtering right table in WHERE clause when doing a LEFT JOIN

Putting right-table conditions in WHERE filters out NULL rows, turning the LEFT JOIN into an INNER JOIN.

❌ Incorrect
LEFT JOIN orders o ON u.id = o.user_id WHERE o.amount > 0 // Charlie discarded!
✅ Correct
LEFT JOIN orders o ON u.id = o.user_id AND o.amount > 0 // Correct: Charlie retained

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler