Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views20 pages

DBMS Ia2

Uploaded by

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

DBMS Ia2

Uploaded by

Arathi M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

DBMS QUESTION BANK FOR 2ND IA

1. Explain how group By clause works? What is the difference between WHERE and Having?
Ans - The GROUP BY clause in SQL is used to arrange identical data into groups based on one
or more columns. It is often used with aggregate functions (like COUNT(), SUM(), AVG(),
MAX(), MIN()) to perform operations on each group of data, rather than on individual rows.
How GROUP BY Works:
1. Grouping Rows: The GROUP BY clause collects rows that have the same values in specified
columns into groups.
2. Aggregate Function Application: After rows are grouped, aggregate functions can be applied
to perform calculations on each group, like counting the rows in a group or summing a
column's values.
3. Order of Execution: The GROUP BY clause is executed after the WHERE clause but before the
ORDER BY clause.
Basic Syntax:
SELECT column_name(s), aggregate_function(column_name)
FROM table_name
WHERE condition
GROUP BY column_name(s);

Comparison WHERE Clause HAVING Clause


Basis

It is used to perform filtration on It is used to perform filtration on


Definition
individual rows. groups.

It is implemented in column
Basic It is implemented in row operations.
operations.

The WHERE
clause fetches the The HAVING clause first fetches
Data specific data from the complete data. It then
fetching particular rows separates them according to the
based on the given condition.
specified condition

Aggregate The WHERE clause does not allow to The HAVING clause can work with
Functions work with aggregate functions. aggregate functions.

The HAVING clause acts as a post-


Act as The WHERE clause acts as a pre-filter.
filter.

We can use the WHERE clause with the


The HAVING clause can only use
Used with SELECT, UPDATE, and DELETE
with the SELECT statement.
statements.

The GROUP BY clause comes after the The GROUP BY clause comes
GROUP BY
WHERE clause. before the HAVING clause.
2. List out and explain the different types of JDBC drivers.
Ans - JDBC drivers are client-side adapters (installed on the client machine, not on the
server) that convert requests from Java programs to a protocol that the DBMS can
understand. JDBC drivers are the software components which implements interfaces in JDBC
APIs to enable java application to interact with the database. Now we will learn how many
JDBC driver types does Sun defines? There are four types of JDBC drivers defined by Sun
Microsystem that are mentioned below:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

1. JDBC-ODBC bridge driver – Type 1 driver


Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-1
driver is also called Universal driver because it can be used to connect to any of the
databases.

Advantages
 This driver software is built-in with JDK so no need to install separately.
 It is a database independent driver.
Disadvantages
 As a common driver is used in order to interact with different databases, the data transferred
through this driver is not so secured.
 The ODBC bridge driver is needed to be installed in individual client machines.
 Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.

2. Native-API driver – Type 2 driver ( Partially Java driver)


The Native API driver uses the client -side libraries of the database. This driver converts JDBC
method calls into native calls of the database API. In order to interact with different
database, this driver needs their local API, that’s why data transfer is much more secure as
compared to type-1 driver. This driver is not fully written in Java that is why it is also called
Partially Java driver.

Advantage
 Native-API driver gives better performance than JDBC-ODBC bridge driver.
Disadvantages
 Driver needs to be installed separately in individual client machines
 The Vendor client library needs to be installed on client machine.
 Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
 It is a database dependent driver.

3. Network Protocol driver – Type 3 driver (fully Java driver)


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. Here all the database
connectivity drivers are present in a single server, hence no need of individual client-side
installation.

Advantages
 Type-3 drivers are fully written in Java, hence they are portable drivers.
 No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.
 Switch facility to switch over from one database to another database.
Disadvantages
 Network support is required on client machine.
 Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4. Thin driver – Type 4 driver (fully Java driver)


Type-4 driver is also called native protocol driver. This driver interact directly with database.
It does not require any native database library, that is why it is also known as Thin Driver.

Advantages
 Does not require any native library and Middleware server, so no client-side or server-side
installation.
 It is fully written in Java language, hence they are portable drivers.
Disadvantage
 If the database varies, then the driver will carry because it is database dependent.

3. Explain SELECT, ALTER, UPDATE statements in SQL with example.

Ans - In SQL, the SELECT, ALTER, and UPDATE statements are fundamental commands used for
retrieving, modifying, and updating data or table structures in a database. Here’s a breakdown of
each statement with examples.
1. SELECT Statement

The SELECT statement is used to retrieve data from one or more tables in a database. It allows users
to specify which columns to display and can include conditions to filter results.

Syntax:

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example:

SELECT FirstName, LastName

FROM Employees

WHERE Department = 'Sales';

- **Explanation**: This query retrieves the `FirstName` and `LastName` of employees from the
`Employees` table who work in the Sales department.

Common Clauses with SELECT:

- **WHERE**: Adds conditions to filter records.

- **ORDER BY**: Sorts the results by one or more columns.

- **GROUP BY**: Groups rows with similar values (often used with aggregate functions).

- **JOIN**: Combines rows from two or more tables based on related columns.

2. ALTER Statement

The ALTER statement is used to modify the structure of an existing table. It can be used to add,
delete, or modify columns, and also to change constraints on the table.

Syntax:

ALTER TABLE table_name

ADD column_name datatype;

ALTER TABLE table_name

DROP COLUMN column_name;

ALTER TABLE table_name

MODIFY COLUMN column_name new_datatype;

Example:

-- Add a new column

ALTER TABLE Employees

ADD DateOfBirth DATE;

-- Modify the data type of a column

ALTER TABLE Employees

MODIFY COLUMN LastName VARCHAR(50);

-- Drop a column
ALTER TABLE Employees

DROP COLUMN MiddleName;

- **Explanation**:

- The first command adds a new column `DateOfBirth` of type `DATE` to the `Employees` table.

- The second command changes the `LastName` column to a data type of `VARCHAR(50)`.

- The third command removes the `MiddleName` column from the `Employees` table.

3. UPDATE Statement

The **UPDATE** statement is used to modify existing data within a table. This statement allows you
to change values in one or more rows, based on specified conditions.

Syntax:

UPDATE table_name

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

WHERE condition;

Example:

UPDATE Employees

SET Salary = Salary * 1.1

WHERE Department = 'Sales';

- **Explanation**: This query updates the `Salary` field by increasing it by 10% for employees in the
Sales department.

4. Define Triggers. Brief about triggers with syntax and example.

Ans: A trigger is a set of SQL statements that automatically executes (or “fires”) in response to
specific events on a table or view in a database. Triggers are commonly used to enforce business
rules, maintain audit trails, and automate tasks like data validation or integrity checks.

Characteristics of Triggers

- **Automatically Executed**: Triggers activate in response to an event (INSERT, UPDATE, DELETE).

- **Associated with Tables/Views**: They are defined on a specific table or view.

- **Before or After Events**: Triggers can be set to execute either *before* or *after* the triggering
event occurs.

- **Non-queryable**: Triggers do not return results and cannot be directly queried.

Types of Triggers

1. **Before Triggers**: Execute before the triggering event (e.g., before inserting or updating a row).

2. **After Triggers**: Execute after the triggering event (e.g., after inserting or deleting a row).

3. **Instead of Triggers** (specific to certain databases like SQL Server): Execute in place of a
triggering event, typically on views to simulate an updateable view.

Syntax of a Trigger:

CREATE TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}


ON table_name

FOR EACH ROW

BEGIN

-- Trigger code (SQL statements)

END;

Explanation of Syntax

- **CREATE TRIGGER trigger_name**: Creates a trigger with a specified name.

- **BEFORE/AFTER/INSTEAD OF**: Specifies when the trigger should be fired relative to the event.

- **INSERT, UPDATE, DELETE**: Defines the type of event that will activate the trigger.

- **ON table_name**: Specifies the table to which the trigger is attached.

- **FOR EACH ROW**: Ensures the trigger fires for each affected row in the table.

- **BEGIN ... END**: Encloses the trigger’s logic (the SQL statements to execute).

Example of a Trigger

**Scenario**: Suppose we want to automatically log any salary updates in the `Employees` table into
a `Salary_Audit` table, recording the employee's ID, old salary, new salary, and the timestamp of the
update.

1. **Create the Audit Table**:

CREATE TABLE Salary_Audit (

Employee_ID INT,

Old_Salary DECIMAL(10, 2),

New_Salary DECIMAL(10, 2),

Change_Date TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

2. **Create the Trigger**:

CREATE TRIGGER trg_after_salary_update

AFTER UPDATE ON Employees

FOR EACH ROW

BEGIN

INSERT INTO Salary_Audit (Employee_ID, Old_Salary, New_Salary, Change_Date)

VALUES (OLD.Employee_ID, OLD.Salary, NEW.Salary, CURRENT_TIMESTAMP);

END;

- **Explanation**:

- The trigger `trg_after_salary_update` fires **after** an **UPDATE** on the `Employees` table.

- **FOR EACH ROW** means the trigger applies to each row affected by the update.

- The `INSERT INTO Salary_Audit` statement logs the employee's ID, old salary (`OLD.Salary`), new
salary (`NEW.Salary`), and the timestamp into the `Salary_Audit` table.
5. Define referential integrity constraint. Explain the importance of referential integrity
constraint. How is this constraint implemented in SQL.

Ans: A referential integrity constraint is a rule in a relational database that ensures consistency
between related tables by maintaining valid relationships between them. It requires that a foreign
key in one table must either match a primary key in another table or be null. This constraint helps
prevent orphaned records and keeps related data in sync across tables.

Importance of Referential Integrity Constraint

1. **Maintains Data Consistency**:

- Ensures that there are no orphaned records in the database. For example, if an order references a
customer ID, referential integrity guarantees that this customer exists in the customers table.

2. **Enforces Logical Relationships**:

- Referential integrity helps in establishing meaningful relationships between tables, which


supports accurate queries and data retrieval.

3. **Prevents Accidental Deletion or Modification**:

- Referential integrity constraints prevent accidental deletion or modification of referenced data,


ensuring that related records remain valid.

4. **Simplifies Database Management**:

- By enforcing consistent relationships, referential integrity constraints reduce the need for manual
checks, making database management easier and reducing potential errors.

Implementing Referential Integrity Constraint in SQL:

In SQL, referential integrity is typically implemented using **foreign keys**. A foreign key in a child
table references the primary key of a parent table. This setup enforces referential integrity by
ensuring that the values in the foreign key column(s) match values in the parent table’s primary key
column(s).

Syntax:

CREATE TABLE ParentTable (


ParentID INT PRIMARY KEY,
ParentData VARCHAR(50)
);

CREATE TABLE ChildTable (


ChildID INT PRIMARY KEY,
ParentID INT,
ChildData VARCHAR(50),
FOREIGN KEY (ParentID) REFERENCES ParentTable(ParentID)
ON DELETE CASCADE
ON UPDATE CASCADE
);

**Explanation of Constraints**:

- **FOREIGN KEY**: Specifies the column in `ChildTable` (`ParentID`) that references the `ParentID`
column in `ParentTable`.

- **ON DELETE CASCADE**: If a record in the `ParentTable` is deleted, all related records in
`ChildTable` will also be deleted. This prevents orphaned records.
- **ON UPDATE CASCADE**: If the `ParentID` in the `ParentTable` is updated, all corresponding
`ParentID` values in the `ChildTable` will also be updated to match.

Example of Referential Integrity in Action

Suppose we have a `Customers` table and an `Orders` table:

CREATE TABLE Customers (


CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(50)
);

CREATE TABLE Orders (


OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
ON DELETE CASCADE
);

- **Purpose**: Here, the `CustomerID` column in the `Orders` table is a foreign key that references
the `CustomerID` column in the `Customers` table.

- **ON DELETE CASCADE**: If a customer is deleted from the `Customers` table, all orders related to
that customer in the `Orders` table will automatically be deleted.

6. Demonstrate insertion, deletion and modification anomalies. Why are they considered bad?
Illustrate with example.

Ans: Insertion, Deletion, and Modification Anomalies are issues that arise in poorly designed
databases, often due to redundancy and a lack of normalization. These anomalies create
inconsistencies and make data management error-prone, leading to a lack of data integrity.

1. Insertion Anomaly

Definition: An insertion anomaly occurs when adding a new record is difficult or impossible due to
the table’s design. This issue usually arises when certain fields are dependent on other fields, even if
they’re not yet relevant.

Example**:

Suppose we have a table called `Employee_Project` that stores information about employees and the
projects they are working on.

| Employee_ID | Employee_Name | Project_ID | Project_Name |

|-------------|---------------|------------|-----------------|

| 101 | Alice |1 | Database Design |

| 102 | Bob |2 | Web Development |

| 103 | Charlie |3 | Mobile App |

- **Problem**: If a new employee joins but has not yet been assigned to any project, we cannot add
their details without leaving `Project_ID` and `Project_Name` fields empty or using nulls.

- **Why It’s Bad**: This results in a partial record, which can lead to data inconsistencies and unused
space. Proper database design should allow us to record employees independently of projects, likely
by using separate `Employee` and `Project` tables.
2. Deletion Anomaly

Definition**: A deletion anomaly occurs when deleting a record unintentionally removes additional,
valuable data. This is common when data from two different entities is stored in the same table.

Example**:

Using the `Employee_Project` table again:

| Employee_ID | Employee_Name | Project_ID | Project_Name |

|-------------|---------------|------------|-----------------|

| 101 | Alice |1 | Database Design |

| 102 | Bob |2 | Web Development |

| 103 | Charlie |3 | Mobile App |

- **Problem**: If we delete the entry for `Project_ID = 1` because the Database Design project is
completed, we also lose all information about `Employee_ID = 101` (Alice), even though we may
want to keep her employment records.

- **Why It’s Bad**: Valuable employee information is lost due to poor table structure. Separate
tables for employees and projects would allow us to delete a project without affecting the
employee’s records.

3. Modification Anomaly

Definition**: A modification anomaly occurs when changing data in one place requires changes in
multiple rows, which can lead to inconsistencies if updates are not made consistently.

Example**:

Consider the `Employee_Project` table once more:

| Employee_ID | Employee_Name | Project_ID | Project_Name |

|-------------|---------------|------------|-----------------|

| 101 | Alice |1 | Database Design |

| 102 | Bob |1 | Database Design |

| 103 | Charlie |2 | Web Development |

- **Problem**: If the `Project_Name` for `Project_ID = 1` changes to "Database Architecture," we


would need to update multiple rows. If we forget to update one row, we create inconsistent data.

- **Why It’s Bad**: This increases the chance of data inconsistency, where some rows reflect the
new project name and others still show the old name. Proper design, such as a separate `Projects`
table, would allow us to update the project name in only one place.

Why These Anomalies Are Considered Bad

1. **Data Redundancy**: These anomalies often result from redundant data, leading to wasted
storage and an increased chance of inconsistency.

2. **Data Integrity Issues**: Anomalies create situations where the data can become inconsistent or
incorrect.

3. **Difficult Maintenance**: When redundant information is spread across multiple rows,


maintaining and updating data becomes cumbersome and error-prone.

7. Write a note on aggregate functions in SQL with examples.


Ans - SQL aggregation function is used to perform the calculations on multiple rows of a single
column of a table. It returns a single value.

It is also used to summarize the data.

1. COUNT FUNCTION

COUNT function is used to Count the number of rows in a database table. It can work on both
numeric and non-numeric data types.

COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null.

Syntax :

COUNT(*) or COUNT( [ALL|DISTINCT] expression )

2. SUM Function

Sum function is used to calculate the sum of all selected columns. It works on numeric fields only.

Syntax

SUM() or SUM( [ALL|DISTINCT] expression )

3. AVG function

The AVG function is used to calculate the average value of the numeric type. AVG function returns
the average of all non-Null values.

Syntax

AVG() or AVG( [ALL|DISTINCT] expression )

4. MAX Function

MAX function is used to find the maximum value of a certain column. This function determines the
largest value of all selected values of a column.

Syntax

MAX() or MAX( [ALL|DISTINCT] expression )

5. MIN Function

MIN function is used to find the minimum value of a certain column. This function determines the
smallest value of all selected values of a column.

Syntax

MIN() or MIN( [ALL|DISTINCT] expression )

8. Consider the following COMPANY database


EMP(Name,SSN,Salary,SuperSSN,Gender,Dno)
DEPT(DNum,Dname,MgrSSN,Dno)
DEPT_LOC(Dnum,Dlocation)
DEPENDENT(ESSN,Dep_name,Sex)
WORKS_ON(ESSN,Pno,Hours)
PROJECT(Pname,Pnumber,Plocation,Dnum)
Write the SQL queries for the following
(i)Retrieve the name, address, salary of employees who work for the Research department.
SELECT E.Name, E.Salary
FROM EMP E, DEPT D
WHERE E.Dno = D.DNum
AND D.Dname = 'Research';
Explanation: This query joins the EMP and DEPT tables to retrieve the employee names (E.Name),
salary (E.Salary), and any additional attributes like address (if present in the schema) of employees
who work for the department named 'Research'.

(ii) Find the names of employees who work on all projects controlled by department number4.
SELECT E.Name
FROM EMP E
WHERE NOT EXISTS (
SELECT P.Pnumber
FROM PROJECT P
WHERE P.Dnum = 4
AND NOT EXISTS (
SELECT W.ESSN
FROM WORKS_ON W
WHERE W.ESSN = E.SSN
AND W.Pno = P.Pnumber
)
);
Explanation: This query uses a double NOT EXISTS to find employees (E.Name) who work on all
projects controlled by department number 4. The inner subquery checks that there is no project
under department 4 that the employee is not working on.

iii) Retrieve the SSN of all employees who either in department no :4 or directly supervise an
employee who work in department number :4
SELECT DISTINCT E.SSN
FROM EMP E
WHERE E.Dno = 4
OR E.SSN IN (
SELECT E2.SuperSSN
FROM EMP E2
WHERE E2.Dno = 4
);
Explanation: This query finds employees (E.SSN) who either work in department number 4 (E.Dno =
4) or directly supervise an employee who works in department 4 (E2.SuperSSN = E.SSN). The IN
clause ensures that supervisors of employees in department 4 are included.

(iv) Retrieve the names of employees who have no dependents.


SELECT E.Name
FROM EMP E
WHERE NOT EXISTS (
SELECT D.ESSN
FROM DEPENDENT D
WHERE E.SSN = D.ESSN
);
Explanation: This query uses NOT EXISTS to find employees (E.Name) who do not have any
dependents. It checks that no entries exist in the DEPENDENT table for the employee's SSN.
(v) Retrieve each department number, the number of employees in the department and their
average salary.
SELECT E.Dno, COUNT(*) AS Num_Employees, AVG(E.Salary) AS Avg_Salary
FROM EMP E
GROUP BY E.Dno;
Explanation: This query groups employees by their department number (E.Dno), counts the number
of employees in each department (COUNT(*)), and calculates the average salary (AVG(E.Salary)) for
each department.

9. What is an Integrity Constraint? Explain the importance of Referential Integrity Constraint.


Ans- Integrity Constraint
An Integrity Constraint is a set of rules used to ensure the accuracy and consistency of data within a
relational database. These constraints enforce the validity of the data, ensuring that only correct,
consistent, and authorized data is stored in the database. Integrity constraints prevent the entry of
invalid data and help maintain relationships between tables.

There are several types of integrity constraints, including:


1. Domain Constraints: Specify the permissible values for a column.
2. Entity Integrity: Ensures that the primary key for each table is unique and not null.
3. Referential Integrity: Ensures that relationships between tables remain consistent.
4. Unique Constraints: Ensure that a column (or set of columns) contains only unique values.
5. Check Constraints: Specify a condition that must be true for each row in the table.

Referential Integrity Constraint:


Referential Integrity is a crucial type of integrity constraint that ensures the consistency of
relationships between tables in a relational database. It enforces that a **foreign key** value in one
table must either match a **primary key** value in another related table or be null.

Importance of Referential Integrity Constraint:


1. **Maintains Data Consistency**: It ensures that the relationships between tables remain
consistent. For example, if a row in one table references a row in another table via a foreign key, that
referenced row must exist.
2. **Prevents Orphan Records**: It prevents the creation of orphan records—records that reference
non-existent entries in another table. For example, a foreign key constraint will ensure that you
cannot have an order referencing a customer that doesn’t exist.
3. **Ensures Valid Data Relationships**: It ensures that relationships between data (like between a
customer and an order) remain valid and that no invalid data can be entered, which prevents
anomalies in the data.
4. **Cascading Operations**: Referential integrity constraints allow for **cascade delete** or
**cascade update** rules. For example:
- **Cascade Delete**: If a record in the parent table (e.g., Customer) is deleted, all related records in
the child table (e.g., Orders) can be automatically deleted, preventing orphaned rows.
- **Cascade Update**: If a primary key value in the parent table is updated, all related foreign key
values in the child table are updated to maintain consistency.
5. **Prevents Deletion of Referenced Records**: Without referential integrity, you might delete a
record that other records reference, causing invalid foreign key references.

Example of Referential Integrity Constraint

Consider two tables:


- **Employee** table:
- **EmployeeID** (Primary Key)
- **Name**
- **DepartmentID** (Foreign Key)
- **Department** table:
- **DepartmentID** (Primary Key)
- **DepartmentName**
Here, **DepartmentID** in the **Employee** table is a **foreign key** that references
**DepartmentID** in the **Department** table. Referential integrity enforces the following:
- You cannot insert an **Employee** with a **DepartmentID** that does not exist in the
**Department** table.
- If you try to delete a **Department** that is referenced by an employee, the database will either
prevent the deletion or cascade the deletion to the related employees (if cascade delete is enabled).
#### **Referential Integrity Constraint in SQL**
To enforce referential integrity, you can define foreign keys in SQL like this:
CREATE TABLE Department (
DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(100)
);

CREATE TABLE Employee (


EmployeeID INT PRIMARY KEY,
Name VARCHAR(100),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Department(DepartmentID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
- The `ON DELETE CASCADE` ensures that when a row from the **Department** table is deleted, all
employees associated with that department will also be deleted.
- The `ON UPDATE CASCADE` ensures that if the **DepartmentID** is updated in the
**Department** table, the change will propagate to the **Employee** table, maintaining data
consistency.

10. Explain the types of update anomalies in SQL with an example.

Ans: In a relational database, update anomalies occur when there are inconsistencies in the data due
to the way that data is stored and modified. These anomalies typically arise in poorly designed
database schemas, particularly those that do not follow the principles of normalization. Update
anomalies can lead to data integrity issues, redundancy, and difficulties in maintaining data.

There are three primary types of update anomalies:

1. Insertion Anomaly

2. Deletion Anomaly

3. Modification Anomaly

1. Insertion Anomaly:

An insertion anomaly occurs when certain attributes cannot be inserted into the database without
the presence of other attributes. This can happen in scenarios where data is interdependent.

Example:**

In this table, if we want to insert a new course, say **History**, but do not have a student enrolled
in it yet, we can't add the course without also adding a **StudentID**, **StudentName**, and
**Instructor**. This is problematic if the course is not yet associated with any student.

Issue: - If a new **History** course needs to be added but there are no students yet enrolled, it
cannot be represented in this table without creating a misleading record for a student who is not
actually taking that course.

2. Deletion Anomaly
A **deletion anomaly** occurs when the deletion of a certain piece of data inadvertently results in
the loss of additional data that is not intended to be deleted. This often happens when multiple
types of information are stored in a single row.

Example:**

If we delete the record for **Jane Doe**, who is taking Math with Dr. Smith, we also lose the
information that **Dr. Smith** teaches the **Math** course. This data is lost even though we may
want to keep the record of the instructor.

Issue**:

- Important information (instructor's information) is lost because it was stored redundantly in


conjunction with the student data. If there were no other students in Math, Dr. Smith's information
would be deleted with Jane Doe's record.

3. Modification Anomaly

A **modification anomaly** occurs when changes to a piece of data require multiple rows to be
updated, leading to potential inconsistencies if all rows are not updated properly.

Example:**

Now suppose **Dr. Smith** changes his name to **Dr. Johnson**. If we fail to update all
occurrences of **Dr. Smith** in the table, we might end up with some records showing the old name
and some with the new name, leading to data inconsistency.

Issue**:

- If you forget to update the name for **Jane Doe**, the data now has two different names
associated with the same instructor, which creates confusion and inconsistency in the database.

11. What is SQL J? How it is different from JDBC?

Ans - SQLJ is a set of programming extensions for embedding SQL (Structured Query Language)
statements directly within Java code. It allows developers to combine Java and SQL in a more
structured and readable manner, compared to the traditional approach of using JDBC (Java Database
Connectivity). SQLJ provides a simpler, more declarative syntax for embedding SQL into Java
programs, similar to how embedded SQL works with other languages like C or COBOL.

Differences:

1. SQL Type:
SQLJ: Primarily supports static SQL, which means SQL queries are predefined and embedded in the
Java code at compile time.

JDBC: Allows dynamic SQL, meaning SQL queries are constructed and executed at runtime.

2. Type Safety:
SQLJ: Offers strong type safety. It checks if the SQL query matches the
expected data types in Java during the compile phase, preventing type-related
issues.
JDBC: Is less type-safe, since type checking occurs at runtime. The developer
needs to ensure the correct mapping between SQL result types and Java types,
which may lead to runtime exceptions if mismatches occur.
3. Code Complexity:

SQLJ: Provides cleaner and more readable code by allowing SQL queries to be embedded directly in
Java using #sql syntax.

JDBC: Tends to be more verbose and complex, requiring explicit handling of SQL queries as strings,
setting parameters, and managing ResultSet objects.

4. Performance:

SQLJ: Generally provides better performance for static SQL, as queries are precompiled, and
execution plans can be optimized by the database engine in advance.

JDBC: Performance can vary depending on the complexity of dynamic queries.

5. Development Process:

SQLJ: Requires an additional precompilation step. SQLJ code must be processed by a translator that
converts SQLJ code into standard Java code.

JDBC: Is directly supported by the Java language, so no precompilation is necessary.

6. Error Handling:

SQLJ: Since SQL is statically checked at compile time, many SQL-related errors can be caught before
runtime.

JDBC: Since SQL is executed at runtime, errors are encountered during query execution, making error
handling more complex.

12. Write a short note on granting and revoking of privileges in SQL. Bring out the different clauses
of SELECT-FROM-WHERE-GROUP-HAVING with an example for each.

13. Demonstrate working of Assertion & Triggers in database? Explain with an example.
Ans - 1. Assertions in a Database:
Assertions are database constraints used to enforce conditions or rules across multiple tables or
records. Unlike primary keys, foreign keys, or unique constraints, which are tied to a single table,
assertions are typically used for more complex, inter-table constraints. They ensure that certain
conditions are always true for the data in the database.

How Assertions Work:


- Assertions are global constraints in a database that must hold true for the entire database.
- They are evaluated automatically whenever a data manipulation operation (INSERT, UPDATE,
DELETE) occurs that could potentially violate the assertion.
- If a data modification would violate an assertion, the database prevents the modification, ensuring
data integrity.
Syntax:
CREATE ASSERTION assertion_name
CHECK (condition);
assertion_name: A unique name for the assertion.
condition: A boolean condition or expression that must be true for the database to remain in a valid
state.

Example:
Suppose you have two tables: `EMPLOYEES` (storing employee data) and `DEPARTMENTS` (storing
department data). You want to ensure that the total salary of employees in a department never
exceeds a set budget for that department.
CREATE ASSERTION salary_budget_check
CHECK (
NOT EXISTS (
SELECT D.DNum
FROM DEPARTMENTS D
WHERE (SELECT SUM(E.Salary)
FROM EMPLOYEES E
WHERE E.Dno = D.DNum) > D.Budget
)
);
This assertion ensures that the sum of employee salaries in any department does not exceed that
department’s budget.
Limitations:
- Assertions are not commonly supported by all databases (e.g., many popular DBMSs like MySQL do
not support assertions directly).
- Assertions can be expensive to enforce because the database system has to evaluate the condition
every time relevant data is modified.
- They are non-standard and database-dependent, meaning that using them might not work in all
databases or could lead to performance issues.
2. Triggers in a Database:
Triggers are special procedures or database scripts that automatically execute (or "fire") in response to
certain events in the database, such as `INSERT`, `UPDATE`, or `DELETE` operations on a particular
table. Triggers are a powerful tool to automate certain processes and enforce business rules or data
integrity.
How Triggers Work:
- Triggers are associated with a specific table or view.
- They are activated automatically before or after a specific type of data modification (like INSERT,
UPDATE, or DELETE) occurs on that table.
- Triggers can be defined to execute **BEFORE** or **AFTER** the event happens, which allows you
to either enforce constraints or apply changes as soon as the event is triggered.

Types of Triggers:
1. BEFORE Trigger: Executes before the triggering event (e.g., before an insert).
2. AFTER Trigger: Executes after the triggering event has completed.
3. INSTEAD OF Trigger: Used for views, allowing the trigger to substitute or override the standard
operation (e.g., for complex views that are not inherently updatable).

Syntax:
CREATE TRIGGER trigger_name
{ BEFORE | AFTER | INSTEAD OF } { INSERT | UPDATE | DELETE }
ON table_name
[ FOR EACH ROW ]
BEGIN
-- Trigger actions (SQL statements)
END;
- trigger_name: The unique name of the trigger.
- { BEFORE | AFTER | INSTEAD OF }: Specifies whether the trigger should run before, after, or instead of
the actual operation.
- { INSERT | UPDATE | DELETE }: Specifies the event that fires the trigger.
- table_name: The table to which the trigger is bound.
- FOR EACH ROW: Specifies that the trigger should be fired once for each row affected by the event
(common for row-level triggers).

Example:
Suppose you have a `SALES` table and you want to automatically update the `TOTAL_SALES` column in
the `EMPLOYEES` table every time a new sale is recorded.
CREATE TRIGGER update_total_sales
AFTER INSERT ON SALES
FOR EACH ROW
BEGIN
UPDATE EMPLOYEES
SET TOTAL_SALES = TOTAL_SALES + :NEW.amount
WHERE EMPLOYEES.id = :NEW.employee_id;
END;
- This trigger fires AFTER an `INSERT` on the `SALES` table and updates the `TOTAL_SALES` of the
employee involved in the sale. The `:NEW` keyword refers to the newly inserted row in the `SALES`
table.

14. Consider the Sailors-Boats-Reserves DB described


s (sid, sname, rating, age)
b (bid, bname, color)
r (sid, bid, date)
Write each of the following queries in SQL.
1. Find the colors of boats reserved by Alber.
SELECT b.color
FROM Sailors s
JOIN Reserves r ON s.sid = r.sid
JOIN Boats b ON r.bid = b.bid
WHERE s.sname = 'Alber';
Explanation: This query joins the Boats, Reserves, and Sailors tables. It filters based on the
sailor name 'Alber' and retrieves the colors of the boats (b.color) that Alber reserved.
2. Find the boat reservation date of Akber
SELECT r.date
FROM Sailors s
JOIN Reserves r ON s.sid = r.sid
WHERE s.sname = 'Akber';
Explanation: This query joins the Reserves and Sailors tables to find the reservation date
(r.date) for the sailor named 'Akber'.
3. Find all sailor ids of sailors who have a rating of at least 8 or reserved boat 103.
SELECT DISTINCT s.sid
FROM Sailors s
LEFT JOIN Reserves r ON s.sid = r.sid
WHERE s.rating >= 8
OR r.bid = 103;
Explanation: This query finds all sailor IDs (s.sid) of sailors who either have a rating of 8 or
higher (s.rating >= 8) or have reserved boat 103 (r.bid = 103). The LEFT JOIN ensures all
sailors are considered, even if they haven't reserved a boat.
4. Find the names of sailors who have not reserved a boat whose name contains the string
“storm”. Order the names in ascending order.
SELECT s.sname
FROM Sailors s
WHERE s.sid NOT IN (
SELECT r.sid
FROM Reserves r
JOIN Boats b ON r.bid = b.bid
WHERE b.bname LIKE '%storm%'
)
ORDER BY s.sname ASC;
Explanation: This query retrieves the names of sailors (s.sname) who have not reserved a
boat with the name containing 'storm'. It uses a subquery to find the sid of sailors who
reserved such boats and excludes them from the final result using NOT IN. The results are
ordered in ascending order (ORDER BY s.sname ASC).
5. Find the sailor ids of sailors with age over 20 who have not reserved a boat whose name
includes the string “thunder”.
SELECT s.sid
FROM Sailors s
WHERE s.age > 20
AND s.sid NOT IN (
SELECT r.sid
FROM Reserves r
JOIN Boats b ON r.bid = b.bid
WHERE b.bname LIKE '%thunder%'
);
Explanation: This query retrieves the sailor IDs (s.sid) of sailors who are over 20 years old
(s.age > 20) and who have not reserved a boat with the name containing 'thunder'. It uses a
subquery to find and exclude sailors who reserved such boats.

15. Explain stored procedure language in SQL with an example.


Ans - Stored Procedure Language in SQL refers to the use of stored procedures, which are a set of
SQL statements that can be executed as a single unit. Stored procedures are stored in the database
and can be invoked by applications or other SQL scripts. They encapsulate complex business logic
and can be reused across applications, promoting modularity and maintainability.

Advantages of Stored Procedures:**


1. **Performance**: Since stored procedures are precompiled and stored in the database, they can
execute faster than individual SQL statements sent from applications.
2. **Modularity**: They allow you to write complex SQL logic in one place and reuse it without
rewriting the logic each time.
3. **Security**: Stored procedures can encapsulate sensitive operations and restrict direct access to
the underlying tables. Users can be granted permission to execute a stored procedure without
granting permission on the underlying tables.
4. **Maintainability**: Changes can be made in the stored procedure without affecting the
applications that use it, making it easier to maintain and update the database logic.
5. **Reduced Network Traffic**: Instead of sending multiple SQL statements over the network, a
single call to a stored procedure can reduce network overhead.
Syntax for Creating a Stored Procedure**
The general syntax for creating a stored procedure in SQL is as follows:
CREATE PROCEDURE procedure_name
[ (parameter1 datatype, parameter2 datatype, ...) ]
AS
BEGIN
-- SQL statements
END;
- `procedure_name`: The name of the stored procedure.
- `parameter1`, `parameter2`: Optional parameters that can be passed to the procedure.
- `datatype`: The data type for each parameter.
- The SQL statements inside the `BEGIN ... END` block represent the logic of the procedure.

Example of a Stored Procedure**

Let’s consider a simple example where we create a stored procedure to insert a new employee
record into an `Employees` table.

Step 1: Create the Employees Table**


First, we need to create a table for storing employee information:
CREATE TABLE Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
HireDate DATE,
Salary DECIMAL(10, 2)
);
Step 2: Create the Stored Procedure**
Now, we create a stored procedure named `AddEmployee` that takes parameters for the new
employee’s details:
CREATE PROCEDURE AddEmployee
@FirstName VARCHAR(50),
@LastName VARCHAR(50),
@Email VARCHAR(100),
@HireDate DATE,
@Salary DECIMAL(10, 2)
AS
BEGIN
INSERT INTO Employees (FirstName, LastName, Email, HireDate, Salary)
VALUES (@FirstName, @LastName, @Email, @HireDate, @Salary);
END;
Step 3: Execute the Stored Procedure**
To insert a new employee using the `AddEmployee` stored procedure, you would execute it with the
required parameters:
EXEC AddEmployee
@FirstName = 'John',
@LastName = 'Doe',
@Email = '[email protected]',
@HireDate = '2024-10-23',
@Salary = 60000.00;
Explanation of the Example**
1. **Table Creation**: The `Employees` table is created to store employee data.
2. **Stored Procedure**: The `AddEmployee` procedure is defined with parameters for each
employee attribute. The `INSERT` statement within the procedure uses these parameters to insert a
new employee into the `Employees` table.
3. **Execution**: The procedure is called using the `EXEC` statement, passing the necessary values
for the parameters. This executes the SQL statements defined within the stored procedure.

16. Consider the following relation schema


Works(Pname,Cname,salary)
Lives(Pname,Street,City)
Located_in (Cname, city)
Manager(Pname,Mgrname)
Write the SQL queries for the following
i) Find the names of all persons who live in the city Bangalore.
ii) Retrieve the names of all person of "Infosys" whose salary is between Rs .50000
iii)Find the names of all persons who lives and work in the same city
iv)List the names of the people who work for “Tech M” along with the cities they live in.
v)Find the average salary of “Infosys” persons

You might also like