SQL Left Join

Galaxy Glossary

How does a LEFT JOIN work in SQL?

A LEFT JOIN in SQL returns all rows from the left table (the table specified before the LEFT JOIN keyword) and the matching rows from the right table. If there's no match in the right table, the columns from the right table will contain NULL values for those rows.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The LEFT JOIN, a crucial component of SQL, allows you to combine data from two or more tables based on a related column. Unlike an INNER JOIN, which only returns rows where there's a match in both tables, a LEFT JOIN returns all rows from the left table, regardless of whether there's a match in the right table. This is particularly useful when you need to retrieve all information from one table, even if there's no corresponding data in the other. Imagine you have a table of customers and a table of orders. A LEFT JOIN on customer ID would show every customer, even those who haven't placed any orders yet. The order-related columns for those customers would be NULL. This is a fundamental operation in relational database management systems, enabling complex queries and insightful data analysis.

Why SQL Left Join is important

LEFT JOINs are essential for retrieving complete information from a table, even when there's no corresponding data in a related table. This is crucial for reporting, data analysis, and ensuring comprehensive views of your data.

Example Usage


CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    City VARCHAR(50)
);

-- Attempt to insert a record without a first name
INSERT INTO Customers (CustomerID, LastName, City)
VALUES (1, 'Doe', 'New York');
-- This will result in an error because FirstName is NOT NULL

-- Correct insertion
INSERT INTO Customers (CustomerID, FirstName, LastName, City)
VALUES (2, 'John', 'Doe', 'London');

SELECT * FROM Customers;

Common Mistakes

Want to learn about other SQL terms?