0% found this document useful (0 votes)
78 views128 pages

Kamal Sir Database

The document discusses the advantages of Database Management Systems (DBMS) over File Management Systems (FMS), highlighting aspects such as data redundancy, integrity, security, and efficient query processing. It also covers SQL queries for manipulating student and course data, explains two-tier and three-tier client-server architectures, and details the need for locks in DBMS with examples of shared and exclusive locks. Additionally, it addresses integrity constraints, the concept of data abstraction, and differences between primary and candidate keys, among other database-related topics.

Uploaded by

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

Kamal Sir Database

The document discusses the advantages of Database Management Systems (DBMS) over File Management Systems (FMS), highlighting aspects such as data redundancy, integrity, security, and efficient query processing. It also covers SQL queries for manipulating student and course data, explains two-tier and three-tier client-server architectures, and details the need for locks in DBMS with examples of shared and exclusive locks. Additionally, it addresses integrity constraints, the concept of data abstraction, and differences between primary and candidate keys, among other database-related topics.

Uploaded by

teamhawk32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Explain in detail about database management system advantages


over file management system.
Answer: Advantages of Database Management System (DBMS) over
File Management System (FMS):

1. Data Redundancy and Consistency: FMS often duplicates data,


causing inconsistencies. DBMS centralizes data storage, ensuring
consistency and reducing redundancy.

2. Data Integrity: FMS lacks mechanisms to enforce data accuracy.


DBMS ensures integrity through validation rules and constraints.

3. Data Security: FMS offers limited security, while DBMS provides


robust features like authentication, role-based access, and encryption.

4. Data Access and Sharing: FMS struggles with concurrent access.


DBMS uses transaction management to enable safe data sharing among
multiple users.
5. Data Independence: Changes in FMS data structures affect
applications. DBMS ensures data independence, making systems
flexible.

6. Efficient Query Processing: FMS lacks a query language. DBMS


uses SQL for quick and efficient data retrieval and manipulation.

7. Backup and Recovery: FMS has no built-in recovery options.


DBMS automates backup and recovery, ensuring data safety.

8. Scalability and Performance: FMS slows down with large data.


DBMS handles large datasets efficiently and scales easily.

9. Data Relationships: FMS cannot manage complex data relationships.


DBMS uses relational models for better organization.
10. Concurrency Control: FMS cannot handle multiple users
effectively. DBMS ensures safe concurrent access with transaction
control.

2. Write SQL Queries for following set of tables:


Student (enrno, name, courseId, emailId, cellno)
Course (courseId, course_nm, duration)
(i) Add a column city in student table.
(ii) Find out list of students who have enrolled in 'computer' course.
(iii) List name of all courses with their duration.
(iv) List name of all students start with 'a'.
(v) List email Id and cell no of all mechanical engineering students.
Answer: (i). Add a column city in the student table

ALTER TABLE Student ADD city VARCHAR(50);


(ii) Find out the list of students who have enrolled in the 'Computer'
course
SELECT S.name
FROM Student S
JOIN Course C ON S.courseId = C.courseId
WHERE C.course_nm = 'Computer';
(iii) List the name of all courses with their duration
SELECT course_nm, duration
FROM Course;

3. Describe in details about two-tier and three-tire client-server


architectures
Answer:
Two-Tier Architecture
In a two-tier client-server architecture, the system is divided into two
distinct layers: the client and the server. The client is responsible for the
user interface and application logic, while the server manages the
database and handles data storage and retrieval. The client
communicates directly with the server, making this a simple and
straightforward design.

An example of this architecture is a desktop application connected


directly to a database. While it is easy to develop and deploy, it has
limited scalability. As the number of clients increases, the server’s
performance can degrade significantly, making it unsuitable for large-
scale applications.
Three-Tier Architecture
In a three-tier architecture, the system is divided into three layers: the
client layer, the application layer, and the database layer. The client layer
manages the user interface, while the application layer (middle-tier)
handles business logic, processing, and communication between the
client and the database. The database layer stores and retrieves data.
This separation of concerns makes the three-tier architecture more
scalable and maintainable. For example, large e-commerce platforms
often use this model because it can handle a high number of
simultaneous users. However, it is more complex to develop and
requires additional infrastructure, which can increase costs.

4. What is the need of lock in DBMS? Explain shared lock and


exclusive lock with the help of examples.
Answer:
Need for Locks in DBMS
Locks in a Database Management System (DBMS) are essential to
ensure data consistency, integrity, and isolation during concurrent
transactions. When multiple users or processes access the database
simultaneously, conflicts may arise, such as dirty reads, lost updates, or
inconsistent data. Locks help manage these issues by controlling access
to data and ensuring that transactions comply with the ACID (Atomicity,
Consistency, Isolation, Durability) properties.
1. Shared Lock (S-Lock)
A shared lock allows multiple transactions to read a resource
simultaneously but prevents any transaction from modifying it.
 Use Case: Read-only operations.
 Example:
o Transaction T1 acquires a shared lock on a record to read it.
o While T1 holds the shared lock, another transaction T2 can
also acquire a shared lock on the same record to read it.
o However, neither T1 nor T2 can modify the record until both
release their shared locks.

2. Exclusive Lock (X-Lock)


An exclusive lock allows only one transaction to read and modify a
resource. No other transaction can access the resource, even for reading,
until the lock is released.
 Use Case: Write operations.
 Example:
o Transaction T1 acquires an exclusive lock on a record to
update it.
o While T1 holds the exclusive lock, no other transaction (e.g.,
T2) can read or write the record.
o T2 must wait until T1 releases the lock before accessing the
record.
5. Consider a relation schema R = {A, B, C, D, E} with the following
functional dependencies:{ A→ BCDE , BC →ADE , D →A} . Write
the primary key, candidate key, super key, and composite key of R.
Answer:
To determine the primary key, candidate keys, super keys, and
composite keys for the given relation R = (A, B, C, D, E) with functional
dependencies:
1. A→BCDEA
2. BC→ADEBC
3. D→AD

Step 1: Candidate Key(s): A candidate key is a minimal set of attributes


that can uniquely determine all attributes of the relation.
Attribute Closure
 Closure of A({A}+):
o From A→BCDEA , A+={A,B,C,D,E}
o A alone is sufficient to determine all attributes, so AAA is a
candidate key.
 Closure of D({D}+):
o From D→A and A→BCDEA , D+={D,A,B,C,E}
o D can also determine all attributes, so DDD is another
candidate key.
Thus, the candidate keys are: {A,D}\{A, D\}{A,D}

Step 2: Primary Key


 The primary key is one of the candidate keys chosen by the
database designer.
 Either A or D can be chosen as the primary key. For this example,
let’s select: A as the primary key.

Step 3: Super Keys


 A super key is any set of attributes that can uniquely identify all
attributes in the relation.
 All candidate keys are super keys. Additionally, any set of
attributes that includes a candidate key is also a super key.
The super keys are:
{A},{D},{A,D},{A,B},{D,C} and so on (including any superset of {A}
or {D}).

Step 4: Composite Keys


 A composite key is a candidate key consisting of two or more
attributes.
 In this case, since both candidate keys A and D are single
attributes, there are no composite keys.

6. What are the structural constraints on a relational database?


Explain with example.
Answer: Structural constraints in relational databases refer to the rules
and limitations applied to relationships between tables and the attributes
of those tables. These constraints ensure the consistency, integrity, and
validity of the database. The main types of structural constraints are:
i. Domain Constraints: Restricts type and range of values.
Example: Age must be between 18 and 65.
CREATE TABLE Employee (
Age INT CHECK (Age BETWEEN 18 AND 65)
);
ii. Key Constraint: Ensures uniqueness (Primary/Unique Key).
Example: CREATE TABLE Student (
StudentID INT PRIMARY KEY,
RollNumber INT UNIQUE
);
iii. Null Constraint: Restricts whether a column can accept null values.
Example: CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT NOT NULL
);

7. Define primary key, candidate key, and foreign key.


Answer:
i. Primary Key: Uniquely identifies each row in a table. Cannot be null
or duplicate.
Example: CREATE TABLE Student (
StudentID INT PRIMARY KEY,
Name VARCHAR(50)
);
ii. Candidate Key: A set of attributes that can uniquely identify rows.
One candidate key is selected as the primary key.
Example: CREATE TABLE Employee (
EmpID INT,
Email VARCHAR(100),
PRIMARY KEY (EmpID) );
iii. Foreign Key: References a primary key in another table, linking two
tables.
Example: CREATE TABLE Employee (
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID) table
);

8. Construct a schema diagram for the bank database as shown


below.
branch(branch_name, branch_city, assets)
customer (ID, customer_name, customer_street, customer_city) loan
(loan number, branch_name, amount)
borrower (ID, loan_number)
account (account_number, branch_name, balance)
depositor (ID, account_number)
Specify the keys for the schema, stating any assumptions you make.

Answer:
1.branch(branch_name, branch_city, assets)
Primary Key: branch_name (Assuming each branch has a unique name).

2.customer(ID, customer_name, customer_street, customer_city)


Primary Key: ID (Assuming each customer has a unique identifier).

3.loan(loan_number, branch_name, amount)


Primary Key: loan_number (Assuming each loan has a unique number).
Foreign Key: branch_name references branch(branch_name).

4.borrower(ID, loan_number)
Primary Key: (ID, loan_number) (A composite key assuming one
customer can borrow multiple loans and a loan can belong to multiple
borrowers).
Foreign Keys: ID references customer(ID).
loan_number references loan(loan_number).

5.account(account_number, branch_name, balance)


Primary Key: account_number (Assuming each account has a unique
number).
Foreign Key: branch_name references branch(branch_name).

6.depositor(ID, account_number)
Primary Key: (ID, account_number) (A composite key assuming one
customer can have multiple accounts and an account can belong to
multiple depositors).
Foreign Keys: ID references customer(ID).
account_number references account(account_number).
2. Schema Diagram
Here is the representation of the schema diagram for the bank database:
Tables and their relationships:
branch is linked to loan and account via branch_name.
customer is linked to borrower and depositor via ID.
loan is linked to borrower via loan_number.
account is linked to depositor via account_number.

3. Assumptions
Each branch has a unique name (branch_name).
Each customer has a unique ID (ID).
Each loan is uniquely identified by loan_number.
Each account is uniquely identified by account_number.
Relationships like borrower and depositor allow multiple
associations (many-to-many).
9. Explain how the outer join operations are different from the
natural join.
Natural Join:
 A natural join combines rows from two tables based on all
common attributes (same name and domain).
 Rows with matching values in the common attributes are included
in the result, and unmatched rows are excluded.
 Example:If Table A has rows (1,X),(2,Y)and Table B has
(1,Z),(3,W) the result of the natural join will be:(1,X,Z) (matching
on the common attribute).
Outer Join:
 An outer join includes unmatched rows from one or both tables in
addition to the rows that satisfy the join condition.
 Types of outer joins:
1. Left Outer Join: Includes all rows from the left table and
matching rows from the right table. If no match is found,
NULL values are used for the right table's attributes.
2. Right Outer Join: Includes all rows from the right table and
matching rows from the left table. NULL values are used for
the left table's attributes when no match exists.
3. Full Outer Join: Combines the results of both left and right
outer joins, including all rows from both tables with NULLs
for unmatched rows.
Difference:
 A natural join only includes matching rows, while an outer join
includes unmatched rows as well, depending on its type.

10 Discuss the views and their updatability in SQL.


A view in SQL is a virtual table that presents data from one or more
tables. It is not stored physically but dynamically retrieves the data
whenever queried. Views are often used to simplify complex queries,
limit access to sensitive data, or display only specific portions of a table.

The ability to update a view depends on how it is defined. If the view is


created on a single base table and includes all necessary columns to
uniquely identify rows (like the primary key), it is updatable. For
example, a simple view like CREATE VIEW EmpView AS SELECT
emp_id, emp_name FROM Employees; is updatable if emp_id is the
primary key.

However, when a view involves joins, aggregation (e.g., SUM,


COUNT), or derived columns, it becomes non-updatable because the
database cannot determine how changes to the view should be reflected
in the underlying tables. For instance, a view summarizing data, like
CREATE VIEW DeptSummary AS SELECT dept_id, COUNT(emp_id)
FROM Employees GROUP BY dept_id;, is non-updatable as it does not
directly map to specific rows in the base table.
11. What are integrity constraints? Why are they important?
Integrity constraints are rules in SQL that ensure the accuracy and
consistency of data within a database. They enforce restrictions such as
ensuring that every row in a table has a unique identifier (primary key),
maintaining valid relationships between tables (foreign key), or
preventing invalid data entry (NOT NULL, CHECK).

These constraints are crucial because they maintain the logical


consistency of data, prevent duplication, and ensure that relationships
between tables are preserved. For example, a foreign key constraint
ensures that a customer ID referenced in a loan table must exist in the
customer table, thus preserving referential integrity. Without integrity
constraints, databases risk becoming inconsistent or unreliable, leading
to incorrect query results or errors in applications that depend on the
data.
12. List the name of all students whose names start with 'a'.
SELECT name
FROM Student
WHERE name LIKE 'a%';
13. List email ID and cell number of all Mechanical Engineering
students.
SELECT S.emailId, S.cellno
FROM Student S
JOIN Course C ON S.courseId = C.courseId
WHERE C.course_nm = 'Mechanical Engineering';
14 . Difference between primary key and candidate key with
appropriate example.
Example:

Candidate Keys:
 StudentID: Uniquely identifies each student.
 Email: Unique for each student.
 Phone: Unique for each student.

Primary Key:
 If we choose StudentID as the main unique identifier for the table,
it becomes the primary key.
 Email and Phone remain candidate keys but are not selected as the
primary key.

15. How does DBMS provide data abstraction? Explain the concept
of data independence.

DBMS provides data abstraction by hiding the complex details of data


storage, management, and retrieval from users. It ensures that users can
interact with the database without needing to know how the data is
stored or organized internally. This is achieved through the following
three levels of abstraction:

1. Physical Level:
o The lowest level of abstraction.
o Describes how data is stored in physical storage devices
(hard disks, SSDs) and the data structures used ( B-trees,
indexing).
o Users are unaware of this level; only database administrators
and system software interact directly with it.
2. Logical Level:
o The middle level of abstraction.
o Describes the overall structure of the database, such as tables,
fields, and relationships.
o Focuses on what data is stored and its organization without
detailing how it is physically stored.
o Database administrators and designers use this level to define
the schema.
3. View Level:
o The highest level of abstraction.
o Provides tailored views of the database to different users or
user groups.
o Ensures users see only the relevant information they need,
such as a report or a dashboard, hiding unnecessary data.
o For example, in a library management system, a librarian
might see only book availability, while an administrator
might see financial data.

Data abstraction simplifies database usage for different user groups,


ensuring a clear separation between how data is stored and how it is
accessed or presented.

Data Independence

Data independence refers to the ability to modify the database schema


at one level without affecting other levels. This concept is crucial for
maintaining flexibility and minimizing the impact of changes on
applications or users.

1. Physical Data Independence:


o Refers to changes in the physical storage of data without
impacting the logical schema.
o Example: If the database changes the indexing method or
storage location, applications using the database remain
unaffected.
2. Logical Data Independence:
o Refers to changes in the logical schema (e.g., altering a table
or its relationships) without affecting the view level or user
applications.
o Example: Adding a new column to a table or merging two
tables should not disrupt existing queries or reports that do
not use the changed data.

16. Write about different types of attributes in ER model. Show the


notation of each.
Answer:

In the Entity-Relationship (ER) model, attributes describe the


properties or characteristics of an entity or relationship. These attributes
are represented with ellipses (ovals) connected to their respective
entities or relationships. Below are the types of attributes along with
their explanations and notations:

1. Simple Attribute: A simple attribute cannot be divided further


into smaller components.
o Example: Student Name, Age, Gender.
o Notation: Represented by a single ellipse connected to the
entity.

2. Composite Attribute : A composite attribute can be divided into


smaller sub-parts, each representing meaningful data.
o Example: Full Name can be divided into First Name and
Last Name.
o Notation: Represented by an ellipse with its sub-parts
connected as smaller ellipses.

3. Derived Attribute : A derived attribute is not stored in the


database directly but can be derived from other attributes.
o Example: Age can be derived from the Date of Birth.
o Notation: Represented by a dashed ellipse.

4. Single-Valued Attribute: An attribute that holds only a single


value for a particular entity.
o Example: Roll Number for a student.
o Notation: Represented by a single ellipse (same as a simple
attribute).

5. Multi-Valued Attribute: An attribute that can hold multiple


values for a particular entity.
o Example: Phone Numbers for a student who may have more
than one contact number.
o Notation: Represented by a double ellipse.

6. Key Attribute: An attribute that uniquely identifies an entity in a


set.
o Example: Student ID or Employee ID.
o Notation: Represented by an ellipse with the attribute name
underlined.
17. Why is concurrency control needed? Explain the problems that
would arise when concurrency control is not provided by the
database system.
Answer:
Concurrency control is essential in database systems to manage the
simultaneous execution of multiple transactions in a consistent and
efficient manner. In a multi-user environment, multiple users or
applications might access and modify the database at the same time.
Without proper concurrency control, the database system could face
several issues, leading to incorrect or inconsistent data.

Concurrency control is essential to prevent issues that arise when


multiple transactions execute simultaneously without proper
synchronization. Here are the problems explained briefly:

1. Lost Update Problem:


When two transactions update the same data simultaneously, one update
overwrites the other, leading to data loss. For example, if one transaction
adds $50 to a balance while another deducts $30, the final balance might
reflect only one of these changes, not both.

2. Dirty Read Problem:


A transaction reads uncommitted changes made by another transaction.
If the first transaction rolls back, the second transaction holds invalid or
inconsistent data. For instance, reading a salary increase that gets
reverted leads to incorrect calculations.
3. Uncommitted Dependency Problem:
Similar to the dirty read, this happens when one transaction depends on
uncommitted changes of another. If the changes are rolled back, the
dependent transaction processes invalid data.

4. Inconsistent Analysis Problem (Non-Repeatable Read):


When a transaction reads the same data multiple times and finds
different values because another transaction modifies it. For example,
summing sales records while new records are being added results in
inconsistent totals.

5. Phantom Problem:
Occurs when a transaction retrieves a set of rows, and another
transaction inserts, deletes, or updates rows that affect the original
query result. For example, retrieving employees with salaries
above $5000 might change if a new employee is added during the
process.

18. Discuss Two-Phase Locking Protocol and Strict Two-Phase


Locking Protocol.

Answer:
Two-Phase Locking Protocol (2PL)

Two-Phase Locking Protocol is a method used in database systems for


concurrency control, ensuring serializability. It operates in two distinct
phases:

1. Growing Phase:
o Transactions acquire locks (read or write) as needed.
o No locks can be released in this phase.
o The transaction’s lock set "grows."
2. Shrinking Phase:
o Transactions release locks, but they cannot acquire new
locks.
o The transaction’s lock set "shrinks."

Characteristics:

 Ensures conflict serializability (transactions execute in a


serializable order).
 Can lead to deadlocks, where two or more transactions wait
indefinitely for locks held by each other.

Strict Two-Phase Locking Protocol (Strict 2PL)

Strict Two-Phase Locking Protocol is an enhanced version of 2PL. It


enforces stricter locking rules:

1. Lock Holding:
o All exclusive (write) locks are released only after the
transaction commits or aborts.
o This prevents other transactions from accessing data
modified by an uncommitted transaction.

Characteristics:

 Prevents cascading rollbacks, as no uncommitted changes are


visible to other transactions.
 Simplifies recovery, as only committed changes are considered.
 May reduce concurrency because locks are held for a longer time.
19. By considering suitable examples, describe the usage of SQL
CREATE and ALTER statements.

Answer:
The CREATE statement is used to create new database objects such as
tables, databases, indexes, or views.

CREATE TABLE Student (

StudentID INT PRIMARY KEY,

Name VARCHAR(50),

Age INT,

Email VARCHAR(100)

);

Where,

StudentID INT PRIMARY KEY: Creates a column StudentID as an


integer and sets it as the primary key.

Name VARCHAR(50): Creates a column Name that can store up to 50


characters.

Age INT: Stores the age as an integer.

Email VARCHAR(100): Stores the email address with up to 100


characters.

CREATE DATABASE SchoolDB;


Creates a new database named SchoolDB.
The ALTER statement is used to modify an existing database object,
such as adding, deleting, or modifying columns in a table.
ALTER TABLE Student
ADD Address VARCHAR(100);
Adds a new column Address to the Student table to store the student's
address.

20. Let E1 and E2 be two entities in an E/R diagram with simple


single-valued attributes. R1 and R2 are two relationships between
E1 and E2, where R1 is one-to-many and R2 is many-to-many. R1
and R2 do not have any attributes of their own. Calculate the
minimum number of tables required to represent this situation in
the relational model.
Answer:

To represent the given scenario in the relational model, we need to


analyze the entities and relationships:

Entities and Relationships:

1. Entities:
o E1: Represents one entity with simple single-valued
attributes.
o E2: Represents another entity with simple single-valued
attributes.
2. Relationships:
o R1: A one-to-many relationship between E1 and E2.

o R2: A many-to-many relationship between E1 and E2.


Step 1: One-to-Many Relationship (R1)

 In a one-to-many relationship:
o The primary key of the "one" side (E1) is included as a
foreign key in the "many" side (E2).
o There is no need for a separate table for R1 as there are no
attributes associated with the relationship.

Step 2: Many-to-Many Relationship (R2)

 In a many-to-many relationship:
o A separate table is created to represent the relationship
(R2).
o This table will have:
 The primary key of E1 as a foreign key.

 The primary key of E2 as a foreign key.

Step 3: Total Number of Tables

 Table for E1: To store the attributes of entity E1.


 Table for E2: To store the attributes of entity E2.
 Table for R2: To represent the many-to-many relationship.

Since R1 does not require a separate table, the total number of tables is:

Minimum Number of Tables = 3

1. Table for E1.


2. Table for E2.
3. Table for R2.

The minimum number of tables required is 3.


21. Types of database users and their interaction with the database
system:
1. Database Administrator (DBA): Manages and oversees the
database system, including maintenance, backup, and security.
2. Database Designers: Design the database structure, schemas, and
relationships between data.
3. Application Programmers: Develop applications that interact with
the database using SQL queries or APIs.
4. End Users: Access the database for data retrieval, updates, and
reporting through queries or applications.
5. System Analysts: Analyze business needs and design solutions
involving database interaction.

22. Set operations in SQL:


1. UNION: Combines the results of two or more SELECT statements
and removes duplicates.
o Example: SELECT column1 FROM table1 UNION SELECT
column1 FROM table2;
2. UNION ALL: Similar to UNION, but includes duplicate values.
3. INTERSECT: Returns only the common records between two
SELECT statements.
o Example: SELECT column1 FROM table1 INTERSECT SELECT
column1 FROM table2;
4. EXCEPT (or MINUS in some databases): Returns records from the
first SELECT statement that are not present in the second.
o Example: SELECT column1 FROM table1 EXCEPT SELECT
column1 FROM table2;

23. SQL queries for marks relation:


1. Create mark_grade relation:
CREATE TABLE mark_grade (
ID INT PRIMARY KEY,
score INT,
grade CHAR(1));

2. Display the grade for each student:


SELECT ID,
score,
CASE
WHEN score < 40 THEN 'F'
WHEN score >= 40 AND score < 60 THEN 'C'
WHEN score >= 60 AND score < 80 THEN 'B'
WHEN score >= 80 THEN 'A'
END AS grade
FROM marks;
3. Find the number of students with each grade:
SELECT grade, COUNT(*) AS number_of_students
FROM (
SELECT
CASE
WHEN score < 40 THEN 'F'
WHEN score >= 40 AND score < 60 THEN 'C'
WHEN score >= 60 AND score < 80 THEN 'B'
WHEN score >= 80 THEN 'A'
END AS grade
FROM marks
) AS grade_counts
GROUP BY grade;

24. ACID Properties:


1. Atomicity: Ensures all operations in a transaction are completed or
none are, maintaining data consistency.
Usefulness: Prevents partial updates, ensuring data integrity during
failures.
2. Consistency: Ensures the database remains in a valid state before
and after a transaction.
Usefulness: Maintains data rules, avoiding invalid states.

3. Isolation: Ensures transactions do not interfere with each other.


**Usefulness**: Prevents concurrency issues like dirty reads or lost
updates.

4. Durability: Ensures that once a transaction is committed, it remains


persistent despite system crashes.
Usefulness: Guarantees data is safe and reliable after completion.
b. The terms serializable and serial (or serial schedules) relate to the
order of transaction execution in a database:
1. Serial Schedule:
o Transactions are executed one after another without any
overlap.
o No interleaving of operations from different transactions
occurs.
o Guarantees consistency as there is no interference.
2. Serializable Schedule:
o Allows interleaved execution of transactions.
o The result of the interleaved schedule must be equivalent to
a serial schedule.
o Ensures consistency while improving concurrency.
C. To determine if the corresponding schedule is conflict-serializable,
we need to analyze the precedence graph (also known as a
serialization graph), where:
 Each node represents a transaction (T1, T2, T3, T4).
 Each directed edge between nodes indicates a dependency
between transactions (one transaction conflicts with and must
happen before another).
Conflict-serializability criteria:
 The schedule is conflict-serializable if the precedence graph has
no cycles.
Observing the Graph in Fig. A2:
In the given graph, we see that there are edges forming a cycle
involving the transactions. This cycle indicates that there is no way to
order the transactions in a serial (non-interleaved) way that maintains
the dependencies.

25. Main Characteristics of the Database Approach and How It Differs


from Traditional File Systems:
 Data Abstraction: Separates the logical organization of data from
its physical storage, simplifying data access for users.
 Data Integrity: Enforces constraints (e.g., primary and foreign
keys) to maintain accurate, consistent data across the system.
 Reduced Data Redundancy: Stores data in a central location,
allowing multiple applications to access it, which reduces
duplicate data.
 Data Security: Provides user authentication and role-based access
control to protect sensitive data.
 Data Independence: Allows changes to data structure without
affecting application functionality, enhancing flexibility.
 Complex Query Support: Enables advanced data retrieval and
manipulation through SQL, supporting complex operations
without extensive code.
 Data Sharing: Facilitates multi-user access, allowing authorized
users to share and update data in real-time.
 Scalability: Designed to handle large volumes of data and
concurrent users efficiently.
 Differences from Traditional File Systems:
o Traditional file systems lack data integrity controls, leading
to inconsistencies.
o File systems have limited security and access control, making
them less secure.
o Data redundancy and isolation are common in file systems,
leading to inefficiency.
26. Client/Server Architecture Models in Application Development:
 Two-Tier Architecture:
o Client directly connects to the database server, managing
both application logic and data storage on the server side.
o Simpler model, suitable for small applications but limited in
scalability.
o Client handles requests directly, which can lead to
performance issues with high user loads.
o Commonly used in local applications, where each client
connects independently to the database.
 Three-Tier Architecture:
o Adds an application server between the client and the
database, separating application logic from data storage.
o Application server handles requests and processes them
before interacting with the database.
o Enhances security by isolating clients from direct database
access.
o Increases scalability, as it distributes the load and can
support more users.
o Common in web applications, with the client as a browser,
the application server handling business logic, and the
database server storing data.
 Multi-Tier Architecture:
o Extends the three-tier model by adding additional layers
(e.g., authentication, caching, load balancing).
o Useful for large-scale applications requiring high
performance, security, and flexibility.
o Each layer can be modified or scaled independently,
improving maintainability.
o Commonly used in complex enterprise applications with
high user demand and security requirements.

27. Data Definition Language (DDL) and Examples of DDL Commands


in DBMS:
 Definition of DDL:
o DDL is a subset of SQL used to define, modify, and delete
database structures (e.g., tables, schemas, indexes).
o It controls the database schema, organizing how data is
stored without affecting actual data manipulation.
 DDL Commands:
o CREATE: Defines new tables, databases, or indexes;
structures data storage as per application needs.
 Example: CREATE TABLE Students (ID INT, Name
VARCHAR(50));
o ALTER: Modifies existing database structures, such as adding
or removing columns.
 Example: ALTER TABLE Students ADD COLUMN Age
INT;
o DROP: Deletes tables or databases, removing both structure
and data.
 Example: DROP TABLE Students;
o TRUNCATE: Removes all records from a table without
deleting the table structure; faster than DELETE.
 Example: TRUNCATE TABLE Students;
 SCL (SQL Control Language) Example:
o GRANT: Provides permissions to users, controlling their
access to tables or databases.
 Example: GRANT SELECT ON Students TO User1;
 Purpose of DDL:
o Establishes and modifies the data schema, ensuring a
structured, secure environment.
o Provides the foundation for database organization, allowing
applications to store and retrieve data effectively.

28. What are functions of data models ? how many categories of


data models ?describe them.
=>
Functions of Data Models
Data models serve several important functions in defining how data is
structured, stored, and managed within a database or system. The key
functions include:
1. Data Organization: Data models define the logical structure of
the data, such as how data is organized, related, and stored.
2. Data Relationships: They help establish relationships between
different data entities, clarifying how different data sets are
interconnected.
3. Data Integrity: Data models enforce rules and constraints to
ensure data accuracy and consistency, such as primary keys,
foreign keys, and validation rules.
4. Data Abstraction: They provide a layer of abstraction between the
physical storage of data and the logical view of the data, making it
easier for users and developers to interact with complex data
structures.
5. Facilitates Communication: They act as a communication tool
between stakeholders (developers, data architects, and business
users), ensuring a common understanding of how data is structured
and used.
6. Support for Application Development: Data models serve as
blueprints for building applications that interact with databases.
Developers can use data models to define how data will be handled
within the application.
Categories of Data Models
Data models are generally categorized into three major types:
1. Conceptual Data Model
o Purpose: A high-level, abstract view of the system, focusing
on defining the entities, relationships, and constraints without
getting into implementation details.
o Features:
 Emphasizes what the system contains, not how it's
implemented.
 Typically used during the early design phase to capture
business requirements.
o Example: Entity-Relationship (ER) diagram showing how
customers, products, and orders are related.
2. Logical Data Model
o Purpose: Refines the conceptual model by specifying the
structure of data more precisely, including attributes, data
types, and relationships.
o Features:
 Does not depend on a specific database management
system (DBMS).
 Defines how data should be structured logically, such as
tables, columns, and relationships.
o Example: ER diagram with detailed attributes for each entity,
showing primary keys, foreign keys, and other constraints.
3. Physical Data Model
o Purpose: Focuses on the actual implementation of the
database, including how data is stored in memory, indexed,
and accessed.
o Features:
 Takes into account performance considerations, storage
space, and physical storage of data.
 Includes details like table structures, indexes,
partitioning, and other DBMS-specific features.
o Example: SQL scripts for creating tables, defining indexes,
and configuring storage settings in a particular database like
MySQL, Oracle, or PostgreSQL.
These three categories help data architects and developers move from a
high-level understanding of data to an actual implementation that
supports application development and business operations.

29. Define dynamic SQL and embedded SQL


Dynamic SQL
Dynamic SQL refers to SQL queries that are constructed and executed
at runtime, rather than being predefined in the code. This allows the SQL
query to be built dynamically based on conditions, user input, or other
parameters. Dynamic SQL is typically used when the structure of the
query is not known in advance and needs to be flexible.
Examples of situations where dynamic SQL is used:
 When the database schema might change, and the SQL query
needs to adapt.
 For constructing queries where table names, column names, or
values are determined dynamically based on user input or program
logic.
A common use case is in applications that allow users to search for
different combinations of criteria, where the query is built dynamically
based on the user's choices.
Embedded SQL
Embedded SQL refers to the inclusion of SQL statements directly
within the code of a host programming language (like C, Java, or
Python). These SQL statements are not dynamically constructed but are
fixed parts of the application code. The SQL code is "embedded" within
the host language, and the host language's preprocessor or compiler
typically processes the SQL statements.
In embedded SQL, SQL queries are written directly into the program
code. The host language interacts with the database by embedding SQL
statements in specific syntaxes.
Key Differences:
1. Dynamic SQL is constructed and executed at runtime, allowing
more flexibility in query structure.
2. Embedded SQL is predefined within the application code, with
SQL queries written directly in the source code of the host
language.

30. List two reasons why null values might be introduced into a
database
=>
Two common reasons why null values might be introduced into a
database are:
1. Missing or Unknown Data:
Null values can represent cases where the data is not yet available
or is unknown at the time of entry. For example, a customer may
not provide their phone number or email address during
registration, so those fields would be left null until the data is
obtained.
2. Not Applicable Data:
Some fields in a database may not apply to every record. For
instance, in a table storing employee information, a "termination
date" field would be null for employees who are currently
employed because the information is not applicable to them.
Null values are used to represent the absence of data, which can differ
from a zero or an empty string, as those could have specific meanings in
some cases

31. Retrieve the name of each employee who lives in "Dinajpur."


 Relational Algebra Expression:
π_person_name(σ_city='Dinajpur'(employee))
 Explanation:
o σ_city='Dinajpur'(employee) selects the rows from the
employee relation where the city is "Dinajpur."
o π_person_name(...) projects only the person_name attribute
from the selected rows.

32. Retrieve the name of each employee whose salary is greater than
Tk. 25,000.
 Relational Algebra Expression:
π_person_name(σ_salary>25000(works))
 Explanation:
o σ_salary>25000(works) selects rows from the works relation
where the salary is greater than Tk. 25,000.
o π_person_name(...) projects only the person_name attribute
from the selected rows.

33. Retrieve the name of each employee who lives in "Dinajpur" and
whose salary is greater than Tk. 25,000.
 Relational Algebra Expression:
π_person_name(σ_city='Dinajpur'(employee) ⨝
σ_salary>25000(works))
 Explanation:
o σ_city='Dinajpur'(employee) selects employees who live in
"Dinajpur."
o σ_salary>25000(works) selects employees whose salary is
greater than Tk. 25,000.
o ⨝ performs a natural join between the filtered results of the
employee and works relations based on the common attribute
person_name.
o Finally, π_person_name(...) projects the names of the
employees who meet both conditions.

34. Define terms entity, entity type and entity set with full of
examples
Entity
An entity refers to any object, thing, or concept that can be distinctly
identified in a given domain. An entity can represent a physical object
(like a person or a car), a concept (like a course or a department), or
even an event (like a meeting or a transaction). Each entity is
characterized by specific attributes (also called properties) that define its
properties or characteristics.
Example:
 Person: An individual, like "John Smith" or "Sarah Brown", can
be considered an entity. The entity would have attributes like
name, age, and address.
 Car: A specific car, like "Toyota Corolla with VIN 123ABC", is an
entity, with attributes like model, color, and registration number.
Entity Type
An entity type refers to a collection or category of entities that share
common characteristics and attributes. It is essentially a blueprint or
template that defines the structure of a group of related entities. Entity
types are abstract descriptions of objects or concepts within a domain,
whereas entities are specific instances of those entity types.
Example:
 Person: The entity type "Person" could have attributes like Name,
Age, Address. The entity type defines the structure, while specific
individuals like "John Smith" and "Sarah Brown" are actual
entities.
 Car: The entity type "Car" would have attributes such as Make,
Model, Year, Color. Specific cars such as "Toyota Corolla" or
"Ford Mustang" are instances of this entity type.
Entity Set
An entity set is a collection of all entities of a particular entity type. It
represents the entire collection of instances that fall under a specific
entity type in a given database or domain. In other words, an entity set is
a set or group of similar entities that share the same type and attributes.
Example:
 Entity Set for Person: The entity set "Person" could include
multiple specific entities like:
o John Smith (Name: John Smith, Age: 35, Address: 123 Main
St.)
o Sarah Brown (Name: Sarah Brown, Age: 29, Address: 456
Oak Ave.)
o Emily Davis (Name: Emily Davis, Age: 42, Address: 789
Pine Rd.)
All these specific persons are part of the "Person" entity set.
 Entity Set for Car: The entity set "Car" could include:
o Toyota Corolla, 2020, Red
o Ford Mustang, 2018, Blue
o Honda Civic, 2022, Black
All these specific cars belong to the "Car" entity set.

35. Explain the difference between a weak and a strong entity set
with an appropriate relationship set
Strong Entity Set
A strong entity set (also called a regular entity set) is an entity set
where each entity can be uniquely identified by a set of attributes,
known as the primary key. These entities have sufficient attributes to be
distinguished from other entities in the set. Strong entities exist
independently of other entities.
 Identification: Strong entities have a primary key that uniquely
identifies each entity in the set.
 Example: A Student entity set, where each student can be
uniquely identified by their student ID.
o Attributes: StudentID, Name, Age, Major
o The StudentID is the primary key.
Weak Entity Set
A weak entity set is an entity set that cannot be uniquely identified by
its own attributes alone. It depends on a strong entity set (called the
owner or identifying entity) for its identification. A weak entity set has
a partial key that, together with the key of the strong entity, is used to
uniquely identify the weak entity.
 Identification: A weak entity does not have a primary key of its
own; it relies on a foreign key from the associated strong entity
and some additional attributes (known as a partial key) to
uniquely identify each entity.
 Dependence: A weak entity set cannot exist without its identifying
strong entity.
 Example: A Dependent entity set, where each dependent is
associated with a Employee (strong entity). A dependent can be
uniquely identified by a combination of the EmployeeID (from the
Employee entity) and the DependentName (partial key).
o Attributes: DependentName, Relationship
o The combination of EmployeeID (from the Employee entity)
and DependentName forms a unique identification for the
dependent.
Relationship Set
In ER modeling, a relationship set represents the associations between
entity sets. A relationship set connects two or more entity sets, and the
entities involved in the relationship can be either weak or strong.
For weak entities, there is usually a special relationship called an
identifying relationship that connects the weak entity set to its
identifying strong entity set. This relationship is used to establish the
identity of the weak entity.
 Identifying Relationship: A special type of relationship used to
connect a weak entity set to the strong entity set that helps in its
identification. This relationship is represented by a double
diamond in an ER diagram.
Example of Weak and Strong Entity Set with Relationship:
1. Strong Entity Set: Employee
o Attributes: EmployeeID, Name, Position
o EmployeeID is the primary key.
2. Weak Entity Set: Dependent
o Attributes: DependentName, Relationship
o Cannot be uniquely identified by DependentName alone, but
can be identified using EmployeeID (from the Employee
entity) and DependentName.
o Partial key: DependentName (only partially identifies the
dependent).
3. Relationship Set: HasDependent (Identifying Relationship)
o Connects Employee (strong entity) with Dependent (weak
entity).
o In this case, the HasDependent relationship helps uniquely
identify each Dependent by linking it with the corresponding
EmployeeID from the Employee entity.
36. Consider a database that includes the entity sets students,
courses, and section from the university schema and that
additionally records the mark that students received in different
exams of different sections. Construct and E-R diagram that models
exams as entities and uses a ternary relationship as part of the
design.

Entities and Attributes


1. Student:
o Attributes: StudentID (Primary Key), Name, Major, Email,
etc.
2. Course:
o Attributes: CourseID (Primary Key), CourseName, Credits,
etc.
3. Section:
o Attributes: SectionID (Primary Key), Instructor, Room,
Schedule, etc.
o A section represents a specific offering of a course (e.g., a
particular semester and instructor).
4. Exam (new entity to represent exams):
o Attributes: ExamID (Primary Key), Date, Type (e.g.,
Midterm, Final), etc.
o Exams are linked to specific sections and courses, and
students take these exams.
Ternary Relationship: TakesExam
The relationship TakesExam links Students, Sections, and Exams, and
it also records the marks a student receives in an exam. This ternary
relationship connects the three entities and models the fact that a student
takes an exam in a specific section of a course and receives a mark.
 Attributes of the relationship:
o Mark: The grade or score a student receives for a particular
exam in a particular section.
Structure of the E-R Diagram:
1. Student is connected to TakesExam via a relationship that
indicates which exams the student has taken.
2. Section is connected to TakesExam via a relationship that
indicates which section the exam is associated with.
3. Exam is connected to TakesExam via a relationship that indicates
which exams the students take in which sections of which courses.
E-R Diagram Elements:
1. Entities:
o Student: Represented by a rectangle.
o Course: Represented by a rectangle.
o Section: Represented by a rectangle.
o Exam: Represented by a rectangle.
2. Attributes:
o For each entity, list the relevant attributes (e.g., for Student,
include StudentID, Name, etc.).
3. Relationships:
o TakesExam: A ternary relationship that connects Student,
Section, and Exam. It is represented by a diamond shape.
o The relationship TakesExam will have the attribute Mark to
record the mark the student received for the exam.
4. Cardinality:
o A Student can take many Exams in different Sections.
o A Section can have many Exams, and many students can
take these exams.
o An Exam can be associated with many Sections and many
Students can take it.

37. Consider the following structure of generalization and


specialization as shown in Fig. A1. Explain how the attributes are
inherited to the entity sets instructor and secretary.
Generalization and specialization are key concepts in database design,
particularly in the entity-relationship (E-R) model. The given question
revolves around how attributes are inherited in a hierarchical structure
involving a higher-level entity and its specialized sub-entities.

Generalization:
 Definition: Generalization is the process of combining two or
more lower-level entities into a single higher-level entity based on
common attributes.
 In the given diagram (Fig. A1), the higher-level entity is employee.
Specialization:
 Definition: Specialization is the process of creating sub-entities
from a higher-level entity based on distinct attributes or roles.
 In the diagram, the sub-entities are instructor and secretary.
Inheritance of Attributes:
1. Higher-Level Entity: employee
o The employee entity contains common attributes:
 person_name
 street
 city
o These attributes are shared by all entities in the hierarchy
(instructor and secretary).
2. Sub-Entities: instructor and secretary
o Both instructor and secretary inherit the common attributes
(person_name, street, city) from the employee entity.
o Additionally, these sub-entities have their own specific
attributes:
 instructor:
 salary
 secretary:
 hours_worked
3. Inheritance Mechanism:
o The attributes from the higher-level entity (employee) are
automatically included in the sub-entities (instructor and
secretary). This avoids duplication and ensures consistency in
the database design.
4. Specialized Attributes and Role Differentiation:
o While both instructor and secretary share the common
attributes of an employee, their distinct roles are represented
by their specific attributes (salary for instructors and
hours_worked for secretaries).

Example:
Consider an employee named John:
 If John is an instructor:
o Attributes: person_name = John, street = Main St, city =
Dinajpur, salary = 50,000.
 If John is a secretary:
o Attributes: person_name = John, street = Main St, city =
Dinajpur, hours_worked = 40.

38. Explain why and when does an administrator grant


authorization.

An administrator grants authorization in a database management system


(DBMS) to ensure secure access and proper usage of the database by
different users. Authorization is the process of assigning specific
privileges to users or groups based on their roles and requirements.
Below is an explanation of why and when an administrator grants
authorization:
To Control Access to Sensitive Data:
o Some data in a database may be sensitive or confidential
(e.g., employee salaries or customer details). Authorization
ensures that only authorized users can view, modify, or delete
such data.
To Assign Role-Specific Permissions:
o Different users or roles within an organization (e.g.,
managers, employees, or auditors) require different levels of
access. Authorization allows the administrator to grant
permissions tailored to the role of each user.
To Maintain Data Integrity:
o Restricting unauthorized users from making changes ensures
the accuracy and consistency of the data.
To Enhance Security:
o Authorization helps prevent malicious activities like
unauthorized data modifications, deletions, or leakage.
To Comply with Policies and Regulations:
o Organizations often have policies or legal requirements
regarding data access and privacy. Authorization ensures
compliance with these rules.

When a User Account is Created:


o New users are granted specific privileges based on their role,
ensuring they only have access to relevant parts of the
database.
When User Responsibilities Change:
o If a user is promoted, transferred, or changes roles, their
authorization may be updated to match their new
responsibilities.
When a New Resource is Added:
o When new tables, views, or databases are created, an
administrator assigns access permissions to relevant users.

39. Consider a view V whose definition references only relation r.


Answer the following questions:

If a user is granted SELECT authorization on V, does that user


need to have SELECT authorization on r as well? Why or why not?
Answer:
No, the user does not need to have SELECT authorization on r.
 A view is a virtual table in the database that is defined by a query
over one or more base relations (in this case, r).
 When SELECT authorization is granted on the view V, the user can
access the data exposed by the view without directly interacting
with the base relation r.
 The DBMS controls access to r internally, ensuring that users
can only access the data in the format and scope defined by the
view. This helps enforce security by restricting access to sensitive
parts of the base relation.

40. If a user is granted UPDATE authorization on V, does that user


need to have UPDATE authorization on r as well? Why or why not?
Answer:
Yes, the user typically needs to have UPDATE authorization on r.
 Views are often used as a restricted or customized representation of
a base table. For an UPDATE operation on a view to take effect,
the DBMS must translate the changes back to the underlying
relation r.
 If the user does not have UPDATE authorization on r, the DBMS
cannot apply the changes to the base table.
 Exception: If the view is specifically designed to allow updates
(e.g., using triggers or rules), the DBMS may permit updates
without direct access to r. However, this depends on the
implementation of the database system.

41. Define trigger? Explain its importance in database system with


an example.

In database design and management, a trigger is a set of SQL statements


that automatically execute in response to certain events on a specific
table or view. These events can include INSERT, UPDATE, or DELETE
operations. Triggers are stored and managed within the database and can
enforce rules, maintain audit trails, or perform complex data validation
and processing tasks without needing manual intervention.

Importance of Triggers in a Database System:

1. Enforcing Business Rules: Triggers can enforce business rules


automatically, ensuring consistency and integrity in data, such as setting
default values or validating input.
2. Data Integrity and Consistency: By running automatically, triggers
help maintain consistent data, ensuring that changes in one part of the
database are reflected correctly in related areas. For instance, if an
employee's role changes, a trigger might automatically update related
data.

3. Automated Audit Trails: Triggers are useful for tracking changes to


sensitive data. For example, a trigger can record who made changes and
when, helping maintain a history of data modifications.

4. Cascading Operations: They can automate cascading updates or


deletions. For instance, when a customer account is deleted, a trigger can
automatically delete all associated records, like orders and transaction
history.

Example of a Trigger:

Suppose we have a Sales database with two tables: Orders and


Inventory. When a new order is placed, it’s important to reduce the stock
count of the ordered item in the Inventory table. A trigger can automate
this task.
Trigger Example:

CREATE TRIGGER update_inventory


AFTER INSERT ON Orders
FOR EACH ROW
BEGIN
UPDATE Inventory
SET stock_quantity = stock_quantity - NEW.quantity
WHERE product_id = NEW.product_id;
END;

In this example:

The update_inventory trigger activates after a new row is inserted into


the Orders table.

The trigger updates the Inventory table by reducing the stock_quantity


for the specified product_id, ensuring that the inventory reflects the
recent order.

This approach helps automate stock management without needing


separate code or manual checks, enhancing efficiency and accuracy in
the database system.
42. Does the two-phase locking protocol ensure conflict
serializability? Justify your answer with appropriate examples.
43. Explain briefly the languages supported by database systems.
44. Write SQL queries for the following set of tables:

 Employee (employee_id, first_name, last_name, salary,


joining_date, department)
 Reward (employee_ref_id, date_reward, amount)

(i) Get all "Last_Name" values in lowercase.


(ii) Display all the values of the "First_Name" column using the
alias "Employee Name".
(iii) Get all employees in ascending order by first name and
descending order by salary.
(iv) Get all the details about employees with a salary between
2,000,000 and 5,000,000.
(v) Get the first name and the reward amount for employees who
have rewards using a "Right Join".

42: Yes, the Two-Phase Locking (2PL) protocol ensures conflict


serializability. Here's how:

1. Phases of 2PL:
o Growing Phase: A transaction can acquire locks but cannot
release any.
o Shrinking Phase: A transaction can release locks but cannot
acquire new ones.
2. Conflict Serializability:
o 2PL prevents cyclic dependencies between transactions.
o It ensures that conflicting operations (like read-write or
write-write) are executed in a specific order, avoiding any
non-serializable interleaving of transactions.
3. Precedence Graph:
o The strict order of lock acquisition in 2PL avoids cycles in
the precedence graph, ensuring that the resulting schedule is
conflict-equivalent to some serial schedule.
4. Theoretical Justification:
o If a schedule follows the 2PL protocol, it guarantees conflict
serializability by ensuring that the locking order preserves the
serializability order.
5. Limitations:
o While 2PL guarantees conflict serializability, it does not
prevent deadlocks, which occur when transactions wait
indefinitely for each other's locks.
Thus, the 2PL protocol is a widely used concurrency control method that
ensures conflict serializability in database systems

43. Ans : Database Management Systems (DBMS) typically support the


following four types of languages, each designed for a specific purpose
in database management:

1. Data Definition Language (DDL):


o Used to define the structure of the database (e.g., tables,
schemas, indexes).
o Common commands: CREATE, ALTER, DROP,
TRUNCATE.
2. Data Manipulation Language (DML):
o Used for managing data within the database, such as
inserting, updating, or retrieving data.
o Common commands: SELECT, INSERT, UPDATE,
DELETE.
3. Data Control Language (DCL):
o Manages permissions and access control for database users.
o Common commands: GRANT, REVOKE.
4. Transaction Control Language (TCL):
o Manages database transactions to ensure data consistency and
integrity.
o Common commands: COMMIT, ROLLBACK,
SAVEPOINT.
44:

(i) To retrieve all “Last_Name” in lowercase from the Employee table in


MySQL, we can use the LOWER() function in a SELECT query. Here's
the query:

SELECT LOWER(Last_Name) AS lowercase_lastname


FROM employee;

Explanation:
 LOWER(Last_Name): Converts the Last_Name column values to
lowercase.
 AS lowercase_lastname: Provides an alias for the resulting
column to make it more descriptive.

(ii)

To display all the values of the First_Name column using the alias
"Employee Name" in MySQL, We can use the following query:
SELECT First_Name AS "Employee Name"
FROM Employee;
Explanation:

 First_Name: The column from which data is retrieved.


 AS "Employee Name": Assigns the alias "Employee Name" to
the displayed column in the result set.

(iii)
To get all employees sorted in ascending order by First_Name and
descending order by Salary in MySQL, We can use the ORDER BY
clause with multiple columns, specifying the sort order for each column:
SELECT *
FROM Employee
ORDER BY First_Name ASC, Salary DESC;

Explanation:

1. ORDER BY First_Name ASC: Sorts the results in ascending


order by First_Name.
2. Salary DESC: For employees with the same First_Name, sorts
them in descending order by Salary.

(iv)

To get all the details about employees whose salaries are between
2,000,000 and 5,000,000 in MySQL, We can use the BETWEEN
operator in the WHERE clause:

SELECT *
FROM Employee
WHERE Salary BETWEEN 2000000 AND 5000000;

Explanation:

 Salary BETWEEN 2000000 AND 5000000: Filters rows where


the Salary value is within the range of 2,000,000 to 5,000,000
(inclusive).
 SELECT *: Retrieves all columns for the matching rows.

(v)
To retrieve the First_Name and Reward_Amount of employees who
have received rewards using a RIGHT JOIN in MySQL, We can write
the query as follows:

SELECT e.First_Name, r.Reward_Amount


FROM Employee e
RIGHT JOIN Rewards r ON e.Employee_ID = r.Employee_ID;
Explanation:

1. RIGHT JOIN: Ensures all rows from the Rewards table are
included, along with matching rows from the Employee table.
2. e.Employee_ID = r.Employee_ID: Matches the employee's ID
from the Employee table with the reward information from the
Rewards table.
3. SELECT e.First_Name, r.Reward_Amount: Retrieves the first
name of the employee and their reward amount.

45. Explain ACID properties and illustrate them through


example in database management?
46. Discuss how do you implement atomicity and durability?
47. Draw an ER diagram for a system containing al entities,
relationships, cardinalities and opportunities. Also include
all intersection entities.
Answer:
45. ACID properties are fundamental principles that ensure reliable and
consistent transaction processing in database management systems. ACID
stands for Atomicity, Consistency, Isolation, and Durability. Here's a
detailed explanation of each property with an example:

1. Atomicity
Definition: Ensures that a transaction is treated as a single unit of work.
Either all operations in the transaction are executed successfully, or none
of them is applied. If any part of the transaction fails, the entire transaction
is rolled back.
Example:
Consider a bank transfer:
 Account A is debited $100.
 Account B is credited $100.
If the debit succeeds but the credit fails (e.g., due to a system error),
Atomicity ensures that the entire transaction is undone, so no money is
deducted from Account A.

2. Consistency
Definition: Ensures that a transaction transforms the database from one
valid state to another valid state, maintaining all defined rules (constraints,
triggers, etc.).
Example:
Suppose a database has a rule that the total balance of all accounts must
equal $10,000. After the transfer of $100 from Account A to Account B,
the total balance must still be $10,000. Consistency ensures this rule is
enforced after every transaction.

3. Isolation
Definition: Ensures that transactions occur independently of one another.
The intermediate state of a transaction is invisible to other transactions
until the transaction is committed.
Example:
Two transactions occur simultaneously:
 T1: Transfers $100 from Account A to Account B.
 T2: Reads the balance of Account A.
If T1 has not yet committed, T2 will see the original balance of Account
A, not the intermediate state after the debit operation.

4. Durability
Definition: Ensures that once a transaction is committed, the changes are
permanent, even in the event of a system failure.
Example:
After the $100 transfer from Account A to Account B is committed, the
database guarantees that this change is saved. Even if the system crashes
right after the commit, the updated balances will persist when the system
recovers.

46. MySQL achieves Atomicity and Durability primarily through its


transaction management system. Here's how each property is
implemented and can be ensured:

1. Atomicity
Atomicity ensures that a transaction is executed as a single unit of work—
either all the changes made by the transaction are applied, or none at all.
How Atomicity is Implemented in MySQL:
START TRANSACTION;
-- Step 1: Debit $100 from Account A
UPDATE accounts
SET balance = balance - 100
WHERE account_id = 'A';

-- Step 2: Credit $100 to Account B


UPDATE accounts
SET balance = balance + 100
WHERE account_id = 'B';

-- Check for any error and decide to commit or rollback


IF @@error
THEN ROLLBACK;

-- Undo all changes if an error occurs


ELSE COMMIT;

-- Apply all changes if successful


END IF;

2. Durability
Durability ensures that once a transaction is committed, its changes are
permanently stored, even in the event of a system crash.
How Durability is Implemented in MySQL:
-- Check the current durability setting
SHOW VARIABLES LIKE 'innodb_flush_log_at_trx_commit';

-- Set the durability level to ensure logs are flushed on every commit
SET GLOBAL innodb_flush_log_at_trx_commit = 1;

-- Start a transaction and commit it


START TRANSACTION;

-- Perform some operations


INSERT INTO accounts (account_id, balance) VALUES ('C', 200);

-- Commit the transaction


COMMIT;
48.ER Diagram is known as Entity-Relationship Diagram, it is used to
analyze to structure of the Database. It shows relationships between
entities and their attributes. An ER Model provides a means of
communication. ER diagram of the Company has the following
description :
 Company has several departments.
 Each department may have several Locations.
 Departments are identified by a name, d_no, Location.
 A Manager control a particular department.
 Each department is associated with number of projects.
 Employees are identified by name, id, address, job, date_of_joining.
 An employee works in only one department but can work on several
project.
 We also keep track of number of hours worked by an employee on
a single project.
 Each employee has a dependent
 Dependent has D_name, Gender, and relationship.
ER Diagram of Company :
This Company ER diagram illustrates key information about Company,
including entities such as employee, department, project and dependent.
It allows to understand the relationships between entities.
Entities and their Attributes are-
 Employee Entity: Attributes of Employee Entity are Name, Id,
Address, Gender, Dob and Doj. Id is Primary Key for Employee
Entity.
 Department Entity : Attributes of Department Entity are D_no,
Name and Location. D_no is Primary Key for Department Entity.
 Project Entity : Attributes of Project Entity are P_No, Name and
Location. P_No is Primary Key for Project Entity.
 Dependent Entity : Attributes of Dependent Entity are D_no,
Gender and relationship.
Relationships are :
 Employees works in Departments – Many employee works in one
Department but one employee can not work in many departments.
 Manager controls a Department – employee works under the
manager of the Department and the manager records the date of
joining of employee in the department.
 Department has many Projects – One department has many projects
but one project can not come under many departments.
 Employee works on project – One employee works on several
projects and the number of hours worked by the employee on a
single project is recorded.
 Employee has dependents – Each Employee has dependents. Each
dependent is dependent of only one employee.
49. Convert the following ER diagram into a relational database
schema, indicating primary keys and referential integrity constraints.

1. Lot Table

a. Attributes: LotNumber (PK), CreateDate, CostOfMaterials

b. Primary Key (PK): LotNumber

2. ProductionUnits Table

a. Attributes: serial# (PK), exactWeight, ProductType,


ProductDesc, qualityTest, LotNumber (FK)

b. Primary Key (PK): serial#

c. Foreign Key (FK): LotNumber references Lot(LotNumber)

3. RawMaterials Table

a. Attributes: material-ID (PK), type, UnitCost

b. Primary Key (PK): material-ID

4. Includes Table (Associative Entity)

a. Attributes: LotNumber (FK), material-ID (FK)

b. Primary Key (PK): Composite key of LotNumber and material-


ID

c. Foreign Keys (FK):

i. LotNumber references Lot(LotNumber)

ii. material-ID references RawMaterials(material-ID)

5. CreatedFrom Table (Associative Entity)


a. Attributes: LotNumber (FK), material-ID (FK), Units

b. Primary Key (PK): Composite key of LotNumber and material-


ID

c. Foreign Keys (FK):

i. LotNumber references Lot(LotNumber)

ii. material-ID references RawMaterials(material-ID)

Explanation:

Flow Diagram for Database Schema

Here's a conceptual flow diagram showing the relationships among


tables:

1. Lot has a one-to-many relationship with ProductionUnits.

2. Lot has a many-to-many relationship with RawMaterials (handled


by Includes and CreatedFrom tables).

+-----------------+ +----------------------+

| Lot | | ProductionUnits |

+-----------------+ +----------------------+

| LotNumber (PK) |-----> Includes | serial# (PK) |

| CreateDate | | exactWeight |

| CostOfMaterials | | ProductType |
+-----------------+ | ProductDesc |

| qualityTest |

| LotNumber (FK) |

+----------------------+

+-----------------+ +----------------------+

| RawMaterials | | Includes |

+-----------------+ +----------------------+

| material-ID (PK)| | LotNumber (FK) |

| type | | material-ID (FK) |

| UnitCost | +----------------------+

+-----------------+

+-----------------+
| CreatedFrom |

+-----------------+

| LotNumber (FK) |

| material-ID (FK)|

| Units |

+-----------------+

50. Identify an attribute in the ER diagram that might represent a


composite attribute, and explain why/how it might represent a
composite attribute.

Attribute: ProductDesc in the ProductionUnits entity.

Explanation: ProductDesc could represent a composite attribute if it


contains multiple pieces of information about the product, such as color,
dimensions, and other product specifications. In a relational model, this
composite attribute would ideally be broken down into multiple columns
for each part of the description (e.g., color, dimension, material, etc.) to
ensure normalization and improve query performance.

Reference: Composite Attributes: The attributes that can be divided into


smaller subparts, which represent more basic attributes with
independent meaning. These are useful to model situations in which a
user sometimes refers to the composite attribute as unit but at other
times refers specifically to its components.
51. Identify an attribute in the ER diagram that could represent a
derived attribute and explain why/how it might represent a derived
attribute.

Attribute: CostOfMaterials in the Lot entity.

Explanation: CostOfMaterials could be a derived attribute because it


may be calculated as the sum of the UnitCost of each raw material used
in the lot multiplied by the number of units of each material (as defined
in the CreatedFrom relationship). This attribute can be computed from
existing data in other tables rather than being stored directly in the Lot
table, which helps avoid data redundancy.

Reference: Derived Attributes: An attribute which is derived from


another attribute is called as a ‘derived attribute. Example: ‘Age’
attribute is derived from another attribute ‘Date’.

52. How does DBMS provide data abstraction? explain the concept of
data independence.

How DBMS Provides Data Abstraction.

A Database Management System (DBMS) provides data abstraction to


simplify user interaction with the data. It hides the complexities of how
data is stored, organized, and maintained. This abstraction is achieved
through three levels of architecture:

1. Physical Level (Internal Level):

Describes how data is physically stored in the database.


Deals with complex details like storage allocation, indexing, and file
structures.

Abstracted away from the users and application developers.

2. Logical Level (Conceptual Level):

Describes what data is stored in the database and the relationships


among the data.

Provides a unified view of the database, independent of the physical


storage.

Focuses on schema design, including tables, columns, and constraints.

3. View Level (External Level):

Describes how users see the data.

Users interact with specific parts of the data through views tailored to
their needs.

Abstracts away both logical and physical details to provide user-specific


perspectives.

Concept of Data Independence:

Data independence refers to the ability to change the schema at one


level of the DBMS without affecting the schema at the next higher level.
It ensures that applications and users remain insulated from changes in
data representation or organization.

1. Logical Data Independence:

Refers to the independence of the external schema (user view) from


changes in the conceptual schema.

Example: Adding or modifying tables, attributes, or relationships in the


database should not require changes to user views or application
programs.

2. Physical Data Independence:

Refers to the independence of the conceptual schema from changes in


the physical schema

Example: Reorganizing data storage (e.g., changing file structures or


indexes) should not affect the logical schema or user applications.

Importance of Data Independence:

Reduces system maintenance overhead.

Enhances flexibility and scalability of the database system.

Facilitates easier adaptation to changes in requirements or technology.


53. explain insertion, deletion and modification anomalies with
suitable examples.

1. Insertion Anomaly

An insertion anomaly occurs when you cannot add data to the database
due to missing information or data dependencies.

Example:

Consider a table Student_Course:

Student_ID Student_Name Course_ID Course_Name

101 Alice C101 Physics

102 Bob C102 Chemistry

 Issue: If a new course (e.g., C103, "Mathematics") is introduced


but no student is currently enrolled in it, you cannot insert this
course without leaving the Student_ID and Student_Name fields
blank, which violates integrity constraints.

 Solution: Separate the data into two tables:

o Student(Student_ID, Student_Name)

o Course(Course_ID, Course_Name)
2. Deletion Anomaly

A deletion anomaly occurs when deleting a piece of data inadvertently


results in the loss of additional information.

Example:

Using the same Student_Course table:

Student_ID Student_Name Course_ID Course_Name

101 Alice C101 Physics

102 Bob C102 Chemistry

 Issue: If Alice (Student_ID 101) drops out, deleting her record will
also remove the information about the "Physics" course if it's not
offered to other students.

 Solution: Use separate tables for students and courses to


preserve course data:

o Student(Student_ID, Student_Name)

o Course(Course_ID, Course_Name)

o Enrollment(Student_ID, Course_ID)

3. Modification Anomaly

A modification anomaly occurs when changing a single piece of data


requires multiple updates, which may lead to inconsistencies if some
updates are missed.

Example:
Again, using the Student_Course table:

Student_ID Student_Name Course_ID Course_Name

101 Alice C101 Physics

102 Bob C101 Physics

 Issue: If the name of the course "Physics" is changed to


"Advanced Physics," you need to update all rows where
Course_ID = C101. Missing any row leads to inconsistent data.

 Solution: Normalize the database:

o Separate courses into a Course table:

 Course(Course_ID, Course_Name)

o Reference the Course_ID in the Enrollment table.

54. Describe in detail about timestamp based concurrency control


techniques.

Timestamp-Based Concurrency Control Techniques:

Timestamp-based concurrency control is a non-locking protocol used in


databases to manage concurrent transactions. It ensures serializability
by ordering transactions based on timestamps. This approach uses
timestamps to determine the execution order of transactions, ensuring
that conflicting operations are executed in the same order as their
timestamps.
1.Timestamp:

Each transaction is assigned a unique timestamp (TS) when it starts.

This timestamp indicates the transaction's priority and serves as a


logical "time" for ordering.

2.Read Timestamp (RTS):

Associated with each data item.

Stores the largest timestamp of a transaction that successfully read the


data item.

3.Write Timestamp (WTS):

Associated with each data item.

Stores the largest timestamp of a transaction that successfully wrote


the data item.

4.Assumptions:

A smaller timestamp indicates an older transaction.

An older transaction has a higher priority over newer ones.


Advantages of Timestamp-Based Concurrency Control:

1.Non-Blocking:

No waiting or locking; transactions either proceed or abort.

2.Deadlock-Free:

Transactions do not block, eliminating the possibility of deadlock.

3.Serializability:

Ensures the schedule is serializable, with the transaction execution


order following their timestamps.

55. Explain in detail about database management system advantages


over file management system.

Answer: A Database Management System (DBMS) offers several


advantages over traditional file management systems, including:

1.Data Redundancy and Inconsistency:

File Management System: Data is stored in multiple files, which can


lead to data redundancy and inconsistency.

DBMS: Centralized data storage allows efficient control of data


redundancy and ensures data consistency across the database.
2.Data Integrity:

File Management System: Integrity constraints are difficult to enforce.

DBMS: Allows setting constraints (e.g., primary keys, foreign keys) to


maintain data integrity, ensuring data accuracy and reliability.

3.Data Security:

File Management System: Basic security options, often lack fine-


grained access control.

DBMS: Provides robust security features, allowing permissions to be set


at different levels, such as user, role, or even individual data items.

4.Data Sharing:

File Management System: Limited sharing capabilities, as files can


often only be accessed by one user or program at a time.

DBMS: Supports multiple users and applications accessing data


concurrently, supporting better data sharing and collaboration.

5.Data Independence:

File Management System: Changes to the file structure may require


changes in application code.
DBMS: Provides data abstraction, so data structure changes do not
require changes in application code.

6.Backup and Recovery:

File Management System: Limited or manual backup and recovery


mechanisms.

DBMS: Automated backup and recovery features ensure data is


protected against loss and can be easily restored.

56. Write SQL Queries for the given tables:

The tables provided are:

1.employee (fields: emp_id, first_name, last_name, salary, joining_date,


department)

2.reward (fields: emp_ref_id, date_reward, amount)

Let's write the SQL queries for each sub-part:

I. Get all "Last_Name" in lowercase.

SELECT LOWER(last_name) AS last_name_lowercase

FROM employee;

II. Display all the values of the "First_Name" column using the alias
"employee name".
SELECT first_name AS "employee name"

FROM employee;

III. Get all employees in ascending order by first name and descending
order by salary.

SELECT *

FROM employee

ORDER BY first_name ASC, salary DESC;

IV.Get all the details about employees with a salary between 2,000,000
and 5,000,000.

SELECT *

FROM employee

WHERE salary BETWEEN 2000000 AND 5000000;

V. Get the first name, the reward amount for employees who have
rewards using "Right Join".

SELECT employee.first_name, reward.amount

FROM employee

RIGHT JOIN reward ON employee.emp_id = reward.emp_ref_id;


56. Differentiate between primary key and a candidate key with
appropriate example.

Example:

The emp_id column is chosen as the primary key because it is a simple,


unique identifier for each employee.

Both email and phone_number are candidate keys since they can
uniquely identify an employee, but they are not chosen as the primary
key in this case. If the emp_id was not available, either email or
phone_number could be used as the primary key.
57.Discuss two phase locking protocol and strict two-phase locking
protocols.

2PL locking protocol

Every transaction will lock and unlock the data item in two different
phases.

 Growing Phase − All the locks are issued in this phase. No locks
are released, after all changes to data-items are committed and
then the second phase (shrinking phase) starts.

 Shrinking phase − No locks are issued in this phase, all the changes
to data-items are noted (stored) and then locks are released.

The 2PL locking protocol is represented diagrammatically as follows −

In the growing phase transaction reaches a point where all the locks it
may need has been acquired. This point is called LOCK POINT.

Two phase locking is of two types −


Strict two phase locking protocol

A transaction can release a shared lock after the lock point, but it
cannot release any exclusive lock until the transaction commits. This
protocol creates a cascade less schedule.

Cascading schedule: In this schedule one transaction is dependent on


another transaction. So if one has to rollback then the other has to
rollback.

Rigorous two phase locking protocol

A transaction cannot release any lock either shared or exclusive until it


commits.

The 2PL protocol guarantees serializability, but cannot guarantee that


deadlock will not happen.

Example

Let T1 and T2 are two transactions.

T1=A+B and T2=B+A

Here,

Lock-X(B) : Cannot execute Lock-X(B) since B is locked by T2.

Lock-X(A) : Cannot execute Lock-X(A) since A is locked by T1.


In the above situation T1 waits for B and T2 waits for A. The waiting
time never ends. Both the transaction cannot proceed further at least
any one releases the lock voluntarily. This situation is called deadlock.

The wait for graph is as follows −

Wait for graph: It is used in the deadlock detection method, creating a


node for each transaction, creating an edge Ti to Tj, if Ti is waiting to
lock an item locked by Tj. A cycle in WFG indicates a deadlock has
occurred. WFG is created at regular intervals.

58. By considering suitable examples, describe the usage of SQL CREATE


and ALTER statements.

Ans:

Usage of SQL CREATE and ALTER Statements

SQL (Structured Query Language) is the standard language for


managing and manipulating relational databases. Two of the
fundamental SQL statements used for defining and modifying database
structures are the CREATE and ALTER statements.

1. CREATE Statement
The CREATE statement is used to create new database objects such as
tables, views, indexes, or databases. It defines the structure of the
object by specifying the columns, data types, and constraints.

Example: Creating a Table

CREATE TABLE Employees (

Employee_ID INT PRIMARY KEY,

First_Name VARCHAR(50) NOT NULL,

Last_Name VARCHAR(50) NOT NULL,

Hire_Date DATE,

Salary DECIMAL(10, 2)

);

In this example:

 A new table named Employees is created.

 It has five columns: Employee_ID, First_Name, Last_Name,


Hire_Date, and Salary.

 Employee_ID is defined as the primary key, ensuring that it is


unique for each record.

 First_Name and Last_Name are required fields (NOT NULL), while


Hire_Date and Salary can be left empty.

2. ALTER Statement
The ALTER statement is used to modify the structure of an existing
database object. This can include adding or dropping columns,
changing data types, or modifying constraints.

Example: Adding a Column

ALTER TABLE Employees

ADD Email VARCHAR(100);

In this example:

 A new column named Email of type VARCHAR with a maximum


length of 100 characters is added to the existing Employees table.

Example: Modifying a Column

ALTER TABLE Employees

MODIFY Salary DECIMAL(15, 2);

In this example:

 The Salary column's data type is changed to allow for larger


decimal values by increasing the precision from 10 to 15.

Example: Dropping a Column

ALTER TABLE Employees

DROP COLUMN Hire_Date;

In this example:

 The Hire_Date column is removed from the Employees table.


Note that this operation will permanently delete all data in that
column for every record.
59. Explain the structure of SQL SELECT statement with suitable
example.

The SQL SELECT statement is used to query data from one or more
tables in a database. It allows users to specify exactly which data they
want to retrieve and how they want it presented. The structure of the
SELECT statement can vary based on the complexity of the query, but
it generally follows a standard format.

Basic Structure of the SELECT Statement

The basic structure of the SELECT statement includes several clauses


that can be used in various combinations:

SELECT [DISTINCT] column1, column2, ...

FROM table_name

[WHERE condition]

[GROUP BY column]

[HAVING condition]

[ORDER BY column [ASC|DESC]]

[LIMIT number];

Components of the SELECT Statement

1. SELECT: This clause specifies the columns you want to retrieve.


You can select specific columns or use * to select all columns.
2. DISTINCT: This optional keyword is used to return only unique
values, eliminating duplicate records from the result set.

3. FROM: This clause specifies the table (or tables) from which to
retrieve the data.

4. WHERE: This optional clause allows you to filter records based on


specified conditions.

5. GROUP BY: This optional clause is used to group rows that have
the same values in specified columns into summary rows, like
aggregates (COUNT, SUM, AVG, etc.).

6. HAVING: This optional clause is used to filter groups created by


the GROUP BY clause based on a condition.

7. ORDER BY: This optional clause specifies the order in which the
results should be returned, either in ascending (ASC) or
descending (DESC) order.

8. LIMIT: This optional clause specifies the maximum number of


records to return.

Example of the SELECT Statement

Let’s consider an example using a database table named Employees,


which has the following structure:

Employee_ID First_Name Last_Name Department Salary

101 John Doe HR 60000

102 Emma Smith Finance 75000


Employee_ID First_Name Last_Name Department Salary

103 Alice Johnson HR 70000

104 Mike Brown IT 80000

Example Query

1. Basic Select Query

To select all columns from the Employees table:

SELECT * FROM Employees;

2. Select Specific Columns

To select specific columns, like First_Name and Salary:

SELECT First_Name, Salary FROM Employees;

3. Using WHERE Clause

To filter employees with a salary greater than 65000:

SELECT * FROM Employees

WHERE Salary > 65000;

4. Using GROUP BY and HAVING

To find the average salary of employees in each department, and only


include departments where the average salary is greater than 65000:

SELECT Department, AVG(Salary) AS Average_Salary

FROM Employees

GROUP BY Department
HAVING AVG(Salary) > 65000;

5. Using ORDER BY

To select all employees ordered by their Salary in descending order:

SELECT * FROM Employees

ORDER BY Salary DESC;

6. Using LIMIT

To select the top 2 highest-paid employees:

SELECT * FROM Employees

ORDER BY Salary DESC

LIMIT 2;

60. What is entity relationship model? Explain the steps to reduce the
ER diagram to ER database schema.

An Entity-Relationship Model represents the structure of


the database with the help of a diagram. ER Modelling is a systematic
process to design a database as it would require you to analyze all data
requirements before implementing your database.
Converting an ER diagram into tables involves a systematic process
starting from table mapping to refining and reviewing.

Step 1: Analyze the Entities

 Identify each distinct entity in the diagram represented by a


rectangle.

 Examine the attributes associated with each entity which are its
characteristics represented by ellipses within the rectangle.

Step 2: Create Separate Tables for Each Entity

 For each entity, create a corresponding table in the database with


each attribute as a column in the table.

 Assign the primary key as a column in the respective table.

Step 3: Map Relationships

 For one-to-many relationships, add a foreign key in the “many”


table referencing the “one” table’s primary key.

 For many-to-many, create a linking table with foreign keys to both


related tables.

Step 4: Normalize the Tables

 Analyze the tables for redundancies and potential data


inconsistencies.

 Apply normalization techniques like decomposition to split tables


and eliminate redundancy, improving data integrity and reducing
storage space.
Step 5: Verify and Refine

 Review the created tables and relationships for accuracy and


efficiency.

 Refine the schema as needed based on further analysis or specific


requirements of your database.

61. Discuss the necessity of lock in DBMS. Illustrate shared lock and
exclusive lock with the help of example.

Locking is the process by which a DBMS restricts access to a row in a


multi-user environment. When a row or column is exclusively locked,
other users are not permitted to access the locked data until the lock is
released. This ensures that two users cannot simultaneously update
the same column in a row.

1. Shared Lock (S-Lock)

A shared lock allows multiple transactions to read a resource (e.g., a


data item), but it prevents any transaction from modifying it. Multiple
transactions can hold a shared lock simultaneously.

Example:

Consider two transactions, T1 and T2, both trying to read the same data
item A.
 T1 requests a shared lock on data item A to read it. It is granted
the lock.

 T2 also requests a shared lock on the same data item A to read it.
It is also granted the lock because shared locks allow concurrent
reading by multiple transactions.

Scenario:

 T1: SELECT balance FROM Accounts WHERE AccountID = 'A'

 T2: SELECT balance FROM Accounts WHERE AccountID = 'A'

Both transactions are allowed to read the value of A simultaneously,


but neither can modify it until they release the shared lock.

2. Exclusive Lock (X-Lock)

An exclusive lock allows a transaction to both read and write (modify)


the resource, but it prevents any other transaction from accessing the
resource (either reading or writing) until the exclusive lock is released.

Example:

Now, let's say transaction T3 wants to update the value of A, while T1


and T2 have shared locks on A.

 T3 requests an exclusive lock on A to update it.

 Since T1 and T2 are holding shared locks, T3 has to wait until both
transactions release their locks.

 Once T1 and T2 complete their read operations and release the


shared locks, T3 is granted the exclusive lock, allowing it to read
and modify A.
Scenario:

 T1: SELECT balance FROM Accounts WHERE AccountID = 'A'


(shared lock, allowed)

 T2: SELECT balance FROM Accounts WHERE AccountID = 'A'


(shared lock, allowed)

 T3: UPDATE Accounts SET balance = balance - 100 WHERE


AccountID = 'A' (exclusive lock, waits for T1 and T2 to release
locks)

Once T1 and T2 finish, T3 gets the exclusive lock, modifies A, and


releases the lock. No other transaction can access A while T3 holds the
exclusive lock.

62. Define integrity constraint. Explain its enforcement by DBMS with


illustrative example.

An integrity constraint is a rule that limits the type of data that can be
entered into a database table. Integrity constraints are used to ensure
that data is accurate, consistent, and reliable. They can be applied at
the table or column level.

Types of Integrity Constraints:

Integrity constraints can be of four types:


1. Domain constraint

2. Entity integrity constraint

3. Referential integrity constraint

4. Key constraint

Domain constraint

In DBMS, Domain constraints can be defined as a set of values that are


valid for an attribute. The domain’s data type includes string, character,
integer, time etc. The value must be in the corresponding domain of
the attribute.

Example

Name Semester Age

Adarsh 1st 19

Kushal 4th 20

Akash 3rd 20

Vishal 7th H

Now in the table above, we can observe in the column Age, the data
type of the domain is an integer but the attributes data type is a
character.

Entity integrity constraint


This constraint states that in DBMS we can not make the primary key
with the value NULL. Now, this is because if the primary key is NULL,
then we won’t b able to determine or identify the tuple in the relation.
But in a relation, there can be NULL values but they must be not the
primary key.

Example

S_No Name Semester Age

1 Adarsh 1st 19

2 Kushal 4th 20

3 Akash 3rd 20

Vishal 7th 21

In the above example, we can see, that in the S_No column and last
tuple, the attribute is null, so it can not be assigned as the primary key.

Referential integrity constraint

This constraint is defined between two tables. Let us consider tables A


and B, so in this constraint, if a foreign key is referred to as a primary
key of another table then the contents of the foreign key of table A
must be null or available to tp table B.

Example

TABLE 1
S_No Name Semester Code

1 Adarsh 1st 1258

2 Kushal 4th 2451

3 Akash 3rd 5758

4 Vishal 7th 9654

5 Sankalp 5th 4178

TABLE 2

Code City

4178 Patna

2451 Delhi

9654 Mumbai

1258 Pune

Now in the example above, we can see that in table 1, Code 5758 is not
valid, as this attribute is not defined in table 2 and also the attribute is
assigned as the primary key, and also Code in table 1 is assigned the
foreign key.

Key constraint
In DBMS, a key is used to uniquely identify an entity in an entity set. An
entity set can have multiple keys but out only one can be a primary key.
This primary key should not be null and must be unique. Although it
can contain a null and a non-null unique value.

Example

S. No Name Semester Code

1 Adarsh 1st 1258

2 Kushal 4th 2451

3 Akash 3rd 5758

4 Vishal 7th 9654

4 Sankalp 5th 4178

In the example above, S_No can not be defined as a primary key


because it contains a duplicate value. All the rows must be unique.
63. Does two phase locking protocol ensure conflict serializability?
Justify your answer with appropriate examples.

Yes, the Two-Phase Locking (2PL) protocol ensures conflict


serializability, which means that any schedule generated by 2PL is
guaranteed to be equivalent to some serial schedule, in which
transactions are executed one after the other without interleaving.

How 2PL Works:

The 2PL protocol divides the execution of a transaction into two


phases:

1. Growing Phase: A transaction can acquire locks (shared or


exclusive) but cannot release any locks.

2. Shrinking Phase: A transaction can release locks but cannot


acquire any new locks.

This ensures that once a transaction releases a lock, it cannot obtain


more locks, preventing deadlocks and ensuring serializability.

Justification with Example:

Consider two transactions, T1 and T2, both trying to access data items
A and B:

 T1: Reads A, Writes A, Reads B, Writes B.

 T2: Reads B, Writes B, Reads A, Writes A.

Without 2PL, if T1 reads A while T2 writes to A, a conflict occurs, and


the results may not be serializable. However, under 2PL:
1. T1 acquires a lock on A, reads and writes to A.

2. T2 tries to lock A, but it has to wait until T1 releases its lock.

3. T1 locks B, completes its operations, and releases both locks.

4. T2 can now lock and modify A and B.

This prevents T2 from accessing A while T1 is modifying it, enforcing a


serializable schedule equivalent to executing T1 first, followed by T2.

64. Write SQL Queries for following set of tables:

student (enrno, name, course_Id, email_Id, cell_no)

course (course_Id, course_nm, duration)

(i) Add a column city in student table.

(ii) Find out list of students who have enrolled in “computer” course.

(iii) List name of all courses with their duration.

(iv) List name of all students start with ‘a.’

(v) List email Id and cell no of all mechanical engineering students.

(i) Add a column city in the student table.

sql

Copy code

ALTER TABLE student ADD city VARCHAR(50);


(ii) Find out the list of students who have enrolled in the "computer"
course.

sql

Copy code

SELECT s.name

FROM student s

JOIN course c ON s.course_Id = c.course_Id

WHERE c.course_nm = 'computer';

(iii) List the names of all courses with their duration.

sql

Copy code

SELECT course_nm, duration

FROM course;

(iv) List the names of all students whose names start with 'a.'

sql

Copy code

SELECT name

FROM student

WHERE name LIKE 'a%';

(v) List email Id and cell no of all mechanical engineering students.


sql

Copy code

SELECT s.email_Id, s.cell_no

FROM student s

JOIN course c ON s.course_Id = c.course_Id

WHERE c.course_nm = 'mechanical engineering';

Each query serves its specific purpose in interacting with the student
and course tables as described in the questions.

65. Describe in details about two-tier and three-tier client-server


architectures.

2 Tier Architecture

A 2 tier architecture refers to a software architecture in which a


presentation layer runs on a client and a data layer is available on a
server. Separating these two components into two different physical
locations results in a two-tier architecture, as opposed to a single-tier
architecture. The application on the client-side establishes a
connection with the server in order to communicate with the data
layer. The server-side is responsible for providing query processing and
transaction management functionalities. On the client-side, the user
interface and application programs are run. The 2 tier architecture has
two tiers which are:
 Client tier that represents the clients.

 Data tier that holds the database server.

The diagram below shows a simple representation of a 2 tier


architecture.

2 tier architecture

The 2 tier architecture has the following advantages:

 Applications can be easily developed and deployed due to


simplicity.

 The database server and application logic is physically close,


which offers higher performance, provided the users are
manageable.

On the other hand, the 2 tier architecture disadvantages are:

 The performance of the application is degraded with increasing


users. When simultaneous client requests are made, application
performance degrades rapidly due to the fact that clients
necessitate separate connections and increased CPU memory.

 Since the client holds most of the application logic, difficulties


often arise in controlling software versions and distributing new
versions.

 It’s often difficult to implement reliable security since users need


to have login information for every data server.

3 Tier Architecture

A 3 tier architecture refers to a software architecture in which the user


presentation interface, the business logic and the data storage server
are developed and maintained as independent modules on separate
hardware platforms. The client does not directly communicate with the
database server. Instead, the client interacts with an application server
which further communicates with the data tier which contains the
database server that is used for query processing and transaction
management. The business tier serves as a medium for the exchange
for partially processed data between the database server and the
client. A three-tier architecture often allows any one of the three tiers
to be upgraded or replaced independently. The three tiers of this
software architecture are:

1. Presentation tier which represents the clients.

2. Business tier which acts as an intermediary for partially processed


data.

3. Data tier which holds the database server.


The diagram below shows a simple representation of a 3 tier
architecture.

3 tier architecture

The 3 tier architecture has the following advantages:

 It can scale without degraded performance since no separate


connections from each client are not required.

 There is improved data integrity because data corruption from


client applications can be eliminated by passing the data in the
business tier for validation.

 It’s often easier to implement improved security since client


applications don’t have direct database access.

 It’s possible to scale or change the implementation of a tier on its


own without affecting other tiers of the system.

On the other hand, 3 tier architecture disadvantages are:

 There is increased complexity of implementation as the


communication points are increased (presentation tier to
business tier to the data tier, instead of direct client tier to data
tier communication).
66. Explain ACID properties and illustrate them through examples.

Ans: ACID Properties in Databases:

ACID stands for Atomicity, Consistency, Isolation, and Durability. These


are key properties that ensure reliable processing of database
transactions. Each property with explanations and examples:

1. Atomicity

Definition: A transaction must be treated as an indivisible unit,


meaning that either all of its operations are executed, or none are. If
any part of the transaction fails, the entire transaction is rolled back,
leaving the database unchanged.

Example: Suppose you are transferring money from Account A to


Account B. The transaction consists of two steps:

1. Deduct $100 from Account A.

2. Add $100 to Account B.

If step 1 completes but step 2 fails (e.g., due to a system crash),


Atomicity ensures that the $100 is not deducted from Account A. Both
steps will either succeed or fail together.

2. Consistency

Definition: A transaction must take the database from one valid state
to another, maintaining the integrity of the database. This means that
any data written to the database must be valid according to all defined
rules, including constraints, cascades, and triggers.

Example: In a banking system, if a constraint specifies that an account


balance cannot be negative, Consistency ensures that no transaction
can result in a negative balance. If a withdrawal leaves an account with
insufficient funds, the transaction will be aborted to maintain
consistency.

3. Isolation

Definition: Transactions occurring concurrently should not affect each


other. The intermediate states of a transaction should be invisible to
other transactions. Isolation ensures that one transaction cannot see
the effects of another unfinished transaction.

Example: Assume two users are trying to withdraw money from the
same bank account at the same time. Without isolation, both
withdrawals might result in an overdraft because both transactions
could "see" the same initial balance. With Isolation, one transaction
must complete before the other sees the updated balance.

4. Durability

Definition: Once a transaction has been committed, it will remain


committed even in the case of a system failure. Durability ensures that
the result of the transaction is permanently stored in the database.

Example: After successfully transferring money between two accounts,


even if the database crashes right afterward, the changes (i.e., the
transferred money) will remain in place once the system is restored.
67. Write and explain the structure of SQL UPDATE, DELETE statement
with suitable example.

Answer: SQL UPDATE and DELETE Statements:

The UPDATE and DELETE statements in SQL are used to modify and
delete data in a table respectively. The structure and examples of each:

1. UPDATE Statement:

The UPDATE statement modifies the existing data in one or more


columns of a table.

Syntax:

UPDATE table_name

SET column1 = value1, column2 = value2, ...

WHERE condition;

table_name: The table where data is updated.

SET: Specifies the columns and their new values.

WHERE: Condition that identifies which rows to update. Without


WHERE, all rows will be updated.

Example:

UPDATE student

SET email_Id = 'newemail@example.com', cell_no = '9876543210'

WHERE enrno = 101;


This query updates the email and cell number of the student with enrno
= 101. If the WHERE clause is omitted, all records in the table will be
updated.

2. DELETE Statement:

The DELETE statement removes one or more rows from a table.

Syntax:

DELETE FROM table_name

WHERE condition;

table_name: The table from which rows will be deleted.

WHERE: Condition to specify which rows to delete. Without WHERE, all


rows will be deleted.

Example:

DELETE FROM student

WHERE enrno = 102;

This query deletes the student with enrno = 102 from the student table.
If no WHERE clause is used, all rows in the table would be deleted.
68. why concurrency is needed? Explain the problems that would arise
when concurrency control is not provided by the database system.

Answer: Concurrency control is a critical aspect of database


management systems (DBMS) because it ensures that multiple users or
processes can access and modify the database simultaneously without
leading to conflicts or inconsistencies. Without concurrency control,
several problems can arise, particularly in multi-user environments.
Let's explore these issues:

1. Lost Updates

 Problem: A "lost update" occurs when two transactions


simultaneously update the same data, but only one of the
updates is saved. This happens if one transaction reads the value,
then another transaction changes it, and the first transaction
writes back the original value, overwriting the second
transaction's change.

 Example:

o Transaction A reads a bank balance of $100, and Transaction


B also reads the same balance. Transaction A updates the
balance to $120, but Transaction B updates it to $150, and
then Transaction A writes back its update. The balance ends
up at $120, losing the update from Transaction B.

2. Uncommitted Data (Dirty Reads)

 Problem: A "dirty read" occurs when a transaction reads data that


has been modified by another transaction but not yet committed.
If the other transaction is rolled back, the first transaction ends
up with invalid or inconsistent data.

 Example:

o Transaction A updates the price of a product to $20 but has


not yet committed the change.

o Transaction B reads the updated price of $20, but then


Transaction A rolls back its changes.

o Transaction B has now read uncommitted data, leading to


an inconsistency.

3. Inconsistent Reads (Non-repeatable Reads)

 Problem: Inconsistent reads happen when a transaction reads the


same data twice, but the value has changed between reads
because another transaction has modified it.

 Example:

o Transaction A reads the balance of an account ($100).

o Transaction B updates the balance to $120, and commits.

o Transaction A reads the balance again, now seeing $120,


which creates an inconsistency since the balance should not
have changed during its transaction.

o Transaction A updates the balance to $120, but Transaction


B updates it to $150, and then Transaction A writes back its
update. The balance ends up at $120, losing the update from
Transaction B.

4. Phantom Reads

 Problem: A "phantom read" occurs when a transaction reads a set


of rows that match a condition, but another transaction inserts or
deletes rows that would change the result of the query during the
execution of the transaction.

 Example:

o Transaction A queries the database for all customers who


have placed orders worth more than $100.

o Transaction B inserts new orders, affecting the results of


Transaction A's query.

o When Transaction A re-runs the query, it gets different


results, leading to an inconsistent view of the data.

5. Deadlocks

 Problem: A deadlock occurs when two or more transactions are


each waiting for the other to release locks on resources they
need, causing the transactions to get stuck in a cycle of waiting
that never resolves.

 Example:

o Transaction A locks Resource 1 and waits for Resource 2.

o Transaction B locks Resource 2 and waits for Resource 1.


Both transactions are now in a deadlock situation, unable to proceed.

6. Data Integrity Issues

 Problem: Without proper concurrency control, the database may


end up in an inconsistent state, violating integrity constraints (like
foreign key relationships, unique constraints, etc.).

 Example:

o Transaction A inserts a new customer with an invalid


reference to an order in the database.

o Transaction B tries to delete that order, violating the foreign


key constraint, because Transaction A's insert was not
properly synchronized.

7. Incorrect Resulting State (Isolation Violations)

 Problem: Concurrency issues can cause transactions to behave as


if they are running in isolation when, in reality, they interact. This
can lead to a situation where transactions see "partial" results of
other transactions, creating a state that would not occur if the
transactions were executed one by one.

 Example:

o Transaction A calculates the total price of an order based on


individual items.
o Transaction B simultaneously adds or removes items from
the order.

o The total price calculation may be wrong because


Transaction A wasn't aware of the changes made by
Transaction B.

69. Consider a relation scheme R=(A,B,C,D,E) on which the following


functional dependencies hold:{A~BCDE,BC~ADE,D->A}. Write the
primary key, candidate key, super key and composite key of R?

Answer:

1. Primary key

It is the first key used to identify one and only one instance of an entity
uniquely.

2. Candidate key

A candidate key is an attribute or set of attributes that can uniquely


identify a tuple.

3. Super Key

Super key is an attribute set that can uniquely identify a tuple. A super
key is a superset of a candidate key.

4. Composite key
Whenever a primary key consists of more than one attribute, it is
known as a composite key.

The Relation is shown:

Primary key – A

Candidate key-A, BC

Super key-A, BC, AE, AD and ABC

Composite key-BC

70. A weak entity set can always be made into a strong entity set by
adding to it's attributes the primary key attributes of it's identifying
entity set. Outline what sort of redundancy will result if we do so.

Answer: Converting a weak entity set into a strong entity set by adding
the primary key attributes of its identifying entity set can lead to
redundancy in several ways:

1. Attribute Duplication: The weak entity will now include both its own
attributes and the primary key attributes of the identifying entity. If the
identifying entity already has these attributes in the database, this will
create redundancy, as the same information is stored in multiple
places.

2. Data Consistency Risks: With duplicated values, there is a risk of


inconsistencies. If the primary key attributes of the identifying entity
change, the corresponding attributes in the weak entity may not be
updated consistently, leading to potential integrity issues.
3. Increased Storage Requirements: Storing the same information
multiple times can lead to increased storage consumption. This is
particularly significant in large databases, where numerous weak
entities might replicate the identifier attributes.

4. Complexity in Updates and Maintenance: When updates are


required, maintaining all redundant information can complicate
database operations. Developers and database administrators must
ensure that changes are reflected across all instances, increasing the
complexity of data management.

5. Possible Schema Redesign Implications: Such redundancy may imply


that the overall database schema has to be evaluated and potentially
redesigned, leading to additional overhead in terms of time and
resources. In summary, while converting a weak entity to a strong
entity by adding the primary key of its corresponding entity can
enhance its independence, it also introduces several redundancy issues
that can affect data integrity, storage, and maintenance.

71. Write and explain the structure of SQL , ORDER BY, ORDER BY ASC,
and ORDER BY DESC Clause with suitable example.

Answer: The order by clause is used to sort the result set of a query by
one or more columns is ascending (ASC) or DESC order.

Syntax:

select column1, column2,

from table_name
order by column_name ASC/DESC;

Example:

A table students with column : id, name , marks

1. Order by in ASC order:

select*from students

order by marks;

Sorts row by marks in asc order.

2.Order by ASC explicity:

select*from students

order by marks ASC;

2.Oder by DESC explicity:

select*from students

order by marks DESC;


72. Draw an ER diagram for a car insurance company that has a set of
customers each of whom owns on e or more cars. Each car has
associated with it 0 to any number of recorded accidents.

Answer: To construct an E-R diagram for a car-insurance company, we


need to identify the entities, their attributes, and the relationships
between them. Based on the given information, we can identify the
following entities:

1. Customer: This entity represents the customers of the car-


insurance company. It has attributes such as customer ID, name,
address, and contact information.

2. Car: This entity represents the cars owned by the customers. It


has attributes such as car ID, make, model, year, and registration
number.

3. Accident: This entity represents the recorded accidents


associated with each car. It has attributes such as accident ID,
date, location, and description.

Relationships between these entities:

1. Each customer can own one or more cars. This is a one-to-many


relationship between the Customer entity and the Car entity. We
can represent this relationship by drawing a line with an arrow
from the Customer entity to the Car entity, and label it as "owns".

2. Each car can have zero to many recorded accidents. This is also a
one-to-many relationship between the Car entity and the
Accident entity. We can represent this relationship by drawing a
line with an arrow from the Car entity to the Accident entity, and
label it as "has".

73. Write and explain the structure of SQL, DROP and RENAME
databases with suitable examples.

1. DROP DATABASE Command

The DROP DATABASE command is used to permanently delete an


entire database, including all of its tables, data, and structure. This
operation cannot be undone, so it should be used with caution.

DROP DATABASE database_name;

Example: DROP DATABASE electronics_lab;

This command will delete the electronics_lab database along with all
its associated data.
2. RENAME DATABASE Command

Renaming a database is used to change its name. However, most SQL


database systems (e.g., MySQL, PostgreSQL) do not provide a direct
RENAME DATABASE command. Instead, this functionality can be
achieved by creating a new database, copying the data, and deleting
the old one, or using a system-specific approach.

Example:

CREATE DATABASE electronics_lab_v2;

-- Copy tables from old database to new database

USE electronics_lab;

SHOW TABLES;

-- For each table:

RENAME TABLE electronics_lab.table1 TO electronics_lab_v2.table1;

-- Drop the old database

DROP DATABASE electronics_lab;


74. Signify the concept of aggregation in ER diagram with example

Answer:

Aggregation is a concept in Entity-Relationship (ER) diagrams used to


express a relationship between relationships. It helps to simplify
complex models by showing a higher-level abstraction. Think of it like
forming a "super" relationship that involves multiple entities and their
relationships.

Illustration of this with an example:

Imagine we have three entities: Student, Course, and Instructor. A


student can enroll in a course (Enrolls relationship), and an instructor
can teach a course (Teaches relationship).

Here's a simplified ER diagram without aggregation:

Student --- Enrolls --- Course

Instructor --- Teaches --- Course

In a more complex scenario, suppose a Project involves a student


enrolling in a course and being guided by an instructor. Instead of
creating another relationship, we can use aggregation to form a higher-
level abstraction.

Aggregation

_______
|Project|

/ \

/ \

Student --- Enrolls --- Course --- Teaches --- Instructor

In this diagram:

 Student enrolls in a Course.

 Instructor teaches the Course.

 The Project (aggregation) involves these relationships together,


showing that a project is an overarching concept involving
students, courses, and instructors.

This higher-level abstraction makes it easier to understand complex


relationships by bundling them into a single aggregate entity.

You might also like