DBMS Lab Manual Updated
DBMS Lab Manual Updated
(CS2207)
LABORATORY MANUAL & RECORD
B.Tech (Common for CSE II YEARS)
(With effect from 2022-23 admitted batches)
(II YEAR- ISEM)
MISSION
To impart high standard value-based technical education in all aspects of Computer
Science and Engineering through the state of the art infrastructure and innovative
approach.
To produce ethical, motivated, and skilled engineers through theoretical knowledge
and practical applications.
To impart the ability for tackling simple to complex problems individually as well
as in a team.
To develop globally competent engineers with strong foundations, capable of “out of
the box” thinking so as to adapt to the rapidly changing scenarios requiring socially
conscious green computing solutions.
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
COURSE OBJECTIVES
1. Students are advised to come to the laboratory at least 5 minutes before (to the starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab with
the synopsis / program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if any)
needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system
allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab observation
note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must maintain
the discipline and decency in the laboratory.
7. Computer labs are established with sophisticated and high end branded systems, which
should be utilized properly.
8. Students / Faculty must keep their mobile phones in SWITCHED OFF mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out; if anybody
found loitering outside the lab / class without permission during working hours will be treated
seriously and punished appropriately.
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the
lab after completing the task (experiment) in all aspects. He/she must ensure the system / seat
is kept properly
CS2207 DATABASE MANAGEMENT SYSTEMS LAB
Syllabus
5. Establish Constraints
Primary Key: Unique identifier for each record.
Foreign Key: Link between related tables.
Unique Constraint: Ensure no duplicate values in a column.
Check Constraints: Define specific rules for data (e.g., age > 18).
6. Normalize Data (for Relational Databases)
Reduce redundancy by dividing data into smaller tables and linking them through relationships.
Example: Separate a "Users" table from an "Orders" table.
7. Define Indexes
Improve query performance by creating indexes on frequently searched fields.
8. Implement Schema Validation (NoSQL Databases)
Use JSON Schema or other validation tools to enforce data structure in NoSQL databases. Example:
{
"bsonType": "object",
"required": ["name", "email"],
"properties": {
"name": {
"bsonType": "string",
"description": "must be a string and is required"
},
"email": {
1
"bsonType": "string",
"description": "must be a string and is required"
}
}}
9. Consider Scalability
Use partitioning or sharding for large datasets.
Optimize the schema for read-heavy or write-heavy operations.
10. Test the Schema
Create sample data and test use cases.
Ensure schema meets performance and functional requirements.
11. Maintain and Evolve the Schema
Regularly update the schema as application requirements change.
Use migration tools (e.g., Flyway, Liquibase) to manage schema changes in relational databases.
B.CREATING OF DATABASE
use MyApplicationDB;
5. Define Tables or Collections
Relational Databases: Create tables with columns, data types, and constraints.
Sql:
CREATE TABLE Users (
UserID INT PRIMARY KEY,
UserName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE NOT NULL,
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
2
);
DML COMMANDS :
Data Manipulation Language (DML) commands in SQL are used for managing data within
schema objects. These commands are responsible for inserting, updating, deleting, and
retrieving data from the database tables. The primary DML commands are INSERT, UPDATE,
DELETE, and SELECT
Insert
Update
Delete
Select
1. INSERT Command
Sql code :
4
2. UPDATE Command
The UPDATE command is used to modify existing rows in a table. Sql code :
Example:
3. DELETE Command
Sql code :
4. SELECT Command
Sql code :
5
3. Retrieve the records.
4. Delete a record.
Sql code :
Sql code :
Sql code :
Sql code :
After performing the above steps, the employees table would have the following records:
6
SELECT employee_id, first_name, last_name, email, hire_date, salary FROM employees;
Result:
Creating views in SQL allows you to simplify complex queries, encapsulate data logic, and
present data in a specific format without altering the underlying tables. A view is essentially a
virtual table based on a SELECT query.
A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if the data were
coming from one single table.
Sql code :
8
);
1. Simple View
Create a simple view that combines first name and last name of students into a single column.
View: student_names
Sql code :
Usage:
Sql code :
Create a view that shows a list of students along with the courses they are enrolled in.
Table: enrollments
Sql code :
View: student_course_enrollments
9
Sql code :
Usage:
Sql code :
3. Aggregated View
Create a view that shows the number of courses each student is enrolled in.
View: student_course_count
Sql code :
Usage:
Sql code :
10
INSERT INTO students (student_id, first_name, last_name, enrollment_year) VALUES
(1, 'John', 'Doe', 2023),
(2, 'Jane', 'Smith', 2022),
(3, 'Robert', 'Brown', 2023);
Sql code :
Sql code :
Sql code :
-- View: student_names
Sql code :
-- View: student_course_enrollments
11
SELECT s.student_id, CONCAT(s.first_name, ' ', s.last_name) AS full_name, c.course_name, c.instructor
FROM students s
JOIN enrollments e ON s.student_id = e.student_id JOIN
courses c ON e.course_id = c.course_id;
Sql code :
-- View: student_course_count
Usage Examples:
Sql code :
-- View: student_names
SELECT * FROM student_names;
Sql code :
-- View: student_course_enrollments
SELECT * FROM student_course_enrollments;
Sql code :
-- View: student_course_count
SELECT * FROM student_course_count;
Expected Results
Result of student_names:
12
Result of student_course_enrollments:
Result of student_course_count:
13
F. CREATING TRIGGERS PROGRAM
Creating triggers in SQL allows you to automate certain actions based on events that occur in
your database tables. Triggers are typically used for enforcing business rules, validating data,
and maintaining audit trails. Here, we'll go through a simple and easy example of creating
triggers using a table named employees
Let's consider a table employees with the following structure: Sql code :
Creating a Trigger
Let's create a simple trigger that automatically updates a log table whenever a new record is
inserted into the employees table.
Step-by-Step Example
14
Step 1: Create the log table
First, create a table to store audit logs. This table will store information about the insert
operations on the employees table
Sql code:
Next, create a trigger that fires after an insert operation on the employees table. This trigger will
insert a record into the employee_audit table.
Sql code:
To see the trigger in action, let's insert a new record into the employees table and check the
employee_audit table.
15
Check the employee_audit table sql
Sql code:
Expected Result
After inserting a new record into the employees table, the employee_audit table should contain a
new record logging the insert action.
employee_audit table
16
G.Normalization up to Third Normal Form PROGRAM
Initial Table:
Let's consider a table student_details with the following columns:
student_id INT
student_name VARCHAR(100)
Department VARCHAR(100)
Course VARCHAR(100)
Professor VARCHAR(100)
Sample Data:
student_id student_name department course professor
17
on student_id. However, professor also depends on course, which is not part of the primary key.
To achieve 2NF, we need to split the table into two tables:
Table 1: student_details
student_id INT
student_name VARCHAR(100)
Department VARCHAR(100)
Table 2: course_details
Course VARCHAR(100)
Professor VARCHAR(100)
Sample Data:
student_details
18
course_details
Course professor
In 3NF, if a table is in 2NF, and a non-prime attribute depends on another non- prime attribute,
then it should be moved to a separate table. In our
case, course depends on department, so we need to create a new table
department_courses: Table 1:
student_details
Column Name Data Type
student_id INT
student_name VARCHAR(100)
Table 2: department_courses
department VARCHAR(100)
Column Name Data Type
department VARCHAR(100)
course VARCHAR(100)
Table 3: course_details
19
Column Name Data Type
course VARCHAR(100)
professor VARCHAR(100)
Sample Data:
student_details
student_id student_name department
department_courses
department course
course_details
course professor
20
H. Host Languages in DBMS – Program
1. Create database schema: Define the structure of the database, including tables, indexes,
and relationships.
2. Insert, update, and delete data: Perform CRUD (Create, Read, Update, Delete)
operations on the database.
3. Query the database: Execute SQL queries to retrieve specific data from the database.
4. Implement business logic: Write programs that enforce business rules, perform
calculations, and make decisions based on data in the database.
1. SQL (Structured Query Language): SQL is a standard language for managing relational
databases. It is used to create, modify, and query databases.
2. Python: Python is a popular programming language that is widely used with databases. It
provides libraries such as sqlite3, psycopg2, and mysql-connector-python to interact with
various databases.
3. Java: Java is an object-oriented language that is commonly used with databases. It provides
APIs such as JDBC (Java Database Connectivity) to interact with databases.
4. C#: C# is a modern, object-oriented language that is widely used with databases. It provides
APIs such as ADO.NET to interact with databases.
21
Create a table
CREATE TABLE customers ( id
INT PRIMARY KEY, name
VARCHAR(255), email
VARCHAR(255)
);
Insert data
INSERT INTO customers (id, name, email) VALUES (1, 'John Doe', '[email protected]');
Retrieve data
SELECT * FROM customers;
import sqlite3
# Create a table
cursor.execute('''
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name TEXT, email
TEXT
)
''')
# Insert data
22
cursor.execute("INSERT INTO customers (id, name, email) VALUES (1, 'John Doe',
'[email protected]')")
# Retrieve data
cursor.execute("SELECT * FROM customers") rows =
cursor.fetchall()
# Output:
(1, 'John Doe', '[email protected]')
import java.sql.*;
public class DatabaseExample {
public static void main(String[] args) {
// Load the JDBC driver Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to the database
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/example", "username",
"password");
Statement stmt = conn.createStatement();
// Create a table
stmt.executeUpdate("CREATE TABLE customers (id INT PRIMARY KEY, name
VARCHAR(255), email VARCHAR(255))");
// Insert data
stmt.executeUpdate("INSERT INTO customers (id, name, email) VALUES (1, 'John Doe',
'[email protected]')");
// Retrieve data
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
23
System.out.println(rs.getInt("id") + " " + rs.getString("name") + " " + rs.getString("email"));
}
// Output:
1 John Doe [email protected]
}
}
C# with ADO.NET :-
class DatabaseExample {
static void Main(string[] args) {
// Connect to the database
string connectionString = "Server=localhost;Database=example;User
Id=username;Password=password;";
SqlConnection conn = new SqlConnection(connectionString); conn.Open();
// Create a table
SqlCommand cmd = new SqlCommand("CREATE TABLE customers (id INT
PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))", conn);
cmd.ExecuteNonQuery();
// Insert data
cmd.CommandText = "INSERT INTO customers (id, name, email) VALUES (1, 'John
Doe', '[email protected]')";
cmd.ExecuteNonQuery();
// Retrieve data
cmd.CommandText = "SELECT * FROM customers";
SqlDataReader reader = cmd.ExecuteReader();
24
Console.WriteLine(reader["id"] + " " + reader["name"] + " " + reader["email"]);
}
// Output:
1 John Doe [email protected]
}
}
An interface with embedded SQL is a programming interface that allows a program to interact
with a database management system (DBMS) using SQL statements embedded in the program's
code. This interface provides a way for a program to access, manipulate, and retrieve data from
a database.
Embedded SQL is a technique where SQL statements are embedded directly into a program's
source code, allowing the program to interact with a database without the need for a separate
database interface or API. The SQL statements are typically prefixed with a special keyword,
such as "EXEC SQL", to distinguish them from the rest of the program's code.
In DBMS, an interface with embedded SQL provides a way for a program to interact with a
database using SQL statements embedded in the program's code. This interface allows a
program to:
1. Execute SQL statements to retrieve or manipulate data in a database.
2. Declare and use host variables to exchange data between the program and the database.
3. Use cursors to navigate and manipulate data in a database.
25
Suppose we have a C program that needs to retrieve employee data from a database table called
"Employees". We can use embedded SQL to interact with the database.
C Program Code:
int main() {
EXEC SQL CONNECT TO mydb AS conn1;
EXEC SQL SELECT name, id INTO :emp_name, :emp_id FROM Employees WHERE id =
1;
printf("Employee Name: %s, ID: %d\n", emp_name, emp_id); EXEC SQL
COMMIT WORK RELEASE;
return 0;
}
Output:
Suppose we have a Java program that needs to insert a new order into a database table called
"Orders". We can use embedded SQL to interact with the database.
import java.sql.*;
public class InsertOrder {
public static void main(String[] args) { Connection conn
=
DriverManager.getConnection("jdbc:mydb://localhost:5432/mydb", "username", "password");
26
Statement stmt = conn.createStatement();
stmt.execute("INSERT INTO Orders (customer_id, order_date, total) VALUES (1, '2022-
01-01', 100.00)");
System.out.println("Order inserted successfully!"); conn.close();
}
}
Output:
Suppose we have a Python program that needs to retrieve product data from a database table
called "Products". We can use embedded SQL to interact with the database.
import pyodbc
Output:
27
J. Use of Forms – Program
Forms are a graphical user interface (GUI) component that allows users to interact with a
system, application, or database. Forms provide a way to collect, display, and manipulate data in
a structured and organized manner. Forms can be used in various contexts, including:
1. Data entry: Forms can be used to enter new data into a system or database.
2. Data editing: Forms can be used to edit existing data in a system or database.
3. Data display: Forms can be used to display data from a system or database in a user- friendly
format.
4. Search and filtering: Forms can be used to search and filter data based on specific criteria.
5. Reporting: Forms can be used to generate reports based on data from a system or database.
Use of Forms in DBMS :-
In DBMS (Database Management Systems), forms are used to interact with a database, perform
various tasks, and display data in a user-friendly format. Forms in DBMS provide a way to:
28
5. Improve data consistency and integrity.
Suppose we have a database table called "Employees" with columns "ID", "Name",
"Department", and "Salary". We can create a data entry form to enter new employee data into the
table.
Form Design:
Form Output:
29
Example 2: Customer Order Form
Suppose we have a database table called "Orders" with columns "ID", "Customer ID", "Order
Date", and "Total". We can create a data entry form to enter new order data into the table.
Form Design:
Form Output:
Suppose we have a database table called "Products" with columns "ID", "Name", "Description",
and "Price". We can create a search form to search for products by name or description.
30
Form Design:
Form Output:
31
K. Report Writing – Program
Report writing is the process of creating a document that presents information in a clear and
organized manner, often in a structured format. Reports can be used to communicate
information, analyze data, and make recommendations. Report writing involves:
Suppose we have a database table called "Employees" with columns "ID", "Name",
"Department", and "Salary". We can create a report to display the salary details of all employees
in a department.
32
Report Design:
Report Output :
Suppose we have a database table called "Orders" with columns "ID", "Customer ID", "Order
Date", and "Total". We can create a report to display the order details of all customers.
Report Design:
33
Report Output :
Report Output :
34
35
II.SOME SAMPLE APPLICATIONS ARE GIVEN BELOW:
Experiment-01
Accounting package for shop
1.Shops Table
shop_id: Primary key
shop_name
shop_address
contact_person
contact_number
2.Products Table
product_id: Primary key
product_name
unit_price
stock_quantity
3.Transactions Table
transaction_id: Primary key
transaction_date
shop_id: Foreign key referencing Shops table
total_amount
4.Transaction Details Table
transaction_detail_id: Primary key
transaction_id: Foreign key referencing Transactions table
product_id: Foreign key referencing Products table
quantity
unit_price
total_price
36
VALUES ('2024-07-15', 1, 150.00);
INSERT INTO Transaction_Details (transaction_id, product_id, quantity, unit_price,
total_price)
VALUES (1, 3, 2, 50.00, 100.00),
(1, 5, 1, 50.00, 50.00);
OUTPUT:
37
Age int(2),
Phone int(10)
);
INSERT INTO Customer (CustomerID, CustomerName, LastName, Country, Age, Phone)
VALUES (1, 'Shubham', 'Thakur', 'India','23','xxxxxxxxxx'),
(2, 'Aman ', 'Chopra', 'Australia','21','xxxxxxxxxx'),
(3, 'Naveen', 'Tulasi', 'Sri lanka','24','xxxxxxxxxx'),
(4, 'Aditya', 'Arpan', 'Austria','21','xxxxxxxxxx'),
(5, 'Nishant. Salchichas S.A.', 'Jain', 'Spain','22','xxxxxxxxxx');
Select * from Customer;
OUTPUT
38
Experiment-02
Experiment-03
39
INSERT INTO `tickets` (`id`, `title`, `msg`, `email`, `created`, `status`) VALUES (1, 'Test
Ticket', 'This is your first ticket.', '[email protected]', '2023-04-02 13:06:17', 'open');
CREATE TABLE IF NOT EXISTS `tickets_comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ticket_id` int(11) NOT NULL,
`msg` text NOT NULL,
`created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `tickets_comments` (`id`, `ticket_id`, `msg`, `created`) VALUES (1, 1, 'This is
a test comment.', '2023-04-02 16:23:39');
OUTPUT OF TICKETS
OUTPUT OF COMMENTS
40
Experiment-4
41
CREATE TABLE OrderItems
(
OrderItemID INT PRIMARY KEY,
OrderID INT,
CardID INT,
Quantity INT,
Price DECIMAL(10, 2),
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID),
FOREIGN KEY (CardID) REFERENCES Cards(CardID)
);
Payments Table: Stores information about payments made for orders.
CREATE TABLE Payments
(
PaymentID INT PRIMARY KEY,
OrderID INT,
Amount DECIMAL(10, 2),
PaymentDate DATE,
FOREIGN KEY (OrderID) REFERENCES Orders(OrderID)
);
OUTPUT
42
Experiment-05
43
amount DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (loan_id) REFERENCES loans(loan_id)
);
INSERT INTO insurance (policy_number, policy_holder, insurance_type, premium,
start_date, end_date)
VALUES
('POL001', 'John Doe', 'Life Insurance', 100.00, '2024-01-01', '2025-01-01'),
('POL002', 'Jane Smith', 'Health Insurance', 150.00, '2023-06-15', '2024-06-15');
INSERT INTO loans (account_number, borrower, loan_amount, interest_rate, start_date,
end_date)
VALUES
('LN001', 'John Doe', 50000.00, 5.5, '2023-01-01', '2028-01-01'),
('LN002', 'Jane Smith', 30000.00, 4.0, '2022-07-01', '2027-07-01');
INSERT INTO mortgage_payments (loan_id, payment_date, amount)
VALUES
(1, '2024-07-01', 1000.00),
(1, '2024-08-01', 1000.00),
(2, '2024-07-15', 800.00);
SELECT * FROM insurance;
SELECT * FROM loans;
SELECT * FROM mortgage_payments;
OUTPUT SELECT * FROM insurance;
44
OUTPUT SELECT * FROM mortgage_payments;
Experiment-06
45
contact_number VARCHAR(20),
email VARCHAR(100)
);
CREATE TABLE appointments (
appointment_id INT AUTO_INCREMENT PRIMARY KEY,
doctor_id INT NOT NULL,
patient_id INT NOT NULL,
appointment_date DATE NOT NULL,
appointment_time TIME NOT NULL,
status ENUM('Scheduled', 'Cancelled', 'Completed') DEFAULT 'Scheduled',
FOREIGN KEY (doctor_id) REFERENCES doctors(doctor_id),
FOREIGN KEY (patient_id) REFERENCES patients(patient_id)
);
CREATE TABLE services (
service_id INT AUTO_INCREMENT PRIMARY KEY,
service_name VARCHAR(100) NOT NULL,
service_fee DECIMAL(10, 2) NOT NULL
);
CREATE TABLE billing (
billing_id INT AUTO_INCREMENT PRIMARY KEY,
appointment_id INT NOT NULL,
service_id INT NOT NULL,
amount DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (appointment_id) REFERENCES appointments(appointment_id),
FOREIGN KEY (service_id) REFERENCES services(service_id)
);
INSERT INTO doctors (doctor_name, specialty, contact_number)
VALUES
('Dr. John Smith', 'Cardiologist', '123-456-7890'),
('Dr. Jane Doe', 'Pediatrician', '987-654-3210');
46
INSERT INTO patients (patient_name, date_of_birth, contact_number, email)
VALUES
('Alice Brown', '1990-05-15', '456-789-0123', '[email protected]'),
('Bob Green', '1985-08-20', '789-012-3456', '[email protected]');
INSERT INTO appointments (doctor_id, patient_id, appointment_date, appointment_time)
VALUES
(1, 1, '2024-07-16', '09:00:00'),
(2, 2, '2024-07-17', '10:30:00');
INSERT INTO services (service_name, service_fee)
VALUES
('Consultation', 100.00),
('Check-up', 80.00);
INSERT INTO billing (appointment_id, service_id, amount)
VALUES
(1, 1, 100.00),
(2, 2, 80.00);
SELECT * FROM doctors;
SELECT * FROM patients;
SELECT * FROM appointments;
SELECT * FROM services;
SELECT b.billing_id, p.patient_name, d.doctor_name, s.service_name, s.service_fee,
b.amount
FROM billing b
JOIN appointments a ON b.appointment_id = a.appointment_id
JOIN patients p ON a.patient_id = p.patient_id
JOIN doctors d ON a.doctor_id = d.doctor_id
JOIN services s ON b.service_id = s.service_id;
47
OUTPUT SELECT * FROM doctors;
48
Experiment-07
49
INSERT INTO account_holders (full_name, date_of_birth, address, email, phone_number)
VALUES
('John Doe', '1985-10-15', '123 Main St, Anytown', '[email protected]', '123-456-7890'),
('Jane Smith', '1990-05-20', '456 Elm St, Othertown', '[email protected]', '987-654-
3210');
INSERT INTO bank_accounts (account_number, account_holder_id, account_type, balance,
opened_date)
VALUES
('1234567890', 1, 'Savings', 5000.00, '2020-01-01'),
('9876543210', 2, 'Checking', 10000.00, '2018-05-15');
INSERT INTO transactions (account_number, amount, transaction_type)
VALUES
('1234567890', 1000.00, 'Deposit'),
('9876543210', 500.00, 'Withdrawal'),
('1234567890', 200.00, 'Transfer');
SELECT * FROM account_holders;
SELECT * FROM bank_accounts;
SELECT * FROM transactions;
50
OUTPUT SELECT * FROM transactions;
Experiment-08
51
subject_id INT,
mark INT,
FOREIGN KEY (student_id) REFERENCES students(student_id),
FOREIGN KEY (subject_id) REFERENCES subjects(subject_id)
);
INSERT INTO students (first_name, last_name, date_of_birth) VALUES
('John', 'Doe', '2000-01-01'),
('Jane', 'Smith', '2001-02-02');
INSERT INTO subjects (subject_name) VALUES
('Mathematics'),
('Science');
INSERT INTO marks (student_id, subject_id, mark) VALUES
(1, 1, 85),
(1, 2, 90),
(2, 1, 78),
(2, 2, 88);
SELECT
students.first_name,
students.last_name,
subjects.subject_name,
marks.mark
FROM
marks
JOIN
students ON marks.student_id = students.student_id
JOIN
subjects ON marks.subject_id = subjects.subject_id;
SELECT
students.first_name,
students.last_name,
52
AVG(marks.mark) AS average_mark
FROM
marks
JOIN
students ON marks.student_id = students.student_id
GROUP BY
students.student_id;
UPDATE marks
SET mark = 92
WHERE student_id = 1 AND subject_id = 2;
DELETE FROM marks
WHERE student_id = 2 AND subject_id = 1;
OUTPUT
OUTPUT
53
Experiment-9
Hostel accounting
Managing hostel accounting in a SQL database involves tracking various aspects such as
room allocation, expenses, payments, and resident details. Here's a basic example schema:
CREATE TABLE Students (
student_id INT AUTO_INCREMENT PRIMARY KEY,
NAMES VARCHAR(100),
date_of_birth DATE,
gender ENUM('Male', 'Female', 'Other'),
contact_number VARCHAR(15),
email VARCHAR(100)
);
CREATE TABLE Rooms (
room_id INT AUTO_INCREMENT PRIMARY KEY,
room_number VARCHAR(10) UNIQUE,
capacity INT,
occupancy INT DEFAULT 0,
rent DECIMAL(10, 2)
);
CREATE TABLE Transactions (
transaction_id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT,
amount DECIMAL(10, 2),
transaction_date DATE,
description VARCHAR(255),
FOREIGN KEY (student_id) REFERENCES Students(student_id)
);
CREATE TABLE Expenses (
expense_id INT AUTO_INCREMENT PRIMARY KEY,
amount DECIMAL(10, 2),
expense_date DATE,
54
description VARCHAR(255)
);
INSERT INTO Students (name, date_of_birth, gender, contact_number, email) VALUES
('John Doe', '2000-01-15', 'Male', '1234567890', '[email protected]'),
('Jane Smith', '1999-05-22', 'Female', '0987654321', '[email protected]');
INSERT INTO Rooms (room_number, capacity, rent) VALUES
('A101', 2, 3000.00),
('A102', 2, 3000.00);
INSERT INTO Transactions (student_id, amount, transaction_date, description) VALUES
(1, 3000.00, '2024-07-01', 'Monthly Rent'),
(2, 3000.00, '2024-07-01', 'Monthly Rent');
INSERT INTO Expenses (amount, expense_date, description) VALUES
(1500.00, '2024-07-05', 'Electricity Bill'),
(500.00, '2024-07-10', 'Water Bill');
SELECT * FROM Students;
SELECT * FROM Rooms;
SELECT * FROM Transactions;
SELECT * FROM Expenses;
SELECT SUM(amount) AS TotalIncome FROM Transactions;
SELECT SUM(amount) AS TotalExpenses FROM Expenses;
SELECT
(SELECT SUM(amount) FROM Transactions) -
(SELECT SUM(amount) FROM Expenses) AS NetIncome;
55
OUTPUT SELECT * FROM Students;
56
Experiment-10
57
);
INSERT INTO Categories (name) VALUES
('Action'),
('Comedy'),
('Drama'),
('Horror'),
('Sci-Fi');
INSERT INTO Tapes (title, category_id, release_year, stock) VALUES
('Die Hard', 1, 1988, 5),
('The Mask', 2, 1994, 3),
('The Godfather', 3, 1972, 2),
('The Exorcist', 4, 1973, 4),
('Star Wars', 5, 1977, 6);
INSERT INTO Members (name, date_of_birth, contact_number, email) VALUES
('John Doe', '1980-05-15', '1234567890', '[email protected]'),
('Jane Smith', '1992-11-22', '0987654321', '[email protected]');
INSERT INTO Rentals (tape_id, member_id, rental_date, return_date) VALUES
(1, 1, '2024-07-01', '2024-07-07'),
(2, 2, '2024-07-03', '2024-07-10');
SELECT * FROM Categories;
SELECT * FROM Tapes;
SELECT * FROM Members;
SELECT * FROM Rentals;
SELECT
c.name AS Category,
COUNT(r.rental_id) AS TotalRentals
FROM
Rentals r
JOIN
Tapes t ON r.tape_id = t.tape_id
58
JOIN
Categories c ON t.category_id = c.category_id
GROUP BY
c.name;
SELECT
t.title,
COUNT(r.rental_id) AS RentalCount
FROM
Rentals r
JOIN
Tapes t ON r.tape_id = t.tape_id
GROUP BY
t.title
ORDER BY
RentalCount DESC
LIMIT 5;
SELECT
m.name,
m.contact_number,
m.email,
t.title,
r.rental_date,
r.return_date
FROM
Rentals r
JOIN
Members m ON r.member_id = m.member_id
JOIN
Tapes t ON r.tape_id = t.tape_id
WHERE
59
r.return_date < CURDATE() AND r.return_date IS NOT NULL;
Experiment-11
60
o In the early days, scoring was primitive. Players or umpires used notches on
sticks or tally sticks to record runs.
o Each run was represented by a single notch.
2. Introduction of Written Scores:
o In the late 18th century, scorecards were first introduced, allowing scores to be
recorded on paper.
o The first recorded cricket match scorecard is believed to date to 1776, for a
match at the Vine Cricket Ground in Kent.
19th Century Developments
1. Scorecards Standardized:
o By the mid-19th century, printed scorecards became standard at matches.
o Lord’s Cricket Ground began distributing pre-printed scorecards in 1846,
which marked a significant step in formalizing scorekeeping.
2. Scorers and Symbols:
o Dedicated scorers started recording match events.
o Symbols were introduced to represent different events in the game:
A dot (•) for a ball with no run (origin of the term "dot ball").
Numbers to indicate runs scored per ball.
Letters like "W" for wickets and "b" for byes.
3. Telegraph Boards:
o Large telegraph boards were used to display scores for spectators at the
ground.
61
o The introduction of One-Day Internationals (ODIs) in the 1970s brought new
scoring challenges, including recording strike rates and economy rates.
4. Electronic Scoreboards:
o In the 1980s, electronic scoreboards started replacing manual ones, offering
more detailed real-time information.
Key Milestones in Cricket Scoring History
1776: First known scorecard used in England.
1846: Standardized printed scorecards introduced at Lord’s.
1899: First use of telegraph boards at cricket grounds.
1980s: Electronic scoreboards introduced.
1990s: Computerized scoring systems implemented.
2000s: Real-time online scoring and data analytics became common.
Experiment-12
62
schedule_id INT AUTO_INCREMENT PRIMARY KEY,
program_id INT,
start_time DATETIME,
end_time DATETIME,
FOREIGN KEY (program_id) REFERENCES Programs(program_id)
);
CREATE TABLE Viewers (
viewer_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
date_of_birth DATE,
contact_number VARCHAR(15),
email VARCHAR(100)
);
CREATE TABLE Subscriptions (
subscription_id INT AUTO_INCREMENT PRIMARY KEY,
viewer_id INT,
channel_id INT,
subscription_date DATE,
FOREIGN KEY (viewer_id) REFERENCES Viewers(viewer_id),
FOREIGN KEY (channel_id) REFERENCES Channels(channel_id)
);
INSERT INTO Channels (name, genre) VALUES
('National Geographic', 'Documentary'),
('HBO', 'Entertainment'),
('CNN', 'News'),
('ESPN', 'Sports'),
('Cartoon Network', 'Kids');
INSERT INTO Programs (title, description, duration, channel_id) VALUES
('Wildlife Documentary', 'A documentary about wildlife.', 60, 1),
('Game of Thrones', 'Fantasy drama series.', 60, 2),
63
('Daily News', 'Latest news and updates.', 30, 3),
('Football Live', 'Live football match.', 120, 4),
('Cartoon Show', 'Popular cartoon series.', 30, 5);
INSERT INTO Schedules (program_id, start_time, end_time) VALUES
(1, '2024-07-15 08:00:00', '2024-07-15 09:00:00'),
(2, '2024-07-15 21:00:00', '2024-07-15 22:00:00'),
(3, '2024-07-15 18:00:00', '2024-07-15 18:30:00'),
(4, '2024-07-15 15:00:00', '2024-07-15 17:00:00'),
(5, '2024-07-15 10:00:00', '2024-07-15 10:30:00');
INSERT INTO Viewers (name, date_of_birth, contact_number, email) VALUES
('Alice Johnson', '1985-04-15', '1234567890', '[email protected]'),
('Bob Smith', '1990-07-22', '0987654321', '[email protected]');
INSERT INTO Subscriptions (viewer_id, channel_id, subscription_date) VALUES
(1, 1, '2024-07-01'),
(1, 2, '2024-07-01'),
(2, 3, '2024-07-01'),
(2, 4, '2024-07-01');
SELECT * FROM Channels;
SELECT * FROM Programs;
SELECT * FROM Schedules;
SELECT * FROM Viewers;
SELECT * FROM Subscriptions;
SELECT
s.schedule_id,
p.title,
c.name AS channel_name,
s.start_time,
s.end_time
FROM
Schedules s
64
JOIN
Programs p ON s.program_id = p.program_id
JOIN
Channels c ON p.channel_id = c.channel_id
WHERE
DATE(s.start_time) = '2024-07-15';
SELECT
c.name AS channel_name,
p.title,
p.description,
p.duration
FROM
Programs p
JOIN
Channels c ON p.channel_id = c.channel_id;
SELECT
v.name AS viewer_name,
c.name AS channel_name,
s.subscription_date
FROM
Subscriptions s
JOIN
Viewers v ON s.viewer_id = v.viewer_id
JOIN
Channels c ON s.channel_id = c.channel_id;
65
Output SELECT * FROM Programs;
66
Experiment-13
Personal library
Managing a personal library in a SQL database involves keeping track of books, authors,
genres, and borrowing history. Here's a basic schema to get you started:
CREATE TABLE books (
`id` INT AUTO_INCREMENT,
`title` VARCHAR(255) NOT NULL,
`author` VARCHAR(100) NOT NULL,
`publisher` VARCHAR(100) NOT NULL,
`published_date` DATE NOT NULL,
`genre` VARCHAR(50) NOT NULL,
`summary` TEXT,
`isbn` VARCHAR(20) NOT NULL,
`edition` VARCHAR(20) NOT NULL,
`pages` INT NOT NULL,
`language` VARCHAR(20) NOT NULL,
`format` VARCHAR(20) NOT NULL,
`rating` DECIMAL(3,2) NOT NULL DEFAULT 0.00,
`review` TEXT,
PRIMARY KEY (`id`)
);
CREATE TABLE authors (
`id` INT AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`bio` TEXT,
67
`born` DATE,
`died` DATE,
PRIMARY KEY (`id`)
);
CREATE TABLE book_categories (
`id` INT AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE book_category_mappings (
`id` INT AUTO_INCREMENT,
`book_id` INT NOT NULL,
`category_id` INT NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`book_id`) REFERENCES books(`id`),
FOREIGN KEY (`category_id`) REFERENCES book_categories(`id`)
);
CREATE TABLE book_shelves (
`id` INT AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE book_shelf_mappings (
`id` INT AUTO_INCREMENT,
`book_id` INT NOT NULL,
`shelf_id` INT NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (`book_id`) REFERENCES books(`id`),
FOREIGN KEY (`shelf_id`) REFERENCES book_shelves(`id`)
);
68
CREATE TABLE borrowing_history (
`id` INT AUTO_INCREMENT,
`book_id` INT NOT NULL,
`borrower_name` VARCHAR(100) NOT NULL,
`borrow_date` DATE NOT NULL,
`return_date` DATE,
`is_returned` BOOLEAN NOT NULL DEFAULT FALSE,
PRIMARY KEY (`id`),
FOREIGN KEY (`book_id`) REFERENCES books(`id`)
);
INSERT INTO authors (name, bio, born, died) VALUES
('J.K. Rowling', 'British author', '1965-07-31', NULL),
('J.R.R. Tolkien', 'British author', '1892-01-03', '1973-09-02'),
('George R.R. Martin', 'American author', '1948-09-20', NULL);
INSERT INTO books (title, author, publisher, published_date, genre, summary, isbn, edition,
pages, language, format, rating, review) VALUES
('Harry Potter and the Philosopher\'s Stone', 'J.K. Rowling', 'Bloomsbury', '1997-06-26',
'Fantasy', 'The first book in the Harry Potter series', '9780747532743', 'First Edition', 320,
'English', 'Hardcover', 4.50, 'A great start to the series'),
('The Lord of the Rings', 'J.R.R. Tolkien', 'Allen & Unwin', '1954-07-29', 'Fantasy', 'The
classic high fantasy novel', '9780261103573', 'First Edition', 1216, 'English', 'Hardcover',
4.80, 'A classic'),
('A Game of Thrones', 'George R.R. Martin', 'Bantam Books', '1996-08-01', 'Fantasy', 'The
first book in the A Song of Ice and Fire series', '9780553103547', 'First Edition', 835,
'English', 'Hardcover', 4.60, 'A great start to the series');
INSERT INTO book_categories (name) VALUES
('Fantasy'),
('Science Fiction'),
('Romance');
INSERT INTO book_category_mappings (book_id, category_id) VALUES
(1, 1),
(2, 1),
(3, 1);
69
INSERT INTO book_shelves (name) VALUES
('Fiction'),
('Non-Fiction'),
('Biography');
INSERT INTO book_shelf_mappings (book_id, shelf_id) VALUES
(1, 1),
(2, 1),
(3, 1);
INSERT INTO borrowing_history (book_id, borrower_name, borrow_date, return_date,
is_returned) VALUES
(1, 'John Doe', '2022-01-01', '2022-01-15', TRUE),
(2, 'Jane Doe', '2022-02-01', '2022-02-15', TRUE),
(3, 'Bob Smith', '2022-03-01', '2022-03-15', TRUE);
70
output select * from books;
Experiment -14
2. Boats Table
Details about boats, including their unique ID, name, color, and capacity.
71
Column Data Type Constraints
3. Reservations Table
Tracks which sailor has reserved which boat on a specific date.
SQL Implementation
-- Sailors Table
CREATE TABLE Sailors (
SailorID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL,
Rating INT NOT NULL,
Age DECIMAL(4,1) NOT NULL
);
-- Boats Table
CREATE TABLE Boats (
BoatID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL,
Color VARCHAR(50) NOT NULL,
Capacity INT NOT NULL
72
);
-- Reservations Table
CREATE TABLE Reservations (
ReservationID INT PRIMARY KEY AUTO_INCREMENT,
SailorID INT NOT NULL,
BoatID INT NOT NULL,
ReservationDate DATE NOT NULL,
FOREIGN KEY (SailorID) REFERENCES Sailors(SailorID),
FOREIGN KEY (BoatID) REFERENCES Boats(BoatID)
);
Sample Data
Sailors
Boats
Reservations
1 1 2 2025-01-01
73
ReservationID SailorID BoatID ReservationDate
2 2 3 2025-01-05
3 3 1 2025-01-10
Practice Queries
1. List all sailors who reserved the "Ocean Queen" boat:
2. SELECT Sailors.Name
3. FROM Sailors
4. JOIN Reservations ON Sailors.SailorID = Reservations.SailorID
5. JOIN Boats ON Reservations.BoatID = Boats.BoatID
6. WHERE Boats.Name = 'Ocean Queen';
7. Find the number of reservations made for each boat:
8. SELECT Boats.Name, COUNT(*) AS ReservationCount
9. FROM Boats
10. JOIN Reservations ON Boats.BoatID = Reservations.BoatID
11. GROUP BY Boats.Name;
12. Get sailors who have not made any reservations:
13. SELECT Sailors.Name
14. FROM Sailors
15. LEFT JOIN Reservations ON Sailors.SailorID = Reservations.SailorID
16. WHERE Reservations.SailorID IS NULL;
This schema and queries offer a solid foundation to practice SQL concepts.
Sailors Database Schema
1. Sailors Table
Details about sailors, including their unique ID, name, rating, and age.
74
Column Data Type Constraints
2. Boats Table
Details about boats, including their unique ID, name, color, and capacity.
3. Reservations Table
Tracks which sailor has reserved which boat on a specific date.
SQL Implementation
-- Sailors Table
CREATE TABLE Sailors (
SailorID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL,
Rating INT NOT NULL,
Age DECIMAL(4,1) NOT NULL
);
-- Boats Table
75
CREATE TABLE Boats (
BoatID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL,
Color VARCHAR(50) NOT NULL,
Capacity INT NOT NULL
);
-- Reservations Table
CREATE TABLE Reservations (
ReservationID INT PRIMARY KEY AUTO_INCREMENT,
SailorID INT NOT NULL,
BoatID INT NOT NULL,
ReservationDate DATE NOT NULL,
FOREIGN KEY (SailorID) REFERENCES Sailors(SailorID),
FOREIGN KEY (BoatID) REFERENCES Boats(BoatID)
);
Sample Data
Sailors
Boats
76
Reservations
1 1 2 2025-01-01
2 2 3 2025-01-05
3 3 1 2025-01-10
Practice Queries
1. List all sailors who reserved the "Ocean Queen" boat:
SELECT Sailors.Name
FROM Sailors
JOIN Reservations ON Sailors.SailorID = Reservations.SailorID
JOIN Boats ON Reservations.BoatID = Boats.BoatID
WHERE Boats.Name = 'Ocean Queen';
2. Find the number of reservations made for each boat:
SELECT Sailors.Name
FROM Sailors
LEFT JOIN Reservations ON Sailors.SailorID = Reservations.SailorID
WHERE Reservations.SailorID IS NULL;
This schema and queries offer a solid foundation to practice SQL concepts.
77
Experiment-15
Relational Schema:
Suppliers Table
SupplierID (Primary Key): Unique identifier for each supplier.
Name: Name of the supplier.
Location: Location of the supplier.
Parts Table
PartID (Primary Key): Unique identifier for each part.
Name: Name of the part.
Color: Color of the part.
Supplies Table
SupplyID (Primary Key): Unique identifier for each supply record.
SupplierID (Foreign Key): References SupplierID in the Suppliers table.
PartID (Foreign Key): References PartID in the Parts table.
Quantity: Quantity of the part supplied.
SQL Schema Implementation
-- Suppliers Table
CREATE TABLE Suppliers (
SupplierID INT PRIMARY KEY AUTO_INCREMENT,
78
Name VARCHAR(100) NOT NULL,
Location VARCHAR(100) NOT NULL
);
-- Parts Table
CREATE TABLE Parts (
PartID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100) NOT NULL,
Color VARCHAR(50) NOT NULL
);
-- Supplies Table
CREATE TABLE Supplies (
SupplyID INT PRIMARY KEY AUTO_INCREMENT,
SupplierID INT NOT NULL,
PartID INT NOT NULL,
Quantity INT NOT NULL,
FOREIGN KEY (SupplierID) REFERENCES Suppliers(SupplierID),
FOREIGN KEY (PartID) REFERENCES Parts(PartID)
);
Sample Data
Suppliers
Parts
79
PartID Name Color
1 Bolt Silver
2 Nut Black
3 Screw Gold
Supplies
1 1 2 500
2 1 3 300
3 2 1 400
4 3 2 600
Practice Queries
1. List all suppliers and the parts they supply:
80
WHERE Parts.Name = 'Bolt';
4. Find parts that are not supplied by any supplier:
SELECT Parts.Name
FROM Parts
LEFT JOIN Supplies ON Parts.PartID = Supplies.PartID
WHERE Supplies.PartID IS NULL;
VIVA QUESTIONS
Basic DBMS Questions
1. What is a database?
A database is an organized collection of data stored electronically to facilitate access,
management, and updating.
2. What is DBMS?
A Database Management System (DBMS) is software used to store, retrieve, and
manage data in databases.
3. What are the advantages of a DBMS?
Data security, reduced redundancy, data integrity, concurrent access, and data
consistency.
4. What is a schema?
A schema is the logical structure of a database, including tables, relationships, and
constraints.
5. What is the difference between DBMS and RDBMS?
o DBMS: Manages data as files without relationships.
o RDBMS: Manages data in tables with relationships.
81
Relational Database Concepts
6. What is a primary key?
A unique identifier for each record in a table.
7. What is a foreign key?
A field in one table that links to the primary key in another table.
8. What is a candidate key?
A set of attributes that can uniquely identify a record in a table.
9. What is normalization?
The process of organizing data to reduce redundancy and improve data integrity.
10. What are the different normal forms?
o 1NF: Eliminates repeating groups.
o 2NF: Removes partial dependency.
o 3NF: Removes transitive dependency.
o BCNF: Ensures every determinant is a candidate key.
11.What is SQL?
SQL (Structured Query Language) is used to interact with a database for querying,
updating, and managing data.
12. What are DDL commands?
Data Definition Language commands: CREATE, ALTER, DROP.
13. What are DML commands?
Data Manipulation Language commands: INSERT, UPDATE, DELETE.
14. What is the difference between DELETE and TRUNCATE?
DELETE: Removes rows with conditions; can be rolled back.
TRUNCATE: Removes all rows; cannot be rolled back.
15. What is the difference between HAVING and WHERE?
WHERE: Filters rows before grouping.
HAVING: Filters groups after aggregation.
16.What is a transaction?
A sequence of database operations treated as a single logical unit of work.
17.What are ACID properties?
o Atomicity: All or nothing execution.
o Consistency: Data remains consistent.
o Isolation: Transactions do not interfere.
82
o Durability: Changes persist after a transaction.
18.What is a deadlock?
A situation where two or more transactions wait for each other indefinitely.
19.What is the difference between COMMIT and ROLLBACK?
o COMMIT: Saves changes permanently.
o ROLLBACK: Reverts changes.
20.What is concurrency control?
Mechanism to ensure multiple transactions execute without conflicts.
83