2304 TMA Final
2304 TMA Final
Answer: Database normalization is a process used in database design to organize data efficiently.
It can help to reduce data redundancy (duplicate data) and improve data integrity (data accuracy
and consistency). It's like organizing a messy filing cabinet: instead of having the same
information in multiple places, you put each piece of information in one spot and then use a
system of cross-references to connect them. The primary objective for normalizing the relations
is to eliminate the below anomalies. Failure to reduce anomalies results in data redundancy, which
may threaten data integrity and cause additional issues as the database increases. Role of
normalization in reducing anomalies in databases are described below:
Insertion Anomalies: Insertion anomalies occur when it is not possible to insert data into
a database because the required fields are missing or because the data is incomplete. For
example, if a database requires that every record has a primary key, but no value is provided
for a particular record, it cannot be inserted into the database.
Deletion anomalies: Deletion anomalies occur when deleting a record from a database and
can result in the unintentional loss of data. For example, if a database contains information
1|Page
about customers and orders, deleting a customer record may also delete all the orders
associated with that customer.
Updating anomalies: Updating anomalies occur when modifying data in a database and
can result in inconsistencies or errors. For example, if a database contains information
about employees and their salaries, updating an employee’s salary in one record but not in
all related records could lead to incorrect calculations and reporting.
So, we can simply state that, Database normalization is the process of organizing the attributes
of the database to reduce or eliminate data redundancy.
Answer: To delete a table in SQL, we may use the DROP TABLE statement. The DROP
TABLE command permanently removes a table from the database. It deletes the table’s structure,
data, and related objects such as indexes and triggers. The operation is irreversible and recovery
is possible only if a backup exists.
Syntax: DROP TABLE table_name;
Example: DROP TABLE Students;
Answer: Aggregate functions perform a calculation on a set of values and return a single value.
The most commonly available SQL aggregate functions across different database systems are used to perform
calculations on a set of values and return a single result.
COUNT() : Returns the number of rows that match a specified criterion. COUNT(*) counts all rows,
including those with NULL values, while COUNT(column_name) only counts non-NULL values.
MAX() : Retrieves the largest value from a column. This function can operate on numeric, string, and
date/time data types.
MIN() : Retrieves the smallest value from a column. Like MAX() , it works with various data types
including numeric, string, and date/time.
3|Page
SUM() : Calculates the total sum of all non-NULL values in a numeric column.
6. What are the differences between DROP, TRUNCATE and DELETE commands?
Answer: In SQL, the DELETE, DROP, and TRUNCATE commands is important for efficient
data management. While these commands are all used to remove data, they differ significantly in
functionality, usage, and performance. The following table lists all the major differences between
DELETE, DROP, and TRUNCATE:
Deletes specific rows based on a Deletes the entire table or Deletes all rows but retains table
Purpose
condition database structure
Slower, as each row is processed Instant removal, affecting Faster than DELETE but slower than
Efficiency
individually schema DROP
Triggers Fires triggers Does not fire triggers Does not fire triggers
4|Page
single, indivisible unit of work. It guarantees that the database moves from one valid state to another,
automatically rolling back changes if any part of the transaction fails, thus preventing partial updates and violating
data integrity rules.
Key ways a transaction ensures consistency include:
Atomicity (All or Nothing): The transaction ensures that if any part of a multi-step process fails, all prior
actions within that transaction are reverted (rolled back) to maintain the original valid state.
Consistency Constraints: Before and after the transaction, the database enforces rules, such as FOREIGN
KEY constraints, UNIQUE indexes, and data type checks, ensuring the database remains valid.
Isolation (Concurrent Control): Through locking mechanisms and isolation levels, transactions are
isolated from each other, preventing intermediate, invalid data from being read or written by concurrent
operations.
Durability: Once a transaction is committed, the changes are permanent, often using write-ahead logging
to survive system failures.
For example, in a bank transfer, a transaction ensures that the deduction from one account and the deposit to
another either both succeed, or both fail, maintaining the total balance integrity.
Intersection (∩): This binary operator returns only the tuples that appear in both union-compatible
relations.
Rename (ρ): This unary operator is used to rename the output relation or its attributes, which is
particularly useful in complex queries involving multiple operations or self-joins.
Division (÷): A more complex operation used for queries that require all tuples of one relation to be
associated with every tuple of another.
Protection Against Ransomware and Cyberattacks: If data is locked by malicious attacks, a secure,
offline, or immutable backup allows you to restore systems without paying ransoms.
6|Page
Data Loss Prevention: It ensures that in the event of hardware failure, software corruption, or human
error, critical files can be recovered to a consistent state.
Customer Trust and Compliance: Regularly updating and testing backups ensures data integrity,
satisfying legal, industry, and regulatory requirements (e.g., GDPR), and maintaining customer
confidence.
Cost Efficiency: While requiring an investment, a recovery plan is far less costly than the massive
financial hit caused by prolonged business downtime and lost critical information.
11. Explain Data Manipulation Language (DML) and Data Definition Language (DDL)
with examples.
Answer:
Data Definition Language(DDL):
Data Definition Language(DDL) is used to define data structures. For example: creating a table, and altering a
table are instructions in SQL. DDL is used to specify a database's structure, which includes its tables, views,
indexes, and constraints. DDL commands come in the following types: CREATE, ALTER, DROP, RENAME,
and TRUNCATE. DDL statements only modify the database's schema; they have no direct effect on the data
within the database. DDL declarations are irreversible and difficult to undo. As for example:
1. CREATE (Create a table)
CREATE TABLE students (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
);
2. ALTER (Modify table structure)
ALTER TABLE students
ADD email VARCHAR(100);
3. DROP (Delete table)
DROP TABLE students;
4. TRUNCATE (Delete all records quickly)
TRUNCATE TABLE students;
So, it could be stated that, DDL deals with the structure/schema, not the actual data content.
12. Explain the concept of data integrity and how it is maintained in a relational database.
Answer:
Data integrity in a relational database means ensuring that data accuracy, consistency, and reliability throughout
its lifecycle, preventing unauthorized or accidental changes. It is maintained through constraints (primary keys,
foreign keys, check constraints) and transactional rules (ACID properties) that enforce data rules at the database
level. It prevents errors, duplication, and corruption so that the database remains trustworthy.
Data integrity in Relational database through few mechanisms. These are described below:
Relational Database Management Systems (RDBMS) use four primary types of integrity constraints:
1. Entity Integrity: Uses primary keys to ensure each row in a table is uniquely identifiable and not null,
preventing duplicate records.
2. Referential Integrity: Maintains relationships between tables using foreign keys. It ensures that a child
record cannot exist without a parent record (e.g., an order cannot exist without a customer).
3. Domain Integrity: Defines valid values for a column, enforcing data types, formats, ranges, and constraints
(e.g., ensuring an age column is always positive).
4. User-Defined Integrity: Enforces specific business rules created by users that do not fall under other
categories.
5. ACID Transactions: Ensures that transactions are Atomic, Consistent, Isolated, and Durable, preventing
data corruption during concurrent operations.
8|Page
6. Data Validation: Checks data against predefined criteria (like constraints) before allowing insertion or
updates.
Answer: A database query is a structured request for information or action sent to a database. Unlike casual
questions, a query must follow strict syntax so the database can interpret and process it correctly. When executed,
it either returns the requested data or performs the specified operation. At its core, a query is code used to interact
with a database. It allows you to ask precise questions or issue commands that the database understands. The
result is either a dataset matching your criteria or a confirmation that the requested changes have been applied.
Database queries can be categorized based on their purpose, whether they view, modify, or analyze data. These
are discussed below:
9|Page
1. Select queries
Select queries are the most basic and widely used type. They retrieve data from a database and present it as a
result set without altering the underlying records. Example: SELECT * FROM Products;
2. Action queries
Action queries modify data or the database structure and are executed with care. Common subtypes include:
Update queries: Change existing records (e.g., give all employees a 5% raise).
Append queries: Add new records from one table to another.
Delete queries: Remove records permanently based on criteria.
Make-table queries: Create a new table from existing data.
Example: DELETE FROM Orders WHERE Status = 'Cancelled';
3. Parameter queries
Parameter queries are dynamic. Instead of using fixed criteria, they prompt the user for input before running.
Example: Searching for a student by entering their specific Roll Number.
4. Aggregate queries
Aggregate (summary) queries perform calculations on groups of records to extract insights:
Sum: Total sales or revenue.
Count: Number of customers or transactions.
Average: Mean value of orders or scores.
Min/Max: Lowest or highest values in a dataset.
Example: SELECT Name FROM Employees WHERE Salary > (SELECT AVG(Salary) FROM Employees);
5. Crosstab queries
Crosstab queries restructure data into a matrix format to analyze relationships between variables. Similar to an
Excel PivotTable, they display data in rows and columns for easier comparison and reporting. Example: Like
Summery Table.
10 | P a g e
15. Explain UPDATE and INSERT command with example.
UPDATE statement in the PL/SQL is used to the modify the existing records in table. It is allowed us to
specify the table name, columns to updated new values for these columns and an optional conditional to the
filter which rows are to be updated.
Syntax for UPDATE Statement
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Explanation:
table_name is the name of the table, which we want to update.
SET column1 = value1, column2 = value2, ... are specified the columns to the updated with their new
values.
WHERE condition is specify which rows are to be update. if we not use where condition all rows in
the table will be update.
Examples on UPDATE Statement
Example 1: Let's update the last name of the students as Anderson whose student_id is 3.
UPDATE students
SET last_name = 'Anderson'
WHERE student_id = 3;
Output:
student_id first_name last_name
1 John Doe
2 Jane Smith
3 Michael Anderson
4 Emily Williams
INSERT statement in the PL/SQL is used to add the new records or rows of data into the table. It allows u to
specify the table name, columns where the data will be inserted and the corresponding values to be inserted
into the columns.
Syntax for INSERT Statement
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Explanation:
table_name is the name of the table, which we want to insert the data.
(column1, column2, ....) are optional lists of the columns in table. If specified, you need to be
provide the values for those columns in the same order.
VALUES (value1, value2, ...) are values to be inserted into specified columns. These values must
match the data types of the provided columns.
11 | P a g e
Examples on INSERT Statement
1 John Doe
2 Jane Smith
Preventing Deadlocks
Deadlock prevention focuses on ensuring at least one of the conditions above never occurs.
Eliminate Mutual Exclusion: Make resources shareable (e.g., read-only files), though this is
impossible for non-sharable resources like printers.
Eliminate Hold and Wait: Require processes to request all resources at once before execution,
or force them to release held resources before requesting new ones.
Eliminate Circular Wait: Impose a unique, ordered numbering system on all resource types
and require processes to request resources in increasing order.
Resolving Deadlocks
When prevention is not feasible, systems use detection and recovery methods:
Detection Algorithms: The system periodically checks for cycles in the Resource Allocation
Graph (RAG).
12 | P a g e
Process Termination: Abort one or all deadlocked processes. This can be done by killing all
processes involved or terminating them one by one until the cycle breaks.
Resource Preemption: Forcibly take resources away from one or more processes and give
them to others until the deadlock is resolved.
Rollback: Revert a process to a previous "safe state" and restart it, which prevents permanent
data corruption.
Stopping Deadlocks before they occur is often better than recovering from them. Deadlock avoidance is an
example of careful resource allocation.
Aggregation:
Aggregation is an abstraction process where a relationship between two entities is treated as a single, high-level
entity. It is used when an entity needs to relate to a relationship rather than just another entity. In other words,
13 | P a g e
Aggregation is a process when relation between two entities is treated as a single entity. Aggregation in
database management systems helps at ensuring that all entities are utilized within the system. Without this
operation, the trivial entities may become inoperative.
Example: A "Center" and a "Course" have a relationship. If we want to track "Inquiry" for that specific Center-
Course pair, we aggregate Center and Course into one unit.
15 | P a g e
Step-by-Step Conversion Process
1. Identify Transitive Dependencies
Check for functional dependencies where a non-prime attribute (not part of the key) determines another
non-prime attribute.
2. Separate the Dependent Attributes
Remove the attributes that are transitively dependent (the "right side" of the dependency) from the
original table.
3. Create a New Table
Place the removed attributes into a new table. The determinant (the attribute they depended on)
becomes the Primary Key of this new table.
4. Establish a Relationship
Keep a copy of the determinant in the original table to act as a Foreign Key, linking the two tables
together.
Limitation: If Department D01 changes its name, we must update multiple rows (Update Anomaly).
16 | P a g e
Conversion to 3NF
To achieve 3NF, move the transitive dependency (Dept_ID _Dept_Name) to a new table.
1. Employee Table
2. Department Table
D01 HR
D02 IT
17 | P a g e