0% found this document useful (0 votes)
55 views30 pages

Question Bank - Module-3 and Module-4 (.5) Key Answers-Updated

dbms question bank with key answers

Uploaded by

Adilyt ytt
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)
55 views30 pages

Question Bank - Module-3 and Module-4 (.5) Key Answers-Updated

dbms question bank with key answers

Uploaded by

Adilyt ytt
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
You are on page 1/ 30

1. What is the importance or nested queries and correlated nested queries.

Give syntax
and examples.

Nested Queries

 Simplifies complex queries by breaking them into smaller, manageable subqueries.


 Enables filtering or calculating values based on the result of another query.
 Avoids the need for complex JOIN operations in some cases.

Syntax

SELECT column1, column2, ...


FROM table1
WHERE column IN (SELECT column FROM table2 WHERE condition);

Example

Suppose you have two tables: Employees and Departments. You want to find the names of
employees who work in the "Sales" department.

SELECT FirstName, LastName


FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE
DepartmentName = 'Sales');

In this example, the inner query (SELECT DepartmentID FROM Departments WHERE
DepartmentName = 'Sales') returns the DepartmentID for the Sales department. The outer
query uses this result to filter employees who work in that department.

Correlated Nested Queries

 Allows for row-by-row evaluation and comparison.


 Executes the inner query for each row processed by the outer query, enabling queries that
require dynamic filtering based on outer query values.
 Often used for comparisons like finding rows that exceed some calculated value in the
same or related rows.

Syntax

SELECT column1, column2, ...


FROM table1 outer_alias
WHERE condition AND column IN (SELECT column FROM table2 inner_alias
WHERE inner_condition AND outer_alias.column = inner_alias.column);
Example

Suppose you want to find employees who earn more than the average salary in their
department.

SELECT FirstName, LastName


FROM Employees e
WHERE Salary > (SELECT AVG(Salary) FROM Employees WHERE
DepartmentID = e.DepartmentID);

In this example, the inner query (SELECT AVG(Salary) FROM Employees WHERE
DepartmentID = e.DepartmentID) calculates the average salary for each department, using
the DepartmentID from the outer query. The outer query compares each employee's salary
to the average salary in their department.

2. Write the EXISTS and UNIQUE Functions in SQL with syntax and Example.

Both EXISTS and UNIQUE are used for testing conditions in SQL, particularly in subqueries.
They help to refine query logic for more complex data retrieval scenarios.

1. EXISTS Function

The EXISTS function is used to check if a subquery returns any results. It returns TRUE if the
subquery returns at least one row and FALSE if the subquery returns no rows.

Syntax

sql
Copy code
SELECT column1, column2, ...
FROM table1
WHERE EXISTS (SELECT 1 FROM table2 WHERE condition);

 EXISTS evaluates whether the inner subquery produces any result.


 If the inner query produces rows, the EXISTS condition is satisfied.

Example

Retrieve the names of employees who work in departments with at least one project.

SELECT FirstName, LastName


FROM Employees e
WHERE EXISTS (SELECT 1 FROM Projects p WHERE p.DepartmentID =
e.DepartmentID);

In this example, the subquery checks if there is at least one project in the same department as the
employee. If so, the EXISTS clause returns TRUE, and the employee's name is selected.

2. UNIQUE Function

The UNIQUE function is used to ensure that a subquery returns unique results, meaning no
duplicate rows exist. If the subquery results are all unique, it returns TRUE; otherwise, it returns
FALSE.

Syntax

SELECT column1, column2, ...


FROM table1
WHERE UNIQUE (SELECT column FROM table2 WHERE condition);

 The subquery checks for duplicates in the result set.


 If no duplicates are found, the condition is satisfied.

Example

Retrieve the departments where each employee has a unique salary.

SELECT DepartmentName
FROM Departments d
WHERE UNIQUE (SELECT Salary FROM Employees e WHERE e.DepartmentID =
d.DepartmentID);

In this example, the subquery ensures that all salaries in each department are unique. If salaries
are unique for a department, the UNIQUE condition returns TRUE, and the department name is
selected.

 EXISTS is used to check the existence of rows in a subquery.


It returns TRUE if the subquery returns any rows.
 UNIQUE ensures that the subquery results contain only unique rows.
It returns TRUE if the subquery results are distinct.

Both functions are useful for filtering data based on the presence or absence of certain
conditions, allowing for more refined SQL queries.

3. What are the different types of joining the tables with syntax and example.
In SQL, joining tables allows you to combine rows from two or more tables based on related
columns. Different types of joins serve different purposes based on how you want to retrieve
the data. The main types of joins in SQL are:

1. INNER JOIN

An INNER JOIN returns only the rows that have matching values in both tables. If there's no
match, those rows are excluded from the result.

Syntax

SELECT column1, column2, ...


FROM table1
INNER JOIN table2
ON table1.common_column = table2.common_column;

Example

Retrieve a list of employees and their department names where the employee works in a
department.

SELECT Employees.FirstName, Employees.LastName,


Departments.DepartmentName
FROM Employees
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

Here, only employees with a matching department will be shown.

2. LEFT JOIN (or LEFT OUTER JOIN)


A LEFT JOIN returns all rows from the left table (table1), and the matched rows from the
right table (table2). If no match is found, NULL values are returned for columns from the
right table.

Syntax

SELECT column1, column2, ...


FROM table1
LEFT JOIN table2
ON table1.common_column = table2.common_column;

Example

Retrieve all employees and their department names, including employees who do not belong
to any department.

SELECT Employees.FirstName, Employees.LastName,


Departments.DepartmentName
FROM Employees
LEFT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

In this case, all employees will be listed, even those who are not assigned to any department.
If an employee does not belong to a department, the DepartmentName will be NULL.

3. RIGHT JOIN (or RIGHT OUTER JOIN)

A RIGHT JOIN is similar to a LEFT JOIN, but it returns all rows from the right table
(table2), and the matched rows from the left table (table1). If no match is found, NULL
values are returned for columns from the left table.

Syntax

SELECT column1, column2, ...


FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;

Example

Retrieve all departments and their employees, including departments that have no
employees.
SELECT Employees.FirstName, Employees.LastName,
Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

In this example, all departments will be listed, even those with no employees. If no
employees belong to a department, the employee columns will be NULL.

4. FULL JOIN (or FULL OUTER JOIN)

A FULL JOIN returns all rows when there is a match in either left or right table. Rows that
do not have a match in either table will have NULL in the non-matching columns.

Syntax

SELECT column1, column2, ...


FROM table1
FULL JOIN table2
ON table1.common_column = table2.common_column;

Example

Retrieve all employees and departments, even if some employees are not in a department
and some departments have no employees.

SELECT Employees.FirstName, Employees.LastName,


Departments.DepartmentName
FROM Employees
FULL JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID;

This query retrieves all employees and departments. For employees not in a department, the
department columns will be NULL. For departments with no employees, the employee
columns will be NULL.

5. CROSS JOIN

A CROSS JOIN returns the Cartesian product of the two tables, meaning every row from the
first table is combined with every row from the second table. This is rarely used unless you
want all possible combinations of rows between two tables.
Syntax

SELECT column1, column2, ...


FROM table1
CROSS JOIN table2;

Example

Retrieve all possible combinations of employees and departments.

SELECT Employees.FirstName, Employees.LastName,


Departments.DepartmentName
FROM Employees
CROSS JOIN Departments;

This query returns every possible pairing of employees and departments, regardless of actual
relationships between them.

6. SELF JOIN

A SELF JOIN is when a table is joined with itself. It is often used when you need to
compare rows within the same table.

Syntax

SELECT a.column1, b.column2, ...


FROM table1 a
INNER JOIN table1 b
ON a.common_column = b.common_column;

Example

Retrieve a list of employees and their supervisors, assuming the Employees table contains a
column SupervisorID referencing the EmployeeID.

SELECT e.FirstName AS EmployeeName, s.FirstName AS SupervisorName


FROM Employees e
INNER JOIN Employees s
ON e.SupervisorID = s.EmployeeID;

In this query, the Employees table is joined with itself to match employees with their
supervisors.
Join Types

1. INNER JOIN: Returns only matching rows from both tables.


2. LEFT JOIN: Returns all rows from the left table and matching rows from the right table,
with NULLs for non-matches.
3. RIGHT JOIN: Returns all rows from the right table and matching rows from the left
table, with NULLs for non-matches.
4. FULL JOIN: Returns all rows where there is a match in either table, with NULLs for
non-matches.
5. CROSS JOIN: Returns the Cartesian product of both tables.
6. SELF JOIN: Joins a table with itself to compare rows within the same table.

These joins provide flexibility in querying data from multiple related tables and allow more
complex data retrieval operations in SQL.

4. Explain all the aggregate functions in SQL.


Here are the main aggregate functions:
1. COUNT(): Counts the number of rows in a set.
Example: SELECT COUNT(*) FROM employees;
2. SUM(): Adds up the values of a specified column.
Example: SELECT SUM(salary) FROM employees;
3. AVG(): Calculates the average value of a specified column.
Example: SELECT AVG(salary) FROM employees;
4. MIN(): Returns the minimum value in a set.
Example: SELECT MIN(salary) FROM employees;
5. MAX(): Returns the maximum value in a set.
Example: SELECT MAX(salary) FROM employees;

5. Illustrate the group by and having clauses with syntax and example.

Students Table

Assuming we have the following students table:

id name age grade department


1 Alice 20 A CS
2 Bob 21 B CS
3 Charlie 22 A EE
4 David 20 C EE
5 Eva 21 B ME
6 Frank 22 A ME
Using GROUP BY

Example 1: Average Age by Department

To find the average age of students in each department:

SELECT department, AVG(age) AS average_age


FROM students
GROUP BY department;

Result

department average_age
CS 20.5
EE 21.0
ME 21.5

Using HAVING

Example 2: Departments with Average Age Greater than 21

To find departments where the average age of students is greater than 21:

SELECT department, AVG(age) AS average_age


FROM students
GROUP BY department
HAVING AVG(age) > 21;

Result

department average_age
ME 21.5

 GROUP BY is used to aggregate data based on one or more columns in this


case, department).
 HAVING is used to filter the results after aggregation (here, filtering for
average ages greater than 21).

6. What is trigger? Explain the mechanism of trigger with syntax and example.
AND
7. Describe before and after triggers with example.
A trigger in SQL is a set of SQL statements that automatically executes when a specified
event occurs on a table or a view. These events can be INSERT, UPDATE, or DELETE
operations on a table. Triggers are used to enforce business rules, ensure data integrity,
automate tasks, and audit changes.

Trigger Mechanism

1. Event: Specifies the event that triggers the execution of the trigger (i.e., INSERT,
UPDATE, or DELETE).
2. Timing: Determines whether the trigger is executed BEFORE or AFTER the event.
3. Action: The SQL statements or logic that the trigger executes in response to the event.

Syntax

CREATE TRIGGER trigger_name


{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- SQL statements to execute
END;

Components of the Syntax

 trigger_name: The name of the trigger.


 {BEFORE | AFTER}: Specifies when the trigger is fired (before or after the event).
 {INSERT | UPDATE | DELETE}: Specifies the event that activates the trigger.
 ON table_name: The table on which the trigger is defined.
 FOR EACH ROW: The trigger is executed for each affected row.
 BEGIN...END: The block where SQL statements are executed.

Before and After Triggers

 BEFORE Trigger: Executes before the triggering event (e.g., before an INSERT,
UPDATE, or DELETE occurs). This is useful when you want to modify the data before
it is inserted or updated.
 AFTER Trigger: Executes after the triggering event has occurred. It is used when you
want to take some action after the event (e.g., logging changes after an update).

Example 1: BEFORE Trigger

Let’s assume we have an employees table, and we want to ensure that the salary of an
employee cannot be set below 30000 before inserting or updating.
Table: employees

emp_id name salary


1 Alice 50000
2 Bob 60000

BEFORE INSERT Trigger

CREATE TRIGGER before_salary_insert


BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF NEW.salary < 30000 THEN
SET NEW.salary = 30000;
END IF;
END;

Explanation

 BEFORE INSERT: The trigger fires before a row is inserted into the employees table.
 NEW.salary: Refers to the value being inserted into the salary column.
 IF NEW.salary < 30000 THEN SET NEW.salary = 30000: Ensures that the salary is
not less than 30000 before the row is inserted.

Example Usage

INSERT INTO employees (name, salary) VALUES ('David', 25000);

The trigger will change the salary to 30000 since 25000 is below the minimum threshold:

emp_id name salary


1 Alice 50000
2 Bob 60000
3 David 30000

Example 2: AFTER Trigger

Now, let’s create an AFTER UPDATE trigger to log any salary changes in a separate
salary_log table.

Table: salary_log
log_id emp_id old_salary new_salary change_date
1 1 50000 55000 2023-09-21 10:10:10

AFTER UPDATE Trigger

CREATE TRIGGER after_salary_update


AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_log (emp_id, old_salary, new_salary, change_date)
VALUES (OLD.emp_id, OLD.salary, NEW.salary, NOW());
END;

Explanation

 AFTER UPDATE: The trigger fires after the UPDATE event on the employees table.
 OLD.salary: Refers to the salary before the update.
 NEW.salary: Refers to the salary after the update.
 NOW(): Captures the current timestamp when the trigger is executed.
 INSERT INTO salary_log: Inserts the details of the salary change into the salary_log
table.

Example

UPDATE employees
SET salary = 55000
WHERE emp_id = 1;

The trigger will log the salary change in the salary_log table:

log_id emp_id old_salary new_salary change_date


1 1 50000 55000 2023-09-21 10:10:10

Key Differences between BEFORE and AFTER Triggers

1. BEFORE Trigger:
 Executes before the event (e.g., INSERT, UPDATE, DELETE).
 Allows you to modify or validate data before it is saved.
 Example: Ensuring data consistency (e.g., ensuring a minimum salary).
2. AFTER Trigger:
 Executes after the event.
 Used when you need to perform actions based on the completed event
(e.g., logging changes).
 Example: Logging data changes into a log table.
 Triggers automate tasks and enforce business logic.
 BEFORE Triggers: Useful for validating or modifying data before it is saved.
 AFTER Triggers: Used to perform tasks after the data has been inserted, updated, or
deleted.

8. Define view. Discuss the SQL create view statement with example.
View in SQL is a virtual table created from a basic SELECT query that retrieves data
from one or more columns of a single table. It can be used to display specific data
without giving direct access to the underlying table.

Syntax
CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
Suppose we have a table called students:
student_id name grade
1 John A
2 Sarah B
3 Mike A

We want to create a view that shows only the names and grades of students who received
an "A" grade.

CREATE VIEW top_students AS


SELECT name, grade
FROM students
WHERE grade = 'A';

Now, the view top_students will display only students with an "A" grade:

SELECT * FROM top_students;

Result

name grade
John A
Mike A
This view simplifies accessing specific data without modifying the original students
table.

9. How do you declare and invoke SQL functions?

A function in SQL is a reusable piece of code that can accept parameters, perform a task
(like calculations or data manipulation), and return a single value. Functions are useful for
simplifying queries, modularizing complex logic, and improving code reusability.

Declaring a SQL Function

To declare a function in SQL, you use the CREATE FUNCTION statement. The function
can accept input parameters and return a specific data type.

Syntax for Declaring a Function

CREATE FUNCTION function_name (parameter1 datatype, parameter2 datatype,


...)
RETURNS return_datatype
AS
BEGIN
-- Function logic goes here
RETURN value;
END;

 function_name: Name of the function.


 parameter1, parameter2: Input parameters for the function.
 return_datatype: The data type of the value the function will return.
 RETURN value: The value returned by the function.

Example: Declaring a Function

Suppose we want to create a function that calculates the square of a number.

CREATE FUNCTION calculate_square (number INT)


RETURNS INT
AS
BEGIN
RETURN number * number;
END;

This function takes an integer number as input and returns its square.

Invoking a SQL Function


Once the function is declared, you can invoke it using a SELECT statement or in other
SQL queries.

Syntax for Invoking a Function

SELECT function_name(arguments);

Example: Invoking the Function

Using the previously created function calculate_square, we can call it with an argument:

SELECT calculate_square(4);

Result

calculate_square(4)
16

Example with Table Data

You can also use the function inside queries involving table data. Assume you have a table
numbers:

num
2
3
5

You can apply the calculate_square function to each row:

SELECT num, calculate_square(num) AS square


FROM numbers;

Result

num square
2 4
3 9
5 25

 Declaring a function is done with CREATE FUNCTION and includes parameters,


logic, and a return value.
 Invoking a function is done using a SELECT statement with the function name and
the required arguments.
 SQL functions are powerful tools to enhance code reusability and simplify complex
queries.

10. Illustrate stored procedures with syntax and example .

A stored procedure in SQL is a precompiled set of SQL statements that can be executed
as a unit. It accepts input parameters, performs operations, and can return values. Stored
procedures improve performance, allow code reuse, and enhance security.

Syntax

CREATE PROCEDURE procedure_name (parameters)


AS
BEGIN
-- SQL statements
END;

Example

CREATE PROCEDURE insert_employee (@name NVARCHAR(50), @salary INT)


AS
BEGIN
INSERT INTO employees (name, salary) VALUES (@name, @salary);
END;

Invoking

EXEC insert_employee 'John', 50000;

11. Discuss update of a View with example.

In SQL, updating a view allows you to modify the underlying table's data through the
view. However, not all views are updatable—only those that meet certain criteria, like
being based on a single table without complex joins, aggregate functions, or DISTINCT
clauses.

Criteria for an Updatable View


 The view must be based on a single table.
 The view should not use GROUP BY, DISTINCT, or aggregate functions.
 All non-nullable columns in the base table must be included in the view.

Example: Updating an Updatable View

Assume we have a students table:


student_id name grade
1 John B
2 Sarah A
3 Mike C

Create a view to show student names and grades:

CREATE VIEW student_grades AS


SELECT student_id, name, grade
FROM students;

You can update the students table through this view:

UPDATE student_grades
SET grade = 'A'
WHERE student_id = 3;

Result (after update)

student_id name grade


1 John B
2 Sarah A
3 Mike A

This updates the grade for student Mike in the base students table.

12. What is alter and drop command? Give syntax and example.

The ALTER command in SQL is used to modify an existing database object, such as
adding, deleting, or changing columns in a table. The DROP command is used to remove
a database object entirely.

ALTER Command

Syntax

ALTER TABLE table_name


ADD column_name datatype;

ALTER TABLE table_name


DROP COLUMN column_name;

Example: Adding a column to the students table


ALTER TABLE students
ADD grade CHAR(1);

DROP Command

Syntax
DROP TABLE table_name;

DROP VIEW view_name;


Example

Dropping the students table:


DROP TABLE students;
This will permanently remove the students table and its data.

13. What is normalization? Explain the practical use of normal forms.

Normalization is a process in database design that organizes data to reduce redundancy


and improve data integrity. It involves structuring a relational database in a way that
ensures each piece of data is stored only once. The process typically involves dividing
large tables into smaller ones and defining relationships between them.

Objectives of Normalization
 Eliminate Redundant Data: Reduce duplication of data across the database.
 Improve Data Integrity: Ensure that the data remains accurate and consistent.
 Simplify Database Maintenance: Make updates easier by having data structured
logically.

Normal Forms

Normalization is often carried out in stages, known as normal forms (NF). The most
commonly used normal forms include:

1. First Normal Form (1NF)


o Ensures that all columns contain atomic (indivisible) values and that each
column contains only one value per row.
o Practical Use: Eliminates repeating groups and ensures that the table is
structured properly.

2. Second Normal Form (2NF)


o Builds on 1NF by ensuring that all non-key attributes are fully functionally
dependent on the primary key.
o Practical Use: Reduces redundancy by eliminating partial dependencies.

3. Third Normal Form (3NF)


o Ensures that all attributes are not only dependent on the primary key but also
independent of each other (no transitive dependency).
o Practical Use: Further reduces redundancy and improves data integrity.

4. Boyce-Codd Normal Form (BCNF)


o A stronger version of 3NF that addresses certain types of anomalies.
o Practical Use: Ensures that every determinant is a candidate key.

Practical Use of Normal Forms

 Data Integrity: By organizing data into normal forms, you ensure that updates,
deletions, and insertions do not lead to inconsistencies.
 Efficient Queries: Normalized databases can improve query performance as they are
structured logically.
 Easier Maintenance: Changes to data structures are more manageable and less prone
to errors, as data is not duplicated across multiple tables.
 Scalability: A well-normalized database can more easily accommodate growth and
changes in data without significant restructuring.

Example

Consider a simple table of orders:

OrderID CustomerName Product Quantity


1 Alice Widget A 10
1 Alice Widget B 5
2 Bob Widget A 20

1NF: Ensure atomic values:

 Split Product into a separate table to avoid repeating CustomerName.

2NF: Remove partial dependencies:

 Create a separate Customers table to ensure CustomerName is dependent only on


OrderID.

3NF: Remove transitive dependencies:

 Ensure all attributes in Products relate only to the product itself, not to
CustomerName.

By following these normal forms, you create a well-structured database that minimizes
redundancy and enhances integrity.
14. Illustrate First, Second and Third normal forms with examples.

First (1NF), Second (2NF), and Third Normal Forms (3NF) using a student example.

Unnormalized Table

Let's start with an unnormalized table of students and their courses:

StudentID StudentName Courses


1 John Math, Science
2 Sarah English
3 Mike Math, History

First Normal Form (1NF)

Definition: A table is in 1NF if all columns contain atomic values, and each column
contains only one value per row.

Example: To convert to 1NF, we need to separate the courses into individual rows:

StudentID StudentName Course


1 John Math
1 John Science
2 Sarah English
3 Mike Math
3 Mike History

Second Normal Form (2NF)

Definition: A table is in 2NF if it is in 1NF and all non-key attributes are fully
functionally dependent on the primary key. This means there should be no partial
dependencies of any column on a composite key.

Example: In our 1NF table, StudentName is dependent only on StudentID. To achieve


2NF, we can split the table into two:

Students Table:

StudentID StudentName
1 John
2 Sarah
StudentID StudentName
3 Mike

Courses Table:

StudentID Course
1 Math
1 Science
2 English
3 Math
3 History

Third Normal Form (3NF)

Definition: A table is in 3NF if it is in 2NF and all the attributes are only dependent on
the primary key, eliminating transitive dependencies.

In our example, there are no transitive dependencies, but let’s illustrate a scenario where
they might exist.

Assume we also have a Department for each course:

StudentID StudentName Course Department


1 John Math Mathematics
1 John Science Science
2 Sarah English Humanities
3 Mike Math Mathematics
3 Mike History Social Studies

To convert to 3NF, we need to eliminate the transitive dependency (Department depends


on Course)

Students Table

StudentID StudentName
1 John
2 Sarah
3 Mike

Courses Table
Course Department
Math Mathematics
Science Science
English Humanities
History Social Studies

StudentCourses Table

StudentID Course
1 Math
1 Science
2 English
3 Math
3 History

 1NF: Ensured all values are atomic, resulting in separate rows for each course.
 2NF: Eliminated partial dependencies by separating student information and course
enrollment into different tables.
 3NF: Removed transitive dependencies by separating course details and their departments
into a distinct table.

This structured approach reduces redundancy and improves data integrity in the database.

15. Define functional dependency with a suitable example.

Functional Dependency is a relationship between two attributes, typically between a key


and a non-key attribute in a database. It occurs when the value of one attribute (or a group
of attributes) uniquely determines the value of another attribute.

Definition

If you have two attributes, A and B, we say that B is functionally dependent on A


(A B) if, for each value of A, there is exactly one value of B associated with it.

Example

Consider a simple table of students:

StudentID StudentName Course


1 John Math
2 Sarah English
StudentID StudentName Course
3 Mike Science
1 John Science
In this table
 StudentID uniquely identifies each student.
 StudentName is functionally dependent on StudentID because knowing the StudentID
allows you to determine the StudentName.

Functional Dependency

StudentID→StudentName
 This means that for each StudentID, there is a single corresponding StudentName.
However, in this case, StudentID does not uniquely determine Course because John is
enrolled in two courses (Math and Science).
 Functional dependency helps to establish relationships within the data and is essential
for database normalization, ensuring that data is structured efficiently and consistently.

16. Write all the Inference rules for functional dependency.

Inference rules for functional dependencies are used to derive new functional dependencies
from existing ones. These rules are essential for reasoning about the relationships between
attributes in a database schema. Here are the commonly recognized inference rules:

1. Reflexivity

 If a set of attributes contains another set, then the entire set functionally
determines the smaller set.

2. Augmentation

 If one attribute set determines another, adding attributes to both sides preserves the
dependency.

3. Transitivity

 If one attribute set determines a second, and that second set determines a third, then the
first set determines the third.
4. Union

 If one attribute set determines two separate sets, it can determine the union of those sets.

5. Decomposition

 If one attribute set determines a combination of two sets, it can determine each set
individually.

6. Pseudotransitivity

If one attribute set determines another and a third set combined with that second set
determines a fourth, then combining the first set with the third will determine the fourth.

7. Negation

does not hold, then it does not imply any new dependencies.

Example

Given the following functional dependencies:

From these, you can derive:

These rules are critical for normalizing database schemas and ensuring data integrity.
17. Explain the Equivalence of sets of functional dependencies.
.

The equivalence of sets of functional dependencies refers to the relationship between


two sets of functional dependencies in a database schema. Two sets are considered
equivalent if they imply the same constraints on the data, meaning they enforce the same
rules regarding how attributes relate to one another.

Definition

Importance

Understanding the equivalence of functional dependencies is crucial for several reasons:

1. Normalization: It helps in the process of normalization by ensuring that the schema


adheres to the same rules, regardless of how the dependencies are expressed.
2. Schema Design: It allows database designers to simplify the representation of functional
dependencies without losing information.
3. Query Optimization: Knowing that two sets of dependencies are equivalent can help
optimize queries and improve performance.

Example

Consider the following sets of functional dependencies:

Equivalence Demonstration
 The equivalence of sets of functional dependencies is a key concept in database
theory.
 It helps ensure that the same constraints and relationships are maintained,
facilitating better database design and integrity.
 Understanding this equivalence enables designers to work with simpler or
alternative sets of dependencies without losing important relationships in the data.

18. What is JDBC? Write the JDBC classes and interfaces with examples.

JDBC (Java Database Connectivity) is an API that enables Java applications to connect
to and interact with databases.

JDBC Classes and Interfaces

 DriverManager: Manages database drivers and establishes connections.

Connection con = DriverManager.getConnection(url, user, password);

 Connection: Represents a connection to a specific database.

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",


"user", "password");

 Statement: Used to execute SQL queries.

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("SELECT * FROM students");

 PreparedStatement: Allows executing parameterized SQL queries.

PreparedStatement pstmt = con.prepareStatement("SELECT * FROM students


WHERE id = ?");
pstmt.setInt(1, 1);

 ResultSet: Represents the result set of a query.


while (rs.next()) {
System.out.println(rs.getString("name"));
}

 SQLException: Handles SQL-related errors.

try {
// JDBC code
} catch (SQLException e) {
e.printStackTrace();
}

Simple Example

Here's a quick example that connects to a MySQL database and retrieves student names:

import java.sql.*;

public class JdbcExample {


public static void main(String[] args) {
try {
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user",
"password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT name FROM students");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

JDBC is essential for Java applications to interact with databases effectively.

19. Write a note on SQLJ and Stored procedures.

SQLJ
 SQLJ is a standard that allows developers to embed SQL statements directly within Java
programs.
 It enables static SQL, which means SQL commands are known at compile time,
improving performance and error checking.
 SQLJ translates these embedded SQL statements into standard JDBC calls, making
database interactions easier and more efficient.

Example

#sql {
INSERT INTO students (id, name) VALUES (:id, :name)
};

Stored Procedures

 Stored procedures are precompiled collections of SQL statements stored in the


database.
 They allow complex operations to be executed with a single call, reducing network
traffic and improving performance.
 Stored procedures encapsulate business logic, promoting code reuse and security.

Example

CREATE PROCEDURE GetStudentById(IN studentId INT)


BEGIN
SELECT * FROM students WHERE id = studentId;
END;

20. Discuss the steps the JDBC connections of internet Bookshop.

To establish a JDBC connection for an Internet Bookshop application, you can follow
these steps:

1. Set Up the Environment

 JDBC Driver: Ensure you have the appropriate JDBC driver for the database you
are using (e.g., MySQL, PostgreSQL).
 Include JDBC Library: Add the JDBC driver JAR file to your project's classpath.

2. Load the JDBC Driver

 Use Class.forName() to load the driver class. This step is optional in newer JDBC
versions, as the driver can auto-register.

Class.forName("com.mysql.cj.jdbc.Driver"); // Example for MySQL


3. Establish a Connection

 Use DriverManager.getConnection() to connect to the database. Provide the database


URL, username, and password.

String url = "jdbc:mysql://localhost:3306/bookshop";


String user = "username";
String password = "password";
Connection con = DriverManager.getConnection(url, user, password);

4. Create a Statement or PreparedStatement

 Use a Statement or PreparedStatement object to execute SQL queries.

String query = "SELECT * FROM books";


Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);

5. Execute Queries and Process Results

 Execute your SQL query and process the ResultSet.

while (rs.next()) {
System.out.println("Book Title: " + rs.getString("title"));
}

6. Handle Exceptions

 Use try-catch blocks to handle SQLException and other potential exceptions.

try {
// JDBC code
} catch (SQLException e) {
e.printStackTrace();
}

7. Close Resources

 Close the ResultSet, Statement, and Connection to free up resources.

rs.close();
stmt.close();
con.close();
Example Code
Here’s a simple example combining the steps:

import java.sql.*;

public class BookshopJDBC {


public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/bookshop", "username",
"password");

Statement stmt = con.createStatement();


ResultSet rs = stmt.executeQuery("SELECT * FROM books");

while (rs.next()) {
System.out.println("Book Title: " + rs.getString("title"));
}

rs.close();
stmt.close();
con.close();
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

These steps outline how to establish a JDBC connection for an Internet Bookshop application,
covering driver setup, connection creation, query execution, and resource management.

You might also like