Dbms Question Bank Full Solution
Dbms Question Bank Full Solution
**Applications of DBMS**:
1. **Banking**: Managing transactions, customer accounts, and
financial records.
2. **Airline Reservation Systems**: Handling flight bookings, schedules,
and customer details.
3. **Telecommunications**: Managing customer information, call data
records, and billing.
4. **Library Management Systems**: Managing books, borrowing
records, and member details.
5. **Hospital Management**: Managing patient records, doctor
appointments, and medical history.
6. **Inventory Systems**: Tracking products, stock levels, and sales
transactions.
7. **E-commerce**: Handling product catalogs, customer information,
and order transactions.
---
---
### 4. State How an Entity-Relationship (ER) Model Represents Real-
World Entities.
---
2. **Logical Level**:
- Describes what data is stored and how it is logically structured.
- Example: Tables, views, and relationships in a relational database.
3. **View Level**:
- Describes how data is viewed by individual users or user groups.
- Example: A user's personal view of their account information in an
application.
---
---
### 7. Explain the DBMS Languages with Examples: DDL, DML, and DCL.
---
### 8. Draw an E-R Diagram for the Library Management System.
Entities:
1. **Book**: Attributes: `BookID`, `Title`, `Author`.
2. **Member**: Attributes: `MemberID`, `Name`, `Address`.
3. **Librarian**: Attributes: `LibrarianID`, `Name`.
Relationships:
1. **Borrows**: Connects `Member` and `Book`.
2. **Manages**: Connects `Librarian` and `Book`.
---
**E-R Diagram**:
An **Entity-Relationship Diagram** is a visual representation of entities,
their attributes, and the relationships between them.
**Generalization**:
Generalization is the process of abstracting common characteristics from
multiple entities into a generalized super-entity. It helps reduce
complexity in the design.
Example:
- A **Student** and **Teacher** entity can be generalized into an
**Employee** super-entity, with shared attributes like `ID`, `Name`, and
`Address`.
---
### 10. Differentiate Strong Entity Set and Weak Entity Set. Demonstrate
the Concept of Both Using Real-Time Examples.
---
### 11. What Are the Constraints in DBMS? Explain with a Proper
Example.
**Constraints in DBMS** are rules that limit the data that can be
entered into the database to ensure data integrity.
---
### 12. Define Primary Key, Foreign Key, NOT NULL Constraints, and
Referential Integrity (Foreign Key) Constraint.
`Employee` table.
---
### 13. Explain the Network Model and Relational Model in Brief.
1. **Network Model**:
- A type of database model that uses a graph structure with nodes
(representing entities) and arcs (representing relationships).
- Supports many-to-many relationships but is more complex than the
relational model.
- Example: Representing a company’s employee and project data
where each employee can work on multiple projects.
2. **Relational Model**:
- Represents data in tables (relations) with rows (tuples) and columns
(attributes).
- Highly flexible and uses SQL for querying and manipulating data.
- Example: A `Customer` table with `CustomerID`, `Name`, and
`Address` as columns.
Unit-2
### 14. **Difference Between Tuple Relational Calculus and Domain
Relational Calculus**
#### Example:
Let’s say we have two tables:
**Table 1: Students**
| Student_ID | Name |
|------------|---------|
|1 | Alice |
|2 | Bob |
**Table 2: Courses**
| Course_ID | Course_Name |
|-----------|--------------|
| C1 | Math |
| C2 | Science |
Relational algebra has several operators used for querying data from
relational databases. The main operators are:
- **Select (σ)**
- **Project (π)**
- **Union (∪)**
- **Set Difference (-)**
- **Cartesian Product (×)**
- **Rename (ρ)**
- **Join (⨝)**
1. **Inner Join** – Returns only the rows with matching values in both
tables.
- Example: Select all employees and their departments from
`Employees` and `Departments` where the department ID matches.
2. **Left Join (Left Outer Join)** – Returns all rows from the left table
and matched rows from the right table. If there is no match, NULL values
are returned for columns from the right table.
- Example: Select all employees and their department, even if some
employees don’t have a department.
3. **Right Join (Right Outer Join)** – Similar to the Left Join but returns
all rows from the right table, along with matching rows from the left.
4. **Full Join (Full Outer Join)** – Returns all rows from both tables,
with matching rows where available. Non-matching rows will have
NULLs in the columns of the other table.
5. **Self Join** – A join where a table is joined with itself, typically used
for hierarchical relationships.
**Employees Table:**
| Dept_ID | Dept_Name |
|---------|-----------|
| D1 | HR |
| D2 | IT |
- **Importance:**
- **Data Integrity**: Ensures that the data remains consistent and
accurate after decomposition.
- **Normalization**: Helps in achieving efficient storage and data
retrieval by eliminating redundancy.
This question is similar to **16** and **17**, and has been addressed
above.
Unit-3
### 23. **Armstrong's Axioms**
### 28. **True or False: Any Relation Schema that Satisfies BCNF Also
Satisfies 3NF**
**Given Schema:**
Consider the following table for a **Bookstore**:
1. **1st Normal Form (1NF)**: Ensure that all attributes have atomic
values. This table is already in 1NF.
UNIT - 4
#### Structure:
- **Nodes**: Each node in a B-tree can contain multiple keys and child
pointers.
- **Root**: The root node can have fewer keys than other nodes.
- **Internal Nodes**: Internal nodes hold keys and child pointers. They
help in navigating the tree.
- **Leaf Nodes**: These contain only keys and no child pointers. They
store the actual data or references to the data.
- **Properties**:
- Every node can have a minimum and maximum number of children,
usually defined as a "degree" `t`.
- A node can have between `t-1` and `2t-1` keys, and between `t` and
`2t` children.
- All leaf nodes are at the same level.
- The keys in each node are kept sorted.
- The tree is balanced, ensuring that operations (insertion, deletion,
search) take logarithmic time.
### 32. **B-tree and Hashing**
Both **B-trees** and **hashing** are used for efficient data retrieval,
but they differ in structure and use cases.
- **B-tree**:
- A B-tree is a self-balancing tree structure that maintains sorted data,
allowing for efficient range queries, search, insertion, and deletion
operations.
- Operations like range queries are efficient in a B-tree, as the data is
sorted and can be traversed sequentially.
- **Hashing**:
- Hashing is a technique where a hash function maps keys to a fixed-size
table (hash table). Each key is hashed to a location in the table for quick
access.
- Hashing is ideal for equality searches but is inefficient for range
queries since the data is not sorted.
#### Comparison:
- **B-tree** is better for range queries, while **hashing** is faster for
direct lookups (equality searches).
- **Static Hashing**:
- In static hashing, the hash table has a fixed size, and the hash function
maps data to a fixed number of slots.
- The size of the table cannot change dynamically, which can lead to
**collisions** (when two keys map to the same slot) or
**underutilization** (empty slots).
- **Dynamic Hashing**:
- In dynamic hashing, the hash table can grow or shrink as data is
inserted or deleted. This allows the table to dynamically adjust its size to
maintain performance.
- This approach uses techniques like **bucket splitting** or
**doubling** to handle collisions effectively.
- **Types of Indices**:
- **Primary Index**: Created on the primary key of a table. It
guarantees uniqueness of each record.
- **Secondary Index**: Created on non-primary key columns to speed
up queries based on those columns.
- **Clustered Index**: The rows of the table are stored in the order of
the index.
- **Non-clustered Index**: The index stores pointers to the rows in the
table, and the rows are not necessarily in index order.
1. **Parsing**: The SQL query is parsed to check for syntax errors and to
generate an initial query tree.
2. **Translation**: The parsed query is translated into a relational
algebra expression.
3. **Optimization**: The query optimizer generates the most efficient
execution plan based on available indexes, cost of operations, and
database statistics.
4. **Execution**: The optimized plan is executed, and the result is
returned to the user.
```
SQL Query → Parser → Query Tree → Query Optimizer → Optimized
Query Plan → Execution → Result
```
### 36. **Different Join Strategies for a Query and Their Performance**
There are several join strategies used in relational databases, each with
different performance implications based on the data size and indexes
available:
2. **Sort-Merge Join**:
- Sort both tables based on the join key, and then merge them by
matching sorted rows.
- **Performance**: O(n log n + m log m) for two sorted tables.
- **Used** for large tables with sorted data.
3. **Hash Join**:
- Create a hash table for the smaller table and probe it using the join
key for the larger table.
- **Performance**: O(n + m) for two tables of size `n` and `m`.
- **Used** when one table is much smaller than the other.
4. **Index Join**:
- Use indexes to find the matching rows.
- **Performance**: Depends on index structure (typically faster than a
full table scan).
- **Linear Search**:
- It sequentially checks each element in the list.
- **Complexity**: O(n) where `n` is the number of elements.
- **Used** for unsorted data.
- **Binary Search**:
- It works by repeatedly dividing the sorted list in half to locate the
search key.
- **Complexity**: O(log n) where `n` is the number of elements.
- **Used** for sorted data.
1. **Divide**: Split the large file into smaller chunks that can fit in
memory.
2. **Sort**: Sort each chunk in memory and write the sorted chunks to
disk.
3. **Merge**: Merge the sorted chunks using a merge process (like in
merge sort), reading and writing data to disk.
two keys hash to the same slot, hashing uses techniques like
**chaining** or **open addressing** to resolve these collisions.
Unit-5
### 44. **ACID Properties of Transactions**
1. **Atomicity**:
- A transaction is treated as a single unit, which either fully completes
or fully fails. If any part of the transaction fails, the entire transaction is
rolled back.
- **Example**: If a bank transfer fails midway, neither the debit nor
the credit takes place. The system reverts to the state before the
transaction started.
2. **Consistency**:
- A transaction ensures that the database transitions from one valid
state to another valid state. It preserves the integrity constraints of the
database, such as primary keys, foreign keys, etc.
- **Example**: A transaction that transfers money from one account
to another maintains the rule that the total balance in the system
remains the same before and after the transaction.
3. **Isolation**:
- Transactions are executed in isolation from each other. Intermediate
states of a transaction are invisible to other transactions until the
transaction is committed.
- **Example**: If two people are transferring money from the same
account, their transactions are executed in such a way that neither can
see the other’s intermediate state.
4. **Durability**:
- Once a transaction is committed, its changes are permanent and will
survive any system failure (such as a crash).
- **Example**: After committing a transaction to withdraw money,
the money will not be lost even if the database crashes immediately
afterward.
```
New → Active → Partially Committed → Committed
↕
Aborted
```
- **Conflict Serializability**:
- A schedule is **conflict serializable** if it can be transformed into a
serial schedule (one transaction after another) by swapping non-
conflicting operations (where two operations do not access the same
data or do not conflict in a way that violates serial execution).
- **Example**: If transactions `T1` and `T2` access different data items,
their operations are conflict-free and can be swapped without affecting
the result.
- **View Serializability**:
- A schedule is **view serializable** if it results in the same final state
as some serial schedule, i.e., the view of data read by transactions is the
same in both schedules.
- **Example**: Even if operations are interleaved, as long as the final
outcome is the same as some serial schedule, it is view serializable.
**Difference**:
- Conflict serializability is a stricter criterion than view serializability.
Every conflict-serializable schedule is view serializable, but not every
view serializable schedule is conflict serializable.
- **Protocol**:
- Transactions must acquire locks on data before accessing it and
release them only after the transaction has committed.
- It guarantees **serializability** (conflict serializability) and prevents
**deadlocks**.
- **Example**:
- Transaction 1 locks data items A and B, performs updates, and then
releases the locks only after it commits. Meanwhile, Transaction 2 must
wait for Transaction 1 to release the locks before it can proceed.
1. **Shared Lock**:
- Allows other transactions to read the data but prevents any
transaction from modifying it.
- **Example**: Transaction 1 acquires a shared lock on a data item,
and Transaction 2 can read the data but cannot modify it.
2. **Exclusive Lock**:
- Prevents other transactions from both reading and modifying the
data.
- **Example**: Transaction 1 acquires an exclusive lock on a data item,
blocking all other transactions from accessing it until the lock is released.
**Difference**:
- Shared locks allow read access by multiple transactions, while exclusive
locks block all other access to the data item.
- **Working**:
- When a transaction performs a read or write, the system checks
whether the transaction's timestamp is earlier or later than the
conflicting transaction's timestamp.
- **No Read-Write Conflict**: A transaction can only read data if no
subsequent transaction has written it.
- **No Write-Write Conflict**: A transaction can only write data if no
subsequent transaction has read or written it.
- **Advantages**:
- Provides an easy-to-implement mechanism for serializability.
- Prevents issues like **lost updates** and **dirty reads**.
- **Types**:
1. **Basic 2PL**: A transaction must acquire all locks before it starts
releasing any.
2. **Strict 2PL**: A transaction holds all locks until it commits or aborts,
ensuring no other transaction can access data during the transaction’s
execution.
- **Wait-Die**:
- When a younger transaction requests a lock held by an older
transaction, it **waits**.
- When an older transaction requests a lock held by a younger
transaction, the younger transaction **dies** (is aborted).
- **Wound-Wait**:
- When a younger transaction requests a lock held by an older
transaction, it **waits**.
- When an older transaction requests a lock held by a younger
transaction, the younger transaction **wounds** (is aborted).
#### Example:
- **Transaction 1** locks **Data A** and waits for **Data B**.
- **Transaction 2** locks **Data B** and waits for **Data A**.
- Both transactions are in a deadlock state because each is waiting for
the other to release a lock, and neither can proceed.
Unit-6
3. **Hash Functions**:
- A hash function transforms input data into a fixed-size string of
characters, which is typically a hash value or digest.
- **Example**: **SHA-256** (Secure Hash Algorithm 256-bit) is
commonly used in various applications like digital signatures and
certificate generation.
- **Advantages**: Used for integrity checks and ensuring data has not
been tampered with.
- **Disadvantages**: Not reversible (you cannot recover the original
data from the hash).
4. **Digital Signatures**:
- Digital signatures use asymmetric encryption to ensure the
authenticity and integrity of a message or document.
- **How it works**: The sender creates a hash of the message,
encrypts it with their private key, and sends it along with the message.
The recipient can decrypt the signature using the sender's public key and
verify the message integrity.
- **Example**: **RSA**, **DSA** (Digital Signature Algorithm).
6. **Hybrid Cryptography**:
- Hybrid systems combine both symmetric and asymmetric
cryptography. Typically, asymmetric encryption is used to securely
exchange a symmetric key, which is then used to encrypt the data.
- **Example**: **SSL/TLS** protocols use this approach for secure
communication over the internet.
#### **Example**:
- Consider a vulnerable login form where the username and password
are used directly in an SQL query like this:
```sql
SELECT * FROM users WHERE username = 'user_input' AND password =
'password_input';
```
- An attacker could inject the following input into the username field:
```sql
' OR '1'='1
```
This would change the SQL query to:
```sql
SELECT * FROM users WHERE username = '' OR '1'='1' AND password =
'password_input';
```
This would always return true (`'1'='1'` is always true), allowing the
attacker to bypass authentication.
1. **Uniqueness**:
- **PRIMARY KEY**: Ensures that the values in the column (or columns)
are unique, and it also automatically enforces **NOT NULL**. There can
only be one **PRIMARY KEY** constraint in a table.
- **UNIQUE**: Also ensures uniqueness, but it allows **NULL** values.
A column with a **UNIQUE** constraint can have multiple **NULLs**
(since NULL is considered a unique value).
2. **Nullability**:
- **PRIMARY KEY**: Cannot have **NULL** values.
- **UNIQUE**: Can have **NULL** values (multiple **NULLs** are
allowed).
3. **Usage**:
- **PRIMARY KEY**: Used to uniquely identify each record in the table.
- **UNIQUE**: Used to ensure that the values in the column(s) are
unique but does not necessarily act as a primary identifier for the
records.
**Example**:
```sql
CREATE TABLE students (
id INT PRIMARY KEY, -- Primary Key constraint, ensures uniqueness
and non-nullability
email VARCHAR(255) UNIQUE -- Unique constraint, allows NULL values
but ensures uniqueness
);
```
---
---
### 58. **SQL Queries for the Given Tables**
#### Tables:
- **T1 (rollno, stuname, age, city, branchcode)**
- **T2 (branchcode, branchname)**
---
---
---
1. **COUNT()**:
- Example: To count the number of students in the table:
```sql
SELECT COUNT(*) FROM students;
```
2. **SUM()**:
- Example: To calculate the total amount of sales:
```sql
SELECT SUM(sales_amount) FROM sales;
```
3. **AVG()**:
- Example: To find the average salary of employees:
```sql
SELECT AVG(salary) FROM employees;
```
4. **MAX()**:
- Example: To find the highest score from a students table:
```sql
SELECT MAX(score) FROM exam_results;
```
5. **MIN()**:
- Example: To find the lowest temperature recorded:
```sql
SELECT MIN(temperature) FROM weather;
```
---
#### **Example**:
```sql
DECLARE
CURSOR student_cursor IS
SELECT name FROM students;
student_name VARCHAR(50);
BEGIN
OPEN student_cursor;
FETCH student_cursor INTO student_name;
WHILE student_cursor%FOUND LOOP
DBMS_OUTPUT.PUT_LINE(student_name);
FETCH student_cursor INTO student_name;
END LOOP;
CLOSE student_cursor;
END;
```
---
---
#### Example:
```sql
CREATE TRIGGER before_insert_student
BEFORE INSERT ON students
FOR EACH ROW
BEGIN
IF :new.age < 18 THEN
RAISE_APPLICATION_ERROR(-20001, 'Student age must be 18 or
older');
END IF;
END;
```
This trigger checks if a student's age is less than 18 before inserting into
the `students` table and raises an error if true.
---
#### Example:
```sql
CREATE PROCEDURE get_student_details (IN student_id INT)
BEGIN
SELECT * FROM students WHERE rollno = student_id;
END;
```
This procedure fetches the details of a student by their `rollno`.
---
```plsql
DECLARE
total_sum NUMBER := 0;
BEGIN
FOR i IN 1..100 LOOP
IF MOD(i, 2) = 0 THEN
total_sum := total_sum + i;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Sum of even numbers between 1 and 100: '
|| total_sum);
END;
```
This PL/SQL block calculates the sum of all even numbers between 1 and
100 and outputs the result.