0% found this document useful (0 votes)
19 views46 pages

Dma Epa

The document provides an analysis of examination papers for the Database Management course across three semesters, detailing the topics covered, questions asked, and marks allocated for each question. It includes a breakdown of topics such as Creating Relational Databases, Interactive SQL, Advanced Features of SQL, PL/SQL Programming, and Database Security. The document also outlines specific questions from past exams, highlighting the focus areas for students preparing for future assessments.

Uploaded by

tranve115
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)
19 views46 pages

Dma Epa

The document provides an analysis of examination papers for the Database Management course across three semesters, detailing the topics covered, questions asked, and marks allocated for each question. It includes a breakdown of topics such as Creating Relational Databases, Interactive SQL, Advanced Features of SQL, PL/SQL Programming, and Database Security. The document also outlines specific questions from past exams, highlighting the focus areas for students preparing for future assessments.

Uploaded by

tranve115
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/ 46

Examination Paper Analysis and Solution

Database Management (22416) S.Y. Diploma: Sem 4


Top Summer-23 Winter-23 Winter-22
ic Name of Topic
No. Question Marks Question Marks Question Mark
1.(a) 2 1.(a) 2
1.(a) 2
1.(b) 2 1.(b) 2
1.(b) 2
Creating Relational 2.(a) 4 1.(f) 2
1 4.(a) 4
Database 2.(c) 4
5.(a) 6
4.(c) 4
Total 8 Total 14 Total 14
1.(c) 2
2.(b) 4 2.(a) 4
2.(a) 4
2.(d) 4 2.(d) 4
3.(a) 4
3.(c) 4 3.(a) 4
Interactive SQL for data 4.(d) 4
2 4.(c) 4 4.(b) 4
extraction 5.(a) 6
5.(a) 6 5.(b) 6
6.(c) 6
5.(b) 6 6.(a) 6

Total 28 Total 26 Total 28


1.(d) 2 1.(c) 2
1.(c) 2
1.(g) 2 1.(d) 2
1.(g) 2
3.(b) 4 2.(b) 4
2.(c) 4
4.(b) 4 3.(b) 4
3 Advance Features of SQL 3.(d) 4
5.(b) 6 4.(c) 4
4.(b) 4
6.(b) 6 6.(b) 6
6.(b) 6

Total 22 Total 24 Total 22


1.(d) 2 2.(b) 4 1.(e) 2
3.(a) 4 3.(c) 4 2.(c) 4
4.(a) 4 5.(c) 6 3.(c) 4
4.(e) 4 6.(b) 6 4.(d) 4
4 PL/SQL Programming 5.(c) 6 4.(e) 4
6.(c) 6 5.(c) 6

Total 26 Total 20 Total 24


1.(e) 2 1.(f) 2
1.(e) 2
2.(d) 4 1.(g) 2
1.(f) 2
3.(d) 4 3.(d) 4
3.(b) 4
Database security and 4.(a) 4 6.(c) 6
5 4.(d) 4
transaction processing 4.(e) 4
6.(a) 6

Total 18 Total 18 Total 14


Examination Paper Analysis and Solution

Exam Unit No Question no as per MSBTE paper Mark


Year and Name s

Summe Unit1: 1.(a) Enlist any four DDL commands. 2


r-2023 Creating 1.(b) State use of i) Commit and ii) Rollback commands 2
Relational 2.(a) Define the following terms with respect to any relation:
Database i) Cardinality
ii) Degree
iii) Domain 4
iv) Attribute
Winter- Unit1: 1.(a) Define term i)relation ii)domain 2
2023 Creating 1(b) list types of database users 2
Relational 1.(f) List any four relational algebra operator. 2
Database 2.(c) Difference between primary key constraint and not null 4
constraint.
4.(c)Write SQL statements for following 4
i) create table student with rollno, name, date_of_birth,
percentage, assign rollno as primary key .
ii)add new column email in student table.
iii)change name of table student to stud_info.
iv)delete table stud_info with its structure and data.

Winter Unit1: 1.(a) List any four RDBMS softwares. 2


2022 Creating 1.(b) Define Attribute and Domain. 2
Relational 4.(a) Differentiate between Truncate and Drop table 4
Database
command.
5.(a) Write SQL commands for following statements:
i) Create table for following schema 6
Student (Roll-No, Name, Class, DOB).
ii) To add new column percentage to student table.
Iii) To drop column DOB from student table.
Summe Unit2 : 2.(b) Describe any two set operators with suitable example. 4
r-2023 Creating 2.(d) Consider the following schema student (RNO, Name, 4
Relational Course, Percentage)
Database
Write SQL commands for the following :
i) Display the records having ‘A’ as first character in name of
students.
ii) Display the records having course as ‘cm’ and percentage
more than 70.
iii) Display all records in descending order of name.
iv) Display minimum and maximum percentage.
3.(c) Describe Group by and Having clause with suitable
example 4
4.(c) Consider the Schema Emp (E.NO, E. Name, Department,
Salary, 4
Bonus). Write SQL command for the following.
i) Insert one record with suitable data.
ii) Display all records having a salary between 5000 and 10000.
iii) Get the total salary of all the employees.
iv) Display E.No., E.Name and total payment (i.e. Salary and
Bonus) of all employees.
Examination Paper Analysis and Solution
5.(a) Consider the schema
Department (DNO, D Name, Location, Manager), Write SQL
commands for the following:
6
i) Create department table with suitable data type and size of
each attribute.
ii) Add one more attribute as Ph-no with suitable data type.
iii) Add the constraint primary key to D No.
5.(b) Consider the following Schema:
Supplier (S No., S. Name, location, Ph. No.) Product (P. No., P.
Name, Price) 6
Shipment (S. No. P No. Qty.)
Write SQL commands for the following:
i) Change the location of supplier to 'S2' to 'Pune'. ii) Display all
records from product relation having 'v' anywhere in the P
name.
iii) Display S No., P. No., Qty, and S Name using tables
Supplier and Shipment.
iv) Display S No., P No., P Name using the relations Product
and Shipment.
v)Display all records from product having price more than 2000.
vi) Display S Name and Location from Supplier having location
as 'Mumbai'.
Winter- Unit 2 : 1.(c)State use of Range searching operators. 2
2023 Creating 2.(a) Describe concept of subqueries with examples. 4
Relational 3.(a) Explain any four-aggregate function with examples. 4
Database 4.(d) Differentiate between WHERE and HAVING clause. 4
5.(a) Describe commit, rollback and save point with example. 6
6.(c) Consider the following database Employee 6
(emp_id,emp_name,emp_city,emp_addr,emp_dept,join_data)i)
Display the emp_id of employees who live in city ‘Mumbai’ or
‘Delhi’
ii)Change employee name ‘Aakash’ to ‘Jayesh’
iii)Display the total number of employees whose dept number is
5
Winter Unit 2: 2.(a) Consider following schema: Employee (Emp_no., 4
2022 Creating Ename, Job, Salary, Join date, Dept no) Write SQL
Relational queries for following statements
Database
i) Add following record in Employee table
Emp No = 100, Ename = Sagar, Job = Manager,
Salary= 80000. Joindate = 10-Jan-2021, Deptno = 10
ii) Change the name of employee 'Raj' to Rajesh'.
iii) Delete all employees whose job is 'Salesman'.
iv) Display details of employee whose job is Clerk'.
2.(d) Describe Grant and Revoke command with syntax and
example.
3.(a) Describe Commit and Rollback command example. 4
4.(b) Describe any four string functions with example.
5.(b) Consider following schema: 4
Employee (Emp-no, Ename, Job, Salary, Joindate, Dept- 4
no) 6
Write SQL queries for following statements
i) List employees with having Alphabet "A as second letter in
their name.
ii)Display details of employee whose salary between 20000
and 50000.
iii)Display salary of all employees by increasing salary with
Examination Paper Analysis and Solution
10%.
iv)Display details of employee except job as clerk.
v)Display details of employee whose job is clerk and dept_no
is 10.
vi)Display details of employee whose name does not contain
pattern 'ra.
6.(a) Consider following Schema
Emp(Empid, Empname, Job, Salary, Deptno) Dept 6
(Deptno, Dname, Location)
Write SQL commands for the following
statements.
i) Display all employee names in capital letters.
ii) Display total number of employees whose job is 'Clerk'.
iii)Display maximum salary of each department.
iv)Display details of employee in descending order of salary
v)Display employee names and their respective department
name.
vi)Display names of employee whose salary is greater than
salary of Vijay'.
Summe Unit 3: 1.(c)Define composite index 2
r-2023 Advance 1.(g) Define synonym and state its use 2
Feature of 2.(c) Write a command to create and drop synonym of any 4
SQL
relation.
3.(d) Create a sequence for the following specification. 4
4.(b) Describe the use of Index and write command to create an 4
Index.
6.(b) Consider a Schema EMP (E No, E Name, Dept, Salary) 6
Write SQL Commands for the following:
i) Create a view EMP – V by fetching E No, Dept, Salary from
Emp
ii) Change Dept. to ‘Marketing’ of E No = 123 in view.
iii) Dropping view Emp – V
Winter- Unit 3: 1.(d) Define view. State its uses. 2
2023 Advance 1.(g)Give need of sequence. 2
Feature of 3.(b) Describe two types of indexes with examples. 4
SQL 4.(b) Explain creating and dropping synonym with the help of 4
example.
5.(b)i) create a view called stud_info of information_technology 6
course students.
ii)Display contents of view.
iii)Modify the data using view stud_info i.e modify email address
of ‘yogesh’.
iv)Remove the stud_info.
6.(a) create a sequence - 6
i) sequence name is seq_1, start with 1 , increment by
1 ,minimum value 1 , maximum value 20 .
ii) Use a seq_1 to insert the values into table student[ID
number(10) Name char(20)];
iii)Change the seq_1 max value 20 to 50;
iv) drop the sequence
Winter Unit 3: 1.(c) Define view and write syntax for creating view. 2
2022 Advance 1.(d) State uses of synonyms (any two). 2
Feature of 2.(b) Define Index and explain it's types. 4
SQL
3.(b) Consider following schema
4
Employee (Emp_id, Emp_name, Job, Salary, Dept-no)
Write SQL commands for following statements:
i) Create view Emp_ VU20 that containts details of employee in
Examination Paper Analysis and Solution
Dept-no 20.
ii) Display employee details from view Emp_VU20 whose
salary is greater than 50,000/-.
4.(c) Write SQL statements to perform following
operations 4
i) Create short name e30 for Emp_vu30 view.
ii) Create unique index on Emp_no column of Emp table.
6.(b) Write SQL commands to perform following
operations on sequence
i) Create a sequence with following specifications: 6
Name : DB_SEQ
Starting value 1
Maximum value: 100
Increment by : 2
ii) Modify a sequence named DB_SEQ with following
specifications
Increment by: 3
Maximum value : 200
ii)Remove a sequence named DB_SEQ from database.

Summe Unit 4: 1.(d) State any two advantages of PL/SQL 2


r-2023 PL/SQL 3.(a) Write a PL/SQL code to display 1 to 10 odd numbers 4
Programmi 4.(a) Describe Implicit and Explicit cursor 4
ng 4
4.(e) Write a PL/SQL program to find the largest of three
numbers.
5.(c) Create a trigger which invokes on updation of record in 6
Department table.
6.(c) i) Write a function to find area of a circle and call the 6
function.
ii) Create a stored procedure to accept name and greet user
with name.
Winter- Unit 4: 2.(b)Explain steps of cursor implementation with syntax and 4
2023 PL/SQL example.
Programmi 3.(c) Write a PL/SQl program to display 10 reverse numbers. 4
ng Use for loop.
5.(c) Write PL-SQL program which accept the customer ID from 6
the user, if user enter an invalid ID then the exception invalid_id
is raised using exception handling.
6.(b) write PL-SQL code to print largest number from three 6
numbers(accept three numbers from user).
Winter Unit 4: 1.(e) Define Trigger and list its types. 2
2022 PL/SQL 2.(c) Describe block structure of PL/SQL. 2
Programmi 3.(c) Write a PL/SQL code that accepts 3 numbers from 4
ng
user and display largest number.
4.(d) Define cursor. Write step by step syntax to declare, 4
open, fetch and close cursor in PL/SQL block.
4.(e) Write a PL/SQL code that handles divide by zero 4
exception.
5.(c) Write PL/SQL function/procedure for following
statements: 6
i)Write a function circle_area ( ) to lind area of circle, use
radius as input parameter.
ii)Write a procedure emp_count ( ) to count number of
employee in department, use dept_no as input parameter.
Examination Paper Analysis and Solution
Summe Unit 5: 1.(e) Enlist different types of Database Users 2
r-2023 Database 1.(f) Enlist ACID properties of transactions 2
security and 3.(b) Describe the different types and causes of Database 4
transaction
failure.
processing
4.(d) Describe different states of transaction with a neat 4
diagram 6
6.(a) Write SQL commands for the following:
i) Create User ‘ABC’ with password as ‘IF4I’
ii) Grant privilege of select, delete, update on table EMP to
user.
iii) Take back privilege of Delete from user ‘ABC’ on Relation
Emp.
Winter- Unit 5: 1.(e) State properties of transaction. 2
2023 Database 2.(d) Describe use of grant and revoke commands with suitable 4
security and example.
transaction 3.(d) Explain ACID properties of transaction. 4
processing 4.(a) Define database backup. Describe how database backup 4
helps to avoid failures.
4.(e)Create a trigger which invokes on updating of record on 4
emp table
Winter Unit 5: 1.(f)Draw state diagram of transaction1.(g)List any four causes 2
2022 Database of database failures. 2
security and 3.(d) Define transaction and explain ACID properties of 4
transaction
transaction.
processing
6.(c) Write sQL commands for following statement 6
i) Create user Rajesh having password as Rajesh@123.
ii) Assign ALL privileges on Book table to Rajesh.
iii) Remove INSERT and DELETE privileges on book
table from Rajesh.
Examination Paper Analysis and Solution

Unit1: Creating Relational Database

Q.1 Define Following (W-23,S-23,W-22) 2 Marks

Ans:

 Database: A database is a collection of tables, with related data.


 Table or Relation: Each table in a relational database contains rows (Tuples) and columns
(fields)
 Column: One column (data element) contains data of one and the same kind, for example the
column postcode.
 Domain: Domain is defined as the set of all unique values permitted for an attribute. For
example, a domain of date is the set of all possible valid dates
 Tuple: A row (= tuple, entry or record) is a group of related data, for example the data of one
student.
 Redundancy: It is the repetition of the same data in multiple places within a database
 Primary Key: It is a column of a table or a set of columns that helps to identify every record
present in that table uniquely.
 Cardinality: cardinality refers to the uniqueness of data values contained in a column. High
cardinality means that the column contains a large percentage of totally unique values. Low
cardinality means that the column contains a lot of “repeats” in its data range
 Foreign Key: A foreign key is the linking pin between two tables.
 Composite Key: A compound key (composite key) is a key that consists of multiple columns,
because one column is not sufficiently unique.
 Index: An index in a database resembles an index at the back of a book.
 The degree of relationship (also known as cardinality) is the number of occurrences in one
entity which are associated (or linked) to the number of occurrence in another.

Q.2 Enlist any four relational algebra operators. (S-19) 2 Marks

Ans:

 SELECT (symbol: σ)
 PROJECT (symbol: π)
 RENAME (symbol: ρ)
 UNION (υ)
 INTERSECTION (∩)

Q.3 List any four RDBMS softwares. (S-23) 2 Marks

Ans:

 MySQL
Examination Paper Analysis and Solution
 Microsoft SQL Server
 SQLite
 Oracle Database

Q.4 Enlist any four DDL commands. (S-23) 2 Marks

Ans:

i) create

ii)drop

iii) alter

iv)rename

v)rename

Q.5 State use of i) Commit and ii) Rollback commands (S-23) 2 Marks

Describe Commit, Rollback and save point with example (S-19) 4 Marks

Ans:

[2 Marks Answer]

i) Commit: It permanently saves all the changes made in the transaction of a database or table.

ii) Rollback : This command restores the database or table to last committed state. It is also used with
SAVEPOINT command to jump to a savepoint in an ongoing transaction.

[4 Marks Answer]

1) Commit:

This command is used to end the transaction and also make its effect permanent to database.
Commit deletes or removes the save points if any.

Syntax:

commit;

(OR)

commit work;

2) Rollback

A rollback command is used to undo the work done in current transaction.

Syntax:
Examination Paper Analysis and Solution
Rollback;

Syntax to rollback to a particular save point:

Rollback to savepoint<savepoint_name>;

Example:

Rollback to save point SV1;

3) Savepoint:

Save points define breakpoints for the transaction to have partial rollback. Save points are treated as
marker to divide lengthy transaction to smaller one.

Syntax:

savepoint<savepoint_name>;

Example:

Savepoint SV1;

Unit2 : Creating Relational Database


Q.1 State the use of ‘Like’ Operator. (W-19) 2 Marks

Ans:

The LIKE operator is used in a WHERE clause to search for a specified

pattern in a column.

There are two operator often used in conjunction with the LIKE

operator:

 %:The percent sign represents zero, one, or multiple characters


 _: The underscore represents a single character.

Q.2 Describe any two set operators with suitable example. (S-23) 4 Marks

Ans:

 Set operators combine the results of two component queries into a single result.
 Queries containing set operators are called as compound queries.

Set operators in SQL are represented with following special keywords as: Union, Union all,
intersection & minus.

1) Union: The Union of two or more sets contains all elements, which are present in either or both.
Union works as or. The duplicates of both the tables will appear only once.
Examination Paper Analysis and Solution
e.g. select ename from emp1 union select ename from emp2;

2) Union all: The Union of 2 or more sets contains all elements, which are present in both, including
duplicates.

e.g. select ename from emp1 union all select ename from emp2;

3) Intersection: The intersection of two sets includes elements which are present in both.

e.g. select ename from emp1 intersect select ename from emp2;

4) Minus: The minus of two sets includes elements from set1 minus elements of set2.

e.g. select ename from emp1 minus select ename from emp2;

Q.3 Consider the following schema student (RNO, Name, Course, Percentage) Write SQL commands
for the following : (S-23) 4 Marks

i) Display the records having ‘A’ as first character in name of

Students.

Ans:

Select * from student where Name like ‘A%’;

Ii)Display the records having course as ‘cm’ and percentage more than 70.

Ans:

Select * from student where Course=’cm’ and Percentage >70;

iii) Display all records in descending order of name.

Ans:

Select * from student order by Name desc;

iv) Display minimum and maximum percentage.

Ans:

Select min(Percentage), max(Percentage) from student;

Q.4 Describe the use of primary key and unique key constraints with example? (W-19) 4 Marks

Ans:

There are two Entity constraints:

1.Primary Key constraint

2. Unique Constraint
Examination Paper Analysis and Solution

1. Primary Key constraint: It is use to avoid redundant/duplicate value entry within the row of
specified column in table. It restricts null values too.

Syntax:

create table table_name

(column_name datatype(size),

column_name data_type constraint

constraint_name primary key);

Example:

create table emp

(id number (5) constraint id_pk primary key,

name varchar2 (10),

sal number (10));

2. Unique Constraint: The UNIQUE constraint uniquely identifies each record in a database table.
The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column
or set of columns.

syntax:

create table table_name

(column_name data_type,

column_name data_type constraint

constraint_name unique);

Example:

create table persons

(p_id num constraint p_uk unique,

firstname varchar2(20),

city varchar2(20));

Q.5 Write any two types of join with example of each? ( W-19) 4 Marks

Ans:
Examination Paper Analysis and Solution
1)Inner Join: An INNER JOIN is a type of SQL join that combines rows from two tables based on a
related column, including only the rows where there is a match.

For example:

SELECT employees.EmployeeID, employees.FirstName, employees.LastName,


departments.DepartmentName

FROM employees INNER JOIN departments

ON employees.DepartmentID = departments.DepartmentID;

This query retrieves a list of employees and their department names, combining data from the
employees and departments tables based on the common DepartmentID column. The result
includes only rows with matching DepartmentID values in both tables.

Output :

2)Left Join :

 A LEFT JOIN is a type of join operation in relational databases that returns all rows from the
left table and the matched rows from the right table.
 If there is no match, NULL values are returned for columns from the right table.
 This type of join is useful when you want to retrieve all records from the left table and include
matching records from the right table.

Let's consider an example with two tables: employees and departments. The employees table
contains information about employees, including their employee_id, employee_name, and
department_id. The departments table contains information about different departments, including
department_id and department_name.

Here are the tables:


employees:
employee_id employee_name department_id
1 John 101
2 Jane 102
3 Bob 101
4 Alice 103
departments:
department_id department_name
101 HR
102 IT
103 Finance
Now, let's perform a LEFT JOIN on these tables based on the department_id:

SELECT employees.employee_id, employees.employee_name, employees.department_id,


departments.department_name
FROM employees
LEFT JOIN departments ON employees.department_id = departments.department_id;

The result of the LEFT JOIN will include all rows from the employees table and matching rows from
the departments table.
Examination Paper Analysis and Solution
If there is no match, NULL values will be displayed for columns from the departments table.
Output:
employee_id employee_name department_id department_name
1 John 101 HR
2 Jane 102 IT
3 Bob 101 HR
4 Alice 103 Finance
In this example, you can see that all employees are included in the result, and the department_name
is displayed if there is a match.
If there is no match (e.g., employee with employee_id 4 in department 103), NULL values are
displayed for the columns from the departments table.

3)Right Join
A right join, also known as a right outer join, is a type of SQL join that returns all the rows from the
right table (table2) and the matched rows from the left table (table1). If there are no matches, NULL
values are returned for the columns from the left table.

Here's a simple example to illustrate a right join:

Consider two tables: Employees and Departments.


Employees Table:
EmployeeID Name DepartmentID
1 John 101
2 Alice 102
3 Bob 103
4 Mary NULL
Departments Table:
DepartmentID DepartmentName
101 HR
102 IT
104 Finance
I
n this example, the Employees table contains information about employees including their name and
the department they belong to. The Departments table contains information about various
departments along with their IDs.
Let's perform a right join to get all employees along with their corresponding department information:

SELECT Employees.EmployeeID, Employees.Name, Departments.DepartmentName


FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;

Output:
EmployeeID Name DepartmentName
1 John HR
2 Alice IT
3 Bob NULL
NULL NULL Finance
In the output:
 John and Alice have departments (HR and IT, respectively), so their information is displayed
along with their department names.
 Bob doesn't have a department assigned (NULL in the DepartmentID column), so his
department information shows as NULL.
Examination Paper Analysis and Solution
 Mary's information is included from the Employees table, even though there is no
corresponding department information for her in the Departments table. This is because of the
right join, which includes all rows from the right table (Departments) regardless of whether
there is a match in the left table (Employees).

4)Full Outer Join


A Full Outer Join is a type of SQL join that returns all rows from both tables being joined, regardless of
whether there is a match between the columns being joined. If there is no match, the result will
contain NULL values for columns from the table that doesn't have a match.

Let's consider two tables, employees and departments, and we want to perform a full outer join
based on the department_id column. Here are the example tables: Table: employees
employee_id employee_name department_id
1 John 101
2 Jane 102
3 Bob 103
4 Alice 101
Table: departments
department_id department_name
101 HR
102 IT
104 Finance

Now, let's perform a full outer join on the department_id column:

SELECT employees.employee_id, employees.employee_name, employees.department_id,


departments.department_name
FROM employees
FULL OUTER JOIN departments ON employees.department_id = departments.department_id;

The result would look like this:


employee_id employee_name department_id department_name
1 John 101 HR
2 Jane 102 IT
3 Bob 103 NULL
4 Alice 101 HR
NULL NULL 104 Finance
In this example:
 Rows 1 and 4 have matching department IDs (101), so the columns from both tables are
combined in the result.
 Row 2 has a matching department ID (102) from the employees table, and the corresponding
department name is included from the departments table.
 Row 3 has a department ID (103) in the employees table that does not have a match in the
departments table. As a result, the department_name column is filled with NULL.
 Row with department ID 104 is present only in the departments table, so the employee-
related columns are filled with NULL.
Examination Paper Analysis and Solution

Q.6 Describe Group by and Having clause with suitable example (S-23) 4 Marks

Ans:

Group by: -

It is used to group rows that have the same values. The grouping can happen after retrieval of rows
based on a certain condition.

In Group By clause aggregate function can be performed with one command

Syntax: -

select statements...

group by column_name1[, column_name2,...];

Example: -

select gender from members

group by gender;

Having clause: -

 It is used to restrict the rows affected by the group by clause.


 This can be used in conjunction with the group by clause.
 Having imposes a condition on the group by clause which further filters the groups created by
group by clause.

Syntax:

select statements...

group by column_name1[,column_name2,...]

[having condition];

Example: -

select branch,max(per)

from student

group by branch;

This will display maximum percentage of each branch.

Q.7 Consider the Schema Emp (E.NO, E. Name, Department, Salary, Bonus).

Write SQL command for the following. (S-23) 4 Marks


Examination Paper Analysis and Solution
i) Insert one record with suitable data.

Ans:

insert into Emp values (001,’Anita’,’Sales’,20000,3000);

ii) Display all records having a salary between 5000 and 10000.

Ans:

select * from Emp

where Salary

between 5000 and 10000;

iii) Get the total salary of all the employees.

Ans:

select sum(Salary) from Emp;

iv) Display E.No., E.Name and total payment (i.e. Salary and Bonus) of all employees

Ans:

select E.NO, E.Name, Salary, Bonus from Emp;

Q.8 Consider the schema

Department (DNO, D Name, Location, Manager),

Write SQL commands for the following: (S-23) 6 Marks

i) Create department table with suitable data type and size of each attribute.

Ans:

create table Department

DNO number(5),

DName varchar2(25),

Location varchar2(20),

Manager varchar2(30)

);
Examination Paper Analysis and Solution
ii) Add one more attribute as Ph-no with suitable data type.

Ans:

alter table Department add (Ph-no number (12));

iii) Add the constraint primary key to D No.

Ans:

alter table Department add constraint Department_DNO_pk primary key( DNO );

(OR)

create table Department

DNO number(5) constraint Department_DNO_pk primary key,

DName varchar2(25),

Location varchar2(20),

Manager varchar2(30)

);

Q.9 Consider the following Schema:


Supplier (S No., S. Name, location, Ph. No.)
Product (P. No., P. Name, Price)
Shipment (S. No. P No. Qty.)
Write SQL commands for the following: (S-23) 6 Marks

i) Change the location of supplier to 'S2' to 'Pune'.


Ans: Update Supplier set location=’Pune’ where SNO=’S2’;

ii) Display all records from product relation having 'v' anywhere in the P name.
Ans:
select * from Product where PName like ‘%v%’;

iii) Display S No., P. No., Qty, and S Name using tables Supplier and Shipment.
Ans:

select Supplier.SNo, Shipment.PNo, Shipment.Qty, Supplier.SName


from Supplier,Shipment
where Supplier.SNo = Shipment.SNo ;

(or)

select Supplier.SNo, Shipment.PNo, Shipment.Qty, Supplier.SName


from Supplier join Shipment on Supplier.SNo = Shipment.SNo ;

iv) Display S No., P No., P Name using the relations Product and Shipment.
Ans:

selectShipment.SNo, Product.PNo. Product.PName


Examination Paper Analysis and Solution
from Product, Shipment
where Shipment.PNo = Product.PNo ;

(or)
selectShipment.SNo, Product.PNo. Product.PName
from Product join Shipment
on Shipment.PNo = Product.PNo ;

v)Display all records from product having price more than 2000.
Ans:
select PNo, PName,Price from Product where Price>2000;

(OR)

select * from Product where Price>2000;

vi) Display S Name and Location from Supplier having location as 'Mumbai'.

Ans:
select SName, Location from Supplier where Location
=’Mumbai’;

Q.10 Describe concept of subqueries with example. (W-19) 4 Marks


Ans:

Subquery is a select statement that is embedded in a clause of another SELECT statement i.e.
nesting of queries or query within query.

Types of subqueries
1) Single row subqueries
2) Multiple row subqueries
3) Multiple column subqueries

Single row subqueries: A single row subquery is one that returns one
row from inner SELECT statement. This type of subquery uses single
row operators = , > , >= , < , <= , < >

Syntax:
SELECT column_name1… column_name n
FROM <table_name>
WHERE column1 operator
(SELECT column from table_name where condition);

Example :
Display the employee details whose job title is the same as that of employee 1005.

Select empno,ename,job,salary,deptno
From emp
Where job=(select job from emp where empno=1005);

Multiple row subqueries: Subqueries that return more than one roware called multiple-row
subqueries. Multiple row operators are used instead of a subquery, with a multiple row subquery.

Operator Meaning
In Equal to any member in the list.
Examination Paper Analysis and Solution
Any Compare value to each value returned by the
subquery.
All Compare value to every value returned by the
subquery.

Syntax:

SELECT column_name1… column_name n

FROM table_name

WHERE column1 operator (SELECT column from <table_name> where condition);

example

Find the employees who earn the same salary as minimum salary for departments.

Select empno,ename,job,salary,deptno

From emp

Where salary IN (select min(salary) from emp group by deptno);

Multiple column subqueries

Queries that return the values from more than one column are called multiple column subqueries.

syntax:

SELECT column_name1, ….. column_name n

FROM table_name

WHERE (column_name, column_name) IN

(SELECT column_name, column_name….from

Table_name Where <condition> );

Example: Display the name, department number, salary and commission of any employee whose
salary and commission matches both the commission and salary of any employee in department 10

Query:

Select empno,deptno,salary,comm

From emp

Where (salary,comm) IN (select salary,comm from emp where deptno=10);

Q.11 Consider the following schemas

Student(rollno, name, dt_of_birth,telephone)

Marks (rollno, sub1_marks, sub2_marks, per)


Examination Paper Analysis and Solution
Write SQL queries for the following. (W-19) 4 Marks

i) Display student’s rollno, name, and marks of both subjects for all Students.

Ans:

Select Student.rollno, Student.name,

marks.sub1_marks, marks.sub2_marks

from Student, marks

where Student.rollno=marks. Rollno;

ii)Delete all those students records who secured less than 35%

Ans:

Delete from Student where

rollno=(Select rollno from marks where per<35);

iii)Display all the students whose name start with ‘A’

Ans:

Select * from Student where name like ‘A%’;

iv)Update telephone number of student with rollno 101 as 9800010111

Ans:

Update Student set telephone=9800010111 where rollno=101;

Q.12 Consider following schema:

employee{empid,empname,designation,salary,deptno}

dept { deptno,deptname,location}

Write SQL queries for following : (W-19) 6 Marks

i)Find maximum salary for deptno=10;

Ans:

Select max(salary) from employee where deptno=10;

ii) Increase salary of all employee by 5%

Ans:

Update employee set salary=salary+(salary*0.05);


Examination Paper Analysis and Solution
iii)Get the names of all ‘Manager’

Ans:

Select empname from employee where designation=’Manager’;

iv) Display deptnames located at ‘Pune’ and ‘Nagpur’.

Ans:

Select deptname from dept

where location=’Pune’ or location=’Nagpur’;

Q.13 Consider schema ‘employee’ created by ‘user1’

Write SQL queries for following : (W-19) 6 Marks

i) Grant ‘select’ and ‘insert’ permissions to user2.

Ans:

grant select, insert on employee to user2;

ii) Assign all privileges for the user user3.

Ans:

grant all on employee to user3;

iii) Remove ‘select’ permission from user2 for table ‘employee’.

Ans:

revoke select on employee from user2;

iv) Grant ‘update’ permission to user2 and user3

Ans:

grant update on employee to user2, user3;

v) Remove all permission from user3.

Ans:

revoke all on employee from user3;

vi) Assign ‘resource’ permission to user2.

Ans:

grant resource to user2;


Examination Paper Analysis and Solution

Q14.State the use of between clause (S-19) 2 Marks

Ans:

 The SQL BETWEEN clause allows user to easily test if an expression is within a range of
values (inclusive). The values can be text, date, ornumbers.
 It can be used in a SELECT, INSERT, UPDATE, or DELETE statement. The SQL BETWEEN
Condition will return the records where expression is within the range of value1 and value2
inclusive of the the values.

Q15. Compare group by and having clause (S-19) 2 Marks

Sr.No group by having


1 The GROUP BY Clause HAVING Clause is utilized
is utilized in SQL with in SQL as a conditional
the SELECT statement to Clause with GROUP BY
organize similar data into Clause.
groups. It combines the
multiple records in single
or more columns using
aggregate functions.
2 GROUP BY returns only This conditional clause
one result per group of data. returns rows where aggregate
function results match with
given conditions only.

Q.16 Give any four string functions with example.(S-19) 4 Marks

Ans:

1.initcap(str)

Converts first letter of string to capital letter.

Example:

Select initcap(‘rdbms’) from dual;

2. lower(str)

Converts a string to all lowercase characters.

Example:

Select lower(‘RDBMS’) from dual;


Examination Paper Analysis and Solution
3. upper(str)

Converts a string to all uppercase chracters.

Example:

Select upper(‘rdbms’) from dual;

4. length(str)

Find outs the length of given string.

Example:

Select length(‘rdbms) from dual;

5.ltrim(str)

Removes leading spaces from a string

Example:

Select ltrim(‘ RDBMS’) from dual;

6. rtrim(str)

Removes trailing spaces from a string

Example:

Select rtrim(‘RDBMS ’) from dual;

7. Lpad(char1,length,char2)

It returns char1, left-padded to given length with the sequence of

characters in char2.

Example:

Select lpad(‘RDBMS’,10,’*’) from dual;

8. Rpad(char1,length,char2)
Examination Paper Analysis and Solution
It returns char1, right-padded to given length

with the sequence of characters in char2.

Example

Select rpad(‘RDBMS’,10,’*’) from dual;

9. Translate(char,from string, to string)

It returns expr with all occurrences of each character in from_string

replaced by its corresponding character in to_string

Example:

Select translate(‘Hickroy’,’H’,’D’) from dual;

10. Replace(char,searchstring,[repstring])

It returns character string with each occurrences of searchstring

replaced with [repstring]

Example:

Select replace(‘Tick and Tock’,’T’,’Cl’) from dual;

11. Substr(char,m,n)

It returns substring of character string that stack at m character and is

of length n

Example:

Select subs(‘RDBMS’,1,2) from dual;

12. Concat(str, str2)

It merges two or more strings or a string and a data value together

Example:
Examination Paper Analysis and Solution

select concat('summer ','24') from dual;

13. Chr(n)

Returns a character binary equivalent of n.

select chr(65) from dual;

14. Ascii(char)

Returns a decimal representation of a character.

Q17. Describe GRANT and Revoke with its syntax and example.(S-19) 4 Marks

Ans:

Grant:

This command is used to give permission to user to do operations on

the other user s object.

Syntax:

Grant <object privileges>on< object name> to <username>[with

grant option] ;

Example:

Grant select,update on emp to user1;

Revoke:

This command is used to withdraw the privileges that has been granted to a user.

Syntax:

Revoke <object privileges>on<object name>

from <username> ;
Examination Paper Analysis and Solution
Example:

Revoke select, update on emp from user1;

Q.18 Consider following schema:

Depositor (cust_name, acc_no)

Borrower (cust_name, loan_no)

Solve following queries:(S-19) 4 Marks

(i) Find customer name having saving account as well as loan Account.

Ans: Select d.Cust_name

From depositor d, borrower b

Where d. Cust_name=b.cust_name;

(ii) Fine customer names having loan account but not the savings account.

Ans:

Select b.cust_name from borrower

minus

Select d.cust_name from depositor

Where d. Cust_name=b.cust_name;

(any other relevant logic can be cosidered for the query)

Q.19 Attempt any TWO of the following:

(i) Create the table as named 'student' with field as roll no, name, address, DOB and percent.

Ans:

create table student

(rollno number(5),

name char(20),

address varchar2(40),
Examination Paper Analysis and Solution
DOB date,

percent number(5,2)

);

(ii) Add a column 'city' to student table.

Ans:

alter table student add (city char(20));

(iii) Change the name of ‘student' table to; ‘student_info'.

Ans:

rename student to student_info;

(iv) Remove/ delete the data or records from student info table.

Ans:

truncate table student_info ;

OR

delete from student_info;

Q20 Attempt any TWO of the following:

Consider the following data base schema

student (roll_no, name, city, marks, result). Write queries for the following:

(i) Display all students having result as first class.

Ans:

Select * from student where result=’first class’;

(ii) Update roll_no of each student by adding 18 to it.

Ans:

update student set roll_no=roll_no+18;


Examination Paper Analysis and Solution
(iii) Delete percent column from table.

Ans:

alter table student drop column percent;

(iv) Display student whose city is 'Mumbai'

Ans:

Select * from student where city=’Mumbai’;

Q.21 Describe system and object privileges and also describe use of Grant and Revoke commands
with suitable example.(W-19) 4 Marks

Ans:

System Privileges: System privileges are privileges given to users to allow them to perform certain
functions that deal with managing the database and the server.

e.g: Create user, Create table, Drop table etc.

Object Privileges:

Object privileges are privileges given to users as rights and restrictions to change contents of
database object – where database objects are things like tables, stored procedures, indexes, etc.

e.g.

Select, inserts, delete, update, execute, references etc.

Grant:

This command is used to give permission to user to do operations on the other user’s object.

Syntax:

Grant <object privileges>

on <object name> to

<username>[with grant option] ;

Example:

Grant select, update on emp to user1;

Revoke:

This command is used to withdraw the privilege that has been

granted to a user.
Examination Paper Analysis and Solution
Syntax:

Revoke <object privileges>

on <object name> from

<username> ;

Example:

Revoke select, update on emp from user1;

Unit 3: Advance Feature of SQL

Q1. Define Composite Index (S-23) 2 Marks


Ans:
Composite Index: An index created on more than one column is called composite index

Q2. Define synonym and state its use(S-23) 2 Marks

Ans:
Definition:
Synonym is an alternative name for database object, referred to as the database object that can exist
on a local or remote server.

Use:
Synonyms are used mainly to make it easy for users to access database objects owned by other
users.
They hide the underlying object's identity and make it harder for a malicious program or user to
target the underlying object.

Q3. Write a command to create and drop synonym of any relation. (S-23,W-19) 4 Marks
Ans:

Create synonym command Syntax:


Create synonym synonym_name for name_of_base_table;

eg : Create Synonym Emp for Employee_Details;

Drop synonym Command Syntax:


DROP SYNONYM synonym_name;

e.g : Drop Synonym Emp;

Q4. Create a sequence for the following specification.

Name ABC, Starting value: 10, Maximum value: 100,

Increment by 10. (S-23) 4 Marks

Ans:

Create Sequence ABC

Start with 10
Examination Paper Analysis and Solution
Increment by 10

Minvalue 10

Maxvalue 100;

Q5. Describe the use of Index and write command to create an Index.(S-23)

Define the index with its characteristics.(W-19)

Ans:

Indexing is used to optimize the performance of a database by minimizing the number of disk
accesses required when a query is processed.

• The index is a type of data structure. It is used to locate and access the data in a database table
quickly.

• An index is a schema object.

• For example, if you want to reference all pages in a book that discusses a certain topic, you first
refer to the index, which lists all the topics alphabetically and is then referred to one or more specific
page numbers.

Creating an Index:

Syntax:

CREATE INDEX index

ON TABLE column;

where the index is the name given to that index and TABLE is the name of the table on which that
index is created and column is the name of that column for which it is applied.

Definition of index:

An index is a schema object. It is used by the oracle server to speed

up the retrieval of rows by using a pointer.

Characteristics of index:

1. It can reduce disk i/o by using a rapid path access to locate data quickly.

2. Indexes are logically and physically independent of the table they index.

3. These are maintained automatically by the oracle server.


Examination Paper Analysis and Solution
Q.6 Consider a Schema EMP (E No, E Name, Dept, Salary)

Write SQL Commands for the following: (S-23) 4 Marks

i) Create a view EMP – V by fetching E No, Dept, Salary from

Emp

Ans:

create view EMP-V as select ENO,Dept,Salary from Emp;

ii) Change Dept. to ‘Marketing’ of E No = 123 in view.

Ans:

update Emp-V set Dept=‟Marketing‟ where ENO=123 ;

iii) Dropping view Emp – V

Ans:

drop view Emp-V ;

Q7. Write syntax to create view. (W-19) 2 Marks

Ans

create view <view name>

as select <query>;

OR

CREATE VIEW name AS SELECT column1, column2.....FROM

table_nameWHERE [condition];

Q8. State the use of sequence. (W-19) 2 Marks

Ans:

A sequence refers to a database object that is capable of generating

unique and sequential integer values.

Syntax:

Create sequence<seq_name>

[increment by num][start with num]


Examination Paper Analysis and Solution
[maxvaluenum] [minvaluenum]

[cycle/no cycle][cache/no cache]

OR

 Sequence is a set of integers 1, 2, 3 … that are generated and supported by some database
systems to produce unique values on demand.
 A sequence is a user defined schema bound object that generates a sequence of numeric
values.
 Sequences are frequently used in many databases because many applications require each
row in a table to contain a unique value and sequences provides an easy way to generate
them.
 The sequence of numeric values is generated in an ascending or descending order at defined
intervals and can be configured to restart when max_value exceeds.
OR
 Sequence:
 It is database object that generate/produce integer values in sequential order.
 It automatically generates primary key and unique key values.
 It may be ascending or descending order
 It can be used for multiple tables.
 Sequence numbers are stored and generated independently of tables

Q8. Create Sequence seq-1 with starting value 1 and maximum value 20
with an increment of 1. Consider schema Customer (custno,
custname, telephone) and use seq-1 for inserting a row in customer
Table.(W-19) 4 Marks

Ans:
Create Sequence seq-1
Start with 1
Increment by 1
Minvalue 1
Maxvalue 20;

For inserting the value using sequence


insert into customer values (seq-1.nextval, '1', 'George',1234567890);

Q.9 Describe simple and composite index.(W-19) 4 Marks


Describe different types of Indexes with examples.(S-19) 4 Marks

Ans:

1) Simple index (Single column): An index created on single column of


a table is called a Simple Index.

Syntax: Create index index_name on <tablename><column name>;

e.g.:
Create index on employee (empno);

2)Composite (concatenated): Indexes that contain two or more columns


from the same table which are useful for enforcing uniquely identify a
Row.
Examination Paper Analysis and Solution
Syntax: Create index index_name on <tablename><Column_name1,
Column_name2>;

e.g.:
Create index on employee (ename, empno);

3) Unique indexes are used not only for performance, but also for data integrity. A unique index does
not allow any duplicate values to be inserted into the table.

Syntax :
Create unique index index_name on table_name(column_name);

e.g:
Create unique index index_empno on emp(empno);

Q10. Consider following schema:


Person {personid,name,address,city,telephone}
Write queries for following:(W-19) 4 Marks

i) Create sequence seq-pid with start value 100 and maximum value
120 and increment by 1.
Use seq-pid to insert personid into table person.
Ans:
Insert into person (personid) values (seq_pid.nextval);

ii) Create view view-person containing details of persons from city


“Mumbai” and “Pune”

Ans:
Create view person as select * from person where city=’Mumbai’
or city=’Pune’;

iii) Create synonym syn-person on table person owned by user ‘Scott’


delete synonym syn-person.
Ans:
create synonym syn_person for scott.person;
Drop synonym syn_person;

Q11. Create synonyms for class tables.Write steps to create synonyms. (S-19) 4 Marks
The following code shows how to create a synonym for the class table

Ans:

Create synonyms for class tables.

The following code shows how to create a synonym for the class table

Example:

Create Synonym Class.syn for class;


Examination Paper Analysis and Solution
Write steps to create synonyms

Syntax:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .]

synonym_name

FOR [schema.] object_name;

Q12. Create sequence for department table and also altered the created sequence.(S-19) 4 Marks

Ans:

Create sequence deptid

Start with 1

Increment by 1

Maxvalue 100;

Altering the created sequence

Alter sequence deptid maxvalue 1500;

Unit 4: PL/SQL Programming


Q1. State any two advantages of PL/SQL(S-23) 2 Marks.
Ans:
 It improves performance against running SQL queries multiple times.
 It is secure, as the code is in the database and hides the internal database details from the
user.
 It provides strong features, such as exception handling, procedure, function, cursors, triggers
which saves time on design and debugging.
 Applications written in PL/SQL are fully portable.

Q2. Write a PL/SQL code to display 1 to 10 odd numbers (S-23) 4 Marks


Ans:
DECLARE
I number;
BEGIN
I: =1;
Loop
Dbms_output.put_line(I);
I: =I+2;
Exit when I>10;
End loop;
END;
Examination Paper Analysis and Solution

Q3. Describe Implicit and Explicit cursor(S-23) 4 Marks


Ans:
Implicit cursors:
 It is automatically created by Oracle whenever an SQL statement is executed when there is
no explicit cursor for the statement. Programmers cannot control the implicit cursors and
the information in it.
 Cursor attributes are %FOUND, %ISOPEN, %NOTFOUND and %ROWCOUNT. The SQL cursor
has additional attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for use
with the FORALL statement.

Example: -
The following program will update the table and increase the salary of each customer by 500 and use
the SQL%ROWCOUNT attribute to determine the number of rows affected −

DECLARE
total_rows number (2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows:= sql%rowcount;
dbms_output.put_line( total_rows|| ' customers selected ');
END IF;
END;

Explicit cursors:
They are programmer-defined cursors for gaining more control over the context area. An explicit
cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.

Working with an explicit cursor includes the following steps −


• Declaring the cursor for initializing the memory
• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory

Declaring the Cursor


 Declaring the cursor defines the cursor with a name and the associated SELECT statement.

CURSOR c_customers IS SELECT id, name, address FROM customers;

Opening the Cursor


 Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it.

OPEN c_customers;

Fetching the Cursor


Examination Paper Analysis and Solution

 Fetching the cursor involves accessing one row at a time.

FETCH c_customers INTO c_id, c_name, c_addr;

Closing the Cursor


 Closing the cursor means releasing the allocated memory.

CLOSE c_customers;

Q4. Write a PL/SQL program to find the largest of three numbers. (S-23) 4 Marks
Ans:
declare
a number;
b number;
c number;
begin
dbms_output.put_line('Enter a:');
a: =&a;
dbms_output.put_line('Enter b:');
b: =&b;
dbms_output.put_line('Enter c:');
c: =&c;
if (a>b) and (a>c)
Then
dbms_output.put_line('A is GREATEST'||a);
elsif (b>a) and (b>c)
then
dbms_output.put_line('B is GREATEST'||b);
else
dbms_output.put_line('C is GREATEST'||c);
end if;
end;

Q5. Create a trigger which invokes on updation of record in Department table.(S-23) 6 Marks
Ans:
create trigger trigger_update
on department
after update
as
begin
select * from department;
end;

Q6. i) Write a function to find area of a circle and call the function.
ii) Create a stored procedure to accept name and greet user with name. (S-23) 6 Marks
Ans:
i)
Function Creation
SQL>create or replace function circle_area (radius in number) return
number as
pi constant number:= 3.14;
area number;
begin
Examination Paper Analysis and Solution
area:= pi * radius *radius;
return area;
end circle_area;

Function Calling
begin
dbms_output.put_line(circle_area(3));
end;

(OR)

SQL>declare
r number;
ans number;
begin
r: =&r;
ans:=circle_area(r);
dbms_output.put_line(“radius=” ||r);
dbms_output.put_line(“Area of circle ="||ans);
end;

ii) Stored procedure to accept name and greet user with name.
create or replace procedure Greet_User (user_name in varchar2)
is
begin
dbms_output.put_line(“Greet” || user_name);
end;

Q7. Explain steps of cursor implementation with syntax and example. (W-23) 4 Marks
Ans:
Cursor: it is temporary work area created in system memory when SQL statement is exceuted .
Types of Cursors:
 Implicit Cursor
 Explicit Cursor

Explicit cursor implementation steps are as follows −


• Declaring the cursor for initializing the memory
• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory

Syntax for creating explicit cursor:


Cursor cursor name IS select statement;

Example:
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
Examination Paper Analysis and Solution
CLOSE c_customers;
END;

Q.8 Write a PL/SQl program to display 10 reverse numbers. Use for loop. (W-23) 4 Marks
Ans:
DECLARE
a number (2);
BEGIN
FOR a IN REVERSE 1 .. 10 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;

Q9. Write PL-SQL program which accepts the customer ID from the user, if user enter an invalid ID,
then the exception invalid_id is raised using exception handling. (W-23) 6Marks
Ans:

DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;

ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;

EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;

Output:

Enter value for cc_id: -6 (let's enter a value -6)


old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

Q10. write PL-SQL code to print largest number from three numbers (accept three numbers from
user). (W-23) 6Marks
Ans:
declare
a number: =&a;
b number: =&b;
c number: =&c;
Examination Paper Analysis and Solution
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c);
if a>b AND a>c
then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c
then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;

Output:
a=10 b=12 c=5
b is greatest

Q.11 Define Trigger and list its types. (W-22) 2Marks


Ans:
Trigger: A PL/SQL trigger is a named database object that encapsulates and defines a set of actions
that are to be performed in response to an insert, update, or delete operation against a table.
Types of Triggers:
1. Row-level trigger
2. Statement-level trigger
3. Before-trigger
4. After-trigger

Q.12 Describe block structure of PL/SQL. (W-22) 4 Marks


Ans:
Block structure of PL/SQL
DECLARE
declaration part
BEGIN
executable statements
EXCEPTION
error handling statements
END;
End of PL/SQL block

 From the above block, declare and exception blocks are not compulsory block.
 Whereas begin and end blocks are compulsory block.
 If executable statements from begin consisting of any error, then that error will be handled in
exception block.
 PL/SQL is not case-sensitive

Q.13 Write a PL/SQL code that accepts 3 numbers from user and display largest number. (W-
22)4Marks
Ans:
declare
a number: =&a;
b number: =&b;
c number: =&c;
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c);
Examination Paper Analysis and Solution
if a>b AND a>c
then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c
then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;

Output:
a=10 b=12 c=5
b is greatest

Q.14 Define cursor. Write step by step syntax to declare, open, fetch and close cursor in PL/SQL
block. (W-22)4 Marks
Ans:
Cursor: it is temporary work area created in system memory when SQL statement is exceuted .
Types of Cursors:
 Implicit Cursor
 Explicit Cursor

Explicit cursor implementation steps are as follows −


• Declaring the cursor for initializing the memory
• Opening the cursor for allocating the memory
• Fetching the cursor for retrieving the data
• Closing the cursor to release the allocated memory

Syntax for creating explicit cursor:


Cursor cursor name IS select statement;

Example:
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;

Q.15.Write a PL/SQL code that handles divide by zero exception. (W-22) 4 Marks
Ans:
declare
a number (5): = 10;
b number (5): =0;
Examination Paper Analysis and Solution
c number (5);
myex EXCEPTION;
begin
c: =a/b;
if b=0 then
raise myex;
end if;
dbms_output.put_line(c);
EXCEPTION
when myex then
dbms_output.put_line('divide by zero exception occurred');
end;

Output:
divide by zero exception occurred

Q.16.Write PL/SQL function/procedure for following statements:


i)Write a function circle_area () to find area of circle, use radius as input parameter.
ii)Write a procedure emp_count ( ) to count number of employees in department, use dept_no as
input parameter (W-22) 6 Marks
Ans:
i)PL/SQL code for defining circle_area() function:
CREATE OR REPLACE FUNCTION circle_area (radius NUMBER)
RETURN NUMBER IS
pi CONSTANT NUMBER (7,2): =3.14;
area NUMBER (7,2);
BEGIN
area: = pi * (radius * radius);
RETURN area;
END;
PL/SQL code for calling circle_area() function:
DECLARE
c number (5,2);
BEGIN
c: = circle_area(1);
dbms_output.put_line('Area of circle: ' || c);
END;
ii) Procedure creation
CREATE OR REPLACE PROCEDURE emp_count(dept_no IN NUMBER)
IS
BEGIN

DECLARE
CURSOR c
IS SELECT * FROM emp where deptno=dept_no;
TYPE emp_tab IS TABLE OF c%ROWTYPE INDEX BY BINARY_INTEGER;
v_emp_tab emp_tab;
BEGIN
OPEN c;
FETCH c BULK COLLECT INTO v_emp_tab;
DBMS_OUTPUT.PUT_LINE(v_emp_tab.COUNT);
CLOSE c;
END;
END;
Examination Paper Analysis and Solution
To execute procedure
exec emp_count(10);

Unit 5: Database security and transaction processing


Q1. Enlist different types of Database Users(S-23) 2Marks.
Ans:
Database users are as follows:
1. Database Administrators (DBA)
2. Database Designers.
3. System Analysts.
4. Application Programmers
5. Naive Users
6. Sophisticated Users

Q2. Enlist ACID properties of transactions(S-23) 2Marks.


Ans:
ACID properties are as follows:
1.Atomicity
2.Consistency
3.Isolation,
4. Durability

Q3. Describe the different types and causes of Database failure. (S-23) 4 Marks
Ans:
1. Hardware Failure/System crash:
There is a hardware malfunction that causes the loss of the content of volatile storage, and it brings
transaction processing to a halt. The content of non-volatile storage remains intact and is not
corrupted or changed.
2. Software Failure:
The database software or the operating system may be corrupted or fail to work correctly, that may
cause the loss of the content of volatile storage, and results in database failure.
3. Media Failure:
A disk block loses its content as a result of either a head crash or failure during a data transfer
operation.
4. Network Failure:
A problem with network interface card or network connection and cause network failure.
5. Transaction Failure
i) Logical error: the transaction can no longer continue with its normal execution because of some
internal condition, such as wrong input values, data not found, data overflow or resource limit
exceeded.
ii) System error: A system entered in state like deadlock
6. Application software Error:
The problem with software accessing the data from database. -This may cause database failure as
data cannot be updated using such application to it. -Logical errors in the program cause one or more
transaction failures.
7. Physical disaster
The problem was caused by floods, fire, earthquakes etc.

Q4. Describe different states of transaction with a neat diagram (S-23) 4 Marks
Ans:
Examination Paper Analysis and Solution

These are different types of Transaction States:


1. Active State –
When the instructions of the transaction are running then the transaction is in active state. If all the
read and write operations are performed without any error then it goes to the partially committed state,
if any instruction fails, it goes to the failed state.
2. Partially Committed –
After completion of all the read and write operation the changes are made in main memory or local
buffer. If the changes are made permanent on the Database, then the state will change to “committed
state” and in case of failure it will go to the “failed state”.
3. Failed State –
When any instruction of the transaction fails, it goes to the “failed state” or if failure occurs in making a
permanent change of data on Database.
4. Aborted State –
After having any type of failure, the transaction goes from “failed state” to “aborted state” and since in
previous states, the changes are only made to local buffer or main memory and hence these changes
are deleted or rolled-back.
5. Committed State –
It is the state when the changes are made permanent on the Data Base and the transaction is
complete and therefore terminated in the “terminated state”
6. Terminated State –
If there isn't any roll-back or the transaction comes from the “committed state”, then the system is
consistent and ready for new transaction and the old transaction is terminated.

Q5. Write SQL commands for the following:


i) Create User ‘ABC’ with password as ‘IF4I’
ii) Grant privilege of select, delete, update on table EMP to user.
iii) Take back privilege of Delete from user ‘ABC’ on Relation
Emp. (S-23) 6 Marks.
Ans:
i) create user ABC identified by IF4I;
ii) grant select, delete, update on EMP to user;
iii) revoke Delete on Emp from ABC;

Q6. State properties of transaction. (W-23) 2Marks


Ans:
Properties of transaction are as follows:
1.Atomicity
2.Consistency
3.Isolation,
4.Durability

Q7. Describe use of grant and revoke commands with suitable example. (W-23) 4Marks
Examination Paper Analysis and Solution
Ans:
Grant: This command is used to give permission to the user to do operations on the other user’s
object.
Syntax: Grant <object privileges> on <object name> to <username> [with grant option];
Example: Grant select, update on emp to user1;

Revoke: This command is used to withdraw the privilege that has been granted to a user.
Syntax: Revoke <object privileges> on <object name> from <username>;
Example: Revoke select, update on emp from user1;

Q8. Explain ACID properties of transaction. (W-23) 4 Marks.


Ans:
1. Atomicity
Atomicity is based on the concept that each transaction be “all or nothing”: if any one part of the
transaction in a sequence fails, then the entire transaction fails, and there will be no change in
database state.
This property states that, either all operations contained by a transaction are done successfully or
none of them complete at all. To maintain the consistency of data this property is very useful.
2. Consistency
The consistency property ensures that the transaction executed on the database system will bring the
database from its original consistent state to another.
3. Isolation
The isolation property ensures that the system state should be same that would be obtained if
transactions were executed sequentially, i.e., one after the other. The effect of any incomplete
transaction should not be visible to other transactions. This can be achieved by isolation.
4. Durability
The durability property ensures that after the transaction is committed successfully the updates made
should remain permanent in the database even in the event of power loss, crashes or errors.

Q9. Define database backup. Describe how database backup helps to avoid failures. (W-23) 4 marks
Ans:
Database backup: Database Backup is storage of data that means the copy of the data.
It is a safeguard against unexpected data loss and application errors.
It protects the database against data loss.
If the original data is lost, then using the backup it can reconstructed The
backups are divided into two types:
1. Physical Backup
2. Logical Backup
1. Physical backup: Physical Backups are the backups of the physical files used in storing and
recovering your database, such as data files, control files and archived redo logs, log files. It is a copy
of files storing database information to some other location, such as disk, some offline storage like
magnetic tape.
2.Logical backup: Logical Backup contains logical data which is extracted from a database. It
includes backup of logical data like views, procedures, functions, tables, etc.
Database backup helps to avoid failures in following way:
 In case any kind of failure strikes your SQL server databases, a proper plan and a way of
recovery from that failure is needed, beforehand. A good backup can indeed be the best way
to recover from most of the failures, especially when your data is too critical or important.
 In case you lose a database or any of the tables becomes corrupt, then you can simply reload
your data from the backup. In addition, if you lose the whole server, then you may need to set
up a new server and re-install the SQL Server backup software, before using any of your
backups.
Examination Paper Analysis and Solution
 One of the most effective ways to prevent any kind of data loss and to recover your original
data in case of any failure is to store your entire SQL server database off-site. A secure
offshore backup can save you from many serious hassles in

Q10. Create a trigger which invokes on updating of record on emp table (W-23) 4 Marks
Ans:
create trigger trigger_update on emp
after update as
begin
Select * from employee;
end;
end;

Q11.Draw state diagram of transaction(W-22) 2Marks


Ans:

Q12. List any four causes of database failures(W-22) 2Marks


Ans:
Types of database failure:
1. Hardware Failure/System crash
2. Software Failure
3. Media Failure
4. Network Failure
5. Transaction Failure
6. Application software Error:
7. Physical disaster

Q13. Define transaction and explain ACID properties of transaction. (W-22) 4Marks
Ans:
Transaction:
Any logical work or set of work that is done on the data of a database is known as a transaction.
1. Atomicity
Atomicity is based on the concept that each transaction be “all or nothing”: if any one part of the
transaction in a sequence fails, then the entire transaction fails, and there will be no change in
database state.
This property states that, either all operations contained by a transaction are done successfully or
none of them complete at all. To maintain the consistency of data this property is very useful.
2. Consistency
The consistency property ensures that the transaction executed on the database system will bring the
database from its original consistent state to another.
3. Isolation
Examination Paper Analysis and Solution
The isolation property ensures that the system state should be same that would be obtained if
transactions were executed sequentially, i.e., one after the other. The effect of any incomplete
transaction should not be visible to other transactions. This can be achieved by isolation.
4. Durability
The durability property ensures that after the transaction is committed successfully the updates made
should remain permanent in the database even in the event of power loss, crashes or errors.

Q14. Write SQL commands for following statement


i) Create user Rajesh having password as Rajesh@123.
ii) Assign ALL privileges on Book table to Rajesh.
iii) Remove INSERT and DELETE privileges on book table from Rajesh. (W-22) 6Marks
Ans:
i) Create user Rajesh having password as Rajesh@123
CREATE USER Rajesh IDENTIFIED BY Rajesh@123

ii) Assign all privileges on Book Table to Rajesh


GRANT ALL ON Book TO Rajesh;

iii) Remove INSERT and DELETE privileges on book table from Rajesh.
REVOKE INSERT, DELETE ON book FROM Rajesh;

You might also like