Sql Practical Examples With Joins Complete Guide
Understanding the Core Concepts of SQL Practical Examples with Joins
SQL Practical Examples with Joins
Types of SQL Joins
- INNER JOIN
- LEFT JOIN (or LEFT OUTER JOIN)
- RIGHT JOIN (or RIGHT OUTER JOIN)
- FULL JOIN (or FULL OUTER JOIN)
- CROSS JOIN
- SELF JOIN
1. INNER JOIN
Purpose: Returns rows when there is at least one match in both tables.
Example:
Imagine we have two tables, employees
and departments
.
Table: employees | employee_id | name | department_id | |-------------|---------|---------------| | 1 | John | 101 | | 2 | Mary | 102 | | 3 | Alice | 103 |
Table: departments | department_id | dept_name | |---------------|-----------| | 101 | HR | | 102 | Finance | | 104 | IT |
Query:
SELECT employees.name, departments.dept_name
FROM employees
INNER JOIN departments ON employees.department_id = departments.department_id;
Result: | name | dept_name | |-------|-----------| | John | HR | | Mary | Finance |
This query fetches employees along with their respective department names, excluding Alice who doesn't belong to any department listed.
2. LEFT JOIN (or LEFT OUTER JOIN)
Purpose: Returns all rows from the left table and matched rows from the right table. If no match is found, NULLs are returned for columns from the right table.
Example:
SELECT employees.name, departments.dept_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;
Result: | name | dept_name | |-------|-----------| | John | HR | | Mary | Finance | | Alice | NULL |
Alice is included in the result set despite not having a matching department.
3. RIGHT JOIN (or RIGHT OUTER JOIN)
Purpose: Returns all rows from the right table and matched rows from the left table. If no match is found, NULLs are returned for columns from the left table.
Example:
SELECT employees.name, departments.dept_name
FROM employees
RIGHT JOIN departments ON employees.department_id = departments.department_id;
Result: | name | dept_name | |-------|-----------| | John | HR | | Mary | Finance | | NULL | IT |
The IT department is included in the result set as a standalone since there are no employees assigned to it.
4. FULL JOIN (or FULL OUTER JOIN)
Purpose: Returns all rows when there is a match in either left or right table records. If no match is found, the result is NULL on the side that doesn’t have a match.
Note: Not all SQL databases support FULL OUTER JOIN directly. You might need to use a UNION of LEFT and RIGHT JOINs as a workaround.
Query:
SELECT employees.name, departments.dept_name
FROM employees
FULL JOIN departments ON employees.department_id = departments.department_id;
Result: | name | dept_name | |-------|-----------| | John | HR | | Mary | Finance | | Alice | NULL | | NULL | IT |
Notice both Alice and the IT department are included in the result set.
5. CROSS JOIN
Purpose: Returns the Cartesian product of rows from the tables involved in the join.
Example:
SELECT employees.name, departments.dept_name
FROM employees
CROSS JOIN departments;
Result: | name | dept_name | |-------|-----------| | John | HR | | John | Finance | | John | IT | | Mary | HR | | Mary | Finance | | Mary | IT | | Alice | HR | | Alice | Finance | | Alice | IT |
Each employee is matched with every department, resulting in 9 records.
6. SELF JOIN
Purpose: Allows a table to be joined with itself. Useful when you need to compare rows of the same table.
Example: Suppose we need to find all pairs of employees who belong to the same department.
Table: employees | employee_id | name | department_id | |-------------|---------|---------------| | 1 | John | 101 | | 2 | Mary | 101 | | 3 | Alice | 102 |
Query:
SELECT e1.name AS Employee1, e2.name AS Employee2
FROM employees e1
JOIN employees e2 ON e1.department_id = e2.department_id AND e1.employee_id != e2.employee_id;
Result: | Employee1 | Employee2 | |-----------|-----------| | John | Mary | | Mary | John |
John and Mary share the same department.
Conclusion
Online Code run
Step-by-Step Guide: How to Implement SQL Practical Examples with Joins
Prerequisites
Create Sample Databases and Tables: We'll create two simple tables named
Employees
andDepartments
. These tables will have some fictional data to demonstrate joins.Employees Table
EmployeeID
: Unique identifier for each employee.FirstName
: Employee's first name.LastName
: Employee's last name.DepartmentID
: ID of the department where the employee works.
Departments Table
DepartmentID
: Unique identifier for each department.DepartmentName
: Name of the department.
Let's start by creating these tables and inserting some sample data into them.
-- Create the Employees table
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
-- Insert sample data into the Employees table
INSERT INTO Employees (EmployeeID, FirstName, LastName, DepartmentID) VALUES
(1, 'John', 'Doe', 1),
(2, 'Jane', 'Smith', 1),
(3, 'Emily', 'Jones', 2),
(4, 'Michael', 'Brown', 3),
(5, 'Sarah', 'Wilson', NULL); -- No department assigned
-- Create the Departments table
CREATE TABLE Departments (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50)
);
-- Insert sample data into the Departments table
INSERT INTO Departments (DepartmentID, DepartmentName) VALUES
(1, 'Sales'),
(2, 'Marketing'),
(3, 'Finance');
Now, let's proceed with different types of joins.
1. INNER JOIN
The most common type of join, INNER JOIN returns rows when there is a match in both tables.
Example: Retrieve the names and department names of employees who are assigned to a department.
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
INNER JOIN
Departments d ON e.DepartmentID = d.DepartmentID;
Steps Explained:
- FROM Employees e: We start with the
Employees
table. The aliase
makes it easier to write and read queries involving multiple tables. - INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID: Join condition is added to ensure that only those rows where
EmployeeID
inEmployees
matchesDepartmentID
inDepartments
are returned. The aliasd
is used forDepartments
table. - SELECT: The columns to be retrieved are specified from each table.
Result:
FirstName | LastName | DepartmentName
----------|----------|-----------------
John | Doe | Sales
Jane | Smith | Sales
Emily | Jones | Marketing
Michael | Brown | Finance
Notice that the employee Sarah Wilson
does not appear, as she has no matching DepartmentID
.
2. LEFT JOIN (or LEFT OUTER JOIN)
Left join returns all records from the left table (Employees
in this example) and the matched records from the right table (Departments
). If there is no match, results are NULL
on the side of the right table.
Example: Find the names and department names of all employees, including those without a department.
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
LEFT JOIN
Departments d ON e.DepartmentID = d.DepartmentID;
-- or LEFT OUTER JOIN instead of LEFT JOIN
Steps Explained:
- LEFT JOIN Departments d ON e.DepartmentID = d.DepartmentID: This part ensures that all employees are included in the result set. Only matched rows from
Departments
will have actual values; otherwise, they will containNULL
.
Result:
FirstName | LastName | DepartmentName
-----------|----------|-----------------
John | Doe | Sales
Jane | Smith | Sales
Emily | Jones | Marketing
Michael | Brown | Finance
Sarah | Wilson | NULL
Here, Sarah Wilson
appears with a NULL
value in the DepartmentName
column since her DepartmentID
is NULL
.
3. RIGHT JOIN (or RIGHT OUTER JOIN)
Right join returns all records from the right table (Departments
in this case) and the matched records from the left table (Employees
). It includes departments regardless of whether there’s an employee assigned to them or not.
Example: Fetch the names of departments along with the names of any corresponding employees. Departments without employees should still appear.
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
RIGHT JOIN
Departments d ON e.DepartmentID = d.DepartmentID;
-- or RIGHT OUTER JOIN instead of RIGHT JOIN
Steps Explained:
- RIGHT JOIN Departments d ON e.DepartmentID = d.DepartmentID: By using the right join, the query includes all records from the
Departments
table. If no employees correspond to a department, the fields from theEmployees
table will beNULL
.
Result:
FirstName | LastName | DepartmentName
----------|------------|----------------
John | Doe | Sales
Jane | Smith | Sales
Emily | Jones | Marketing
Michael | Brown | Finance
NULL | NULL | IT -- Assuming 'IT' was added to the table
In this example, we’ve assumed an additional department 'IT'
to show how departments without employees would look in the output (NULL
for FirstName
and LastName
).
4. FULL JOIN (or FULL OUTER JOIN)
A full join returns all records when there is a match in either left (Employees
) or right (Departments
) table. Rows with no match will contain NULL
on the side of the non-matching table.
Example: List all employees and departments, showing all combinations of employees and departments (including ones where there’s no match).
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
FULL JOIN
Departments d ON e.DepartmentID = d.DepartmentID;
-- or FULL OUTER JOIN instead of FULL JOIN
Note: Not all SQL databases (like MySQL) support FULL JOIN directly. However, you can achieve similar functionality using a combination of UNION operator with LEFT AND RIGHT joins.
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
LEFT JOIN
Departments d ON e.DepartmentID = d.DepartmentID
UNION ALL
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
RIGHT JOIN
Departments d ON e.DepartmentID = d.DepartmentID
WHERE
e.EmployeeID IS NULL;
Result:
FirstName | LastName | DepartmentName
-----------|------------|----------------
John | Doe | Sales
Jane | Smith | Sales
Emily | Jones | Marketing
Michael | Brown | Finance
Sarah | Wilson | NULL
NULL | NULL | IT -- Assuming 'IT' was added to the table
This result shows all employees and departments, even if there are no matching records between the tables.
5. CROSS JOIN
Cross join produces a Cartesian product of the two tables. This means every row from the first table is combined with every row from the second table, generating a huge result set.
Example: Combine every employee with every department to see possible assignments.
SELECT
e.FirstName,
e.LastName,
d.DepartmentName
FROM
Employees e
CROSS JOIN
Departments d;
Steps Explained:
- CROSS JOIN Departments d: Cross join combines every row from the
Employees
table with every row in theDepartments
table.
Result:
FirstName | LastName | DepartmentName
----------|----------|-----------------
John | Doe | Sales
John | Doe | Marketing
John | Doe | Finance
Jane | Smith | Sales
Jane | Smith | Marketing
Jane | Smith | Finance
Emily | Jones | Sales
Emily | Jones | Marketing
Emily | Jones | Finance
Michael | Brown | Sales
Michael | Brown | Marketing
Michael | Brown | Finance
Sarah | Wilson | Sales
Sarah | Wilson | Marketing
Sarah | Wilson | Finance
Notice that each employee appears with each department, resulting in a significant number of rows. This join is typically useful for generating permutations or combinations of data but is less commonly used due to its size.
6. SELF JOIN
A self join is a join performed on a single table to create a result set based on relationships within the same table.
Example Scenario:
Suppose we have a table called EmployeeHierarchy
which represents the managerial structure within a company. Each row has an EmployeeID
, FirstName
, LastName
, and a ManagerID
that refers to another EmployeeID
in the same table.
Creating the Self Join Table:
CREATE TABLE EmployeeHierarchy (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
ManagerID INT,
FOREIGN KEY (ManagerID) REFERENCES EmployeeHierarchy(EmployeeID)
);
-- Insert sample data into the EmployeeHierarchy table
INSERT INTO EmployeeHierarchy (EmployeeID, FirstName, LastName, ManagerID) VALUES
(1, 'Alice', 'Johnson', NULL), -- Alice is the CEO, no manager
(2, 'Bob', 'Williams', 1), -- Bob reports to Alice
(3, 'Charlie', 'Davis', 1), -- Charlie reports to Alice
(4, 'David', 'Miller', 2); -- David reports to Bob
Self Join Example: Fetch the names of each employee along with their manager's name.
SELECT
e1.FirstName AS EmployeeFirstName,
e1.LastName AS EmployeeLastName,
CONCAT(e2.FirstName, ' ', e2.LastName) AS ManagerName
FROM
EmployeeHierarchy e1 -- Alias for employee
LEFT JOIN
EmployeeHierarchy e2 -- Alias for manager
ON
e1.ManagerID = e2.EmployeeID;
Steps Explained:
- LEFT JOIN EmployeeHierarchy e2: We join the same table under different aliases.
e1
represents each employee, ande2
represents each manager. - ON e1.ManagerID = e2.EmployeeID: The join is performed where the
ManagerID
of an employee corresponds to theEmployeeID
of another row in the same table.
Result:
EmployeeFirstName | EmployeeLastName | ManagerName
------------------|-----------------|-------------
Alice | Johnson | NULL
Bob | Williams | Alice Johnson
Charlie | Davis | Alice Johnson
David | Miller | Bob Williams
- Alice Johnson is listed without a manager (since her
ManagerID
isNULL
). - Bob Williams and Charlie Davis report directly to Alice Johnson.
- David Miller reports to Bob Williams.
Conclusion
Understanding different SQL joins can greatly enhance your ability to analyze and manage relational data. Here’s a quick recap of what we covered:
- INNER JOIN: Returns rows with matching values in both tables.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all rows from the left table and matched rows from the right table; unmatched rows from the right table become
NULL
. - RIGHT JOIN (or RIGHT OUTER JOIN): Returns all rows from the right table and matched rows from the left table; unmatched rows from the left table become
NULL
. - FULL JOIN (or FULL OUTER JOIN): Includes all rows when there is a match in either table; unmatched rows become
NULL
. - CROSS JOIN: Combines each row from the left table with every row from the right table (Cartesian product).
- SELF JOIN: Performs a join operation on a single table.
Top 10 Interview Questions & Answers on SQL Practical Examples with Joins
Top 10 SQL Questions with Practical Join Examples
Q1: What is the difference between INNER JOIN and LEFT JOIN?
Answer:
INNER JOIN: Retrieves only the rows where there is a match in both tables.
SELECT employees.name, departments.dept_name FROM employees INNER JOIN departments ON employees.dept_id = departments.id;
LEFT JOIN (or LEFT OUTER JOIN): Includes all rows from the left table, and any matching rows from the right table. If no match is found on the right side, the result is NULL on those columns.
SELECT employees.name, departments.dept_name FROM employees LEFT JOIN departments ON employees.dept_id = departments.id;
Practical Example:
Imagine you want to list all employees along with their department names. An INNER JOIN
will exclude employees who don't belong to any department. A LEFT JOIN
ensures that all employee details are listed, showing NULL
for department names if they aren’t assigned to any department.
Q2: How would you find customers who didn't place any orders?
Answer:
This scenario can be effectively handled using a LEFT JOIN
.
SELECT customers.customer_id, customers.customer_name
FROM customers
LEFT JOIN orders ON customers.customer_id = orders.customer_id
WHERE orders.order_id IS NULL;
Explanation:
The query lists all customers and tries to match them with orders based on customer_id
. For customers without corresponding orders, the order_id
will be NULL
, fulfilling the condition.
Q3: Write a query to display product name and supplier name in a single table.
Answer:
Using an INNER JOIN
here because every product should have a supplier associated:
SELECT products.product_name, suppliers.supplier_name
FROM products
INNER JOIN suppliers ON products.supplier_id = suppliers.id;
Explanation:
This query pairs each product with its specific supplier using the supplier_id
.
Q4: How can you retrieve students who attend at least one course?
Answer:
Another practical use of LEFT JOIN
, where we aim to ensure all students are listed, even if they aren't enrolled in any course:
SELECT DISTINCT students.student_name
FROM students
LEFT JOIN enrollments ON students.student_id = enrollments.student_id
WHERE enrollments.course_id IS NOT NULL;
Explanation:
Here, the DISTINCT
keyword is used to avoid duplicates in case a student is enrolled in multiple courses. The condition enrollments.course_id IS NOT NULL
ensures listing only students who have at least one enrollment.
Q5: Display all departments including their managers, assuming not all departments may have a manager.
Answer:
To accommodate departments without managers, a LEFT JOIN
is appropriate:
SELECT departments.dept_name, employees.name AS manager_name
FROM departments
LEFT JOIN employees ON departments.manager_id = employees.id;
Explanation:
Managers are listed alongside their respective departments. Departments without managers will have a NULL
for manager_name
.
Q6: Write a query to fetch book titles along with the author’s name, using multiple join conditions.
Answer:
For this question, assume there's another table book_authors
that links books to authors:
SELECT books.title, authors.name
FROM books
JOIN book_authors ON books.id = book_authors.book_id
JOIN authors ON book_authors.author_id = authors.id;
Explanation:
Multiple joins allow us to relate books and authors through the intermediary book_authors
table, fetching book titles alongside author names.
Q7: Find the list of all products and their categories even if some products don't fall into any category.
Answer:
A FULL OUTER JOIN
ensures that all records from both tables are included. However, MySQL doesn’t support this directly; it’s achievable by combining LEFT JOIN
and RIGHT JOIN
:
SELECT p.product_name, c.category_name
FROM products p
LEFT JOIN categories c ON p.category_id = c.id
UNION ALL
SELECT p.product_name, c.category_name
FROM products p
RIGHT JOIN categories c ON p.category_id = c.id
WHERE p.product_name IS NULL;
Explanation:
The FULL OUTER JOIN
equivalent retrieves all products with their respective categories, along with any categories that do not have associated products.
Q8: What is a self-join, and how can it be used to find employees who report to a specific manager?
Answer:
A SELF-JOIN
is when a table is joined with itself.
SELECT e1.name AS employee_name, e2.name AS manager_name
FROM employees e1
JOIN employees e2 ON e1.manager_id = e2.id
WHERE e2.name = 'John Doe';
Explanation:
We assign aliases (e1
and e2
) to the same table to distinguish between employees and the managers they report to. Here, we're specifically looking for employees directly reporting to John Doe.
Q9: List all cities where a customer lives and where an order was placed.
Answer:
A CROSS JOIN
generates a Cartesian product of rows from two tables. To find overlapping cities, use a regular inner join followed by a self-join concept:
SELECT DISTINCT T1.city
FROM (
SELECT customer_address.city, customer_address.customer_id
FROM customer_address
JOIN orders ON customer_address.customer_id = orders.customer_id
) AS T1
CROSS JOIN (
SELECT customer_address.city
FROM customer_address
JOIN orders ON customer_address.customer_id = orders.customer_id
) AS T2
ON T1.city = T2.city;
However, a cleaner way involves a simple intersection:
SELECT customer_address.city
FROM customer_address
JOIN orders ON customer_address.customer_id = orders.customer_id;
-- This query already lists cities with both customer and order activity.
-- No need for cross-joins unless you specifically need all pairwise combinations.
Explanation:
This query uses a subquery to identify cities that have entries in both tables (customer_address
and orders
).
Q10: Retrieve the names of suppliers who provide products to more than one department.
Answer:
This can be achieved using GROUP BY
along with JOIN
:
SELECT s.supplier_name, COUNT(DISTINCT d.dept_name) AS departments_count
FROM products p
JOIN suppliers s ON p.supplier_id = s.id
JOIN departments d ON p.dept_id = d.id
GROUP BY s.supplier_name
HAVING COUNT(DISTINCT d.dept_name) > 1;
Explanation:
The query combines products
, suppliers
, and departments
. It groups suppliers based on supplier name and counts distinct departments they provide productsto. The HAVING
clause filters suppliers who serve more than one department.
Login to post a comment.