Dms All Unit Imp Questions
Dms All Unit Imp Questions
“MASTER SOLUTIONS”
Semester – CO3K
3 Distinguish between network model and hierarchical model (any 4 points). W-18 4
W-19
W-23
S-24
2
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Ans
6. The View Updating rule: All views of the data which aretheoretically
updatable must be updatable in practice by the DBMS.
3
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
7. The High-level Insert, Update, and Delete rule: The capability ofhandling
a base relation or a derived relation as a single database toperform all DML
operations.
12. The No subversion rule: If the database has any means of handlinga
single record at a time that low-level language must not be able avoidthe
integrity rules which are expressed in a higher-level language thathandles
multiple records at a time.
and Recovery
4
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Embedded DML pre compiler: It converts DML statements embedded in diagram, 2
application. M
Program to normal procedural calls in host language. for correct
DML Compiler: It translates DML statements of high level language explanation
into low level instruction that a query evaluation engine understands.
DDL interpreter: It interprets DDL statements and records them in a
set of tables containing metadata.
Query evaluation Engine: It executes low level instructions generated
by DML compiler and issued by query processor to select efficient ways
to execute query.
DDL interpreter. It has following components
2. Storage Manager Components :
Transaction manager: It ensures that the database remains in
consistent state despite of the system failure and that concurrent
transaction execution proceeds without conflicting.
File Manager: It manages the allocation of space on disk storage and
data structures used to represent information stored on disk
Buffer Manager: It is responsible for fetching data from disk storage
into main memory and deciding what data to cache memory.
3. Disk storage :
Data files: It stores the database.
Data Dictionary: It stores metadata that hold particular values.
Indices: Provide fast access to data items that hold particular values.
Statistical data: It stores statistical information about the data in the
database.
5
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Ans Any 4
differences :
1M each
1 State any two advantages of DBMS over file processing system. W-19 2
Explain advantages of DBMS over file processing system. S-22 4
Ans State any two advantages of DBMS over file processing system. Any two
Advantages of DBMS over file processing system: advanta
ges 1M
each
6
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Ans
2 With neat diagram explain three level architecture of database system. S-22 4
Explain three level architecture of Database system. W-22 4
Ans The three levels present in this architecture are Physical level, Conceptual
level and External level.
Physical Level
This is the lowest level in the three level architecture. It is also known as
the internal level. The physical level describes how data is actually stored
in the database. In the lowest level, this data is stored in the external hard
drives in the form of bits and at a little high level, it can be said that the
data is stored in files and folders. The physical level also discusses
compression and encryption techniques.
Conceptual Level
The conceptual level is at a higher level than the physical level. It is also
known as the logical level. It describes how the database appears to the
7
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
users conceptually and the relationships between various data tables. The
conceptual level does not care for how the data in the database is actually
stored.
External Level
This is the highest level in the three level architecture and closest to the
user. It is also known as the view level. The external level only shows the
relevant database content to the users in the form of views and hides the
rest of the data. So different users can see the database as a different view
as per their individual requirement
9
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
specialized features that help provide shielding to its data. 8. Backup: It
creates a backup subsystem to restore the data if required.
9. Interfaces: It provides different multiple user interfaces like graphical user
interface and application program interface. 10. Easy Maintenance: It is
easily maintainable due to its centralized nature
10
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
JSPM’s
RAJARSHI SHAHU COLLEGE OF ENGINEERING,
POLYTECHNIC
Department of Computer Engineering
Academic Year: 2024-25
UNIT-2 ( 12 Marks)
MSBTE Question bank
S-24 4
11
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ans First Normal Form (1NF):
A relation R is said to be in first normal form (1NF) if the domain
of all attributes of R
are atomic.
OR
A table is in the first normal form if it contains no repeating
elements groups. Example:
Supplier(sno,sname,location,pno,qty)
12
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
CandidateKeys:{teacher_id,subject}
Non-prime attribute: teacher_age The table is in 1 NF because
each
attribute has atomic values. However, it is not in 2NF because
nonprime attribute teacher_age is dependent on teacher_id alone
which is a proper subset of candidate key. This violates the rule
for 2NF as the rule says “no non-prime attribute is dependent on
the proper subset of any candidate key of the table “To make the
table complies with 2NF we can break it in two tables like this:
teacher details tab
A table is said to be in 2NF if both the following conditions hold:
Table is in 1NF (First normal form) No non-prime attribute is
dependent on the proper subset of any candidate key of table. San
attribute that is not part of any candidate key is known as non- prime
attribute. Example: Suppose a school wants to store the data of
teachers and the subjects they teach. They create a table that looks
like this: Since a teacher can teach more than one subjects, the
table can have multiple rows for a same teacher.
CandidateKeys:{teacher_id,subject}
Non-prime attribute: teacher_age The table is in 1 NF because
each attribute has atomic values. However, it is not in 2NF because
nonprime attribute teacher_age is dependent on teacher_id alone
which is a proper subset of candidate key. This violates the rule for
2NF as the rule says “no non-prime attribute is dependent on the
proper subset of any
candidate key of the table “To make the table complies with 2NF
we
can break it in two tables like this: teacher_subject Table
13
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
2 Draw ER diagram for library management system considering S-19 6
issue and return, fine collection facility. Consider appropriate
entities.
ans
14
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ans 3NF: Explana
An entity is said to be in the third normal form when, tion 2M
1) It satisfies the criteria to be in the second normal form. Any
2) There exists no transitive functional dependency. (Transitive example
functional dependency can be explained with the relationship link 2M
between three tables. If table A is functionally dependent on B,
and B is functionally dependent on C then C is transitively
dependent on A).
Let us consider the Schema given:
(Supplier_no,SupplierName,Supplier_city,Order_no,Order_quant
ity,
Order_amount,Product_code,Product name,rate)
Step 1.To convert it into 2NF, We have to decompose the given
table into two tables with fully functional dependencies and
establishing a referential integrity constraint relationship among
the two tables.Table2: Supplier Details
(Supplier_no,Supplier_name,Supplier_city)
Table 3:Order Details
(Order_no,Orderquantity,Order_amount,Supplier_no
Product_code,
product_name,rate)
Now the above two tables are in 2NF
Step 2: To convert the above tables in 3NF, we have to
decomposehem in three tables satisfying the transitive
dependencies
property.
Table 4: Supplier Details
(Supplier_no,Supplier_name,Supplier_city)
Table 5: Product Details:
(Product_code, product_name,rate)
Table 6: Order Details (or Transaction Details)
((Order_no,Supplier_no,Product_code,Order_quantity,Order_am
ount
)
Hence the above three tables are satisfying Transitive
dependencies.
Thus they are in 3NF.
4 Explain strong and weak entity set. W-19 4
ans Strong entity set: Each
An entity set that has sufficient attributes to form a primary key is entity set
called as Strong entity set. 2M
Example: Employee is a Strong entity with attributes as empid,
name,
address, salary, birthdate among which empid can be considered
as
primary key.
Weak entity set:
The entity set which does not have sufficient attributes to form a
primary key is called as Weak entity set.
A weak entity is an entity that cannot be uniquely identified by its
15
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
attributes alone; therefore, it must use a foreign key in conjunction
with its attributes to create a primary key. The foreign key is
typically
a primary key of an entity it is related to.
Example: Employee has "dependents" with name, birthdate, and
relationship to employee and it can be related to employee with the
help of empid, so "dependents" is a weak entity which depends on
strong entity "Employee".
5 Draw an ER diagram for library management system. (Use Books, W-19 6
Publisher & Member entities).
ans
16
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ans
17
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ans
18
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
CREATE TABLE <Table_Name>
(
Column1 datatype,
Column2 datatype, CONSTRAINT <Name> UNIQUE KEY
(Column name)
);
Example:
CREATE TABLE students
(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
UNIQUE (S_Id)
)
OR
CREATE TABLE students
(
S_Id int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255),
City varchar (255),
CONSTRAINT uc_studentId UNIQUE (S_Id, LastName)
)
19
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ans 1. Simple Attribute: Simple attributes are those that cannot be
further divided into sub-attributes.
For example, roll number of a student or the employee
identification number.
2. Composite Attribute: Composite attributes are made up of two
or more simple
attributes.For example, a persons address may be a composite
attribute that is made up of
the persons street address, city, state, and zip code.
3. Single Valued Attribute: Single-valued attributes can only have
one value.
Single-valued attributes are typically used to provide a unique
identifier for an
entity and are often used in databases.
For example, a persons Social Security Number is a single-valued
attribute.
4. Multivalued Attribute: Multivalued attributes can have more
than one value.
For example, a person may have multiple email addresses or phone
numbers.
5. Stored Attribute: Values of stored attributes remain constant and
fixed for an
entity instance and also, and they help in deriving the derived
attributes.
For example, the Age attribute can be derived from the Date of
Birth attribute, and
also, the Date of birth attribute has a fixed and constant value
throughout the life
of an entity. Hence, the Date of Birth attribute is a stored attribute.
6. Derived Attribute: Derived attributes are based on other
attributes and are not
stored directly in the database.
For example: Consider a database of employees. Each employee
has a date of
birth, and we can calculate their age which can be called as derived
attribute.
3 Explain strong entity and weak entity set .draw diagram indicating S-23 6
strong and weak entity set
Explain strong and weak entity set. 4
W-19
single.
20
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
a
diamond symbol
of
an entity set
with the relationship set. Total participation may or may not exist
in the
relationship.
Example:
Student and course relation: Student entity is a strong entity
because it
consists of a primary key called student id which is enough for
accessing each
record uniquely. In the same way, the course entity contains of
course ID attribute
which is capable of uniquely accessing each row.
set.
he identifying
relationship is double.
strong and a weak entity set is
represented by a doublediamond symbol.(known as identifying
relationship)
Example:
Employee is a strong entity because it has a primary key attribute
called Employee number (Employee_No) which is capable of
uniquely
identifying all the employee.Unlike Employee, Dependents is
weak entity because it does not have any primary key .
21
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
4 Draw an ER Diagram of Libarary management system consdiering S-23 6
publisher, member also show primary key , weak entity and strong
entity
ans
22
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
insertion anomaly, update anomaly & deletion anomaly.
Second Normal Form (2NF):
A relation is said to be in the second normal form if it is in first
normal form and all the
non key attributes are fully functionally dependent on the primary
key.
Example
• This table is in first normal form, in that it obeys all the rules of
first normal form.
• In this table, the primary key consists of SNO.
• However, the table is not in second normal form because there
are partial
dependencies of primary keys and columns.
• In the above relation NAME, LOCATION depends on SNO and
QTY on (SNO,
PNO)
• so the table can be split up into two tables as
Supplier(SNO,SNAME,LOCATION)
and SP(SNO,PNO,QTY) and now both the tables are in second
normal form.
Supplier
23
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
2 Draw ER diagram for Hospital management system. (Use Entity- W-23 6
Doctor, Patient, Hospital and Medical Record). Show Primary
Key, and Foreign Key
ans Correct
entities: 2M,
correct
symbols: 2M,
Correct
relationships:
2M
24
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ans
25
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
26
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
JSPM’s
RAJARSHI SHAHU COLLEGE OF ENGINEERING,
POLYTECHNIC
Department of Computer Engineering
Academic Year: 2024-25
UNIT-3 ( 18 Marks)
MSBTE Question bank
27
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
i) Lower(char)-
Returns the input string with all letters in lower case.
Example: SQL>Select lower (‘RAJESH’) from dual;
Output: rajesh
ii) Upper(char)-
Returns the input string with all letters in upper case.
Example: SQL>Select upper (‘rajesh’) from dual;
Output: RAJESH
iii) Ltrim(char,set)-
It removes or trims from left of character string
. Example: SQL>Select Ltrim(‘university’,’univ’) from dual;
Output: ersity
iv) Rtrim(char,set)-
It removes or trims from right of character string.
Example: SQL>Select Rtrim(‘university’,’sity’) from dual;
Output: univer
v) Length(char)-
It returns length of character string.
Example: SQL> Select length(‘University’) from dual;
Output:10
vi) Concat(str1,str2,...)-
Returns the string that result from concatenating the arguments.
Example: Select Concat(‘employee’, ‘name’) from dual;
Output: employee name
vii) Lpad(str, len, padstr)-
Returns the string str, left-padded with the string padstr to a
length of len characters.
Example: Select lpad(ename,10.’*’) from emp where
empno=7782;
viii) Rpad(str,len,padstr)-
Returns the string str, right-padded with the string padstr to a
length of len characters.
Example: Select rpad(ename,10.’*’) from emp where
empno=7782
viii) Substr(Char,m,n)-
It returns a portion of char, beginning at a character m, n
character long.
Example: Select substr(‘College’,3,4) from dual;
Output: lleg
4 Explain joins in SQL with examples. W-18, 4
S-24
28
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
JOIN:
A SQL join is an instruction to combine data from two sets of
data (i.e. two tables). A
JOIN clause is used to combine rows from two or more tables,
based on a related column
between them. SQL Join types are as follows:
1) INNER JOIN or EQUI JOIN:
A join which is based on equalities is called equi join. In equi
join comparison
operator “=” is used to perform a Join.
Syntax:
SELECT
tablename.column1_name,tablename.column1_name
FROM table_name1,table_name2
where
table_name1.column_name=table_name2.column_name;
Example:
Select stud_info.stud_name, stud_info.branch_code,
branch_details.location
From stud_info, branch_details
Where Stud_info.branch_code=branch_details.branch_code;
2) SELF JOIN:
The SQL SELF JOIN is used to join a table to itself, as if the
table were two
tables, temporarily renaming at least one table in the SQL
statement.
Syntax:
SELECT a.column_name, b.column_name
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Example:
Select x.stud_name, y.stud_name
from stud_info x, stud_info y
Where x.leader= y.stud_id;
29
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
3) LEFT OUTER JOIN:
A left outer join retains all of the rows of the “left” table,
regardless of whether there is a
row that matches on the “right” table.
Syntax:
Select column1name,column2name
from table1name any_alias1 ,table2name any_alias2
on any_alias1.columnname(+) = any_alias2.columnname;
OR
Select column1name,column2name
from table1name left outer join table2name
on table1name.columnname= table2name.columnname;
Example:
select last_name, department_name
from employees e, departments d
on e.department_id(+) = d.department_id;
OR
select last_name, department_name
from employees left outer join departments
on employees.department_id = departments.department_id;
30
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
For example:
In emp table and salgrade table. The salgrade table contains
grade and their low
salary and high salary. Suppose you want to find the grade of
employees based on
their salaries then you can use NON EQUI join.
Select e.empno, e.ename, e.sal, s.grade
from emp e, salgrade s
where e.sal between s.lowsal and s.hisal;
4 Explain set operators with example W-18 4
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.
Consider data from two tables emp and employee as
32
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Name char (20)); iii) Change the seq_ 1 max value 20 to 50. iv)
Drop the sequence.
i) create sequence Seq_1 start with 1 increment by 1 minvalue Query 1: 2M,
1 maxvalue Query 2: 2M,
20; Query 3 : 1M,
ii) insert into student values(Seq_1.nextval,’ABC’) Query 4 : 1M
iii) Alter sequence Seq_1 maxvalue 50;
iv) Drop sequence Seq_1
33
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
3 List the SQL ope S-19 4
rations and explain range searching operation ‘between’ and
pattern matching operator ‘like’ with example.
Types of SQL operators :
1) SQL Arithmetic Operators
2) SQL Comparison Operators
3) SQL Logical Operators
Arithmetic operators are used to perform arithmetic operations List of
on operators :
numbers. They are +,-,*, / and %. 2M,
Comparison operators are used in between two variables to between
compare operator :
their values. They are <,>,<=,>=,=,!=or <>,!< and !>.' 1M,
Logical operators are used for the Boolean results in sql queries Like
for operator :
comparison of values from the attributes of the tables. Eg: Any, 1M
Exists,
All, Like, Between, In etc.
Between operator: The BETWEEN operator is used to search
for
values that are within a set of values, given the minimum value
and the maximum value inclusive of both the limits.
Eg: select * from emp where salary between 40000 and 50000;
34
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
This will results in rows from emp table where salary falls in
the range of 40000 to 50000.
Like operator :
The LIKE operator is used to compare a value to similar values
using
wildcard operators. It uses two wild characters as ‘%’ and ‘_’
where ‘%’
represents all characters of the pattern and ‘_’ represents one
single character from pattern.
Eg :
Select ename from emp where ename like ‘S%’;
This will return all employee names starting with ‘S’.
Select ename from emp where ename like ‘_a%;
This will return all employee names whose second character is
‘a’
4 Write syntax for creating synonyms with example. S-19 2
Syntax to create synonym: 1 M for
CREATE SYNONYM SYNONYM_name correct
FOR Table_name; syntax, 1 M
Example to create synonym: for
CREATE SYNONYM offices correct
FOR locations example
5 Write and explain syntax for creating view with example. S-19 4
A view contains rows and columns, just like a real table. The
fields in a view are fields from one or more real tables in the
database.
View has two types:
1. Simple view: The fields in a view are fields from one table
in the
database.
2. Complex view: The fields in a view are fields from more
than one table in the database. You can add SQL functions,
WHERE, and JOIN statements to a view and present the data
as if the data were coming
from different table.
CREATE VIEW Syntax
Create view view_name As
Select column1, column2…
From table_name
Where condition ;
Example
Create view mumbai_customers AS
Select customer_name,contact_name
From customers
Where city=’Mumbai’;
6 Explain any four aggregate functions with example. S-19 4
W-23
35
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
An aggregate function is a function where the values of
multiple rows are grouped together as input on certain criteria
to form a single value of
more significant meaning.
Aggregate functions are :
1) Count()
2) Sum()
3) Avg()
4) Min()
5) Max()
1. Count () - 1) It returns number of rows from the given table
if no attribute is mentioned.
2) If some attribute is mentioned, it gives total number of not
null valfor that attribute.
Eg :Select count(*) from emp;
Returns total number of records from emp table.
1) Select count(telephone) from emp;
Returns total number of employees having telephone numbers.
2. Sum() - It give total of all values from a numeric attribute of
the given table,
Eg :Select sum(salary) from emp;
Returns total salary drawn of all employees from the emp table.
3. Avg () - It gives average of all the numeric values of the
given attribute from the table.
Eg :Select Avg(salary) from emp;
Returns average salary of employees from emp table.
4. Min () - It gives minimum of all the values of the numeric
given attribute from the table.
Eg :Select Min(salary) from emp;
Returns minimum salary value from emp table,
5. Max () - It gives maximum of all the values of the numeric
given attribute from the table.
Eg :Select Max(salary) from emp;
retunes maximum salary value from emp tableues
36
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Syntax: Drop index <index_name>; allowed.)
(OR)
E.g. (Assuming idx_empno created on employee table)
Drop index idx_empno;
8 Consider the table Student (name, marks, dept, age, place, S-19 6
phone, birthdate) Write SQL query for following : (i) To list
students having place as ‘Pune’ or ‘Jalgaon’. (ii) To list
students having same department (dept) as that of ‘Rachana’.
(iii) To change marks of ‘Rahul’ from 81 to 96. (iv) To list
student name and marks from ‘Computer’ dept. (v) To list
student name who have marks less than 40. (vi) To list students
who are not from ‘Mumbai’.
select name from Student where place= ‘Pune’ or Each Correct
place=’Jalgaon’; Query : 1M
(OR)
select name from Students where place in(‘Pune’,‘Jalgaon’);
ii) select name from Student where dept=(select dept from
student where
name=’Rachana’);
iii) update Student set marks=96 where name= ‘Rahul’;
v)select name,marks from Student where dept=‘Computer’;
iv) select name from Student where marks<40;
v) select * from Student where place != ‘Mumbai’;
9 i) Write a command to create table student (RNo., name, S-19 6
marks, dept.) with proper datatype and RNo as primary key.
(ii) Write a command to create and drop sequence.
i) create table student
(
RNO number(5) constraint student _RNOpk primary key,
name varchar2(20),
marks number(4),
dept varchar2(20)
);
(OR)
create table student
(
RNO number(5) ,
name varchar2(20),
marks number(4),
dept varchar2(20),
constraint student_RNO_pk primary key(RNO),
);
ii) Create Sequence:
Create sequence <seq_name>
Start with [initial value]
Increment by [value]
Minvalue [minimum value]
Maxvalue [maximum value]
[cycle/no cycle]
[{cache value / No cache}]
37
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
[{order / No order}];
(OR)
(Creating sequence for Employee number of emp table.)
Create sequence emp_eno_seq
start with 1
increment by 1
maxvalue 100
no cycle
no cache;
Drop sequence:
Drop sequence<Sequence Name>;
(OR)
Drop sequence emp_eno_seq
10 Write SQL command for following : (i) Create user (ii) Grant S-19 6
privileges to user (iii) Remove privileges from user
i) Create user Each correct
CREATE USER <username> IDENTIFIED BY <password>; command:
(OR) 2M
CREATE USER RAJ IDENTIFIED BY RAJ123; (Note: Either
ii) Grant privileges to user. syntax or
GRANT <privilege list> ON <relation name or view name> example can
TO<user list>; be
(OR) considered.
(assuming table Employee for granting permissions to user Any other
‘RAJ’ example
for select, insert, update and delete privilege) allowed
GRANT SELECT, INSERT,UPDATE,DELETE ON
EMPLOYEE TO RAJ;
Iii) Remove privileges from user.
REVOKE <privilege list> ON <relation name or view name >
FROM <user list>;
(OR)
(assuming table Employee for revoking permissions to user
‘RAJ)
REVOKE SELECT, INSERT,UPDATE,DELETE ON
EMPLOYEE FROM RAJ;
38
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
character specified to a total of length specified. Ltrim(String)
-removes white space or other specified characters from the left
end of the string Rtrim(String)--removes white space or other
specified characters from the right end of the string
Replace(String, char,char) – replace all occurrence of a
substring by another substring Substring(String,number) –
extracts substring from the string Translate(String,char,char) –
replace all occurrence of characters by other characters
2 Enlist DML commands. W-19 2
- used to insert new row into table Any 2
- used to delete a row from the table comman ds
– used to modify data in the table. 1M each
Select – used to view data from a table.
3 Explain any four set operators in SQL with example. W-19 4
Set operators combine the results of two component queries 1M each
into a for
single result. Queries containing set operators are called as explanat
compound queries. Set operators in SQL are represented with ion of
following special operator
keywords as: Union, Union all, intersection & minus. s with
1) Union: The Union of two or more sets contains all elements, example
which are present in either or both. Union works as or. The
duplicates of both the tables will appear only once.
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;
4 Describe create & alter command with syntax & example. W-19 4
1) The SQL CREATE TABLE statement is used to create a Each
new comman
table. d 2M
Syntax
The basic syntax of the CREATE TABLE statement is as
follows –
CREATE TABLE table_name
(
column1 datatype (size),
column2 datatype(size),
column3 datatype(size),
....
39
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
);
Example:
CREATE TABLE Persons
(
PersonIDnumber(10),
LastNamevarchar2(20),
FirstNamevarchar2(20),
Address varchar2(20),
City varchar2(20)
);
2)The ALTER TABLE statement is used to add, delete, or
modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop
various constraints on an existing table.
i) To add Columns in a table
Syntax:ALTER TABLE table_name
ADD column_name datatype;
Example
ALTER TABLE Customers
ADD Email varchar2(20);
ii) To delete a column in a table
ALTER TABLE table_name
DROP COLUMN column_name;
Example
ALTER TABLE Customers
DROP COLUMN Email;
iii) To modify a column in a table
Syntax:
ALTER TABLE table_name
MODIFY COLUMN column_name datatype;
Example
ALTER TABLE Customers
MODIFY COLUMN customeridnumeric(10);
iv) To add Constraints in A table
Syntax:
ALTER TABLE table_name
ADD constraint constraintname (column_name);
Example:
ALTER TABLE Customers
ADD constraint primary key(CustomerID);
5 Describe Views and write a command to create view. W-19 4
A view is a virtual table based on the result set of the SQL Explana
statement. tion 3M
The fields in a view are fields from one or more than one table General
in the database. SQL functions, where, join statements can be syntax/
added to a view and the data in it can be presented as if it were example
from one table. The database engine recreates the data, using 1M
the view’s SQL statement, every time a user queries a view. A
view can be updated using the create or replace view command.
For deleting a view, drop query can be used.
40
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
General syntax to create a view:
create view viewname as select query.
Eg:
create view vw_student as select stud_id, stud_name,ssc_per
from
student;
6 Define index. Explain it’s types. W-19 4
An Index is a schema object. It is used by the oracle server to Definitio
improve the speed of retrieval of the rows from a table .Indexes n 1M
are of two types based on number of columns included in the Each
index. type
The types of index are: 1½M
1) Simple index: An index created on a single column of table
is
called as simple index
Syntax:
SQL>Create Index index_name on tablename(attribute);
Example:Create index emp_index on emp(empno);
2) Composite Index: An index created on more than one
column is called composite index.
Syntax:
SQL>Create Index index_name on
tablename(attribute1,attribute2);
Example: Create index emp_index on emp(empno,ename);
41
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
SQL>Insert into student
values(2,‟Raj‟,‟CO‟,‟FirstYear‟,‟22-
Sep2002‟,‟Mumbai‟,98896863)
(iv)Undo the insertion of second row:
SQL> rollback;
( OR)
SQL> rollback work;
(v)Create savepoint s1:
SQL>Savepoint s1;
(vi) insert one row into the table:
SQL>Insert into student
values(3,‟Beena‟,‟CO‟,‟FirstYear‟,‟30-
Dec-2002‟,‟Mumbai‟,97846455)
42
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
9 Consider the structure for book table as Book-Master (bookid, W-19 6
bookname, author, no_of copies, price) Write down SQL
queries for following (i) Write a command to create
Book_master table. (ii) Get authorwise list of all books. (iii)
Display all books whose price is between ` 500 & ` 800. (iv)
Display all books with details whose name start with ‘D’. (v)
Display all books whose price is above ` 700. (vi) Display all
books whose number of copies are less than 10.
(i) Write a command to create Book_Master table table. Each
SQL>Create table Book-Master( correct
bookid number(5), Query
bookname char(10), 1M
authorvarchar(20),
no_of_copiesnumber(10),
price number(10,2)
);
(ii) Get authorwise list of all books.
SQL>Select sum(no_of copies) from Book_Master group by
author;
(iii) Display all books whose price is between Rs.500 & Rs. 800
SQL> Select * from Book_Master where price between 500
and
800;
OR
SQL> Select * from Book_Master where price >=500 and
price<=800;
(iv) Display all books with details whose name start with ‘D’
SQL> Select bookname from Book_Master where bookname
like
„D%‟;
(v) Display all books whose price is above Rs. 700
SQL>Select * from Book_Master where price >700;
(vi) Display all books whose number of copies are less than 10
SQL>Select * from Book_Master where no_of_copies<10;
SELECT AVG(Price)
FROM Products;
2 List any four data types in sql S-22 2
Numeric data types such as: INT , TINYINT , BIGINT ,
FLOAT , REAL , etc.
Date and Time data types such as: DATE , TIME , DATETIME
, etc.
Character and String data types such as: CHAR , VARCHAR
, TEXT , etc.
43
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Unicode character string data types such as: NCHAR ,
NVARCHAR , NTEXT , etc
3 Explain any two DDL commands along with example. S-22 4
Syntax –
Syntax to add a column to an existing table.
44
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
ADD column_name datatype;
Example –
In our Student_info table, we want to add a new column for
CGPA. The syntax would be as below as follows.
Syntax –
Syntax to remove an existing table.
Syntax –
Syntax to drop an existing table.
Syntax –
RENAME TABLE <Table Name> To <New_Table_Name>;
Example:
If you want to change the name of the table from Employee to
Emp we can use rename command as
RENAME TABLE Employee To EMP; syntax for i) Create
Index ii) Drop Index
4 Describe the concept of view with example. State its purpose. S-22 4
45
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
A view is a virtual table based on the result set of the SQL
statement.
The fields in a view are fields from one or more than one table
in the
database. SQL functions, where, join statements can be added
to a
view and the data in it can be presented as if it were from one
table.
The database engine recreates the data, using the view’s SQL
statement, every time a user queries a view. A view can be
updated
using the create or replace view command. For deleting a view,
drop
query can be used.
General syntax to create a view:
create view viewname as select query.
Eg:
create view vw_student as select stud_id, stud_name,ssc_per
from
student;
5 i) Create user ‘RAM’. ii) Grant create, select, insert, update, S-22 6
delete privileges to user ‘RAM’. iii) Remove update privilege
from user ‘RAM’
I)CREATE USER RAM IDENTIFIED BY RAM123;
ii) CREATE USER RAJ IDENTIFIED BY RAJ123;
ii) Grant privileges to user.
GRANT <privilege list> ON <relation name or view name>
TO<user list>;
(OR)
(assuming table Employee for granting permissions to user
‘RAM’
for select, insert, update and delete privilege)
GRANT SELECT, INSERT,UPDATE,DELETE ON
EMPLOYEE TO RAM;
Iii) Remove privileges from user.
REVOKE <privilege list> ON <relation name or view name >
FROM <user list>;
(OR)
(assuming table Employee for revoking permissions to user
‘RAM)
REVOKE SELECT, INSERT,UPDATE,DELETE ON
EMPLOYEE FROM RAM;
49
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
DROP INDEX
The DROP INDEX statement is used to delete an index in a
table.
Syntax:
DROP INDEX index_name ON table_name;
Example:
DROP INDEX id_firstname ON Student;
8 State the use of group by and order by clauses. W-22 4
Group by Clause: 2 M=
Group by clause is used to collect the data as multiple records group by
and group them to produce the result. 2 M=
Syntax: order by
1. SELECT column_name, function(column_name)
2. FROM table_name
3. WHERE condition
4. GROUP BY column_name;
Ex: select avg(sal) from emp_details group by deptno;
Order by Clause:
To view the data in sorted order, the order by clause is used.
By default, the data is sorted in ascending order.
Syntax:
5. SELECT expressions
6. FROM tables
7. [WHERE conditions]
8. ORDER BY expression [ ASC | DESC ];
Ex: select deptno from emp_details order by deptno;
Ex: select deptno from emp_details order by deptno desc; (for
descending order
9 Write the SQL queries for following EMP table. Emp (empno, W-22 6
deptno, ename, salary, designation, city.) i) Display average
salary of all employees. ii) Display names of employees who
stay in Mumbai or Pune. iii) Set the salary of employee
'Ramesh' to 50000. iv)Display names of employees whose
salaries are less than 50000. v) Remove the Record of
employees whose deptno is 10. vi) Remove the column deptno
from EMP table.
i. select avg(salary) from emp; 1 M each
ii. select ename from emp where city=’Mumbai’ or
city=’Pune’;
iii. update emp set salary=50000 where ename=’Ramesh’;
iv. select ename from emp where salary<50000;
v. delete from emp where deptno=10;
vi. alter table emp drop column deptno;
10 Write SQL queries for following. Consider table stud (roll no, W-22 6
name, subl, sub2, sub3) i) Display names of student who got
minimum mark in subl. ii) Display names of students who got
above 40 marks in sub2. iii) Display count of Students failed in
sub2. iv) Display average marks of subl of all students. v)
Display names of students whose name start with 'A' by
50
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
arranging them in ascending order of subl marks. vi) Display
student name whose name ends with h' and subject 2 marks ar6
i. select name from stud where sub1= (select min(sub1) from 1 M each
stud);
ii. select name from stud where sub2>40;
iii. select count(*) from stud where sub2<40;
iv. select avg(sub1) from stud;
v. select name from stud where name like 'A%' order by sub1;
vi. select name from stud where name like '%h' and sub2
between 60 and 75;
11 Write SQL queries for following. 1) Create user named 'user1' W-22 6
having Password '1234 ii) Assign 'insert' and update' Privilege
to 'userl". ii) Remove update Privilege assigned to the userl. iv)
Assign the resource Pemission to userl.
i. create user user1 identified by 1234; 1½M
ii. grant insert, update on system.emp to user1; each
iii. revoke update on system.emp from user1;
iv. grant create session, unlimited tablespace, create table to
user1;
DML commands:
- used to insert new row into table
- used to delete a row from the table
– used to modify data in the table.
– used to view data from a table.
52
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
1) Insert : For adding records in table:
We use Insert into command for adding/inserting data into
table.
Syntax:
Insert into <table name> values (value1, value2, value3…);
Ex:
insert into Student values(1,‟xyz‟,‟12-Jan-1990‟,88,10);
OR
Ex:Insert into
Studentvalues(&R_No,‟&Name‟,‟&DOB‟,&Percentage,&D
_No);
2) Update : For modifying records in table
We use update command for modifying data of a table.
Syntax:
Update <table name>set columnname1=expression where
<condition>;
Ex:
update Student set DOB=‟22-feb-1995‟ where R_No=3;
3) Delete : For deleting records from table:
We use delete command for deleting data of a table.
Syntax:
Delete from <table name>[where <condition>];
Ex:
delete from Student where R_No=2;
4) Select : For viewing the records from table
We use select command for displaying or viewing the records
from a table or
tables.
Syntax:
Select <*/ list of columns> from <table name> [where
<condition> ] ;
Ex :
Select * from Student;
Select R_N0,Name,DOB from Student where Percentage > 80;
5 Explain any two types of join with example. S-23 6
JOIN: Explanati
A SQL join is an instruction to combine data from two sets of on of any
data (i.e. two two types
tables). A with
JOIN clause is used to combine rows from two or more tables, example
based on a 3M each
related column between them. SQL Join types are as follows:
1) EQUI JOIN:
A join which is based on equalities is called equi join. In equi
join comparison
operator “=” is used to perform a Join.
Syntax:
SELECT
tablename.column1_name,tablename.column2_name
53
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
FROM table_name1,table_name2
where
table_name1.column_name=table_name2.column_name;
Example:
Select stud_info.stud_name, stud_info.branch_code,
branch_details.location
From stud_info, branch_details
Where Stud_info.branch_code=branch_details.branch_code;
2) SELF JOIN:
The SQL SELF JOIN is used to join a table to itself, as if the
table were two
tables,temporarily renaming at least one table in the SQL
statement.
Syntax:
SELECT a.column_name, b.column_name
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Example:
Select x.stud_name, y.stud_name
from stud_info x, stud_info y
Where x.leader= y.stud_id;
3) INNER JOIN:The INNER JOIN command returns rows that
have
matching values in both tables.
Syntax:
Select column1_name,column2_name
from table1name INNER JOIN table2name
on table1name.columnname= table2name.columnname;
Example:
Select last_name, department_name
from employees inner join departments
on employees.department_id = departments.department_id;
4) LEFT OUTER JOIN:
A left outer join retains all of the rows of the “left” table,
regardless of whether there is a row that matches on the “right”
table.
Syntax:
Select column1_name,column2_name
from table1name any_alias1 ,table2name any_alias2
on any_alias1.columnname(+) = any_alias2.columnname;
OR
Select column1_name,column2_name from table1name left
outer join table2name
on table1name.columnname= table2name.columnname;
Example:
select last_name, department_name
from employees e, departments d
on e.department_id(+) = d.department_id;
OR
select last_name, department_name
54
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
from employees left outer join departments
on employees.department_id = departments.department_id;
5) RIGHT OUTER JOIN:
A right outer join retains all of the rows of the “right” table,
regardless of whether there is a row that matches on the “left”
table.
Syntax:
Select column1name, column2name from table1name
any_alias1, table2name any_alias2
on any_alias1.columnname =any_alias2.columnname (+);
OR
Select column1name, column2name from table1name
any_alias1 right outer join table2 name any_alias2
on any_alias1.columnname =any_alias2.columnname;
6 Explain view with example S-23 4
A view is a logical table based on another table.View logically Explanati
represents subsets of data from one or more tables .A view on
contains no data of it‟s own but is like a window through which 2M
data from tables can be viewed or changed .The tables on which Example
the view is based are called base tables.SQL functions, where, 2M
join statements can be added to a view and the data in it
can be presented as if it were from one table.The database
engine recreates the data, using the view‟s SQL statement,
every time a user queries a view. A view can be updated using
the create or replace view command. For deleting a view,
dropquery can be used.General syntax to create a view:
create view viewname as select query.
Example:
create view vw_student as select stud_id, stud_name,ssc_per
from
student;
56
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
to the database.
The ROLLBACK command can only be used to undo
transactions since the last
COMMIT or ROLLBACK command was issued.
The syntax for ROLLBACK is:
ROLLBACK TO SAVEPOINT_NAME;
OR
ROLLBACK;
OR
ROLLBACK WORK;
Example:
SQL>ROLLBACK;
5 Write and explain create, update and drop view commands W-23 4
A view is a Virtual Table that is based on the result set of an Create
SQL query. command
Create View: 2M (syntax
A view is created with the CREATE VIEW statement. 1M,
Syntax: explanation
Create view view_name As ½ M,
Select column1, column2… example ½
From table_name M)
Where condition; Update
Example command
Create view mumbai_customers AS 1M (syntax
Select customer_name, contact_name ½ M,
From customers example ½
Where city=’Mumbai’; M)
Update View: Drop1M
A view can be updated with the CREATE OR REPLACE (syntax
VIEW statement. ½ M,
Syntax: example ½
CREATE OR REPLACE VIEW view_name AS M)
SELECT column1, column2, ...
FROM table_name WHERE condition;
Example:
The following SQL adds the "City" column to the "USA
Customers" view:
CREATE VIEW [USA Customers] AS
SELECT CustomerID, CustomerName, City
FROM Customers WHERE Country = ‘USA’;
Drop view:
A view can be deleted with the DROP VIEW statement.
Syntax:
DROP VIEW view_name;
Example:
DROP VIEW [USA Customers];
6 Explain cursor with syntax for declaring ,opening and closing W-23 4
a cursor
57
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
A cursor is a temporary work area created in system memory Cursor
when an SQL statement is executed. A cursor is a set of rows Explanation
together with a pointer that identifies a current row. It 1M
is a database object to retrieve data from result set on row at a Declaration
time. Implicit cursor: these types of cursors are generated and of cursor
used by the system during the manipulation of a DML query. 1M
An implicit cursor is also generated by the system when a Open cursor
single row is selected by a SELECT command. Programmers 1M
cannot control the implicit cursors. Closing
Explicit cursor: this type of cursor is created by the user when cursor 1M
the select command returns more than one row, and only one
row is to be processed at a time. An explicit
cursor can move from one row to another in a result set. An
explicit cursor uses a pointer that holds the record of a row.
1) Declaring cursor:
It defines the cursor with a name and the associated SELECT
statement.
Syntax
CURSOR name IS SELECT statement;
2) Open the cursor: It is used to allocate memory for the cursor
and make it easy to fetchthe rows returned by the SQL
statements into it.
Syntax
OPEN cursor_name;
3) Close the cursor:
It is used to release the allocated memory. The following
syntax is used to close the
above-opened cursors.
Syntax:
Close cursor_name;
7 Write the SQL queries for following EMP table. Emp (empno, W-23 6
deptno, ename, salary, designation, city.) i)list employees with
having alphabate ‘A’ as second letter in their name
II) set salary of all project leader to 50,000
III) display average salary of all employess
Iv) display employee-id of employees who live in city ‘pune’
or nagpur
V) Display employee name ,salary and city from ‘hr’
department who having salary greater than 70,000
Vi)display details of all employee who’s salary same as that of
salary of shashank
1. select * from Emp where emp_name like ‘_A%’; 1M each
2. update Emp set salary=50000 where designation=’project
leader’;
3. select avg(salary) from Emp;
4. select emp_id from Emp where city= ‘Pune’ or
city=’Nagpur’;
5. select emp_name,salary,city from Emp where dept=’HR’
and salary > 70000;
58
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
6. select * from Emp where salary in (select salary from Emp
where
emp_name=’Shashank’);
8 Consider following schema: W-23 6
Bookmaster (bookid,bookname,author,no _of copies,price)
write down sql queries for following :
I) Write a query to create table Book _master table
II) Write a command to create composite Index on book master
table
III) Write a command to drop above index
IV) Display all books whose number of copies are less than 10
V) Display all books whose price is above rs 700
VI) Create synoym for relation book master as book
information
1. create table Book_Master(book_id number(4,0), book_name 1M each
varchar(50), author
varchar(50), no_of_copies(2,0), price number(6,2));
2. create index composite_book_master on
Book_Master(book_id, book_name);
3. drop index composite_book_master;
4. select book_name,author from Book_Master order by price
desc;
5. select * from Book_Master where no_of_copies >50;
6. create or replace public synonym Book_Information for
Book_Master;
9 Write a command to create table Customer (Custo_id, W-23 6
Cust_name, address, Contact_no, City). And write down the
queries for the following: i) Insert one row into table. ii) Save
the data. iii) Insert Second row into the table. iv) Create save
point S1. v) Insert one row into the table
1. create table Customer(Custo_id number(2,0), Cust_name 1 M each
varchar(30), address
varchar(50), Contact_no varchar(10), city varchar(30));
2. insert into Customer values(1,’Ramesh’,’Ganesh Peth’,
‘9123456780’,’Pune’);
3. commit;
4. insert into Customer values (2,’Suresh’,’Sadashiv Peth’,
‘8123456790’,’Pune’);
5. savepoint s1;
6. insert into Customer values (3,’Rajesh’,’Shukrawar Peth’,
‘8912345670’,’Pune’);
Features
GROUP BY clause is used with the SELECT statement.
In the query, the GROUP BY clause is placed after the
WHERE clause.
In the query, the GROUP BY clause is placed before the
ORDER BY clause if used.
In the query, the Group BY clause is placed before the Having
clause.
Place condition in the having clause.
Syntax:
FROM table_name
WHERE condition
60
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
CREATE TABLE student (
name VARCHAR(50),
year INT,
subject VARCHAR(50)
);
INSERT INTO student (name, year, subject) VALUES
('Alice', 1, 'Mathematics'),
('Bob', 2, 'English'),
('Charlie', 3, 'Science'),
('David', 1, 'Mathematics'),
('Emily', 2, 'English'),
('Frank', 3, 'Science')
4 Write and explain syntax for creating and dropping synonyms S-24 4
with example
A synonym is an alternative name for objects such as tables,
views, sequences, stored procedures, and other database
objects.
You generally use synonyms when you are granting access to
an object from another schema and you don't want the users to
have to worry about knowing which schema owns the object.
Create Synonym (or Replace)
You may wish to create a synonym so that users do not have to
prefix the table name with the schema name when using the
table in a query.
Syntax
The syntax to create a synonym in Oracle is:
CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .]
synonym_name
FOR [schema .] object_name [@ dblink];
OR REPLACE
Allows you to recreate the synonym (if it already exists)
without having to issue a DROP synonym command.
PUBLIC
It means that the synonym is a public synonym and is
accessible to all users. Remember though that the user must
first have the appropriate privileges to the object to use the
synonym.
schema
The appropriate schema. If this phrase is omitted, Oracle
assumes that you are referring to your own schema.
object_name
The name of the object for which you are creating the synonym.
It can be one of the following:
table
view
sequence
stored procedure
function
61
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
package
materialized view
java class schema object
user-defined object
synonym
Example
Let's look at an example of how to create a synonym in Oracle.
For example:
SELECT *
FROM suppliers;
If this synonym already existed and you wanted to redefine it,
you could always use the OR REPLACE phrase as follows:
Syntax
The syntax to drop a synonym in Oracle is:
62
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
6 Explain any four joins if SQL Example S-24 4
JOIN:
A SQL join is an instruction to combine data from two sets of
data (i.e. two
tables). A JOIN clause is used to combine rows from two or
more tables, based on a related column between them. SQL
Join types are as follows:
1) EQUI JOIN:
A join which is based on equalities is called equi join. In equi
join comparison
operator “=” is used to perform a Join.
Syntax:
SELECTtablename.column1_name,tablename.column2_name
FROM table_name1,table_name2
Where
table_name1.column_name=table_name2.column_name;
Example:
Select stud_info.stud_name, stud_info.branch_code,
branch_details.location
From stud_info, branch_details
Where Stud_info.branch_code=branch_details.branch_code;
2) SELF JOIN:
The SQL SELF JOIN is used to join a table to itself, as if the
table were two
63
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
tables,temporarily renaming at least one table in the SQL
statement.
Syntax:
SELECT a.column_name, b.column_name
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;
Example:
Select x.stud_name, y.stud_name
from stud_info x, stud_info y
Where x.leader= y.stud_id;
3) INNER JOIN:The INNER JOIN command returns rows that
have
matching values in both tables.
Syntax:
Select column1_name,column2_name
from table1name INNER JOIN table2name
on table1name.columnname= table2name.columnname;
Example:
Select last_name, department_name
from employees inner join departments
on employees.department_id = departments.department_id;
4) LEFT OUTER JOIN:
A left outer join retains all of the rows of the “left” table,
regardless of whether
there is a row that matches on the “right” table.
Syntax:
Select column1_name,column2_name
from table1name any_alias1 ,table2name any_alias2
on any_alias1.columnname(+) = any_alias2.columnname;
OR
Select column1_name,column2_name
from table1name left outer join table2name
on table1name.columnname= table2name.columnname;
Example:
select last_name, department_name
from employees e, departments d
on e.department_id(+) = d.department_id;
OR
select last_name, department_name
from employees left outer join departments
on employees.department_id = departments.department_id;
5) RIGHT OUTER JOIN:
A right outer join retains all of the rows of the “right” table,
regardless of
whether there is a row that matches on the “left” table.
Syntax:
Select column1name, column2name
from table1name any_alias1, table2name any_alias2
on any_alias1.columnname =any_alias2.columnname (+);
OR
64
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Select column1name, column2name
from table1name any_alias1 right outer join table2 name
any_alias2
on any_alias1.columnname =any_alias2.columnname;
7 I) Write a query to create table emp- S-24 6
details(EMP_ID,name,dept) with proper data types and
Emp_ID as primary key and name as NOT NULL constrain
II) Perform all DML command on above created table
10 S-24 6
WRITE SQL COMMAND FOR Following
I) Create user
II) Grant privileges to user
III) Remove privileges to user
i) Create user
CREATE USER <username> IDENTIFIED BY <password>;
(OR)
CREATE USER RAJ IDENTIFIED BY RAJ123;
ii) Grant privileges to user.
GRANT <privilege list> ON <relation name or view name>
TO<user list>;
(OR)
(assuming table Employee for granting permissions to user
‘RAJ’
for select, insert, update and delete privilege)
GRANT SELECT, INSERT,UPDATE,DELETE ON
EMPLOYEE TO RAJ;
Iii) Remove privileges from user.
REVOKE <privilege list> ON <relation name or view name >
FROM <user list>;
(OR)
66
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
67
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
JSPM’s
RAJARSHI SHAHU COLLEGE OF ENGINEERING,
POLYTECHNIC
Department of Computer Engineering
Academic Year: 2024-25
UNIT-4 ( 18Marks)
MSBTE Question bank
68
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Exception Handling: Exception is nothing but an error. Exception
can be raise when
DBMS encounters errors or it can be raised explicitly.
When the system throws a warning or has an error it can lead to an
exception. Such
exception needs to be handled and can be defined internally or user
defined.
Exception handling is nothing but a code block in memory that will
attempt to resolve
current error condition.
Syntax:
DECLARE ;
Declaration section
…executable statement;
EXCEPTION
WHEN ex_name1 THEN ;
Error handling statements/user defined action to be carried out;
END;
Types of Exception:
1) Predefined Exception/system defined exception/named
exception: Are always
automatically raised whenever related error occurs. The most
common errors that can
occur during the execution of PL/SQL. Not declared explicitly i.e.
cursor already open,
invalid cursor, no data found, zero divide and too many rows etc.
Programs are handled
by system defined Exceptions.
2) User defined exception: It must be declare by the user in the
declaration part of the
block where the exception is used. It is raised explicitly in
sequence of statements using:
Raise_application_error(Exception_Number, Error_Message);
3 Explain function PL\SQL with example W-18 4
Function: Description:
Function is a logically grouped set of SQL and Pl/SQL statements 2
that perform a marks,
specific task. A function is same as a procedure except that it Example : 2
returns a value. A marks
function is created using the CREATE FUNCTION statement.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
-name specifies the name of the function.
69
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
function.
the parameters. IN
represents the value that will be passed from outside and OUT
represents the
parameter that will be used to return a value outside of the
procedure.
tain a return statement.
a standalone
function.
Example:
CREATE OR REPLACE FUNCTION Success_cnt
RETURN number
IS cnt number(7) := 0;
BEGIN
SELECT count(*) into cnt
FROM candidate where result='Pass';
RETURN cnt;
END;
/
4 Draw the block structure of PL/SQL . List advantages of PL/SQL W-18 4
70
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Advantages of PL/SQL:
1. PL/SQL is portable and high transaction processing language.
2. PL/SQL is in fact procedural language but it also supports object
oriented
programming.
3. It allows user to write as well as access the functions and
procedures from outside the
programs.
4. It has got built in libraries of packages
5 Write step by step syntax to create, open and close cursor in W-18, 4
PL/SQL. S-23
A cursor holds the rows (one or more) returned by a SQL 2 marks,
statement. Opening: 1
Declaring: This term is used to declare a cursor so that memory mark,
initialization will take place.A cursor is declared by defining the Closing
SQL statement that returns a result set. cursor: 1
Example: mark
Declare CURSOR Winter_18 IS SELECT roll_no, std_name,
percentage FROM
student;
Opening: A Cursor is opened and populates data by executing the
SQL statement defined by the cursor.
Example:
Open Winter_18;
Closing a Cursor: This forces cursor for releasing the allocated
memory assigned/ occupied by cursor.
Example:
CLOSE Winter_18;
6 Write a PL/SQL program which accept the customer ID from the W-18 6
user if user enters an invalid ID then the exception invalid_id is
raised using exception handling.
71
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
DECLARE
c_id numeric(10);
invalid_id_Exception Exception;
BEGIN
c_id:=&c_id;
if(c_id<0) then
raise invalid_id_Exception;
end if;
EXCEPTION
WHEN invalid_id_Exception THEN
dbms_output.put_line('Invalid customer id');
END;
1 State any four PL/SQL data types. S-19 2
1. NUMBER or NUMBER(P,S)
2. PLS_INTEGER
3. CHAR
4. RAW
5. ROWID
6. VARCHAR2
7. DATE
2 Explain PL/SQL block structure with the help of diagram S-19, 4
S-22
Declaration section
A block begins with declarative section where variables, cursors
are declared. It is an Optional block.
Execution section
Executable SQL or PL/SQL Statements are needed to write here
for the execution. It is mandatory block.
Exception section
It is used to handles the exceptions. It is an Optional block.
End statement
It is used to indicate termination of PL/SQL block. It is mandatory
3 Explain cursor with example S-19 4
72
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
A cursor is a temporary work area created in system memory when
a SQL statement is executed. A cursor is a set of rows together with
a pointer that identifies a current row. It is a database object to
retrieve data from a result set one row at a time. It is useful when we
want to manipulate the record of a table in a singleton method, in
other wordsone row at a time. In other words, a cursor can hold
more than one row, but can process only one row at a time. The set
of rows the cursor holds is called the active set.
Each cursor contains the followings 4 steps,
1. Declare Cursor: In this part we declare variables and return a set
of values.
2. Open: This is the entering part of the cursor.
3. Fetch: Used to retrieve the data row by row from a cursor.
4. Close: This is an exit part of the cursor and used to close a
cursor.
5. Eg:
Declare
enumemp.eno%type;
enemp.ename%type;
Cursor cur is select eno, ename from emp where jobname = “mgr”;
Begin
Open cur;
Loop Fetch cur into enum,en;
Exit when cur%NOTFOUND;
Dbms_output.put_line(„emp num ‟||enum||‟ emp name „||en);
End loop;
Close cur;
End; /
The example shows fetching multiple records using cursor. A
cursor is a temporary work area created in system memory when a
SQL
statement is executed. A cursor is a set of rows together with a
pointer that identifies a current row.
In the example, the cursor is defined to hold the rows as defined by
the select query. Once the cursor is defined, the next step is to open
the cursor. When the cursor is opened, it is ready to retrieve the
rows. This is done using the fetch statement. Since there are many
rows, a loop is used to display the values of all the rows.
Once the rows are fetched, the
cursor should be closed.
4 State the use of database trigger and also list types of trigger S-19 4
Use of trigger
Trigger: A trigger is a stored procedure in database which
automatically
invokes whenever a special event in the database occurs. A trigger
can be invoked when a row is inserted into a specified table or
when certain table columns are being updated.
Triggers are written to be executed in response to any of the
following
73
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
events − A database manipulation (DML) statement (DELETE,
INSERT, or
UPDATE)
Database definition (DDL) statements (CREATE, ALTER, or
DROP).
A database operation (SERVERERROR, LOGON, LOGOFF,
STARTUP, or SHUTDOWN).
Triggers can be defined on the table, view, schema, or database
with
which the event is associated.
Triggers can be written for the following purposes –
referential integrity
Types of trigger
s
5 Write a PL/SQL program to calculate factorial of a given number S-19 6
DECLARE
num number:=#
fact number:=1;
BEGIN
while num!=0
loop
fact:=fact*num;
num:=num-1
end loop;
dbms_output.put_line(‘Factorial =’||fact);
END;
/
(OR)
DECLARE
num number:=#
fact number:=1;
i number;
BEGIN
for i in 1..num loop
fact:=fact*i;
end loop;
74
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
database details from the user.
times
2 Explain implicit and explicit cursors W-19 4
A cursor is a temporary work area created in system memory when
an SQL statement is executed. A cursor is a set of rows together
with a pointer that identifies a current row. It is a database object
to retrievedata from result set on row at a time.
Implicit cursor: these types of cursors are generated and used by
the system during the manipulation of a DML query. An implicit
cursor is also generated by the system when a single row is selected
by a SELECT command. Programmers cannot control the implicit
cursors.
Explicit cursor: this type of cursor is created by the user when the
select command returns more than one row, and only one row is to
be
processed at a time. An explicit cursor can move from one row to
another in a result set. An explicit cursor uses a pointer that holds
the
record of a row.
To create an explicit cursor the following steps are used.
1. Declare cursor: this is done in the declaration section of PL/SQL
program.
2. Open: this step is done before the cursor is used to fetch the
records.
3. Fetch: used to retrieve data row by row from the cursor.
4. Close: once the processing of the data is done, the cursor can be
closed
3 Explain Exception handling with it’s types W-19 4
An exception is an error condition during a program execution.
PL/SQL supports programmers to catch such conditions
using EXCEPTION block in the program and an appropriate action
is taken against the error condition.
There are two types of exceptions −
-defined exceptions/Predefined exceptions/Built-in
Exceptions
2) User-defined exception
1) Predefined exceptions- PL/SQL provides predefined Exception,
which are executed when any database rule is violated by a
program.
Example: NO_DATA_FOUND, ZERO_DIVIDE.
Syntax for Predefined Exception Handling:
The general syntax for exception handling is as follows.
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
75
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
2) User defined Exceptions:
PL/SQL allow us to define our own exception according to the
need
of our program. A user defined exception must be declared and
then
raised explicitly.
Syntax for User defined Exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
4 Define database trigger. How to create and delete trigger ? W-19 4
Triggers are stored programs, which are automatically executed or
fired when some events occur. Triggers are, in fact, written to be
executed in response to any of the following events −
INSERT, or UPDATE)
DROP).
Triggers can be defined on the table, view, schema, or database
with
which the event is associated.
Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
76
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
To delete a trigger:
Syntax:
DROP TRIGGER trigger_name.
5 Explain any one control structure in PL/SQL with example W-19 4
PL/SQL has three categories of control statements: conditional
selection statements, loop statements and sequential control
statements.
PL/SQL categories of control statements are:
programming.
The sequential control statements are GOTO, which goes to a
specified statement, and NULL, which does nothing.
1)Conditional Control: IF and CASE Statements:
The IF statement lets us execute a sequence of statements
conditionally. That is, whether the sequence is executed or not
depends on the value of a condition. There are three forms
of IF statements: IF-THEN, IF-THEN-ELSE, and IF-THEN-
ELSIF.
The CASE statement is a compact way to evaluate a single
condition
and choose between many alternative actions.
IF-THEN Statement:The simplest form of IF statement associates
a
condition with a sequence of statements enclosed by the
keywords THEN and END IF (not ENDIF), as follows:
IF condition THEN
sequence_of_statements
END IF;
IF-THEN-ELSE Statement: The second form of IF statement adds
the keyword ELSE followed by an alternative sequence of
statements,
as follows:
77
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
IF condition THEN
sequence_of_statements1
ELSE
sequence_of_statements2
END IF;
IF-THEN-ELSIF Statement: The third form of IF statement uses
the keyword ELSIF (not ELSEIF) to introduce additional
conditions,
as follows:
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_statements3
END IF;
CASE Statement: Like the IF statement, the CASE statement
selects
one sequence of statements to execute.
IF grade = 'A' THEN
dbms_output.put_line('Excellent');
ELSIF grade = 'B' THEN
dbms_output.put_line('Very Good');
ELSIF grade = 'C' THEN
dbms_output.put_line('Good');
ELSIF grade = 'D' THEN
dbms_output. put_line('Fair');
ELSIF grade = 'F' THEN
dbms_output.put_line('Poor');
ELSE
dbms_output.put_line('No such grade');
END IF;
END CASE;
2) Iterative Control: LOOP and EXIT Statements:
LOOP statements let us execute a sequence of statements multiple
times. There are three forms of LOOP statements: LOOP,
WHILELOOP, and FOR-LOOP.
LOOP: The simplest form of LOOP statement is the basic (or
infinite) loop, which encloses a sequence of statements between
the
keywords LOOP and END LOOP, as follows:
LOOP
sequence_of_statements
END LOOP;
WHILE-LOOP:The WHILE-LOOP statement associates a
condition with a sequence of statements enclosed by the
keywords LOOP and END LOOP, as follows:
WHILE condition LOOPsequence_of_statements
END LOOP;
Before each iteration of the loop, the condition is evaluated. If the
78
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
condition is true, the sequence of statements is executed, then
control resumes at the top of the loop. If the condition is false or
null, the
loop is bypassed and control passes to the next statement.
FOR-LOOP:Whereas the number of iterations through
a WHILE loop is unknown until the loop completes, the number
of iterations through a FOR loop is known before the loop is
entered. FOR loops iterate over a specified range of integers. The
range is part of an iteration scheme, which is enclosed by the
keywords FOR and LOOP. A double dot (..) serves as the range
operator. The syntax follows:
FOR counter IN [REVERSE] lower_bound..higher_bound LOOP
sequence_of_statements
END LOOP.
6 Write a PL/SQL program to print n even numbers using For Loop W-19 6
declare Correct
num number; logic 3M
n number:=&n; Correct
begin syntax
for num in 1..n loop 3M
if(mod(num,2)=0) then
dbms_output.put_line(‘Even no are :’||num);
end if;
end loop;
end;
79
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
going to be shown. Else in any other cases there is no opportunity
for outputs.
Syntax
IF <condition> then
Statement 1
Statement 2
.
.
.
.
Statement N
END IF;
Example Queries
SQL> DECLARE
2 N1 INTEGER;
3 BEGIN
4 N1:=10;
5 IF N1 > 10 THEN
6 dbms_output.put_line('The Value is' || N1);
7 END IF;
8 END;
9/
OUTPUT:
INSERT, or UPDATE)
DROP).
Triggers can be defined on the table, view, schema, or database
with
which the event is associated.
Creating Triggers
The syntax for creating a trigger is −
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
80
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
To delete a trigger:
Syntax:
DROP TRIGGER trigger_name.
3 Write a PL/SQL program, which accept the number from user. If S-22 6
user enters an odd number then exception invalid number is raised
using user defined exception handling.
DECLARE
v_input VARCHAR2(10) := 'abc';
v_number NUMBER;
BEGIN
BEGIN
v_number := TO_NUMBER(v_input);
DBMS_OUTPUT.PUT_LINE('Conversion successful.
Number: ' || v_number);
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUT_LINE('Error: Invalid number');
END;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
82
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
4. on [table_name]: This specifies the name of the table associated
with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger
will be executed
for each row being affected.
6. [trigger_body]: This provides the operation to be performed as
trigger is fired
Example:
Given Student Report Database, in which student marks
assessment is recorded. In
such schema, create a trigger so that the total and percentage of
specified marks is
automatically inserted whenever a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE
Tag can be used.
create trigger stud_marks
before INSERT
on
Student
for each row
set Student.total = Student.subj1 + Student.subj2 + Student.subj3,
Student.per
= Student.total * 60 / 100;
4 Write a trigger which invokes on deletion of record on emp table W-22 4
Delete Trigger: 4M
create or replace trigger trg1 before delete on emp_details Or any other
declare correct logic
begin for delete
raise_application_error(-20000,'cannot delete the record'); trigger
end
5 Write a PL/SQL code to check whether specified employee is W-22 6
present in Emp table or not. Accept empno from user. If employee
does not exist display message using exception handling.
PL/SQL Program: 2M
declare =declaration
no emp.empno%type; 2M=select
begin statement
no:=&no; 2M=proper
select empno into no from emp where empno=no; exception
dbms_output.put_line('Empno is present: '||no); message
exception
when no_data_found then
dbms_output.put_line('Empno not present');
end;
83
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
2 State syntax of while loop command S-23 2
Syntax :
WHILE <condition>
LOOP statements;
END LOOP;
3 Explain subquery concept with example S-23 2
Subquery : A subquery is a query which is embedded within Explanati
another query. The outer query is called as main query and inner on 1M
query is called as subquery Example
For Example: 1M
Select * from customer where age = ( Select min(age) from
customer );
The above query will select all rows from customer table with
minimum age.
4 Explain trigger with suitable example S-23 4
Trigger: Correct
Triggers are stored programs, which are automatically executed or explanati
fired when some events occur. Triggers are, in fact, written to be on 2M
executed in response to any Any
of the following events - relevant
example
or UPDATE) 2M
DROP).
Triggers can be defined on the table, view, schema, or database
with which the
event is associated. a
For Example:
create trigger trigger_update
on emp
after update
as begin Select * from employee;
end;
84
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
The above trigger will invoke after update of record in emp table.
5 Write a pl sql program to print odd number from 1to 10 S-23 4
begin 2M for
dbms_output.put_line(„Oddnos from 1 to 10 are :‟); Correct
fornum in 1..10 Logic
loop 2M for
if(mod(num,2)!=0) then correct
dbms_output.put_line(num); syntax
end if;
end loop;
end;
6 Explain for loop syntax in PLSQL with suitable example of S-23 6
printing 10 to 1 reverse number
For Loop :
execute a
sequence of statements once for each integer in the range.
the parameters.
IN
represents the value that will be passed from outside and OUT
represents the
parameter that will be used to return a value outside of the
procedure.
86
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
2) User defined Exceptions:
PL/SQL allow us to define our own exception according to the
need of our program. A
user defined exception must be declared and then raised explicitly.
Syntax for User defined Exception:
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
Example:
DECLARE
A number:=20;
B number:=0;
C number;
BEGIN
dbms_output.put_line(‘First Num : ’||A);
dbms_output.put_line(‘Second Num : ’||B);
C:= A / B;
--Raise built in Exception if B is 0
dbms_output.put_line(‘ Result ’ || C);-- and then Result will not be
displayed
EXCEPTION
WHEN ZERO_DIVIDE THEN
dbms_output.put_line(‘ Trying to Divide by zero :: Error ’);
END;
2 Explain procedures in PL\SQL with example W-23 4
(any relevant example should be considered)
The PL/SQL stored procedure or simply a procedure is a PL/SQL
block which performs one or more specific tasks. It is just like
procedures in other programming languages.
The procedure contains a header and a body. Header: The header
contains the name of the procedure and the parameters or
87
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
variables passed to the procedure.Body: The body contains a
declaration section, execution section and exception
section similar to a general PL/SQL block.When you want to
create a procedure or function, you have to define parameters.
There is
three ways to pass parameters in procedure:
1. IN parameters: The IN parameter can be referenced by the
procedure or function
The value of the parameter cannot be overwritten by the
procedure or the function.
2. OUT parameters: The OUT parameter cannot be
referenced by the procedure or
function, but the value of the parameter can be overwritten
by the procedure or
function.
3. INOUT parameters: The INOUT parameter can be
referenced by the procedure
or function and the value of the parameter can be
overwritten by the procedure or
function.
PL/SQL Create Procedure
Syntax for creating procedure:
CREATE [OR REPLACE] PROCEDURE
procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Example:
The following example creates a simple procedure that
displays the string 'Hello World!'
on the screen when executed
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When above code is executed using SQL prompt, it will
produce the following result:
Procedure created.
PL/SQL program to call procedure
A standalone procedure can be called in two ways:
· Using the EXECUTE keyword
· Calling the name of the procedure from a PL/SQL block
88
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
The above procedure named 'greetings' can be called with
the EXECUTE keyword as:
EXECUTE greetings;
The procedure can also be called from another PL/SQL
block:
BEGIN
greetings;
END;
/
Syntax for drop procedure
DROP PROCEDURE procedure_name;
Example of drop procedure
BEGIN
DROP PROCEDURE greetings;
END;
/
3 Describe sequence in PL\SQL with example W-23 4
(Any relevant example should be considered)
A sequence is used to generate numbers in sequence. You can use
sequences to insert unique values in Primary Key and Unique Key
columns of tables. To create a sequence,
give the CREATE SEQUENCE statement.
Syntax for creating sequence:
CREATE SEQUENCE sequence_name
START WITH initial_value
INCREMENT BY increment_value
MINVALUE minimum value
MAXVALUE maximum value
CYCLE|NOCYCLE ;
.where as:sequence_name: Name of the sequence.
initial_value: starting value from where the sequence starts.
Initial_value should be greater than or equal to minimum value and
less than equal to maximum value.
increment_value: Value by which sequence will increment itself.
Increment_value can be positive or negative.
minimum_value: Minimum value of the sequence.
maximum_value: Maximum value of the sequence.
cycle: When sequence reaches its set_limit it starts from beginning.
nocycle: An exception will be thrown if sequence exceeds its
max_value.
Example
CREATE SEQUENCE sequence_1
start with 1
increment by 1
minvalue 0
maxvalue 100
cycle;
Alter sequence:
Syntax:
alter sequence <sequence_name> maxvalue <number>;
89
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Alter sequence can change the maxvalue in the sequence created.
Example:
ALTER SEQUENCE employee_id_seq
INCREMENT BY 1
START WITH 10000
MINVALUE 1
MAXVALUE 99999
CACHE 10;
Dropping sequence:
Syntax:
drop sequence <sequence_name>;
To drop the sequence the DROP command is used.
Example:
DROP SEQUENCE employee_id_seq;
4 Compare database trigger and procedure(write four diierences and W-23 4
explain theuse of database trigger
5 Write a PL\SQL program to print sum of n odd numbers for using W-23 6
for loop
(Any other correct logic should be considered)
Declare
i number :=1;
sum number := 0;
n number;
begin
n := &n;
for i in 1..n
loop
if mod(i,2) = 1
then
sum := sum + i;
end if;
end loop;
dbms_output.put_line(‘sum= ’||sum);
90
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
end;
OR
Declare
i number :=1;
sum number := 0;
n number;
begin
n := &n;
for i in 1..n
loop
sum := sum + i;
i := i + 2;
end loop;
dbms_output.put_line(‘sum= ’||sum);
end;
1 Write PL/SQL code to print largest number from three numbers S-24 4
(accept 3 numbers from user)
declare
a number:=10;
b number:=12;
c number:=5;
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
91
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
3 Write and explain syntax to create ,open and close cursor in S-24 4
PL/SQL
92
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
5 Explain use of database trigger .list types of trigger writ command S-24 6
to create and delete trigger
93
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
94
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
95
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
JSPM’s
UNIT-5 ( 10Marks)
MSBTE Question bank
OR
2. Integrity: when the contents of the message are changed after the
sender sends it, but before it reaches the intended recipient, we say
that the integrity of the message is lost.
3. Authentication:
96
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Authentication helps to establish proof of identities. The
OR
4. Integrity: when the contents of the message are changed after the
sender sends it, but before it reaches the intended recipient, we say
that the integrity of the message is lost. 3. Authentication:
Authentication helps to establish proof of identities. The
W-19
W-22
W-23
97
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
1. Atomicity: When one transaction takes place, many operations For each
occur under one transaction. Atomicity means either all operations
will take place property and reflect in the database or none of them property - 1
will be reflected. 2. Consistency: Consistency keeps the database Mark
consistent. Execution of a transactionneeds to take place in isolation. It
helps in reducing complications of executing multiple transactions at
a time and preserves the consistency of the database.3. Isolation: It is
necessary to maintain isolation for the transactions. This means one
transaction should not be aware of another transaction getting
executed. Also their intermediate result should be kept hidden. 4.
Durability: When a transaction gets completed successfully, it is
important that the changes made by the transaction should be
preserved in database in spite of system failures
98
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
might have highly restricted access to data, while you go up in the
hierarchy to the administrator, you will get more access
S-22
Active –the initial state; the transaction stays in this state while it is
99
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
S-24
The redo log is a set of operating system files that record all changes
100
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
1 Describe database backups with it’s types. W-19 4
When a normal or full backup runs on a selected drive, all the files
on that drive are backed up. This, of course, includes system files,
application files, user data — everything. Those files are then copied
to the selected destination (backup tapes, a secondary drive or the
cloud), and all the archive bits are then cleared.Normal backups are
the fastest source to restore lost data because all the data on a drive
is saved in one location.
A common way to deal with the long running times required for full
backups is to run them only on weekends. Many businesses then run
incremental backups throughout the week since they take far less
time. An incremental backup will grab only the files that have been
updated since the last normal backup. Once the incremental backup
has run, that file will not be backed up again unless it changes
101
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
An alternative to incremental database backups that has a less
grab only files that have been updated since the last normal backup.
differential backup is run until the next normal backup runs and
clears the archive bit
2 Describe database privileges. Write down the procedure for granting W-19 6
& revoking privileges in database objects to the users.
When multiple users can access database objects, authorization can re for
be controlled to these objects with privileges. Every object has an
owner. Privileges control if a user can modify an object owned by granting
another user. Privileges are granted or revoked either by the instance privilege
administrator, a user with the ADMIN privilege or, for privileges to
a certain object, by the owner of the object. s
1) System Privileges: 2M
2) Object Privileges:
102
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Example: Grant select, update on emp to user1;Procedure for
revoking privileges
<username> ;
3.Sophisticated Users
103
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
The database or schema which is already defined can be modified by
DBA as per the requirements.
5. Granting authorization:
To access the different databases, DBA can grant the authorization
to authorized users only.
6. Performance tuning:
The problems/errors arise in database accessing; can be resolved by
DBA to increase the performance.
7. Regular maintenance:
DBA can monitor the transactions in database and maintain the
database error free by doing the regular maintenance
3. Checkpoints:
Checkpoint records all committed transactions into logs.When
system fails, it check log to determine recovery action.
104
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Define failure. Enlist types of failure W-23 2
on must be treated
as an atomic unit, that is, either all of its operations are executed or
105
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
none. There must be no state in a database where a transaction is left
partially completed. States should be defined either before the
execution of the transaction or after theexecution/abortion/failure of
the transaction.
3 Describe database privileges. Write down the command for granting W-23 6
and revoking privileges on database object to users
1. System Privileges
2. Object Privileges
106
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
1. System Privileges
• For e.g.: create session, create table, create view, create sequence,
create procedure, create role
2. Object Privileges
• Each type of object (for e.g.: table, view, procedure etc.) has
different privileges associated with it.
Grant Privileges
Syntax
Example:
Revoke
107
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
Syntax:
1. System Privileges
2. Object Privileges
1. System Privileges
Syntax
Example:
Revoke
Syntax:
108
RSCOEP COMPUTER ENGINEERING DEPARTMENT MRS.S.S.GHULE
REVOKE privilege-type ON [ TABLE] {table-Name | view-Name}
FROM grantees
Disgruntled Employees.
Jaywant Shikshan Prasarak Mandal’s
RAJARSHI SHAHU COLLEGE OF ENGINEERING’s
POLYTECHNIC
S.No.80, Pune-Mumbai Bypass Highway, Tathawade Campus, Pune.
NBA ACCREDITED
22319
11819
3 Hours / 70 Marks Seat No.
Instructions : (1) All questions are compulsory.
(2) Illustrate your answers with neat sketches wherever necessary.
(3) Figures to the right indicate full marks.
(4) Assume suitable data, if necessary.
Marks
P.T.O.
22319
Marks
4. Attempt any three of the following : 12
a) Explain the four roles of database administrator.
b) State and explain 1NF and 2NF with example.
c) Draw the block structure of PL/SQL . List advantages of PL/SQL.
d) Write step by step syntax to create, open and close cursor in PL/SQL.
e) Explain transaction ACID properties.
––––––––––––––
SUMMER-2019 22319
21819
3 Hours / 70 Marks Seat No.
Marks
1. Attempt any FIVE of the following : 10
(a) Define :
(i) Instance (ii) Schema
(b) List any four advantages of DBMS.
(c) State any two E.F. Codd’s rule for RDBMS.
(d) List DCL commands.
(e) Define Normalization and list its types.
(f) Write syntax for creating synonyms with example.
(g) State any four PL/SQL datatypes.
[1 of 4] P.T.O.
22319 [2 of 4]
3. Attempt any THREE of the following : 12
(a) State and explain 2NF with example.
(b) Explain any four aggregate functions with example.
(c) Explain exception handling in PL/SQL with example.
(d) Explain state of transaction with the help of diagram.
(a) (i) Write a command to create table student (RNo., name, marks, dept.)
with proper datatype and RNo as primary key.
P.T.O.
22319 [4 of 4]
WINTER-2019
22319
11920
3 Hours / 70 Marks Seat No.
Marks
(b) Describe create & alter command with syntax & example.
(a) Draw an ER diagram for library management system. (Use Books, Publisher
& Member entities).
(b) Write a command to create table student (rollno, Stud_name, branch, class,
DOB, City, Contact_no) and write down queries for following :
P.T.O.
22319 [4 of 4]
SUMMER-2022
22319
21222
3 Hours / 70 Marks Seat No.
15 minutes extra for each hour
Marks
22319
22223
3 Hours / 70 Marks Seat No.
Marks
P.T.O.
22319 [2]
Marks
2. Attempt any THREE of the following: 12
a) Explain not null and check constraint with example.
b) Explain any four string functions with example.
c) Describe Grant and Revoke commands with example.
d) Explain trigger with suitable example.
Marks
P.T.O.
22319 [2]
Marks
2. Attempt any THREE of the following : 12
a) State advantages of DBMS over file processing system.
(Any four)
b) Explain pattern matching operators ‘Like’ and range searching
operator ‘Between’ with example.
c) Explain any four aggregate functions with example.
d) Describe exception handling in PL/SQL.
P.T.O.
22319 [4]
Marks
6. Attempt any TWO of the following : 12
a) Write a PL/SQL program to print sum of n odd numbers
using for loop.
b) Write a command to create table Customer (Custo_id, Cust_name,
address, Contact_no, City). And write down the queries for the
following:
i) Insert one row into table.
ii) Save the data.
iii) Insert Second row into the table.
iv) Create save point S1.
v) Insert one row into the table.
c) Describe database privileges. Write down the command for
granting and revoking privileges on database object to users.
SUMMER-2024
JSPM’s
RAJARSHI SHAHU COLLEGE OF ENGINEERING,
POLYTECHNIC
Department of Computer Engineering
Academic Year: 2024-25