DBMS - Module-4 Question Bank
DBMS - Module-4 Question Bank
Qn-2: Define nested queries. Explain their working with suitable examples.
ANS: Nested Query:
A nested query is a query written inside another SQL query. The inner query is
called the nested query (subquery), and the outer query is called the outer query. The
result of the inner query is used by the outer query to retrieve the required data from the
database. Nested queries are generally written inside the WHERE clause of another SQL
query.
Syntax:
SELECT column_name FROM table_name WHERE column_name operator
(SELECT column_name FROM table_name WHERE condition);
Example 1:
Retrieve project numbers of projects that have an employee with last name
‘manjunatha’ as manager.
Here, the inner query first finds project numbers managed by employee
‘manjunatha’. The outer query then retrieves those project numbers from PROJECT
table.
Example 2:
Retrieve names of employees whose salary is greater than all employees in
department 5.
1. IN Operator:
The IN operator is used to check whether a value is present in a set of values
returned by the nested query. If the value matches any one value in the set, the result
becomes TRUE.
Syntax:
Example:
Retrieve project numbers of projects that have employee ‘PLH’ as manager.
Here, the outer query checks whether Pnumber is present in the set returned by the
inner query.
2. ANY Operator:
The ANY operator compares a value with a set of values returned by the nested
query. The condition becomes TRUE if comparison is satisfied with at least one value in
the set. The keyword SOME has the same meaning as ANY.
Syntax:
SELECT column_name FROM table_name WHERE column_name operator
ANY (SELECT column_name FROM table_name WHERE condition);
Example:
If salary is greater than any one salary in department 5:
3. ALL Operator:
The ALL operator compares a value with all values returned by the nested query.
The condition becomes TRUE only if comparison satisfies every value in the set.
Syntax:
Example:
Retrieve employees whose salary is greater than all employees in department 5.
This selects employees whose salary is greater than every salary in department 5.
Qn-4: Explain tuple comparison and use of nested queries in real-world scenarios.
ANS: Tuple Comparison in SQL:
Tuple comparison in SQL is used when more than one attribute value is compared
together in a nested query. The values are written inside parentheses as a tuple, and SQL
compares this group of values with the set of tuples returned by the inner query. This is
useful when comparison depends on multiple columns instead of a single column.
Syntax of Tuple Comparison:
SELECT column_name FROM table_name WHERE (column1, column2) IN
(SELECT column1, column2 FROM table_name WHERE condition);
Here, the outer query compares a pair (or group) of values with the tuple values
returned by the inner query.
2. Employee Management:
Nested queries can retrieve employees whose salary is higher than all employees in a
particular department.
3. College Database:
Nested queries can find students who scored more than the average marks of their class.
4. Online Shopping:
Nested queries can identify customers who purchased products with the highest price in
a category.
These real-world applications show that nested queries are useful for solving
complex data retrieval problems.
Correlated Nested Queries
Qn-5: What are correlated nested queries? Explain their working with example.
EXISTS, NOT EXISTS, UNIQUE
ANS: Correlated Nested Queries:
A correlated nested query is a nested query in which the inner query references an
attribute from the outer query. In this type of query, the inner query is not executed
independently; instead, it is evaluated once for each tuple of the outer query. Therefore,
the inner query depends on the outer query for its execution.
EXISTS Function:
The EXISTS function is used to check whether the result of a correlated nested
query contains at least one tuple.
Returns TRUE → if query result is not empty
Returns FALSE → if query result is empty
Example:
SELECT [Link], [Link] FROM EMPLOYEE AS E WHERE EXISTS
(SELECT * FROM DEPENDENT AS D WHERE [Link] = [Link]);
This selects employees who have at least one dependent.
UNIQUE Function:
The UNIQUE function checks whether the result of a nested query contains
duplicate tuples or not.
Returns TRUE → if no duplicate tuples exist
Returns FALSE → if duplicate tuples exist
It is used to test whether the result of a nested query is a set or multiset.
Syntax:
UNIQUE (subquery)
Example:
Suppose a nested query returns employee department numbers:
If we use:
Thus, the UNIQUE function in SQL is used to test whether a nested query result
contains duplicate tuples or not. Its main purpose is to check the uniqueness of query
results, and it returns TRUE when all tuples are distinct and FALSE when duplicates
exist.
Explicit Sets & Renaming
Qn-7: Explain explicit sets in SQL and how they are used in queries with examples.
ANS: Explicit Sets in SQL:
In SQL, it is possible to use an explicit set of values directly in the WHERE
clause instead of using a nested query. Such a set of values is written inside
parentheses and contains a list of constant values separated by commas. SQL compares
the attribute value with this set and selects the matching tuples.
Syntax:
SELECT column_name FROM table_name WHERE column_name IN
(value1, value2, value3);
Example:
Retrieve the Social Security numbers of all employees who work on project
numbers 1, 2, or 3.
In this query, (1, 2, 3) is an explicit set. SQL checks whether Pno matches any
value in this set, and if a match is found, the corresponding employee SSN is selected.
Thus, explicit sets in SQL are fixed sets of values written directly in the
WHERE clause, and they are used with the IN operator to compare attribute values
easily without using nested queries.
Syntax:
SELECT attribute_name AS new_name FROM table_name;
Here, attribute_name is the original column name and new_name is the renamed
alias displayed in the result.
Example:
Retrieve the last name of each employee and his or her supervisor.
SELECT [Link] AS Employee_name, [Link] AS Supervisor_name
FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.Super_ssn = [Link];
In this query:
[Link] AS Employee_name → renames employee last name as
Employee_name
[Link] AS Supervisor_name → renames supervisor last name as
Supervisor_name
The original database column names remain unchanged, but the query result
shows the new names.
Thus, attribute renaming using AS is used to assign a temporary new name (alias)
to an attribute in SQL query results, making the output clear, meaningful, and easy to
understand without changing the original database table structure.
Joins in SQL
Q-9: Define JOIN. Explain different types of joins in SQL.
ANS:
Definition of JOIN:
A JOIN in SQL is used to combine records from two or more tables based on
a related attribute (common field) between them. It creates a result table by retrieving
matching rows from the joined tables. JOIN is used when data is stored in different
tables but needs to be retrieved together in a single query.
Types of JOIN in SQL:
SQL mainly supports the following types of joins:
1. INNER JOIN
2. OUTER JOIN
3. EQUIJOIN
4. NATURAL JOIN
1. INNER JOIN:
An INNER JOIN returns only those rows that satisfy the join condition in both
tables. It combines records based on matching values in the common attribute. It is the
most commonly used join in SQL.
Example:
SELECT * FROM EMPLOYEE INNER JOIN DEPARTMENT ON
[Link] = [Link];
This query returns only the employee records that have a matching department number.
2. OUTER JOIN:
An OUTER JOIN returns matching rows as well as non-matching rows from one
or both tables. If no match exists, SQL fills the missing values with NULL. Outer joins
are of three types:
LEFT OUTER JOIN → returns all rows from left table and matching rows
from right table.
RIGHT OUTER JOIN → returns all rows from right table and matching
rows from left table.
FULL OUTER JOIN → returns all rows from both tables whether matching
or not.
3. EQUIJOIN:
An EQUIJOIN is a special type of join in which the join condition uses only the
equality (=) operator. If any other operator such as < or > is used, it is not an equijoin.
Example:
SELECT * FROM EMPLOYEE, DEPARTMENT WHERE [Link] =
[Link];
Here, equality operator = is used, so it is an equijoin.
4. NATURAL JOIN:
A NATURAL JOIN is a type of equijoin in which SQL automatically joins tables
by comparing columns having the same name in both tables. The resulting table
contains only one copy of the common attribute.
Example:
SELECT Fname, Lname, Address FROM EMPLOYEE NATURAL JOIN
DEPARTMENT WHERE Dname = 'Research';
Here, SQL automatically joins the tables based on common column names.
Thus, JOIN is used to combine data from multiple tables using common
attributes. Different joins such as INNER JOIN, OUTER JOIN, EQUIJOIN, and
NATURAL JOIN are used depending on the requirement for matching and non-
matching data retrieval.
Qn-10: Explain INNER JOIN, EQUIJOIN and NATURAL JOIN with examples.
ANS:
Multiway Join
Example:
Retrieve the project number, department number, manager’s last name, address,
and birth date.
Aggregate Functions
Qn-13: Explain aggregate functions (COUNT, SUM, AVG, MAX, MIN) with examples.
ANS:
Aggregate Functions in SQL:
2. SUM Function:
The SUM function is used to calculate the total sum of numeric values in a
column.
Example: Find the sum of salaries of all employees
SELECT SUM (Salary) FROM EMPLOYEE;
This query returns the total salary paid to all employees in the EMPLOYEE table.
3. AVG Function:
The AVG function is used to calculate the average (mean) value of numeric data.
Example: Find the average salary of all employees
SELECT AVG (Salary) FROM EMPLOYEE;
This query returns the average salary of employees in the EMPLOYEE table.
4. MAX Function:
The MAX function is used to find the highest value in a column.
Example: Find the maximum salary of employees
SELECT MAX (Salary) FROM EMPLOYEE;
This query returns the highest salary among all employees.
5. MIN Function:
The MIN function is used to find the lowest value in a column.
Example: Find the minimum salary of employees
SELECT MIN (Salary) FROM EMPLOYEE;
This query returns the lowest salary among all employees.
Combined Example:
SQL allows multiple aggregate functions in a single query.
SELECT SUM (Salary), MAX (Salary), MIN (Salary), AVG (Salary) FROM
EMPLOYEE;
This query returns the total salary, highest salary, lowest salary, and average
salary of all employees in one result.
Example 1:
For each department, retrieve the department number, number of employees, and
average salary.
SELECT Dno, COUNT (*), AVG (Salary) FROM EMPLOYEE
GROUP BY Dno;
In this query, SQL groups employees according to department number (Dno).
Then for each department, SQL calculates:
COUNT(*) → Number of employees in that department
AVG(Salary) → Average salary of employees in that department
A separate result is displayed for each department.
Qn-15: Explain HAVING clause and differentiate it from WHERE with examples.
ANS: HAVING Clause in SQL:
The HAVING clause in SQL is used to specify a condition on the summary
information of groups created by the GROUP BY clause. It filters groups after aggregate
functions such as COUNT, SUM, AVG, MAX, and MIN have been applied. Only those
groups that satisfy the HAVING condition are included in the final result. Thus,
HAVING works on groups of tuples, whereas WHERE works on individual tuples.
In this query:
SQL first joins PROJECT and WORKS_ON tables.
Records are grouped by Pnumber and Pname.
COUNT(*) calculates number of employees in each project.
HAVING COUNT(*) > 2 selects only those project groups where more than two
employees are working.
Used to filter individual rows before grouping Used to filter groups after grouping
Example
Using WHERE:
SELECT Dno, AVG(Salary) FROM EMPLOYEE WHERE Salary > 40000
GROUP BY Dno;
Here, WHERE Salary > 40000 filters employee rows first, and then grouping is done.
Using HAVING:
SELECT Dno, AVG(Salary) FROM EMPLOYEE GROUP BY Dno
HAVING AVG(Salary) > 40000;
Here, grouping is done first, average salary is calculated for each department, and
then HAVING selects only those departments whose average salary is greater than
40000.
1. SELECT Clause:
The SELECT clause specifies the attributes or functions to be retrieved from the
database. It determines the columns displayed in the result.
2. FROM Clause:
The FROM clause specifies the relations (tables) required for the query. It may
also include joined tables.
3. WHERE Clause:
The WHERE clause specifies conditions for selecting tuples from the tables. It
may also contain join conditions. Only tuples satisfying the condition are selected.
4. GROUP BY Clause:
The GROUP BY clause divides tuples into groups based on common attribute
values. Aggregate functions are applied separately to each group.
5. HAVING Clause:
The HAVING clause specifies conditions on groups created by GROUP BY. It
filters grouped data after aggregate functions are applied.
6. ORDER BY Clause:
The ORDER BY clause arranges the final result in ascending or descending order
based on specified attributes.
Syntax of Assertion:
The general syntax of assertion is:
CREATE ASSERTION <Name_of_assertion> CHECK (<condition>);
Here:
CREATE ASSERTION → creates a new assertion constraint
Name_of_assertion → name given to the assertion
CHECK(condition) → specifies the condition that must always be TRUE
If the condition becomes FALSE, the assertion is violated.
Working of Assertions:
When an insert, update, or delete operation is performed on the database, SQL
checks whether the assertion condition is satisfied. If the condition remains TRUE, the
operation is allowed. If the condition becomes FALSE, the database rejects the operation
to maintain consistency. Assertions are generally written using conditions similar to the
WHERE clause and often use EXISTS or NOT EXISTS functions.
Example:
Constraint: Salary of an employee should not be greater than the salary of the manager
of that department.
CREATE ASSERTION SALARY_CONSTRAINT
CHECK (
NOT EXISTS (
SELECT * FROM EMPLOYEE E, EMPLOYEE M, DEPARTMENT D
WHERE [Link] > [Link]
AND [Link] = [Link]
AND D.Mgr_ssn = [Link]
)
);
In this assertion:
The assertion name is SALARY_CONSTRAINT.
The nested query checks employees whose salary is greater than their manager’s
salary.
NOT EXISTS ensures that such tuples should not exist in the database.
If any employee salary becomes greater than the manager’s salary, the assertion
condition becomes FALSE and the operation is rejected.
Uses of Assertions:
Used to enforce complex database constraints.
Helps maintain database consistency and correctness.
Useful for conditions involving multiple tables.
Can express constraints that cannot be handled by primary key, foreign key, or
CHECK constraints alone.
Components of Trigger:
A trigger mainly consists of three components:
1. Event:
An event specifies when the trigger should be activated. The trigger executes
automatically whenever the specified database event occurs. SQL supports three main
event types:
INSERT → activated when new records are inserted
UPDATE → activated when existing records are modified
DELETE → activated when records are deleted
Triggers can execute either:
BEFORE the event occurs
AFTER the event occurs
Example:
CREATE TRIGGER ABC BEFORE INSERT ON STUDENTS
This trigger activates before a new record is inserted into the STUDENTS table.
2. Condition:
A condition is an optional part of a trigger. The trigger action executes only if the
specified condition becomes TRUE. If the condition is FALSE, the trigger is skipped.
Conditions are usually written using the WHEN clause.
Example:
WHEN ([Link] > 150000)
This condition checks whether the new salary value is greater than 150000.
3. Action:
The action specifies the operations performed when the event occurs and the
condition becomes TRUE. Actions are written inside the trigger body using SQL
statements.
Example:
BEGIN
[Link] = [Link] * 0.35;
END;
This action automatically calculates and stores the employee bonus as 35% of salary.
Qn-20: Explain triggers with syntax and examples for INSERT, UPDATE and DELETE
operations.
ANS: Triggers in SQL:
A trigger is a procedure that executes automatically whenever a specified event
occurs in the database system. Triggers are activated by database operations such as
INSERT, UPDATE, and DELETE. They are mainly used for maintaining database
consistency, enforcing constraints, and performing automatic actions whenever data
changes occur. SQL provides the CREATE TRIGGER statement to define triggers.
1. INSERT Trigger:
An INSERT trigger executes automatically whenever a new tuple is inserted into a
table. It can execute either before or after insertion.
Example:
Automatically calculate bonus while inserting employee record.
CREATE TRIGGER Emp_Insert BEFORE INSERT ON EMPLOYEE
FOR EACH ROW
BEGIN
[Link] = [Link] * 0.35;
END;
Trigger activates before INSERT operation.
Whenever a new employee record is inserted, the trigger automatically calculates
bonus as 35% of salary.
2. UPDATE Trigger:
An UPDATE trigger executes automatically whenever an existing tuple is
modified in a table. It is useful for checking changes and maintaining consistency.
Example:
Display old and new salary values whenever salary is updated.
CREATE TRIGGER Emp_Update BEFORE UPDATE OF Salary ON EMPLOYEE
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE ('Old Salary: ' || [Link]);
DBMS_OUTPUT.PUT_LINE ('New Salary: ' || [Link]);
END;
Trigger activates before updating Salary attribute.
[Link] stores previous salary value.
[Link] stores updated salary value.
Trigger displays both old and new salary values.
3. DELETE Trigger:
A DELETE trigger executes automatically whenever tuples are deleted from a
table. It can be used for maintaining backup or recording deleted information.
Example:
Store deleted employee details into backup table.
CREATE TRIGGER Emp_Delete BEFORE DELETE ON EMPLOYEE
FOR EACH ROW
BEGIN
INSERT INTO EMP_BACKUP
VALUES (:[Link], :[Link], :[Link]);
END;
Assertions specify conditions that must always Triggers automatically execute actions when
remain TRUE events occur
Views in SQL
Qn-22: Define views. Explain concept, advantages and CREATE VIEW with example.
ANS: Views in SQL:
A view in SQL is a single virtual table derived from one or more base tables. The
view does not store data permanently; instead, it stores the query definition used to
retrieve data from the base tables. Therefore, a view behaves like a virtual table whose
contents are generated dynamically whenever the view is accessed. Views are created
using the CREATE VIEW statement.
Concept of View:
The main concept of a view is to provide users with a customized representation
of database data. A view may contain selected rows and columns from one or more
tables. Since views are virtual tables, changes made in the base tables are automatically
reflected in the view results. Views help simplify complex queries and provide security
by hiding unnecessary data from users.
Advantages of Views:
1. Security:
Views restrict users from accessing all columns and rows of a table. Users can see
only the required data through the view.
2. Simplicity:
Complex SQL queries can be simplified by creating views. Users can access data
using simple queries on views.
3. Data Independence:
Changes in base tables do not directly affect users working on views, thereby
providing logical data independence.
4. Customized Data:
Different users can be provided with different views according to their
requirements.
Example:
Create a view containing employees working in Research department.
CREATE VIEW RESEARCH_DEPT AS SELECT Fname, Lname, Salary
FROM EMPLOYEE, DEPARTMENT WHERE Dno = Dnumber
AND Dname = 'Research';
Thus, a view is a virtual table derived from one or more base tables, used for
security, simplicity, and customized data access. Views are created using the CREATE
VIEW statement and help users retrieve required information easily.
Thus, the view definition is expanded and executed on the original tables
whenever the view is referenced.
Advantage:
No extra storage is required for the view.
Disadvantage:
Inefficient for complex views because the view query must be recomputed
every time it is accessed.
To keep the materialized view up-to-date, the DBMS uses incremental update
techniques, which determine what tuples must be inserted, deleted, or modified
whenever the base tables change.
Advantage:
Faster query processing for frequently used views.
Disadvantage:
Additional storage is required.
The view must be updated whenever base tables change.
Issues in Updating Views
Updating views is often difficult and ambiguous because the view may be derived
from multiple base tables.
3. Join Views
Views defined using joins of multiple tables are generally not updatable because a
modification in the view may require updates in more than one base table.
1. DROP Command
The DROP command is used to remove named schema elements such as tables,
schemas, domains, views, and constraints from the database. When a table is dropped,
both its data and definition are removed from the database catalog.
Syntax:
DROP TABLE table_name CASCADE;
or
DROP TABLE table_name RESTRICT;
DROP Options:
CASCADE: Removes the specified object along with all dependent objects such
as views and constraints.
RESTRICT: Removes the object only if no other schema element depends on it.
2. ALTER Command
The ALTER command is used to modify the structure of existing tables or
schema elements. It supports operations such as adding columns, dropping columns,
changing column definitions, and modifying constraints.
A) Adding a Column
Syntax:
ALTER TABLE table_name ADD COLUMN column_name datatype;
Example:
ALTER TABLE [Link] ADD COLUMN Job VARCHAR(12);
B) Dropping a Column
Syntax:
ALTER TABLE table_name DROP COLUMN column_name CASCADE;
Example:
ALTER TABLE [Link] DROP COLUMN Address CASCADE;
This command removes the Address attribute from the EMPLOYEE table.
Used when object is no longer required Used when structure needs modification
---------------------------------------------------------------END OF MODULE-4--------------------------------------------------------------