3 IM Lab Data Joins and Relational Concepts
3 IM Lab Data Joins and Relational Concepts
Objectives:
Lab Activities:
3.1 - CREATING RELATED TABLES WITH PRIMARY AND FOREIGN KEY CONSTRAINTS
Creating related tables with primary and foreign key constraints using SQL Server Management Studio
(SSMS) involves several steps. In this example, I'll demonstrate how to create two related tables: one
for "Customers" and another for "Orders," with a foreign key relationship between them.
Let's assume you have already connected to your SQL Server instance using SSMS. Here are the
steps:
To populate the "Customers" table with data, you can execute INSERT statements like this:
INSERT INTO Customers (CustomerID, FirstName, LastName, Email)
VALUES (1, 'John', 'Doe', '[email protected]');
To populate the "Orders" table with data, you can execute INSERT statements like this:
INSERT INTO Orders (OrderID, CustomerID, OrderDate, TotalAmount)
VALUES (101, 1, '2023-10-09', 50.00);
This will insert two sample order records into the "Orders" table, with each order associated with
a specific customer through the CustomerID foreign key.
1. Modify the "Enrollments" table to add a foreign key constraint that references both the
"Students" and "Courses" tables. The "Enrollments" table will represent the many-to-many
relationship between students and courses.
CREATE TABLE Enrollments (
EnrollmentID INT PRIMARY KEY,
StudentID INT,
CourseID INT,
CONSTRAINT FK_StudentID FOREIGN KEY (StudentID) REFERENCES
Students(StudentID),
CONSTRAINT FK_CourseID FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
3.2 - WRITING INNER JOIN QUERIES TO RETRIEVE DATA FROM RELATED TABLE
Writing INNER JOIN queries to retrieve data from related tables using SQL Server Management Studio
(SSMS) involves several steps. In this example, we'll use two related tables: "Customers" and "Orders."
The goal is to retrieve data from both tables using an INNER JOIN query. Here are the steps:
This query selects specific columns from both the "Customers" and "Orders" tables and joins them
based on the common "CustomerID" column. The INNER JOIN ensures that only matching rows from
both tables are returned.
SELECT
Students.FirstName,
Students.LastName,
Courses.CourseName
FROM
Students
INNER JOIN
Enrollments
ON
Students.StudentID = Enrollments.StudentID
INNER JOIN
Courses
ON
Enrollments.CourseID = Courses.CourseID;
Modify the previous query to retrieve students and their enrolled courses for a specific department (e.g.,
'Mathematics').
SELECT
Students.FirstName,
Students.LastName,
Courses.CourseName
FROM
Students
INNER JOIN
Enrollments
ON
Students.StudentID = Enrollments.StudentID
INNER JOIN
Courses
ON
Enrollments.CourseID = Courses.CourseID
WHERE
Courses.Department = 'Mathematics';
Write an INNER JOIN query to calculate the total number of students enrolled in each course.
SELECT
Courses.CourseName,
COUNT(Students.StudentID) AS EnrolledStudents
FROM
Courses
INNER JOIN
Enrollments
ON
Courses.CourseID = Enrollments.CourseID
INNER JOIN
Students
ON
Enrollments.StudentID = Students.StudentID
GROUP BY
Courses.CourseName;
In a database with multiple related tables (e.g., "Customers," "Orders," "OrderDetails"), write an INNER
JOIN query to retrieve a list of customers and the products they have ordered.
3.3 - USING LEFT JOIN AND RIGHT JOIN FOR DIFFERENT TYPES OF JOINS.
Using LEFT JOIN and RIGHT JOIN in SQL Server Management Studio (SSMS) allows you to retrieve
data from related tables, emphasizing records from one table or the other. Here are the steps for
performing LEFT JOIN and RIGHT JOIN in SSMS:
Before you can perform LEFT JOIN and RIGHT JOIN, ensure you have related tables with data. In
SSMS, create two tables, such as "Customers" and "Orders," and insert data into them.
A LEFT JOIN retrieves all records from the left table and matching records from the right table (if any).
Here's how to perform a LEFT JOIN:
SELECT
Customers.CustomerID,
Customers.FirstName,
Customers.LastName,
Orders.OrderID,
Orders.OrderDate
FROM
Customers
LEFT JOIN
Orders
ON
Customers.CustomerID = Orders.CustomerID;
This query retrieves customer information and includes orders made by customers (if they exist).
Customers without orders will also be included in the result.
A RIGHT JOIN retrieves all records from the right table and matching records from the left table (if any).
Here's how to perform a RIGHT JOIN:
SELECT
Customers.CustomerID,
Customers.FirstName,
Customers.LastName,
Orders.OrderID,
Orders.OrderDate
FROM
Customers
RIGHT JOIN
Orders
ON
Customers.CustomerID = Orders.CustomerID;
This query retrieves order information and includes customer information (if available) for each order.
Orders without associated customers will also be included in the result.
Execute the queries by clicking the "Execute" button or pressing F5. SSMS will display the results in the
query results pane.
By following these steps, you can use LEFT JOIN and RIGHT JOIN to retrieve data from related tables,
emphasizing records from the left or right table based on your specific requirements.
Before you can perform LEFT JOIN and RIGHT JOIN, create two tables, "Employees" and
"Departments," and insert data into them.
Write a query to retrieve a list of all employees and their corresponding department names using a
LEFT JOIN.
SELECT
Employees.EmployeeID,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM
Employees
LEFT JOIN
Departments
ON
Employees.DepartmentID = Departments.DepartmentID;
Modify the previous query to retrieve only employees who are not assigned to any department.
SELECT
Employees.EmployeeID,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM
Employees
LEFT JOIN
Departments
ON
Employees.DepartmentID = Departments.DepartmentID
WHERE
Departments.DepartmentName IS NULL;
Write a query to retrieve a list of all departments and their employees (if any) using a RIGHT JOIN.
SELECT
Employees.EmployeeID,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM
Employees
RIGHT JOIN
Departments
ON
Employees.DepartmentID = Departments.DepartmentID;
Modify the previous query to retrieve only departments that have no employees assigned.
SELECT
Employees.EmployeeID,
Employees.FirstName,
Employees.LastName,
Departments.DepartmentName
FROM
Employees
RIGHT JOIN
Departments
ON
Employees.DepartmentID = Departments.DepartmentID
WHERE
Employees.EmployeeID IS NULL;
Modify the previous query to use a RIGHT JOIN and retrieve a list of managers and their respective
employees (if any).
Practicing self-joins to work with hierarchical data is a common scenario when dealing with data
structures like organizational charts or threaded comments. Here are the steps to practice self-joins
using SQL Server Management Studio (SSMS):
In SSMS, create a table that will store hierarchical data. For this example, let's create a table named
"Employees" to represent an organizational structure. The table should have at least two columns: an
EmployeeID and a ManagerID which is a self-referencing foreign key to the EmployeeID column,
indicating the manager of each employee.
Insert data into the "Employees" table to represent your hierarchical structure. Ensure that you
establish the relationships between employees and their managers using the ManagerID column.
This query uses a recursive CTE to traverse the hierarchical structure, starting with employees who
have no managers (i.e., top-level managers) and then joining them with their direct reports in each
recursion.
Run the query in SSMS by clicking the "Execute" button or pressing F5. The result will show the
hierarchical structure of your organization.
You can customize the query to filter data or retrieve specific information about the hierarchy. For
example, you can use the CTE to count levels or find employees' direct reports.
In SSMS, create a table named "Employees" with columns EmployeeID, EmployeeName, and
ManagerID. The ManagerID column will be used for the self-join.
Insert sample data into the "Employees" table to represent an organizational hierarchy. Ensure that
employees are related to their respective managers using the ManagerID column.
Write a query using a recursive Common Table Expression (CTE) to retrieve the entire organizational
hierarchy starting from the top-level manager(s).
Write a query using a recursive CTE to retrieve all direct reports of a specific employee. You can
specify the employee's name or ID as a parameter in your query.
Write a query that, given an employee's name or ID, retrieves the name of their manager.
Extend the "Employees" table with a Department column, and write a query to filter employees by
department while maintaining the hierarchical structure.
Write a query that displays the hierarchy in a nested format, showing employees and their direct reports
with appropriate indentation to represent levels.
Create a graphical representation of the hierarchy as an organizational chart using SSMS or another
visualization tool. You can use the results from your CTE query to build the chart.
Expand your "Employees" table with more complex hierarchical scenarios, such as lateral moves,
promotions, or changes in managers. Write queries that handle these scenarios while maintaining data
integrity.