Introduction to SQL Joins

Structured Query Language (SQL) is a powerful tool used for managing and manipulating relational databases. One of the key features of SQL is its ability to combine data from multiple tables through the use of joins. Joins allow users to retrieve related data that is distributed across different tables, facilitating more complex queries and enriching the information available for analysis.

In relational databases, data is often normalized, meaning it is organized into separate tables to reduce redundancy and improve data integrity. For instance, customer information might be stored in one table, while their orders are stored in another. This separation helps manage data efficiently but requires an understanding of how to link these tables to obtain comprehensive insights.

Types of SQL Joins

SQL supports several types of joins, each serving a distinct purpose:

  1. Inner Join: This join returns only the rows that have matching values in both tables. It is useful when you want to see records that are present in both datasets.
  2. Left Join (Left Outer Join): This join returns all the rows from the left table and the matched rows from the right table. If there is no match, it returns NULL for columns from the right table. This is helpful when you want to keep all records from the left table, regardless of whether there is a corresponding record in the right table.
  3. Right Join (Right Outer Join): Conversely, this join returns all the rows from the right table and the matched rows from the left table. If there is no match, it returns NULL for columns from the left table. It is beneficial when you need to retain all records from the right table.
  4. Full Join (Full Outer Join): This join combines the results of both left and right joins. It returns all records from both tables, with NULLs in places where there is no match. This is ideal when you want to see the complete dataset from both tables.
  5. Cross Join: This join produces a Cartesian product of the two tables involved, meaning it returns all possible combinations of rows from both tables. While it can generate a large number of results, it’s rarely used for practical queries due to its broad output.
  6. Self Join: This is a special case where a table is joined with itself. It is useful for querying hierarchical data or comparing rows within the same table.

Practical Examples

The following sections provide SQL scripts to create sample tables and perform various types of joins. Each example is designed to illustrate the practical application of these joins, demonstrating how to combine data effectively from multiple tables. By understanding these concepts, you can leverage SQL to extract meaningful insights from your relational databases.


1. Create Sample Tables

-- Create table for Customers
CREATE TABLE Customers (
    CustomerID INT PRIMARY KEY,
    CustomerName VARCHAR(100)
);

-- Create table for Orders
CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    CustomerID INT,
    OrderDate DATE,
    FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);

-- Create table for Products
CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    ProductName VARCHAR(100),
    SupplierID INT
);

-- Create table for Suppliers
CREATE TABLE Suppliers (
    SupplierID INT PRIMARY KEY,
    SupplierName VARCHAR(100)
);

-- Create table for Employees
CREATE TABLE Employees (
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(100),
    DepartmentID INT
);

-- Create table for Departments
CREATE TABLE Departments (
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(100)
);

-- Create table for Flights
CREATE TABLE Flights (
    FlightID INT PRIMARY KEY,
    AirlineID INT,
    Destination VARCHAR(100)
);

-- Create table for Airlines
CREATE TABLE Airlines (
    AirlineID INT PRIMARY KEY,
    AirlineName VARCHAR(100)
);

-- Create table for Books
CREATE TABLE Books (
    BookID INT PRIMARY KEY,
    Title VARCHAR(100),
    AuthorID INT
);

-- Create table for Authors
CREATE TABLE Authors (
    AuthorID INT PRIMARY KEY,
    AuthorName VARCHAR(100)
);

-- Create table for Reviews
CREATE TABLE Reviews (
    ReviewID INT PRIMARY KEY,
    BookID INT,
    ReviewText VARCHAR(255)
);

2. Insert Sample Data

-- Insert Customers
INSERT INTO Customers VALUES (1, 'John Doe');
INSERT INTO Customers VALUES (2, 'Jane Smith');
INSERT INTO Customers VALUES (3, 'Alice Johnson');

-- Insert Orders
INSERT INTO Orders VALUES (1, 1, '2023-01-01');
INSERT INTO Orders VALUES (2, 1, '2023-02-01');
INSERT INTO Orders VALUES (3, 2, '2023-03-01');

-- Insert Products
INSERT INTO Products VALUES (1, 'Product A', 1);
INSERT INTO Products VALUES (2, 'Product B', 1);
INSERT INTO Products VALUES (3, 'Product C', 2);

-- Insert Suppliers
INSERT INTO Suppliers VALUES (1, 'Supplier A');
INSERT INTO Suppliers VALUES (2, 'Supplier B');

-- Insert Employees
INSERT INTO Employees VALUES (1, 'Bob Brown', 1);
INSERT INTO Employees VALUES (2, 'Eve Davis', 2);
INSERT INTO Employees VALUES (3, 'Charlie Wilson', 1);

-- Insert Departments
INSERT INTO Departments VALUES (1, 'Sales');
INSERT INTO Departments VALUES (2, 'Marketing');

-- Insert Airlines
INSERT INTO Airlines VALUES (1, 'Airline A');
INSERT INTO Airlines VALUES (2, 'Airline B');

-- Insert Flights
INSERT INTO Flights VALUES (1, 1, 'New York');
INSERT INTO Flights VALUES (2, 1, 'Los Angeles');
INSERT INTO Flights VALUES (3, 2, 'Chicago');

-- Insert Authors
INSERT INTO Authors VALUES (1, 'Author A');
INSERT INTO Authors VALUES (2, 'Author B');

-- Insert Books
INSERT INTO Books VALUES (1, 'Book A', 1);
INSERT INTO Books VALUES (2, 'Book B', 1);
INSERT INTO Books VALUES (3, 'Book C', 2);

-- Insert Reviews
INSERT INTO Reviews VALUES (1, 1, 'Great Book!');
INSERT INTO Reviews VALUES (2, 2, 'Interesting Read');

3. Join Examples

Inner Join

-- Inner Join: Get orders with customer details
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

Left Join

-- Left Join: List all employees and their departments
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

Right Join

-- Right Join: List all suppliers and their products
SELECT Suppliers.SupplierName, Products.ProductName
FROM Suppliers
RIGHT JOIN Products ON Suppliers.SupplierID = Products.SupplierID;

Full Join

-- Full Join: List all employees and their departments, including those without departments
SELECT Employees.EmployeeName, Departments.DepartmentName
FROM Employees
FULL OUTER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

Cross Join

-- Cross Join: Get every possible pair of products and suppliers
SELECT Products.ProductName, Suppliers.SupplierName
FROM Products
CROSS JOIN Suppliers;

Self Join

-- Self Join: List employees with their managers (assuming a ManagerID column)
CREATE TABLE EmployeesWithManager (
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(100),
    ManagerID INT
);

-- Insert sample data
INSERT INTO EmployeesWithManager VALUES (1, 'Bob Brown', NULL);
INSERT INTO EmployeesWithManager VALUES (2, 'Eve Davis', 1);
INSERT INTO EmployeesWithManager VALUES (3, 'Charlie Wilson', 1);

-- Self Join to find managers
SELECT e1.EmployeeName AS Employee, e2.EmployeeName AS Manager
FROM EmployeesWithManager e1
LEFT JOIN EmployeesWithManager e2 ON e1.ManagerID = e2.EmployeeID;

Conclusion

This SQL script demonstrates how to create tables, insert sample data, and perform various types of joins to retrieve meaningful information from a database. You can run these scripts in a SQL environment to see how each join works with the provided data.

Here’s a table format for the 50 examples of SQL joins, showcasing the type of join and a brief description of each scenario.

Join TypeExample Description
Inner JoinOrders and customers to get all orders with customer details.
Left JoinEmployees and departments to list all employees with their department.
Right JoinProducts and suppliers to find all suppliers, including those without listed products.
Full JoinCurrent employees and ex-employees to see all who have worked at the company.
Inner JoinBooks and authors to get all published books with author details.
Left JoinDepartments and projects to see all departments with associated projects.
Cross JoinCountries and languages to get every possible country-language pair.
Inner JoinPurchases and items to show all items that were purchased.
Left JoinSales reps and territories to list all sales reps and the territories they cover.
Right JoinCourses and students to find all students, including those not enrolled in courses.
Full JoinPart-time and full-time employees for a complete list of employees.
Self JoinEmployees to see managers and their subordinates.
Inner JoinProduct sales and store locations to find sales per location.
Left JoinArtists and albums to list all artists, showing NULL for those without albums.
Right JoinPatient records and doctors to get a list of doctors, including those without patients.
Full JoinTransaction records and refunds to see all transactions, indicating if refunded.
Inner JoinFlights and airlines to show flights with airline details.
Left JoinBooks and reviews to see all books with their reviews, if any.
Right JoinTeachers and classes to list all classes and their teachers.
Full JoinStaff and payroll records to see all employees and their payroll status.
Inner JoinHotels and room bookings to see booked rooms.
Left JoinInventory and suppliers to list all inventory items and their suppliers.
Right JoinSubscriptions and users to get all users, showing NULL if they’re unsubscribed.
Full JoinSocial media followers and followed to see all connections.
Cross JoinStudents and clubs to see all possible student-club pairs.
Inner JoinOrders and promotions to show orders that used a promotion.
Left JoinDrivers and licenses to list all drivers with their license information.
Right JoinDonors and donation records to get all donors, including non-donors.
Full JoinOrders and shipments to track all orders and shipments, including pending ones.
Inner JoinMovie cast and roles to find actors who played specific roles.
Left JoinClients and invoices to see all clients, including those without invoices.
Right JoinProfessors and courses to list courses and their professors.
Full JoinAttendance and events to show all events with participant status.
Cross JoinRegions and product types to analyze product type distribution by region.
Inner JoinUser profiles and posts to show users who posted content.
Left JoinPets and owners to list all pets, showing NULL if they’re unowned.
Right JoinBank accounts and customers to show all customers, even without accounts.
Full JoinPast and present courses to view all courses ever offered.
Inner JoinRentals and property owners to show rented properties with owner info.
Left JoinArtists and concert dates to see all artists with upcoming concert dates.
Right JoinWarehouse locations and inventory to see all locations, including those without stock.
Full JoinScholarship records and student enrollment to show all students and scholarships.
Cross JoinCities and job openings to show all job listings for each city.
Inner JoinFood orders and restaurants to get restaurant-specific orders.
Left JoinSales and returns to list all sales, marking if returned.
Right JoinEmployees and training sessions to list employees and trainings.
Full JoinProject phases and tasks to show all tasks with phase statuses.
Cross JoinPromotions and product categories to analyze promotion effects on categories.
Inner JoinCharity events and donors to show events with participating donors.
Left JoinPrograms and participants to show all programs with participant details.
Right JoinUser subscriptions and features to see all features, including those not subscribed.

Edvaldo Guimrães Filho Avatar

Published by