QB Unit - 2 Answers
QB Unit - 2 Answers
1.Implement database schema for the following tables refine with the
appropriate integrity constraints. How these constraints contribute in
maintain data consistency & avoid anomalies in the organization’s database.
1. Employees( Employee ID, Name, Email, Department ID, Salary)
2. Departments(Department ID, Dept Name, Manager ID).
Answer:
INTRODUCTION:
A database schema outlines the architecture of a relational database, including tables, fields,
data types, and relationships among entities. It is typically expressed in a formal language
supported by RDBMS and includes integrity constraints that ensure data consistency and
validity.
Logical Schema: Defines the logical structure of the database, including tables and their
relationships.
View Schema: Represents how data is presented to users, often abstracting the underlying
complexity.
Integrity constraints are rules applied to ensure the accuracy and consistency of
data. They include:
PHYSICAL SCHEMA:
EMPLOYEES:
SQL> create table Employees(Eid number(3),Ename varchar2(5),Eemail varchar2(6),
departmentid number(3), salary number(5));
Table created.
SQL> desc Employees
EID NUMBER(3)
ENAME VARCHAR2(5)
EEMAIL VARCHAR2(6)
DEPARTMENTID NUMBER(3)
SALARY NUMBER(5)
DEPARTMENTS :
Table created.
DID NUMBER(3)
DEPTNAME VARCHAR2(5)
MANAGERID NUMBER(5)
o EmployeeID in the Employees table and DepartmentID in the Departments table are
primary keys.
3. Unique Constraints:
o Email in the Employees table ensures no two employees share the same email.
o ManagerID in the Departments table ensures no two departments have the same
manager.
o Ensures that critical data is always present and avoids incomplete records.
5. Check Constraints:
o Ensures that data adheres to business rules (e.g., salaries cannot be negative).
LOGICAL SCHEMA:
EMPLOYEES TABLE:
SQL> insert into Employees values(91,'shrya','mail.m',405,50000);
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
1 row created.
91 DS 79
79 AIDS 91
47 AIML 74
80 DS 8
o Primary keys and unique constraints ensure that no duplicate records are inserted,
avoiding redundancy.
o Foreign keys ensure that relationships between tables are valid. For example:
o Constraints like NOT NULL and foreign keys prevent the insertion of incomplete or
invalid data.
o Foreign key constraints prevent the deletion of records that are referenced by other
tables. For example:
Conclusion:
implementing these integrity constraints not only enhances the reliability of the database but also
supports efficient data management by ensuring that all data adheres to predefined rules, thus
maintaining overall data quality and coherence within the organization’s database.
2.Designa Database schema for the course registration system based on the
following requirements. Clearly define the tables, fields, and integrity
constraints like Primary key, Not Null, Unique, Foreign Key, and Check
constraints.
i. Students(Student ID, Name, Email, Enrollmentyear)
ii. Courses(CourseID, CourseName, Credits)
iii. Registrations(RegistrationID, StudentId, CourseId,
RegistrationdateQuestion).
INTRODUCTION:
Introduction A Course Registration System is essential for managing student enrollments in academic
institutions. This system ensures seamless registration of students for various courses while
maintaining data integrity and consistency. The database schema for this system is designed to
efficiently store and retrieve information related to students, courses, and their respective
registrations. This document outlines the physical schema, logical schema, constraints, and
consistency mechanisms implemented in the database design.
1. Course Registration System – A structured system for managing student enrollments efficiently.
2. Physical Schema – The actual structure of the database, including tables, fields, and data types.
3. Students Table – Stores student details with constraints ensuring valid student records.
4. Courses Table – Holds course information, including credits with specific constraints.
5. Registrations Table – Manages student-course enrollments, ensuring data integrity.
6. Constraints – Enforces data validity through Primary Keys, Foreign Keys, NOT NULL, UNIQUE, and
CHECK constraints.
PHYSICAL SCHEMA:
The database consists of three primary tables: Students, Courses, and Registrations.
1. Students Table
StudentID (INT, PRIMARY KEY, NOT NULL, UNIQUE)
Name (VARCHAR(100), NOT NULL)
Email (VARCHAR(100), NOT NULL, UNIQUE, CHECK (Email LIKE '%@%'))
EnrollmentYear (INT, NOT NULL, CHECK (EnrollmentYear >= 2000 AND
EnrollmentYear <= YEAR(CURDATE())))
SQL> desc student;
STUDENTID NUMBER(7)
STUDENTNAME VARCHAR2(10)
STUDENTEMAIL VARCHAR2(16)
STUDENTENROLLMENTYEAR NUMBER(7)
2. Courses Table
CourseID (INT, PRIMARY KEY, NOT NULL, UNIQUE)
CourseName (VARCHAR(100), NOT NULL)
Credits (INT, NOT NULL, CHECK (Credits BETWEEN 1 AND 10))
SQL>desc course;
COURSEID NUMBER(7)
COURSENAME VARCHAR2(10)
CREDITS NUMBER(7)
3. Registrations Table
RegistrationID (INT, PRIMARY KEY, NOT NULL, UNIQUE)
StudentID (INT, FOREIGN KEY REFERENCES Students(StudentID), NOT NULL)
CourseID (INT, FOREIGN KEY REFERENCES Courses(CourseID), NOT NULL)
RegistrationDate (DATE, NOT NULL, CHECK (RegistrationDate <= CURDATE()))
SQL>desc registration;
REGISTRATIONID NUMBER(10)
STUDENTID NUMBER(7)
COURSEID NUMBER(7)
REGISTRATIONDATE NUMBER(10)
Constraints:
To maintain data integrity, the following constraints have been applied:
1. Primary Key (PK): Ensures unique identification of records in each table (StudentID,
CourseID, RegistrationID).
Logical Schema:
The logical schema represents the relationship between tables:
• This indicates that one student can register for multiple courses, and one course can
have multiple students enrolled.
1. Students Table:
2.Courses Table:
1 row created.
values(78,'dbms',3); 1 row
created.
1 row created.
79 java 4
78 dbms 3
76 python 5
3.Registrations Table:
1 row created.
189 7 79 1
199 8 78 2
198 9 76 5
Consistency:
To maintain database consistency
1. Referential Integrity: Enforced through foreign key constraints, ensuring that registrations
reference only existing students and courses.
Conclusion:
Conclusion The database schema for the Course Registration System is designed to be efficient,
scalable, and secure while ensuring data integrity and consistency. The application of primary keys,
foreign keys, NOT NULL constraints, UNIQUE constraints, and CHECK constraints ensures that the
data remains valid and reliable. By following best database design practices, this system provides a
robust foundation for student course registrations in any academic institution.
Physical Schema:
Users table:
Create table Users (Userid int primary key, name varchar2(10) not null, email varchar2(30) unique
not null, password varchar2(10) not null, address varchar2(30), phone varchar2(20));
desc users;
Name Null? Type
ADDRESS VARCHAR2(30)
PHONE VARCHAR2(10)
Product table:
Create table Products ( ProductID int primary key, name varchar2(15) not null, description
varchar2(15), price number(10,2) not null, stock int not null, category varchar2(10));
desc products;
DESCRIPTION VARCHAR2(15)
CATEGORY VARCHAR2(10)
Orders table:
Create table Orders (OrderID int primary key, UserID int not null, OrderDate timestamp default
current_timestamp, TotalAmount number(10,2) NOT NULL, Status varchar2(20) check (Status IN
('Pending', 'Shipped', 'Delivered', 'Cancelled'))default 'Pending', foreign key (UserID) references
Users(UserID));
desc orders;
ORDERDATE TIMESTAMP(6)
OrderDetails table:
create table OrderDetails ( OrderDetailID int primary key, orderID int not null, productID int not null,
quantity int not null, subtotal number(10,2)not null, foreign key (OrderID) reference Orders(OrderID),
foreign key (ProductID)references Products(ProductID));
desc orderdetails;
Review table:
create table Reviews ( ReviewID int primary key, UserID int not null, ProductID int not null, Rating int
check (Rating BETWEEN 1 AND 5) not null, comment varchar2(30), ReviewDate timestamp default
current_timestamp, foreign key (UserID) references Users(UserID), foreign key (ProductID) references
Products(ProductID));
desc reviews;
Comment VARCHAR2(20)
REVIEWDATE
Logical Schema:
Insert into Users (UserID, Name, Email, Password, Address, Phone) values (1, 'Alice',
'[email protected]', 'pass123', '123 Main St', '9876543210');
1 row created.
Insert into Users (UserID, Name, Email, Password, Address, Phone) values (2, 'Bob',
'[email protected]', 'secure456', '456 Elm St', '8765432109');
1 row created.
Insert into Products (ProductID, Name, Description, Price, Stock, Category) values (101, 'Laptop',
'Gaming Laptop', 2000.50, 10, 'Electronic');
1 row created.
Insert into Products (ProductID, Name, Description, Price, Stock, Category) values(102, 'Phone',
'Smartphone', 50000, 20, 'Electronic');
1 row created.
1 row created.
1 row created.
Insert into OrderDetails (OrderDetailID, OrderID, ProductID, Quantity, Price)values (2001, 1001, 101,
1, 1200.50);
1 row created.
Insert into OrderDetails (OrderDetailID, OrderID, ProductID, Quantity, Price) values (2002, 1002,
102, 1, 699.99);
1 row created.
Insert into Reviews (ReviewID, UserID, ProductID, Rating, “comment”, ReviewDate) values(3001, 1,
101, 5, 'Great product!', CURRENT_TIMESTAMP);
1 row created.
Insert into Reviews (ReviewID, UserID, ProductID, Rating,”comment”, ReviewDate) values (3002, 2,
102, 4, 'Good value.', CURRENT_TIMESTAMP);
1 row created.
Expected Output:
Select *from users;
USERID NAME EMAIL PASSWORD ADDRESS PHONE
--------- --------------- --------------------- ---------- -------------------------- ---------
1 Alice [email protected] pass123 Hyderabad 9876543210
2 Bob bob@gmail .com secure456 Suryapet 8765432109
Select *from products;
PRODUCTID NAME DESCRIPTION PRICE STOCK CATEGORY
---------- --------------- --------------- ---------- ---------- ----------
101 laptop gamming 20000 8 electronic
102 iphone smartphone 50000 8 electronic
Select *from Orders;
ORDERID USERID ORDERDATE TOTALAMOUNT STATUS
------------- ----------- ----------------- ------------------- -----------
1001 1 23-FEB-25 20000 Pending
1002 2 23-FEB-25 50000 Shipped
Select *from OrderDetails;
ORDERDETAILID ORDERID PRODUCTID QUANTITY PRICE SUBTOTAL
------------- ---------- ---------- ---------- ---------- ----------
2001 1001 101 1 1200.5 1200.5
2002 1002 102 1 699.99 699.99
Select *from Reviews;
REVIEWID USERID PRODUCTID RATING Comment REVIEWDATE
---------- ---------- ---------- ---------- --------------- ---------------------------
3002 2 102 4 Good value 23-FEB-25 08.31.27.478000 PM
3003 1 101 5 Super 23-FEB-25 08.32.22.806000 PM
Conclusion:
The designed relational database schema provides a well-structured and efficient way to manage an
Online Shopping System. The schema ensures data integrity, minimizes redundancy, and supports
essential e-commerce functionalities. By enforcing constraints, it maintains accuracy and consistency
across all transactions. This design serves as a solid foundation for developing a scalable and reliable
online shopping platform.
This document outlines the database structure, including the physical schema, integrity constraints,
logical schema, and consistency mechanisms, to maintain a reliable and efficient system.
Patients – Stores patient details like name, date of birth, contact information, and medical
history.
Doctors – Manages doctor information, including specialization, schedules, and contact
details.
Appointments – Tracks patient-doctor appointments with date, time, and status.
Medical Records – Stores patient diagnoses, prescriptions, and treatment history.
Resources – Maintains information about hospital equipment, beds, and other medical
assets.
Database Schema – Defines how data is stored, structured, and related across tables.
Integrity Constraints – Ensures data accuracy using primary keys, foreign keys, and validation
rules.
Logical Schema – Represents relationships between entities like one-to-many (1:M) and
many-to-many (M:N).
Consistency – Maintains reliable data through ACID properties (Atomicity, Consistency,
Isolation, Durability).
5.Consistency:
Consistency is maintained in the system through transaction management and constraints. The
database follows ACID properties:
Atomicity: Ensures transactions are either fully completed or rolled back.
Consistency: Data always remains in a valid state.
Isolation: Ensures multiple transactions do not interfere with each other.
Durability: Data is permanently saved after a transaction is committed.
Expected Output:
Patient Table:
PATIENTID NAME DOB PHONE EMAIL
------------------------------------------------------------------------------------------------
1 Alice 1990-05-15 9876543210 [email protected]
2 chand 2006-10-22 9123456789 [email protected]
------------------------------------------------------------------------------------------------
Doctor Table:
DOCTORID NAME SPECIALIZATION PHONE
--------------------------------------------------------------------------
1 Dr. Pran Cardiology 9112233445
2 Dr. Shrey Neurology 9001122334
--------------------------------------------------------------------------
Appointment Table:
APPOINTMENTID PATIENTID DOCTORID APPOINTMENTDATE STATUS
-------------------------------------------------------------------------------------------------
1 1 1 2025-03-10 Scheduled
2 2 2 2025-03-12 Completed
-----------------------------------------------------------------------------------------
MedicalRecord Table:
RECORDID PATIENTID DIAGNOSIS PRESCRIPTION DATEOFENTRY
------------------------------------------------------------------------------------------------------------------
1 1 Hypertension Medicine A 2025-02-23
2 2 Migraine Medicine B 2025-02-23
HospitalResource Table:
RESOURCEID RESOURCENAME AVAILABILITYSTATUS
--------------------------------------------------------------------------------
1 MRI Scanner Available
2 X-Ray Machine In Use
Conclusion:
The Hospital Management System efficiently organizes patient records, doctor schedules,
appointments, and resources. It ensures data integrity, security, and accessibility, improving hospital
operations and patient care.
Introduction:
Relational algebra and relational calculus are formal query languages used to retrieve data from
relational databases. Relational algebra is procedural, specifying how to retrieve data, while
relational calculus is declarative, specifying what data to retrieve. Tuple Relational Calculus (TRC) and
Domain Relational Calculus (DRC) are two forms of relational calculus. In this solution, we will solve
the given queries using both relational algebra and relational calculus (TRC & DRC). The database
schema consists of three tables: Products, Customers, and Orders. We will also discuss the physical
schema, constraints, logical schema, consistency, and conclusion.
PHYSICAL SCHEMA:
1. Product Table
This table contains information about the products.
1. Product Table
Sql code:
CREATE TABLE product ( productID number PRIMARY KEY, productName VARCHAR2(255) NOT NULL,
price DECIMAL(10, 2) CHECK (price >= 0) ,Category varchar2(15));
SQL> desc product;
LOGICAL SCHEMA:
Insert into Products:
SQL> insert into product values(101,'vivo',12000, 'Electronics');
1 row created.
SQL> insert into product values(102,'shirt',5000,’clothing’);
1 row created.
SQL> insert into product values(104,'laptop',65000, 'Electronics');
1 row created.
SQL> select * from product;
PRODUCTID PRODUCTNAME PRICE CATEGORY
---------- ------------------------------ ---------- --------------
101 vivo 12000 Electronics
102 shirt 5000 clothing
103 redmi 20000 Electronics
104 laptop 25000 Electronics
105 oppo 15000 Electronics
Insert into Customers:
SQL> insert into customers values(501,'Alice','[email protected]','hyd');
1 row created.
SQL> insert into customers values(502,'BBB','[email protected]','adilabad');
1 row created.
SQL> insert into customers values(503,'CCC','[email protected]','hayathnagar');
1 row created.
Output:
CUSTOMERID NAME EMAIL ADDRESS
---------- ---------- --------------- ----------
501 Alice [email protected] Hyd
502 BBB [email protected] Adilabad
503 CCC [email protected] Hayathnagar
Insert into Orders
SQL> insert into order1 values(1001,501,101,5,'15-01-2024');
1 row created.
SQL> insert into order1 values(1002,502,102,2,'25-01-2024');
1 row created.
SQL> insert into order1 values(1003,503,103,6,'5-01-2024');
1 row created.
Output:
ORDERID CUSTOMERID PRODUCTID QUANTITY ORDERDATE
---------- ---------- ---------- ---------- ----------
1001 501 101 5 15-01-2024
1002 502 102 2 25-01-2024
1003 503 103 6 5-01-2024
1004 504 104 3 14-01-2024
1005 505 105 4 10-02-2024
CONSISTENCY:
i. Find the customers who purchased products costing more than Rs. 1000
SQL Query:
SELECT DISTINCT c.name from customers c join order1 o on c.customerID = o.customerID join
product p on o.productId = p.productId where p.price > 1000;
Output:
NAME
------------------------------
BBB
Alice
CCC
EEE
DDD
ii. Retrieve product names and quantities ordered by a specific customer named "Alice"
SQL Query:
SELECT p.productName, o.quantity FROM order1 o JOIN product p ON o.productID = p.productID
JOIN customers c ON o.customerID = c.customerID WHERE c.name = 'Alice';
Output:
iii. Retrieve all orders placed for products in the "Clothing" category
SQL Query:
SELECT o.orderID, o.customerID, o.productID, o.quantity, o.orderdate FROM order1 o JOIN product p
ON o.productID = p.productID WHERE p.productname = 'clothing';
Output:
OrderID CustomerID ProductID Quantity OrderDate
--------- ------------ ------------ --------- ------------
1002 101 102 2 25-01-2024
iv. List the names of customers who ordered at least 5 units of any product
SQL Query:
SELECT DISTINCT c.name FROM customers c JOIN order1 o ON c.customerID = o.customerID WHERE
o.quantity >= 5;
PRODUCTNAME QUANTITY
-------------------------- ----------
vivo 5
OUTPUT:
NAME
------------------------------
Alice
CCC
Conclusion:
In this database system, we successfully created and populated tables for Products, Customers, and
Orders to store structured data. We then executed four SQL queries to extract relevant information,
demonstrating how relational database operations can be used to retrieve insights from data.This
project showcases the power of SQL queries in managing relational databases and extracting
valuable business insights, which can be applied in real-world e-commerce and inventory
management systems.