Question Bank - Module-3 and Module-4 (.5) Key Answers-Updated
Question Bank - Module-3 and Module-4 (.5) Key Answers-Updated
Give syntax
and examples.
Nested Queries
Syntax
Example
Suppose you have two tables: Employees and Departments. You want to find the names of
employees who work in the "Sales" department.
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.
Syntax
Suppose you want to find employees who earn more than the average salary in their
department.
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);
Example
Retrieve the names of employees who work in departments with at least one project.
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
Example
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.
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
Example
Retrieve a list of employees and their department names where the employee works in a
department.
Syntax
Example
Retrieve all employees and their department names, including employees who do not belong
to any department.
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.
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
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.
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
Example
Retrieve all employees and departments, even if some employees are not in a department
and some departments have no employees.
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
Example
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
Example
Retrieve a list of employees and their supervisors, assuming the Employees table contains a
column SupervisorID referencing the EmployeeID.
In this query, the Employees table is joined with itself to match employees with their
supervisors.
Join Types
These joins provide flexibility in querying data from multiple related tables and allow more
complex data retrieval operations in SQL.
5. Illustrate the group by and having clauses with syntax and example.
Students Table
Result
department average_age
CS 20.5
EE 21.0
ME 21.5
Using HAVING
To find departments where the average age of students is greater than 21:
Result
department average_age
ME 21.5
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
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).
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
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
The trigger will change the salary to 30000 since 25000 is below the minimum threshold:
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
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:
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.
Now, the view top_students will display only students with an "A" grade:
Result
name grade
John A
Mike A
This view simplifies accessing specific data without modifying the original students
table.
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.
To declare a function in SQL, you use the CREATE FUNCTION statement. The function
can accept input parameters and return a specific data type.
This function takes an integer number as input and returns its square.
SELECT function_name(arguments);
Using the previously created function calculate_square, we can call it with an argument:
SELECT calculate_square(4);
Result
calculate_square(4)
16
You can also use the function inside queries involving table data. Assume you have a table
numbers:
num
2
3
5
Result
num square
2 4
3 9
5 25
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
Example
Invoking
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.
UPDATE student_grades
SET grade = 'A'
WHERE student_id = 3;
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
DROP Command
Syntax
DROP TABLE table_name;
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:
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
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
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:
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.
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
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.
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.
Definition
Example
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.
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
These rules are critical for normalizing database schemas and ensuring data integrity.
17. Explain the Equivalence of sets of functional dependencies.
.
Definition
Importance
Example
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.
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.*;
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
Example
To establish a JDBC connection for an Internet Bookshop application, you can follow
these steps:
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.
Use Class.forName() to load the driver class. This step is optional in newer JDBC
versions, as the driver can auto-register.
while (rs.next()) {
System.out.println("Book Title: " + rs.getString("title"));
}
6. Handle Exceptions
try {
// JDBC code
} catch (SQLException e) {
e.printStackTrace();
}
7. Close Resources
rs.close();
stmt.close();
con.close();
Example Code
Here’s a simple example combining the steps:
import java.sql.*;
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.