0% found this document useful (0 votes)
8 views11 pages

3 IM Lab Data Joins and Relational Concepts

Uploaded by

davethegreat343
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

3 IM Lab Data Joins and Relational Concepts

Uploaded by

davethegreat343
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Lab 3: Data Joins and Relational Concepts

Objectives:

 Explore the concept of relational databases.


 Understand different types of joins for combining data from multiple tables.

Lab Activities:

1. Creating related tables with primary and foreign key constraints.


2. Writing INNER JOIN queries to retrieve data from related tables.
3. Using LEFT JOIN and RIGHT JOIN for different types of joins
4. Practicing self-joins to work with hierarchical data.

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:

1. Create the "Customers" Table:


Open a new query window in SSMS and execute the following SQL script to create the
"Customers" table:

CREATE TABLE Customers (


CustomerID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Email NVARCHAR(100)
);
2. Create the "Orders" Table:
In the same query window, execute the following SQL script to create the "Orders" table:
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
TotalAmount DECIMAL(10, 2),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
This script creates the "Orders" table with a primary key constraint on the OrderID column and a
foreign key constraint that references the CustomerID column in the "Customers" table.

3. Insert Data into the "Customers" Table:

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]');

INSERT INTO Customers (CustomerID, FirstName, LastName, Email)


VALUES (2, 'Jane', 'Smith', '[email protected]');
This will insert two sample customer records into the "Customers" table.

4. Insert Data into the "Orders" Table:

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);

INSERT INTO Orders (OrderID, CustomerID, OrderDate, TotalAmount)


VALUES (102, 2, '2023-10-10', 75.50);

This will insert two sample order records into the "Orders" table, with each order associated with
a specific customer through the CustomerID foreign key.

Exercise 3.1a: Create Two Tables

1. Open SSMS and connect to your SQL Server instance.


2. Create a new database (if not already created) and select it using the USE statement:
USE YourDatabaseName;
3. Create a table called "Students" with columns for student information, including a primary key:
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName NVARCHAR(50),
LastName NVARCHAR(50),
Email NVARCHAR(100)
);
4. Create a table called "Courses" with columns for course information, including a primary key:
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName NVARCHAR(100),
Instructor NVARCHAR(100)
);

Exercise 3.1b: Add Foreign Key Constraint

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)
);

Exercise 3.1c: Insert Data

1. Insert data into the "Students" and "Courses" tables:


INSERT INTO Students (StudentID, FirstName, LastName, Email)
VALUES (1, 'John', 'Doe', '[email protected]');

INSERT INTO Courses (CourseID, CourseName, Instructor)


VALUES (101, 'Math 101', 'Professor Smith');
2. Insert data into the "Enrollments" table to associate students with courses:
INSERT INTO Enrollments (EnrollmentID, StudentID, CourseID)
VALUES (1, 1, 101);

Exercise 3.1d: Query Data


1. Write SQL queries to retrieve information from the tables. For example:
a. Retrieve all students enrolled in a specific course.
b. Retrieve all courses taken by a specific student.
c. Retrieve the full name of the instructor for a course.

Exercise 3.1e: Update and Delete Data


1. Update existing records in the "Students," "Courses," and "Enrollments" tables.
2. Delete records from the tables while ensuring that referential integrity is maintained.

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:

1. Create Tables and Insert Data (if not already done):


 Before writing INNER JOIN queries, ensure that you have already created the
"Customers" and "Orders" tables and inserted some data into them, as shown in a
previous response.
2. Open SQL Server Management Studio (SSMS):
 Launch SSMS and connect to your SQL Server instance.
3. Open a New Query Window:
 Click on "New Query" to open a new query window in SSMS.
4. Write the INNER JOIN Query:
Write an INNER JOIN query to retrieve data from the related tables. In this case, we want to
retrieve customer information along with their orders:
SELECT
Customers.CustomerID,
Customers.FirstName,
Customers.LastName,
Orders.OrderID,
Orders.OrderDate,
Orders.TotalAmount
FROM
Customers
INNER JOIN
Orders
ON
Customers.CustomerID = Orders.CustomerID;

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.

5. Execute the Query:


 Click the "Execute" button (or press F5) to run the query. SSMS will execute the query
and display the results in the query results pane.
6. View the Results:
 You will see a result set containing columns from both tables, with data joined based on
the "CustomerID" column. This allows you to see which customer made each order.
7. Customize Your Query:
 You can customize your INNER JOIN query as needed. For example, you can add
conditions using the WHERE clause or join multiple tables if your database schema
includes more related tables.

Here's a breakdown of the query:


 The SELECT statement lists the columns you want to retrieve from both tables.
 The FROM clause specifies the tables you are querying ("Customers" and "Orders").
 The INNER JOIN clause defines the join condition, which is based on the "CustomerID"
column in both tables.
 The query retrieves data from both tables, combining it based on the matching "CustomerID"
values.

Exercise 3.2a: Create Tables and Insert Data


Before you can perform INNER JOIN queries, you need related tables with data. In SSMS, create two
tables, such as "Students" and "Courses," and insert data into them.

Exercise 3.2b: Write Basic INNER JOIN Query


Write an INNER JOIN query to retrieve a list of students and the courses they are enrolled in.

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;

Exercise 3.2c: Filter the Results

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';

Exercise 3.2d: Aggregate Data

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;

Exercise 3.2d: Self-Join


Create a table called "Employees" with a self-referencing foreign key called "ManagerID" to represent
employee-manager relationships. Write an INNER JOIN query to retrieve the names of employees and
their respective managers.

Exercise 3.2e: Multiple INNER JOINs

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:

Create Tables and Insert Data (if not already done):

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.

Performing a LEFT JOIN:

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.

Performing a RIGHT JOIN:

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.

View the Results:

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.

Exercise 1: Create Tables and Insert Data

Before you can perform LEFT JOIN and RIGHT JOIN, create two tables, "Employees" and
"Departments," and insert data into them.

Exercise 2: Perform a LEFT JOIN

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;

Exercise 3: Filter Results with LEFT JOIN

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;

Exercise 4: Perform a RIGHT JOIN

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;

Exercise 5: Filter Results with RIGHT JOIN

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;

Exercise 6: Self-Join with LEFT JOIN


Create a table called "Employees" with a self-referencing foreign key called "ManagerID" to represent
employee-manager relationships. Write a query using LEFT JOIN to retrieve a list of employees and
their respective managers.

Exercise 7: Self-Join with RIGHT JOIN

Modify the previous query to use a RIGHT JOIN and retrieve a list of managers and their respective
employees (if any).

3.4 - PRACTICING SELF-JOINS TO WORK WITH HIERARCHICAL DATA

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):

Step 1: Create a Table

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.

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
EmployeeName NVARCHAR(50),
ManagerID INT,
CONSTRAINT FK_ManagerID FOREIGN KEY (ManagerID) REFERENCES
Employees(EmployeeID)
);

Step 2: Insert Data

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.

INSERT INTO Employees (EmployeeID, EmployeeName, ManagerID)


VALUES
(1, 'John', NULL), -- John is the top-level manager
(2, 'Alice', 1), -- Alice reports to John
(3, 'Bob', 1), -- Bob also reports to John
(4, 'Charlie', 2), -- Charlie reports to Alice
(5, 'David', 2), -- David also reports to Alice
(6, 'Eve', 3); -- Eve reports to Bob

Step 3: Querying Hierarchical Data


To retrieve hierarchical data, you'll use a recursive self-join. SQL Server provides a common table
expression (CTE) and the WITH RECURSIVE syntax to make this process easier. Here's an example
query that retrieves the hierarchy starting from the top-level manager:
WITH EmployeeHierarchy AS (
SELECT EmployeeID, EmployeeName, ManagerID
FROM Employees
WHERE ManagerID IS NULL -- Start with top-level managers
UNION ALL
SELECT e.EmployeeID, e.EmployeeName, e.ManagerID
FROM Employees e
INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT EmployeeID, EmployeeName, ManagerID
FROM EmployeeHierarchy;

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.

Step 4: Execute the Query

Run the query in SSMS by clicking the "Execute" button or pressing F5. The result will show the
hierarchical structure of your organization.

Step 5: Customizing the Query

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.

Exercise 3.4a: Create and Populate the Employees Table

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.

Exercise 3.4b: Query the Entire Hierarchy

Write a query using a recursive Common Table Expression (CTE) to retrieve the entire organizational
hierarchy starting from the top-level manager(s).

Exercise 3.4c: Query a Specific Employee's Direct Reports

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.

Exercise 3.4d: Find the Depth of the Hierarchy


Write a query to calculate the depth or level of the hierarchy for each employee. In other words,
determine how many levels down each employee is from the top-level manager.

Exercise 3.4e: Find the Manager of a Specific Employee

Write a query that, given an employee's name or ID, retrieves the name of their manager.

Exercise 3.4f: Filter Employees by Department

Extend the "Employees" table with a Department column, and write a query to filter employees by
department while maintaining the hierarchical structure.

Exercise 3.4g: Display the Hierarchy in a Nested Format

Write a query that displays the hierarchy in a nested format, showing employees and their direct reports
with appropriate indentation to represent levels.

Exercise 3.4h: Display the Hierarchy as an Org Chart

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.

Exercise 3.4i: Add More Complex Hierarchies

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.

You might also like