0% found this document useful (0 votes)
24 views33 pages

DDBS Lab File

The document outlines a series of assignments related to distributed databases, including the creation of tables for student and employee data, SQL queries for data retrieval and manipulation, and horizontal fragmentation algorithms. It includes examples of SQL commands for creating tables, inserting data, and performing queries to analyze employee and project information. Additionally, it discusses access patterns and fragmentation strategies to optimize database performance.

Uploaded by

parul.gupta.ug22
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)
24 views33 pages

DDBS Lab File

The document outlines a series of assignments related to distributed databases, including the creation of tables for student and employee data, SQL queries for data retrieval and manipulation, and horizontal fragmentation algorithms. It includes examples of SQL commands for creating tables, inserting data, and performing queries to analyze employee and project information. Additionally, it discusses access patterns and fragmentation strategies to optimize database performance.

Uploaded by

parul.gupta.ug22
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/ 33

DISTRIBUTED DATABASES

(CDCSC18)

Name: PARUL GUPTA


Roll No: 2022UCD2140
SEM-6, CSDS
DDBS LAB ASSIGNMENT-1
Create 3 tables:

1. Student: Contains student details (attributes: student_id, student_name, age).

2. Enrollment: Contains course enrollment details (attributes: enrollment_id, student_id,


course_id).

3. Course: Contains course details (attributes: course_id, course_name).

QUESTIONS

1. Retrieve student names and the courses they are enrolled in:

SELECT s.student_name,
(SELECT c.course_name
FROM Course c
WHERE c.course_id = e.course_id) AS course_name
FROM Student s
JOIN Enrollment e ON s.student_id = e.student_id;

2. Retrieve all students, along with their enrolled courses (if any)

SELECT Student.student_name, course.course_name


FROM Student
LEFT JOIN Enrollment ON student.student_id = enrollement.student_id
LEFT JOIN Course ON enrollment.course_id = course.course_id;

3. Retrieve all courses, along with the students enrolled in each course (if any):

SELECT c.course_name,
(SELECT s.student_name
FROM Student s
WHERE s.student_id = e.student_id) AS student_name
FROM Course c
LEFT JOIN Enrollment e ON c.course_id = e.course_id;

4. Retrieve all students and courses, showing matches where available and NULL values
otherwise:

SELECT s.student_name, c.course_name


FROM Student s
LEFT JOIN Enrollment e ON s.student_id = e.student_id
LEFT JOIN Course c ON e.course_id = c.course_id

UNION

SELECT s.student_name, c.course_name


FROM Student s
RIGHT JOIN Enrollment e ON s.student_id = e.student_id
RIGHT JOIN Course c ON e.course_id = c.course_id;

Created tables for Q2:


 Employee (attributes: EmpID, Name, Department, Salary).

CREATE TABLE Employee (


EmpID INT PRIMARY KEY,
Name VARCHAR(50) NOT NULL,
Department INT NOT NULL,
Salary DECIMAL(10, 2) CHECK (Salary > 20000),
FOREIGN KEY (Department) REFERENCES Department(DeptID)
);

 Department (attributes: DeptID, DeptName, ManagerID).

CREATE TABLE Department (


DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL,
ManagerID INT UNIQUE
);

Inserting Valid Data:

INSERT INTO Department (DeptID, DeptName, ManagerID) VALUES


(1, 'HR', 101),
(2, 'Finance', 102),
(3, 'IT', 103);

INSERT INTO Employee (EmpID, Name, Department, Salary) VALUES


(1, 'Rajesh Kumar', 1, 45000),
(2, 'Anita Sharma', 2, 55000),
(3, 'Vikram Mehta', 3, 60000),
(4, 'Priya Verma', 1, 30000);

Queries to Violate Constraints

1. Attempt to Insert an Employee with Salary <= 20000:

INSERT INTO Employee (EmpID, Name, Department, Salary) VALUES


(5, 'Rohit Gupta', 2, 20000);
DDBS LAB ASSIGNMENT-2

1. Display whole address of employee along with name


SELECT Ename AS "Emp Name",
CONCAT(E_House, ', ', E_Street, ', ', ECity) AS "Address"
FROM Employee;

2. Display 30% top records of Employees

For SQL Server:

SELECT TOP 30 PERCENT *


FROM Employee
ORDER BY E_Basic_Salary DESC;

3. Display names of employees whose address is "house number 44, street no


25, Rwp"
SELECT Ename
FROM Employee
WHERE CONCAT(E_House, ', ', E_Street, ', ', ECity) = 'House 44, Street 25,
rwp';

4. Display data of employees living in "isb, rwp, khi, or lhr" (without OR


keyword)
SELECT *
FROM Employee
WHERE ECity IN ('isb', 'rwp', 'khi', 'lhr');
5. Display employees whose age is more than 18 and less than 33 (without > or
<)

SELECT *
FROM Employee
WHERE EAge BETWEEN 19 AND 32;

6. Display employees whose name starts with "S" and does not contain "I"
SELECT *
FROM Employee
WHERE Ename LIKE 'S%' AND Ename NOT LIKE '%I%';
7. Display unique cities of employees
SELECT DISTINCT ECity
FROM Employee;

8. Display employees from "isb" ordered by age (youngest to oldest)


SELECT *
FROM Employee
WHERE ECity = 'isb'
ORDER BY EAge ASC;
9. Display employee name and total salary (basic salary + bonus)
SELECT Ename,
(E_Basic_Salary + E_Bonus) AS Total_Salary
FROM Employee;

10. Display total number of employees


SELECT COUNT(*) AS Total_Employees
FROM Employee;
11. Display total employees in each department
SELECT E_Department,
COUNT(*) AS Total_Employees
FROM Employee
GROUP BY E_Department;

12. Display total expenditures of the company


SELECT SUM(E_Basic_Salary + E_Bonus) +
(SELECT SUM(p_bonus) FROM Project) AS Total_Expenditures
FROM Employee;
13. Display names of projects in which ‘Ahmar’ is working
SELECT pName
FROM Project
WHERE Eid = (SELECT Eid FROM Employee WHERE Ename = 'Ahmar');

14. Display total project bonus of ‘Danish’


SELECT SUM(p_bonus) AS Total_Project_Bonus
FROM Project
WHERE Eid = (SELECT Eid FROM Employee WHERE Ename = 'Danish');

15. Display total expenditures of departments where expenditures > 1M


SELECT E_Department,
SUM(E_Basic_Salary + E_Bonus) AS Total_Department_Expenditures
FROM Employee
GROUP BY E_Department
HAVING SUM(E_Basic_Salary + E_Bonus) > 1000000;
16. Create Employee table
CREATE TABLE Employee (
Eid INT PRIMARY KEY,
Ename VARCHAR(50),
EAge INT CHECK (EAge BETWEEN 18 AND 60),
ECity VARCHAR(50),
E_Street VARCHAR(50),
E_House VARCHAR(50),
E_Basic_Salary DECIMAL(10, 2),
E_Bonus DECIMAL(10, 2) DEFAULT 0,
E_Rank VARCHAR(20) CHECK (E_Rank IN ('Manager', 'Developer', 'Admin')),
E_Department VARCHAR(20) DEFAULT 'CS'
);

17. Create Project table


CREATE TABLE Project (
p_id INT,
pName VARCHAR(50),
p_bonus DECIMAL(10, 2),
duration_in_months INT,
Eid INT,
PRIMARY KEY (p_id, Eid),
FOREIGN KEY (Eid) REFERENCES Employee(Eid)
);
18. Insert a record into Employee table (without E_Department and E_Bonus)
INSERT INTO Employee (Eid, Ename, EAge, ECity, E_Street, E_House,
E_Basic_Salary, E_Rank)
VALUES (7, 'Hamza', 29, 'lhr', 'Street 12', 'House 50', 65000,
'Developer');

19. Add 5% increment to all employee salaries


UPDATE Employee
SET E_Basic_Salary = E_Basic_Salary * 1.05;
20. Delete employees with a salary above 1 Million
DELETE FROM Employee
WHERE (E_Basic_Salary + E_Bonus) > 1000000;
21. Change E_Bonus data type to FLOAT
ALTER TABLE Employee
MODIFY COLUMN E_Bonus FLOAT;

22. Add primary key to Employee table


ALTER TABLE Employee
ADD CONSTRAINT PK_Eid PRIMARY KEY (Eid);

23. Drop primary key constraint


ALTER TABLE Employee
DROP CONSTRAINT PK_Eid;

24. Add a new column e_father_name to Employee table


ALTER TABLE Employee
ADD COLUMN e_father_name VARCHAR(50);

25. Drop E_Age column from Employee table


ALTER TABLE Employee
DROP COLUMN EAge;
DDBS LAB ASSIGNMENT-3
Consider the two relations EMP and ASG given in the the image. Insert 100 records in each
by assumed values. Also Apply several predicates to execute the queries, given four different
sites.
1. The first query is issued at four sites and finds the names and budgets of projects given
their location.

SELECT EMP.ENAME, PROJECTS.LOCATION, PROJECTS.BUDGET

FROM EMP

JOIN ASG ON EMP.ENO = ASG.ENOJOIN PROJECTS ON ASG.PNO = PROJECTS.PNO

WHERE PROJECTS.LOCATION IN ('New York', 'Chicago', 'San Francisco', 'Los Angeles');


2. The second query is for Those projects that have a budget of less than or equal to
$200,000 are managed at one site, budget between $240000 and $ 320000 are managed at
second site whereas those between $350000 and $ 450000 budgets are managed at a third
site, whereas those with larger budgets are managed at a fourth site.

SELECT

CASE

WHEN BUDGET <= 200000 THEN 'Site 1'

WHEN BUDGET BETWEEN 240000 AND 320000 THEN 'Site 2'

WHEN BUDGET BETWEEN 350000 AND 450000 THEN 'Site 3'

ELSE 'Site 4'

END AS Site,

PROJECTS.PNO,

PROJECTS.BUDGET

FROM PROJECTS;
DDBS LAB ASSIGNMENT-4

Q)Consider the Relations given in the lab assignment:3, Implement the COM_MIN and
PHORIZONTAL Algorithms (as discussed in the classroom) to obtain the horizontal fragmentations for
any given relation and predicates. The inputs and outputs must be corresponding to these
algorithms given in the book pdf. You can refer to the different predicates given in the book.

Predicates for EMP Table


P1: TITLE = ‘Elect. Eng.’
P2: TITLE = ‘Syst. Anal.’
P3: TITLE = ‘Mech. Eng.’
P4: TITLE = ‘Programmer’

Predicates for ASG Table


P5: RESP = ‘Manager’
P6: RESP = ‘Analyst’
P7: RESP = ‘Engineer’
P8: DUR <= 12
P9: DUR BETWEEN 12 AND 36
P10: DUR > 36

Applying COM_MIN Algorithm:

Minimal predicates-
1.Remove redundancy (if DUR > 36, we don’t need DUR BETWEEN 12 AND 36).
2. Combine independent predicates.

For the EMP Table, we get:

Fragment 1 (EMP_F1): Employees who are Elect. Eng.

Fragment 2 (EMP_F2): Employees who are Syst. Anal.

Fragment 3 (EMP_F3): Employees who are Mech. Eng.

Fragment 4 (EMP_F4): Employees who are Programmer

For the ASG Table, we get:

Fragment 1 (ASG_F1): RESP = ‘Manager’ AND DUR > 36

Fragment 2 (ASG_F2): RESP = ‘Analyst’ AND DUR BETWEEN 12 AND 36

Fragment 3 (ASG_F3): RESP = ‘Engineer’ AND DUR <= 12


Apply P HORIZONTAL Algo:

SQL Queries for EMP Table

CREATE TABLE EMP_F1 AS SELECT * FROM EMP WHERE TITLE = ‘Elect. Eng.’;
CREATE TABLE EMP_F2 AS SELECT * FROM EMP WHERE TITLE = ‘Syst. Anal.’;
CREATE TABLE EMP_F3 AS SELECT * FROM EMP WHERE TITLE = ‘Mech. Eng.’;
CREATE TABLE EMP_F4 AS SELECT * FROM EMP WHERE TITLE = ‘Programmer’;

SQL Queries for ASG Table

CREATE TABLE ASG_F1 AS SELECT * FROM ASG WHERE RESP = ‘Manager’ AND DUR > 36;
CREATE TABLE ASG_F2 AS SELECT * FROM ASG WHERE RESP = ‘Analyst’ AND DUR BETWEEN 12 AND
36;
CREATE TABLE ASG_F3 AS SELECT * FROM ASG WHERE RESP = ‘Engineer’ AND DUR <= 12;

After executing these queries:

EMP is horizontally fragmented into EMP_F1 to EMP_F4.

ASG is horizontally fragmented into ASG_F1 to ASG_F3.

DDBS LAB ASSIGNMENT-5


Step 1: Analyze Access Patterns
- A1: Accesses `EmpID` and `Sal`.
- A2: Accesses `EmpID`, `Name`, `Loc`, and `Dept` (filtered by `Dept = 'Eng'`).
- A3: Accesses `EmpID`, `Name`, `Loc`, and `Dept` (filtered by `Loc = 'STP'`).
- A4: Accesses `EmpID`, `Name`, `Loc`, and `Dept` (filtered by `Loc = 'MPLS'`).

Step 2: Identify Common Attribute Groups


- `EmpID` is accessed by all applications, so it should be included in every fragment.
- `Sal` is only accessed by A1.
- `Name`, `Loc`, and `Dept` are accessed together by A2, A3, and A4.

Step 3: Design Fragments


1. Fragment F1: Contains `EmpID` and `Sal`.
- This fragment is optimized for A1, which only needs `EmpID` and `Sal`.

2. Fragment F2: Contains `EmpID`, `Name`, `Loc`, and `Dept`.


- This fragment is optimized for A2, A3, and A4, which all need `EmpID`, `Name`,
`Loc`, and `Dept`.

Step 4: Validate the Fragmentation Strategy


- A1will access F1 to get `EmpID` and `Sal`.
- A2, A3, and A4 will access F2 to get `EmpID`, `Name`, `Loc`, and `Dept`.
- Since `EmpID` is included in both fragments, it acts as a common key to join the
fragments if needed.

Step 5: Final Fragmentation Schema


The final vertical fragmentation schema is:
- F1(EmpID, Sal)
- F2(EmpID, Name, Loc, Dept)

DDBS LAB ASSIGNMENT-6


ANSWER-1
1.SELECT B.Book_id, B.Title, B.Publisher_Name, B.Pub_Year,
GROUP_CONCAT(A.Author_Name) AS Authors,
BC.Branch_id, BC.No_of_Copies,
P.Address AS Publisher_Address, P.Phone AS Publisher_Phone
FROM BOOK B
JOIN BOOK_AUTHORS A ON B.Book_id = A.Book_id
JOIN PUBLISHER P ON B.Publisher_Name = P.Name
JOIN BOOK_COPIES BC ON B.Book_id = BC.Book_id
GROUP BY B.Book_id, BC.Branch_id;

2. SELECT BL.Card_No, COUNT(BL.Book_id) AS Books_Borrowed


FROM BOOK_LENDING BL
WHERE BL.Date_Out BETWEEN '2017-01-01' AND '2017-06-30'
GROUP BY BL.Card_No
HAVING COUNT(BL.Book_id) > 3;
________________________________________________________
3. -- Step 1: Delete from dependent tables first to maintain referential
integrity
DELETE FROM BOOK_AUTHORS WHERE Book_id = 'BOOK_ID';
DELETE FROM BOOK_COPIES WHERE Book_id = 'BOOK_ID';
DELETE FROM BOOK_LENDING WHERE Book_id = 'BOOK_ID';

-- Step 2: Delete the book from BOOK table


DELETE FROM BOOK WHERE Book_id = 'BOOK_ID';
________________________________________________________

4.CREATE TABLE BOOK_PARTITIONED (


Book_id INT PRIMARY KEY,
Title VARCHAR(255),
Publisher_Name VARCHAR(255),
Pub_Year INT
)
PARTITION BY RANGE (Pub_Year) (
PARTITION p1 VALUES LESS THAN (2000),
PARTITION p2 VALUES LESS THAN (2010),
PARTITION p3 VALUES LESS THAN (2020),
PARTITION p4 VALUES LESS THAN (2030)
);
SELECT * FROM BOOK_PARTITIONED PARTITION (p2);
________________________________________________________
5. CREATE VIEW Available_Books AS
SELECT B.Book_id, B.Title, B.Publisher_Name,
SUM(BC.No_of_Copies) AS Total_Available_Copies
FROM BOOK B
JOIN BOOK_COPIES BC ON B.Book_id = BC.Book_id
GROUP BY B.Book_id;
________________________________________________________
ANSWER-2

1. SELECT S.*
FROM STUDENT S
JOIN CLASS C ON S.USN = C.USN
JOIN SEMSEC SS ON C.SSID = SS.SSID
WHERE SS.Sem = 4 AND SS.Sec = 'C';
________________________________________________________
2. SELECT SS.Sem, SS.Sec, S.Gender, COUNT(*) AS Total_Students
FROM STUDENT S
JOIN CLASS C ON S.USN = C.USN
JOIN SEMSEC SS ON C.SSID = SS.SSID
GROUP BY SS.Sem, SS.Sec, S.Gender;
________________________________________________________
3. CREATE VIEW Test1_Marks AS
SELECT I.USN, I.Subcode, S.Title, I.Test1
FROM IAMARKS I
JOIN SUBJECT S ON I.Subcode = S.Subcode
WHERE I.USN = '1BI15CS101';
________________________________________________________
4. UPDATE IAMARKS
SET FinalCA = (Test1 + Test2 + Test3 - LEAST(Test1, Test2, Test3)) / 2;
________________________________________________________
5. SELECT S.USN, S.SName, SS.Sem, SS.Sec, I.FinalCA,
CASE
WHEN I.FinalCA BETWEEN 17 AND 20 THEN 'Outstanding'
WHEN I.FinalCA BETWEEN 12 AND 16 THEN 'Average'
WHEN I.FinalCA < 12 THEN 'Weak'
END AS CAT
FROM STUDENT S
JOIN CLASS C ON S.USN = C.USN
JOIN SEMSEC SS ON C.SSID = SS.SSID
JOIN IAMARKS I ON S.USN = I.USN
WHERE SS.Sem = 8 AND SS.Sec IN ('A', 'B', 'C')
GROUP BY S.USN, I.FinalCA;

DDBS LAB ASSIGNMENT-7


EXAMPLE 2.14 FROM BOOK
import numpy as np

def bond_energy(sequence, affinity_matrix):


energy = 0
for i in range(len(sequence)):
if i > 0:
energy += affinity_matrix[sequence[i - 1]][sequence[i]]
if i < len(sequence) - 1:
energy += affinity_matrix[sequence[i]][sequence[i + 1]]
return energy

def optimize_order_bond_energy(num_attributes, affinity_matrix):


sequence = list(range(num_attributes))
improved = True
while improved:
improved = False
for i in range(num_attributes):
for j in range(i + 1, num_attributes):
new_sequence = sequence[:]
new_sequence[i], new_sequence[j] = new_sequence[j],
new_sequence[i]
if bond_energy(new_sequence, affinity_matrix) >
bond_energy(sequence, affinity_matrix):
sequence = new_sequence
improved = True
return sequence

if __name__ == "__main__":
num_attributes = int(input("Enter the number of attributes: "))

print("Enter the attribute affinity matrix row by row (separated by


spaces):")
affinity_matrix = []
for i in range(num_attributes):
row = list(map(int, input(f"Row {i + 1}: ").split()))
affinity_matrix.append(row)

affinity_matrix = np.array(affinity_matrix)

print("\nInput Attribute Affinity Matrix:")


print(affinity_matrix)

optimized_sequence =
optimize_order_bond_energy(affinity_matrix.shape[0], affinity_matrix)

print("\nOptimized Attribute Order:")


print(optimized_sequence)
clustered_affinity_matrix =
affinity_matrix[np.ix_(optimized_sequence, optimized_sequence)]
print("\nClustered Affinity Matrix:")
print(clustered_affinity_matrix)

DDBS LAB ASSIGNMENT-8

CREATE TABLE BIIT_Student (


CNIC VARCHAR(20) PRIMARY KEY,
sName VARCHAR(100),
sAge INT,
sCity VARCHAR(100),
Semester INT
);

-- Create NSUT_Student Table


CREATE TABLE NSUT_Student (
CNIC VARCHAR(20) PRIMARY KEY,
sName VARCHAR(100),
sAge INT,
sCity VARCHAR(100),
Semester INT,
phoneNo VARCHAR(15)
);

-- Create UAAR_Student Table


CREATE TABLE UAAR_Student (
CNIC VARCHAR(20) PRIMARY KEY,
sName VARCHAR(100),
sAge INT,
CGPA DECIMAL(3,2),
sCity VARCHAR(100),
Semester INT
);
-- Insert records into BIIT_Student
INSERT INTO BIIT_Student (CNIC, sName, sAge, sCity, Semester) VALUES
('12345-6789012-3', 'Ali Khan', 20, 'Islamabad', 4),
('23456-7890123-4', 'Sara Ahmed', 22, 'Lahore', 6),
('34567-8901234-5', 'Hassan Raza', 21, 'Karachi', 5),
('45678-9012345-6', 'Ayesha Noor', 23, 'Peshawar', 7),
('56789-0123456-7', 'Bilal Saeed', 20, 'Quetta', 3);

-- Insert records into NSUT_Student


INSERT INTO NSUT_Student (CNIC, sName, sAge, sCity, Semester, phoneNo)
VALUES
('12345-6789012-3', 'Ali Khan', 20, 'Islamabad', 4, '03123456789'),
('67890-1234567-8', 'Nadia Jamil', 22, 'Faisalabad', 6, '03214567890'),
('23456-7890123-4', 'Sara Ahmed', 22, 'Lahore', 6, '03325678901'),
('78901-2345678-9', 'Usman Tariq', 24, 'Multan', 8, '03436789012'),
('89012-3456789-0', 'Farah Sheikh', 21, 'Rawalpindi', 5, '03547890123');

-- Insert records into UAAR_Student


INSERT INTO UAAR_Student (CNIC, sName, sAge, CGPA, sCity, Semester) VALUES
('34567-8901234-5', 'Hassan Raza', 21, 3.75, 'Karachi', 5),
('67890-1234567-8', 'Nadia Jamil', 22, 3.90, 'Faisalabad', 6),
('89012-3456789-0', 'Farah Sheikh', 21, 3.45, 'Rawalpindi', 5),
('56789-0123456-7', 'Bilal Saeed', 20, 3.80, 'Quetta', 3),
('45678-9012345-6', 'Ayesha Noor', 23, 3.60, 'Peshawar', 7);

SELECT CNIC FROM BIIT_Student


UNION
SELECT CNIC FROM NSUT_Student;

SELECT sName FROM BIIT_Student


UNION
SELECT sName FROM NSUT_Student
UNION
SELECT sName FROM UAAR_Student;

SELECT CNIC, sName, sAge, sCity, Semester


FROM BIIT_Student
INTERSECT
SELECT CNIC, sName, sAge, sCity, Semester
FROM UAAR_Student;

SELECT sName FROM BIIT_Student


EXCEPT
SELECT sName FROM NSUT_Student;

SELECT * FROM BIIT_Student


WHERE CNIC IN (
SELECT CNIC FROM BIIT_Student
INTERSECT
SELECT CNIC FROM NSUT_Student
INTERSECT
SELECT CNIC FROM UAAR_Student
);
SELECT sCity FROM BIIT_Student
UNION
SELECT sCity FROM NSUT_Student
UNION
SELECT sCity FROM UAAR_Student;

SELECT sCity FROM BIIT_Student


INTERSECT
SELECT sCity FROM NSUT_Student
INTERSECT
SELECT sCity FROM UAAR_Student;

SELECT COUNT(*) FROM BIIT_Student


WHERE CNIC NOT IN (SELECT CNIC FROM NSUT_Student)
AND CNIC NOT IN (SELECT CNIC FROM UAAR_Student);

SELECT COUNT(*) FROM BIIT_Student


WHERE CNIC IN (
SELECT CNIC FROM BIIT_Student
INTERSECT
SELECT CNIC FROM NSUT_Student
INTERSECT
SELECT CNIC FROM UAAR_Student
);

SELECT * FROM NSUT_Student


WHERE CNIC IN (SELECT CNIC FROM BIIT_Student)
AND CNIC NOT IN (SELECT CNIC FROM UAAR_Student);
DDBS LAB ASSIGNMENT-9
Consider Following Tables:-
Student( regNo, sName, sCity, sCGPA, sAge)
Course( cCode, cName, credit_hours)
Enrollment (regNo, cCode, semester, Grade)

Execute SQL queries for the following statements:-


(NOTE: you must use “CARTESIAN PRODUCT” query only.)
1- Display names of all those students who have “A” grades.
2- Display student name and cCode of all those students who have ‘F’ grade in 5th semester.
3- Display data of all those students who have enrolled at least 10 courses.
4- Display grade of ‘Ali’ in course ‘CS101’.
5- Display all Grades of ‘Irshad’ in 7th semester.
6- Display names of all courses and grades of ‘Amir’.
7- Display list of courses which are taught in 7th semester (course name must not repeat).
8- Display list of all students by name and course name they have enrolled.
9- Display total number of ‘F’ grade by ‘Amir’.
10- Display all those students who have not enrolled any course yet.

SELECT DISTINCT s.sName


FROM Student s, Enrollment e
WHERE s.regNo = e.regNo
AND e.Grade = 'A';

SELECT s.sName, e.cCode


FROM Student s, Enrollment e
WHERE s.regNo = e.regNo
AND e.Grade = 'F'
AND e.semester = 5;

SELECT s.regNo, s.sName, s.sCity, s.sCGPA, s.sAge


FROM Student s, Enrollment e
WHERE s.regNo = e.regNo
GROUP BY s.regNo, s.sName, s.sCity, s.sCGPA, s.sAge
HAVING COUNT(e.cCode) >= 10;

SELECT e.Grade
FROM Student s, Enrollment e
WHERE s.regNo = e.regNo
AND s.sName = 'Ali'
AND e.cCode = 'CS101';

SELECT e.Grade
FROM Student s, Enrollment e
WHERE s.regNo = e.regNo
AND s.sName = 'Irshad'
AND e.semester = 7;

SELECT c.cName, e.Grade


FROM Student s, Enrollment e, Course c
WHERE s.regNo = e.regNo
AND e.cCode = c.cCode
AND s.sName = 'Amir';

SELECT DISTINCT c.cName


FROM Course c, Enrollment e
WHERE c.cCode = e.cCode
AND e.semester = 7;

SELECT s.sName, c.cName


FROM Student s, Enrollment e, Course c
WHERE s.regNo = e.regNo
AND e.cCode = c.cCode;

SELECT COUNT(e.Grade) AS Total_F


FROM Student s, Enrollment e
WHERE s.regNo = e.regNo
AND s.sName = 'Amir'
AND e.Grade = 'F';

SELECT s.sName
FROM Student s
WHERE s.regNo NOT IN (
SELECT e.regNo FROM Enrollment e
);
DDBS LAB ASSIGNMENT-10
Conflict Serializability and Conflict Equivalence Checker

This program analyzes transaction histories to:

1. Determine if each history is conflict serializable by building a precedence graph and detecting
cycles.

2. Compare pairs of histories to check if they are conflict equivalent based on conflicting
operation pairs.

from collections import defaultdict, deque

# ---------- INPUT FORMAT ----------


# Each history is a list of operations like: [(op_type, transaction_id,
data_item)]
# Example: [('R', 1, 'x'), ('W', 2, 'x'), ('R', 1, 'y'), ('W', 2, 'y')]

def parse_input():
num_histories = int(input("Enter number of histories (e.g. 3): "))
histories = []
for h in range(num_histories):
print(f"Enter operations for history {h + 1} (e.g., R1x W2x):
")
ops = input().split()
history = [(op[0], int(op[1]), op[2]) for op in ops]
histories.append(history)
return histories

def get_conflicting_pairs(hist1, hist2):


conflicts = []
for i, op1 in enumerate(hist1):
for j, op2 in enumerate(hist2):
if op1[2] == op2[2] and op1[1] != op2[1]:
if (op1[0] == 'W' or op2[0] == 'W'):
conflicts.append((op1, op2))
return conflicts

def build_precedence_graph(schedule):
graph = defaultdict(set)
for i in range(len(schedule)):
op1 = schedule[i]
for j in range(i + 1, len(schedule)):
op2 = schedule[j]
if op1[2] == op2[2] and op1[1] != op2[1]:
if (op1[0] == 'W' or op2[0] == 'W'):
graph[op1[1]].add(op2[1])
return graph

def has_cycle(graph):
visited = set()
rec_stack = set()

def dfs(node):
visited.add(node)
rec_stack.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
if dfs(neighbor):
return True
elif neighbor in rec_stack:
return True
rec_stack.remove(node)
return False

for node in list(graph.keys()):


if node not in visited:
if dfs(node):
return True
return False
def analyze_histories(histories):
for idx, hist in enumerate(histories):
print(f"\nAnalyzing History {idx + 1}:")

graph = build_precedence_graph(hist)
print("Precedence Graph:")
for node in graph:
print(f"T{node} -> {[f'T{n}' for n in graph[node]]}")

if has_cycle(graph):
print("Conflict Serializable: NO (Cycle detected)")
else:
print("Conflict Serializable: YES (No cycles in precedence
graph)")

print("\nPairwise Conflict Equivalence Analysis:")


for i in range(len(histories)):
for j in range(i + 1, len(histories)):
h1, h2 = histories[i], histories[j]
c1 = set(get_conflicting_pairs(h1, h1))
c2 = set(get_conflicting_pairs(h2, h2))
is_equivalent = c1 == c2
print(f"History {i + 1} and History {j + 1}: Conflict
Equivalent? {'YES' if is_equivalent else 'NO'}")
print(f"Conflicting pairs in H{i+1}: {c1}")
print(f"Conflicting pairs in H{j+1}: {c2}")

if __name__ == '__main__':
histories = parse_input()
analyze_histories(histories)

OUTPUT:
Enter number of histories (e.g. 3): 5
Enter operations for history 1 (e.g., R1x W2x):
R1x W2x R1y W1x
Enter operations for history 2 (e.g., R1x W2x):
R1x R2x W1x W2y
Enter operations for history 3 (e.g., R1x W2x):
W1x R2x W2x
Enter operations for history 4 (e.g., R1x W2x):
R1y R2y W1z W2z
Enter operations for history 5 (e.g., R1x W2x):
R1x W1x R2y W2y

Analyzing History 1:
Precedence Graph:
T1 -> ['T2']
T2 -> ['T1']
Conflict Serializable: NO (Cycle detected)

Analyzing History 2:
Precedence Graph:
T2 -> ['T1']
Conflict Serializable: YES (No cycles in precedence graph)

Analyzing History 3:
Precedence Graph:
T1 -> ['T2']
Conflict Serializable: YES (No cycles in precedence graph)

Analyzing History 4:
Precedence Graph:
T1 -> ['T2']
Conflict Serializable: YES (No cycles in precedence graph)

Analyzing History 5:
Precedence Graph:
Conflict Serializable: YES (No cycles in precedence graph)

Pairwise Conflict Equivalence Analysis:


History 1 and History 2: Conflict Equivalent? NO
Conflicting pairs in H1: {(('W', 1, 'x'), ('W', 2, 'x')), (('W', 2,
'x'), ('R', 1, 'x')), (('R', 1, 'x'), ('W', 2, 'x')), (('W', 2, 'x'),
('W', 1, 'x'))}
Conflicting pairs in H2: {(('R', 2, 'x'), ('W', 1, 'x')), (('W', 1,
'x'), ('R', 2, 'x'))}
History 1 and History 3: Conflict Equivalent? NO
Conflicting pairs in H1: {(('W', 1, 'x'), ('W', 2, 'x')), (('W', 2,
'x'), ('R', 1, 'x')), (('R', 1, 'x'), ('W', 2, 'x')), (('W', 2, 'x'),
('W', 1, 'x'))}
Conflicting pairs in H3: {(('W', 1, 'x'), ('R', 2, 'x')), (('W', 1,
'x'), ('W', 2, 'x')), (('W', 2, 'x'), ('W', 1, 'x')), (('R', 2, 'x'),
('W', 1, 'x'))}
History 1 and History 4: Conflict Equivalent? NO
Conflicting pairs in H1: {(('W', 1, 'x'), ('W', 2, 'x')), (('W', 2,
'x'), ('R', 1, 'x')), (('R', 1, 'x'), ('W', 2, 'x')), (('W', 2, 'x'),
('W', 1, 'x'))}
Conflicting pairs in H4: {(('W', 2, 'z'), ('W', 1, 'z')), (('W', 1,
'z'), ('W', 2, 'z'))}
History 1 and History 5: Conflict Equivalent? NO
Conflicting pairs in H1: {(('W', 1, 'x'), ('W', 2, 'x')), (('W', 2,
'x'), ('R', 1, 'x')), (('R', 1, 'x'), ('W', 2, 'x')), (('W', 2, 'x'),
('W', 1, 'x'))}
Conflicting pairs in H5: set()
History 2 and History 3: Conflict Equivalent? NO
Conflicting pairs in H2: {(('R', 2, 'x'), ('W', 1, 'x')), (('W', 1,
'x'), ('R', 2, 'x'))}
Conflicting pairs in H3: {(('W', 1, 'x'), ('R', 2, 'x')), (('W', 1,
'x'), ('W', 2, 'x')), (('W', 2, 'x'), ('W', 1, 'x')), (('R', 2, 'x'),
('W', 1, 'x'))}
History 2 and History 4: Conflict Equivalent? NO
Conflicting pairs in H2: {(('R', 2, 'x'), ('W', 1, 'x')), (('W', 1,
'x'), ('R', 2, 'x'))}
Conflicting pairs in H4: {(('W', 2, 'z'), ('W', 1, 'z')), (('W', 1,
'z'), ('W', 2, 'z'))}
History 2 and History 5: Conflict Equivalent? NO
Conflicting pairs in H2: {(('R', 2, 'x'), ('W', 1, 'x')), (('W', 1,
'x'), ('R', 2, 'x'))}
Conflicting pairs in H5: set()
History 3 and History 4: Conflict Equivalent? NO
Conflicting pairs in H3: {(('W', 1, 'x'), ('R', 2, 'x')), (('W', 1,
'x'), ('W', 2, 'x')), (('W', 2, 'x'), ('W', 1, 'x')), (('R', 2, 'x'),
('W', 1, 'x'))}
Conflicting pairs in H4: {(('W', 2, 'z'), ('W', 1, 'z')), (('W', 1,
'z'), ('W', 2, 'z'))}
History 3 and History 5: Conflict Equivalent? NO
Conflicting pairs in H3: {(('W', 1, 'x'), ('R', 2, 'x')), (('W', 1,
'x'), ('W', 2, 'x')), (('W', 2, 'x'), ('W', 1, 'x')), (('R', 2, 'x'),
('W', 1, 'x'))}
Conflicting pairs in H5: set()
History 4 and History 5: Conflict Equivalent? NO
Conflicting pairs in H4: {(('W', 2, 'z'), ('W', 1, 'z')), (('W', 1,
'z'), ('W', 2, 'z'))}
Conflicting pairs in H5: set()
_______________________________________________________________________

You might also like