0% found this document useful (0 votes)
5 views

Rdbms Solution

The document is a study guide for a course on Relational Database Management Systems (RDBMS) covering various topics such as definitions of DBMS, differences between SQL commands, data vs information, normalization, and transaction control commands. It includes explanations of DDL, DML, DQL, and DCL commands with examples, as well as the importance of normalization in database design. The document serves as a comprehensive resource for students in the Computer Engineering department at N.G. Patel Polytechnic.

Uploaded by

agneydesai151
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Rdbms Solution

The document is a study guide for a course on Relational Database Management Systems (RDBMS) covering various topics such as definitions of DBMS, differences between SQL commands, data vs information, normalization, and transaction control commands. It includes explanations of DDL, DML, DQL, and DCL commands with examples, as well as the importance of normalization in database design. The document serves as a comprehensive resource for students in the Computer Engineering department at N.G. Patel Polytechnic.

Uploaded by

agneydesai151
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

Subject Code: 4330702 Computer Engineering dept.

Subject: RDBMS

N.G. PATEL POLYTECHNIC

Subject Code: 4330702

Subject Name: Relational Database Management System

SEMESTER:3

______________________________________________________________

Q.1 Define DBMS. Write an application of DBMS. [03]

Ans: Database Management System(DBSM) is a Collection of related data element in terms


of row and column and set of program which will manipulates those data.

Application of DBMS:


 Telecom: There is a database to keeps track of the information regarding calls made,
network usage, customer details etc.

 Industry: Where it is a manufacturing unit, warehouse or distribution centre, each one


needs a database to keep the records of ins and outs

 Banking System: For storing customer info, tracking day to day credit and debit
transactions, generating bank statements etc.
 Sales: To store customer information, production information and invoice details.
 Airlines: To travel though airlines, we make early reservations; this reservation
information along with flight schedule is stored in database.

 Education sector: Database systems are frequently used in schools and colleges to
store and retrieve the data regarding student details, staff details, course details, exam
details, payroll data, attendance details, fees details etc.

Q.2 Differentiate 1) DELETE v/s DROP 2) ORDER BY v/s GROUP BY [04]

Ans: (1) Delete Vs Drop

DELETE:

Basically, it is a Data Manipulation Language Command (DML). It is used to delete one or


more tuples of a table. With the help of the “DELETE” command, we can either delete all the
rows in one go or can delete rows one by one. i.e., we can use it as per the requirement or the
condition using the Where clause.

Prepared by: Mr.R.J. Patel Page |1 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

SYNTAX –

If we want to delete the row of the table as per the condition then we use the WHERE
clause,

DELETE FROM table_name WHERE condition;

2. DROP:

It is a Data Definition Language Command (DDL). It is used to drop the whole table. With the
help of the “DROP” command we can drop (delete) the whole structure in one go i.e. it removes
the named elements of the schema. By using this command, the existence of the whole table is
finished or say lost.

SYNTAX –

DROP table <table_name>;

(2) ORDER BY v/s GROUP BY

The main difference between them is that the GROUP BY clause is applicable when we want
to use aggregate functions to more than one set of rows. The ORDER BY clause is applicable
when we want to get the data obtained by a query in the sorting order.

ORDER BY Clause

The ORDER BY clause is used in SQL queries to sort the data returned by a query in ascending
or descending order. If we omit the sorting order, it sorts the summarized result in the ascending
order by default.

The following is the syntax to use the ORDER BY clause in a SQL statement:

SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC];

Group by Clause

The Group by clause is used to group data based on the same value in a specific column. We can often
use this clause in collaboration with aggregate functions like SUM, AVG, MIN, MAX, and COUNT to
produce summary reports from the database

Prepared by: Mr.R.J. Patel Page |2 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

The following is the syntax to use GROUP BY clause in a SQL statement:

SELECT column_name, function(column_name)


FROM table_name
WHERE condition
GROUP BY column_name;

Q.3 Define information and data. List out the difference between them. [3]

Ans: What is Data?

Data is a collection of raw, unorganised facts and details like text, observations, figures,
symbols and descriptions of things etc.

What is Information?

Information is processed, organised and structured data

Data Information
Information comprises processed,
Data is unorganised and unrefined facts organised data presented in a meaningful
context
Data is an individual unit that contains raw
Information is a group of data that
materials which do not carry any specific
collectively carries a logical meaning.
meaning.
Data doesn’t depend on information. Information depends on data.
Raw data alone is insufficient for decision Information is sufficient for decision
making making
The average score of a class is the
An example of data is a student’s test score
information derived from the given data.

Q.4 Define the following term:

(I)Data Item or Fields:

 A field is a character or group of characters that have a specific meaning.


 It is also called a data item. It is represented in the database by a value.
 For Example, customer id, name, society and city are all fields for customer Data.
(II)Records:
A record is a collection of logically related fields. For examples, collection of fields (id,
name, society & city) forms a record for customer.
(III)Files:
 A group of related records. Files are frequently classified by the application for which
Prepared by: Mr.R.J. Patel Page |3 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

they are primarily used (employee file).


(IV)Metadata:
 Metadata is data about data.
 Data such as table name, column name, data type, authorized user and user access
privileges for any table is called metadata for that table.

(c) Explain TCL commands with suitable example. 07

Ans: 1. COMMIT

COMMIT command in SQL is used to save all the transaction-related changes permanently
to the disk. Whenever DDL commands such as INSERT, UPDATE and DELETE are used,
the changes made by these commands are permanent only after closing the current session.

Syntax:

COMMIT;

2. SAVEPOINT

Using the SAVEPOINT command in SQL, we can save these different parts of the same
transaction using different names.

Syntax:

1. SAVEPOINT savepoint_name;

3. ROLLBACK

While carrying a transaction, we must create savepoints to save different parts of the
transaction. According to the user's changing requirements, he/she can roll back the
transaction to different savepoints.

Syntax:

1. ROLLBACK TO savepoint_name;

Q.5 Explain DDL commands with suitable example. [ 07]

Ans: The DDL Commands in Structured Query Language are used to create and modify the schema
of the database

Following are the five DDL commands in SQL:

1. CREATE Command
2. DROP Command
3. ALTER Command
4. TRUNCATE Command
5. RENAME Command
Prepared by: Mr.R.J. Patel Page |4 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Create command

Syntax to create a new table:

1. CREATE TABLE table_name


2. (
3. column_Name1 data_type (size),
4. column_Name2 data_type (size),
5. column_Name3 data_type (size),
6. ...
7. column_NameN data_type (size)
8. );

(2) Drop

DROP is a DDL command used to delete/remove the database objects from the SQL
database. We can easily remove the entire table, view, or index from the database using this
DDL command.

Syntax to remove a table:

1. DROP TABLE Table_Name;

(3) ALTER Command

ALTER is a DDL command which changes or modifies the existing structure of the
database, and it also changes the schema of database objects.

Syntax to add a newfield in the table:

1. ALTER TABLE name_of_table ADD column_name column_definition;

Example: Suppose, you want to add the 'Father's_Name' column in the existing
Student table. To do this, you have to write the following DDL command:

1. ALTER TABLE Student ADD Father's_Name Varchar(60);

(4) TRUNCATE Command

TRUNCATE is another DDL command which deletes or removes all the records from the
table.

This command also removes the space allocated for storing the table records.

Syntax of TRUNCATE command

1. TRUNCATE TABLE Table_Name;

Prepared by: Mr.R.J. Patel Page |5 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

(5) RENAME Command

RENAME is a DDL command which is used to change the name of the database table.

Syntax of RENAME command

1. RENAME TABLE Old_Table_Name TO New_Table_Name;

Q.6 Explain DML& DQL commands with suitable example. [07]

Ans :The structured query language (SQL) commands deal with the manipulation of data
present in the database that belongs to the DML or Data Manipulation Language. This includes
most of the SQL statements.

 INSERT − Insert data into a table.

 UPDATE − Update existing data within a table.

 DELETE − Delete records from a database table.

he syntax for the DML commands are as follows −

INSERT

Insert command is used to insert data into a table.

The syntax for INSERT command is as follows −

Syntax

Insert into <table_name> (column list) values (column values);

For example, if we want to insert multiple rows to the Employee table, we can use the
following command −

Example

Insert into Employee (Emp_id, Emp_name) values (001, “ bhanu”);


Insert into Employee (Emp_id, Emp_name) values (002, “ hari”);
Insert into Employee (Emp_id, Emp_name) values (003, “bob”);

DELETE

Delete command is used to delete records from a database table.

The syntax for the delete command is as follows -

Syntax

Delete from <table_name>WHERE condition;


Prepared by: Mr.R.J. Patel Page |6 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

For example, if we want to delete an entire row of employee id 002, we can use the following
command −

Example

DELETE from Employee WHERE Emp_id=002;

DELETE from employee where emp_name = ‘RAJAN’;

UPDATE

Update command is used to update existing data within a table.

The syntax for the update command is as follows -

Syntax

UPDATE <table_name> SET column_name =value WHERE condition;

For example, if we want to update the name of the employee having the employee id 001, we
can use the command given below −

Example

UPDATE Employee SET Emp_name= Ram WHERE Emp_id= 001;

UPDATE Employee SET Emp_id=5 where emp_name= ‘RAJU’;

DQL (Data Query Language)

SELECT

Select command is used to retrieve data from the database.

The syntax for the select command is as follows −

Syntax

SELECT field1, field2, field.N from <table_name> where <condition>;

For example, if we want to select all rows from the Employee database, we can use the
following command −

Example

SELECT * from Employee;


SELECT emp_name from Employee where emp_id=10;

Prepared by: Mr.R.J. Patel Page |7 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.7 Define Normalization and State requirement of normalization. [04]

Ans: Normalization: In relational database design, the process of organizing data to minimize
redundancy. Normalization usually involves dividing a database into two or more tables
without losing information and defining relationships between the tables.
The goal of normalization process are:

 To minimize data redundancy.


 To minimize update, deletion and insertion anomalies.
 Improve data integrity, scalability and data consistency.
 Reduces disk space.
 The Normal Form is a state of a relation that results from applying some criteria
on that relation.
❖ Various normal forms are given below:
1. First Normal Form (1NF)
2. Second Normal Form (2NF)
3. Third Normal Form (3NF)

(b)Explain the purpose of SAVEPOINT command. SAVEPOINT. 04

Ans: SQL SAVEPOINT command create new save point. SAVEPOINT command save the
current point with the unique name in the processing of a transaction.

 Savepoint is a command in SQL that is used with the rollback command.


 It is a command in Transaction Control Language that is used to mark the transaction
in a table.
 Consider you are making a very long table, and you want to roll back only to a certain
position in a table then; this can be achieved using the savepoint.
 If you made a transaction in a table, you could mark the transaction as a certain name,
and later on, if you want to roll back to that point, you can do it easily by using the
transaction's name.
 we can say savepoint is a bookmark in SQL.

Syntax

SAVEPOINT savepoint_name;

Prepared by: Mr.R.J. Patel Page |8 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Example

SQL> CREATE TABLE emp_data (


no NUMBER (3),
name VARCHAR (50),
code VARCHAR (12)
);

Table created.

SQL> SAVEPOINT table_create;

Savepoint created.

SQL> insert into emp_data VALUES (1,'Opal', 'e1401');

1 row created.

SQL> SAVEPOINT insert_1;

Savepoint created.

SQL> insert into emp_data VALUES (2,'Becca', 'e1402');

1 row created.

SQL> SAVEPOINT insert_2;

Savepoint created.

SQL> SELECT * FROM emp_data;

NO NAME CODE
---------- ------------------------------------------ ------------
1 Opal e1401
2 Becca e1402

SQL ROLLBACK

SQL ROLLBACK command execute at the end of current transaction and undo/undone any
changes made since the begin transaction.

Syntax

ROLLBACK [To SAVEPOINT_NAME];

Example

Above example we are create 3 SAVEPOINT table_create, insert_1 and insert_2. Now we are
rollback to insert_1 SAVEPOINT.
Prepared by: Mr.R.J. Patel Page |9 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

SQL> ROLLBACK TO insert_1;

Rollback complete.

SQL> SELECT * FROM emp_data;

NO NAME CODE
---------- ------------------------------------------ ------------
1 Opal e1401

Q.8 Explain DCL commands with examples. [07]

Ans: It is used to provide different users access to the stored data. It enables the data
administrator to grant or revoke the required access to act as the database.

Two types of DCL commands can be used by the user in SQL. These commands are useful,
especially when several users access the database. It enables the administrator to manage
access control. The two types of DCL commands are as follows:

 GRANT
 REVOKE

GRANT, as the name itself suggests this command allows the administrator to provide
particular privileges or permissions over a database object, such as a table, view, or procedure.
It can provide user access to perform certain database or component operations.

Here is the Syntax of the GRANT Command:

GRANT command1, command2… ON TABLE_NAME TO USER;

For Example:

GRANT INSERT, SELECT on student to XYZ

Thus, using the grant command, XYZ user has been granted permission on the “student”
database objects(table), and he can insert or query the “student” database.

REVOKE

As the name suggests the REVOKE command enables the database administrator to remove
the previously provided privileges or permissions from a user over a database or database
object, such as a table, view, or procedure. The REVOKE commands prevent the user from
accessing or performing a specific operation on an element in the database.

Prepared by: Mr.R.J. Patel P a g e | 10 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Here is the syntax of the REVOKE Command:

REVOKE name_of_command ON name_of_table FROM User_name;

For Example:

REVOKE INSERT, SELECT on student from XYZ;

Thus, when we use this command, the permissions of XYZ (like insert or query) on the
“student” database objects have been removed.

Q.9 Define Schema, Sub-schema and Instance. [03]

Ans: Instance: In simple words, it is the snapshot of the database taken at a particular
moment. It can also be described in more significant way as the collection of the information
stored in the database at that particular moment.

Every time we update the state say we insert, delete or modify the value of the data item in
the record, it changes from one state to other. At the given time, each schema has its own set
of instances.

Schema

It is the overall description or the overall design of the database specified during the database
design. Important thing to be remembered here is it should not be changed frequently.

Sub schema

A sub schema is a subset of the schema and inherits the same property that a schema has. The
plan (or scheme) for a view is often called sub schema.

Q.10 Consider the following table and solve the given queries. [4]

Employee (emo_no, emp_name, desg, salary, dept)

1). create table employee.

Ans 1: create table employee (emo_no number (5), emp_name varchar2(25), desg
varhcar2(10), salary number (10), dept varchar2(10));

2). Display information of all employees whose names start with ‘m’ and end with ‘a’.

Ans 2: select * from employee where emp_name like ‘m%a’;

3). Display department-wise salary total.

Ans 3: select dept, sum(salary) from employee group by dept,


Prepared by: Mr.R.J. Patel P a g e | 11 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

4). Add new column contact_no in employee.

Ans: Alter table employee add (contact_no number (12));

Q.11 Explain the Data Dictionary and its components. [07]

A data dictionary contains metadata i.e., data about the database. The data dictionary is very
important as it contains information such as what is in the database, who is allowed to access
it, where is the database physically stored etc. The users of the database normally don't interact
with the data dictionary; it is only handled by the database administrators.

The data dictionary in general contains information about the following −

 Names of all the database tables and their schemas.


 Details about all the tables in the database, such as their owners, their security
constraints, when they were created etc.
 Physical information about the tables such as where they are stored and how.
 Table constraints such as primary key attributes, foreign key information etc.
 Information about the database views that are visible .

The different types of data dictionary are −

Active Data Dictionary

The data dictionary is automatically updated by the database management system when any
changes are made in the database. This is known as an active data dictionary as it is self-
updating.

Passive Data Dictionary

The passive data dictionary has to be manually updated to match the database. This needs
careful handling or else the database and data dictionary are out of sync.

Components of Data Dictionaries:

Entities: An Entity is thing or object existing in the real world that is distinguishable from all
other objects.

Attributes: An attribute is a properly or characteristics of an entity.

Relationships: A relationship is an association or connection among entities.

Key: A data item or field which is used to identify a record in database is referred to as a key.
Prepared by: Mr.R.J. Patel P a g e | 12 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.12 Explain Single row functions. [ 04]

Ans: Single Row functions - Single row functions are the one who work on single row and
return one output per row. For example, length and case conversion functions are single row
functions.

Example:

 Conversion functions - Accepts character input and returns a character value. Functions
under the category are UPPER, LOWER and INITCAP.

 UPPER function converts a string to upper case.


 LOWER function converts a string to lower case.
 INITCAP function converts only the initial alphabets of a string to upper case.

 Character functions - Accepts character input and returns number or character value.
Functions under the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD,
TRIM and REPLACE.

 CONCAT function concatenates two string values.


 LENGTH function returns the length of the input string.
 SUBSTR function returns a portion of a string from a given start point to an end
point.
 INSTR function returns numeric position of a character or a string in a given string.
 LPAD and RPAD functions pad the given string upto a specific length with a given
character.
 TRIM function trims the string input from the start or end.
 REPLACE function replaces characters from the input string with a given character.

 Date functions - Date arithmetic operations return date or numeric values. Functions under
the category are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY,
ROUND and TRUNC.

 MONTHS_BETWEEN () function returns the count of months between the two dates.
 ADD_MONTHS () function add 'n' number of months to an input date.
 NEXT_DAY () function returns the next day of the date specified.
 LAST_DAY () function returns last day of the month of the input date.
 ROUND () and TRUNC () functions are used to round and truncates the date value.

Prepared by: Mr.R.J. Patel P a g e | 13 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.13 Explain following SQL function. 1). MONTHS_BETWEEN 2). ROUND 3).
FLOOR 4).TO_NUMBER [04]

(1) MOTHS_BETWEEN (): returns the count of months between the two dates.

Syntax:

MONTHS_BETWEEN (date1, date2)

(2) ROUND (): This function is used to return n rounded to integer places to the right of the
decimal point.

Using the following rules ROUND () function is implemented:

 If no integer is defined, then n is rounded to zero places.


 If the integer specified is negative, then n is rounded off to the left of the decimal
point.

Syntax:

ROUND (n [, D])

Parameters:

Name Description

n: A number which will be rounded upto D decimal places.

D: A number indicating up to how many decimal places n will be rounded.

(1) Floor (): The FLOOR () function returns the largest integer value not greater than a number
specified as an argument.
Syntax: FLOOR(N)
Parameters:
N: A number. Ex. (1) floor(4.93)  4. (2) floor(-4.93) -5.
(2) TO_NUMBER (): It is used to convert a string to a number.

Syntax:

TO_NUMBER (char, format mask)

Parameters: char: It is used to specify the string to be converted. format_mask: It is an


optional parameter which is used to specify the format to be used for conversion.

Prepared by: Mr.R.J. Patel P a g e | 14 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Example:

TO_NUMBER( '1342.67', '9999.99')

Output:

1342.67

Q.14 List the different types of joins. Explain any three in detail with the help of an
example. [07]

Ans: Join is a query that is used to combine rows from two or more tables, views, It retrieves
data from multiple tables and creates a new table.

Types of Joins

 Inner Joins (Simple Join)


 Outer Joins
o Left Outer Join (Left Join)
o Right Outer Join (Right Join)
o Full Outer Join (Full Join)
 Equijoins
 Self Joins
 Cross Joins (Cartesian Products)

Inner Joins (Simple Join):

Inner Join is the simplest and most common type of join. It is also known as simple join. It
returns all rows from multiple tables where the join condition is met.

Syntax Image representation of Inner Join

SELECT columns FROM

table1 INNER JOIN table2

ON table1.column = table2.column;

Outer Joins:

An outer join is similar to equijoin but it gets also the non-matched rows from the table. It is
categorized in Left Outer Join, Right Outer Join and Full Outer Join

Prepared by: Mr.R.J. Patel P a g e | 15 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Left Outer Join

Left Outer Join returns all rows from the left (first) table specified in the ON condition and
only those rows from the right (second) table where the join condition is met.

Syntax Image representation of left outer join

SELECT columns

FROM table1

LEFT OUTER JOIN table2

ON table1.column = table2.column;

Right Outer Join

The Right Outer Join returns all rows from the right-hand table specified in the ON condition
and only those rows from the other table where the join condition is met.

Syntax: Image representation of Right Outer Join

SELECT columns

FROM table1

RIGHT OUTER JOIN table2

ON table1.column = table2.column;

Full Outer Join

The Full Outer Join returns all rows from the left hand table and right hand table. It places
NULL where the join condition is not met.

Syntax Image representation of Full Outer Join

SELECT columns

FROM table1 FULL OUTER JOIN table2

ON table1.column = table2.column;

Prepared by: Mr.R.J. Patel P a g e | 16 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Equijoins:

Oracle Equi join returns the matching column values of the associated tables. It uses a
comparison operator (=) in the WHERE clause to refer equality.

Syntax

SELECT column_list

FROM table1, table2....

WHERE table1.column_name =

table2.column_name;

Self-Join:

Self-Join is a specific type of Join. In Self Join, a table is joined with itself (Unary relationship).
A self-join simply specifies that each rows of a table is combined with itself and every other
row of the table.

Syntax

SELECT a. column name, b. column_name...


FROM table1 a, table1 b
WHERE a. common_filed = b. common_field;

Cross Join:

The CROSS JOIN specifies that all rows from first table join with all of the rows of second
table. If there are "x" rows in table1 and "y" rows in table2 then the cross join result set have
x*y rows. It normally happens when no matching join columns are specified.

In simple words you can say that if two tables in a join query have no join condition, then the
Oracle returns their Cartesian product.

Syntax

SELECT * FROM table1 CROSS JOIN table2;

Prepared by: Mr.R.J. Patel P a g e | 17 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.15 Define sub-query and correlated sub-query. Explain with example. [03]

Ans: Sub-query: In Oracle, subqueries are the queries inside a query. Subqueries can be made
using WHERE, FROM or SELECT clause.

Correlated query: A correlated subquery is a subquery that relies on values from the outer
query to execute. In Oracle SQL, a correlated subquery can be used to filter or manipulate data
based on values in the outer query.

Here's an example:
Consider two tables: employees and departments. employees table:
+-----------+---------+----------+-------------+
| employee_id | name | salary | department_id |
+-----------+---------+----------+-------------+
|1 | John | 5000 | 10 |
|2 | Jane | 6000 | 10 |
|3 | Mark | 5500 | 20 |
|4 | Lucy | 4500 | 20 |
+-----------+---------+----------+-------------+
departments table:
+---------------+----------+
| department_id | name |
+---------------+----------+
| 10 | HR |
| 20 | IT |
+---------------+----------+
Now, let's say we want to find all employees who earn the maximum salary in their
department. We can use a correlated subquery to achieve this:
SELECT e1. employee_id, e1.name, e1. salary, e1. department_id
FROM employees e1 WHERE e1. salary = (
SELECT MAX (e2. salary)
FROM employees e2
WHERE e1. department_id = e2. department_id
);
In this query, the outer query is iterating over each employee (aliased as e1), and the correlated
subquery (aliased as e2) calculates the maximum salary for each department. The outer query

Prepared by: Mr.R.J. Patel P a g e | 18 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

then filters the results by matching the employee's salary with the maximum salary in their
department. The output will be:
+-----------+------+--------+--------------+
| employee_id | name | salary | department_id |
+-----------+------+--------+--------------+
|2 | Jane | 6000 | 10 |
|3 | Mark | 5500 | 20 |
+-----------+------+--------+--------------+
Q.16 Explain following SQL function.

1). SUM 2). INITCAP 3). TO_CHAR4). GREATEST [04]

(1) SUM (): The SUM () is a Math function of Oracle. This function is used to sum the values
of given expressions.

Syntax

SELECT SUM(column) FROM tables [WHERE conditions];

(2) INITCAP (): This function is used to convert first letter in capital and rest of the letter in
small case of the given string.

(3) TO_CHAR: TO_CHAR is one of the vital Conversion functions of Oracle. It is used to
convert a number or date to a string.

Syntax:

TO_CHAR (value, format_mask)

Parameters: value: It is used to specify the number or date to be converted. format_mask: It


is an optional parameter which is used to specify the format to be used for conversion.

Example 1: TO_CHAR(1340.64, '9999.9')

Output:

' 1340.6'

Explanation: Here, a number is converted to a string in the desired format.

Example 2: TO_CHAR(sysdate, 'Month DD, YYYY')

Output:

'June 28, 2019'


Prepared by: Mr.R.J. Patel P a g e | 19 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.17 Explain SQL Operators. [07]

Ans: SQL supports following types of operators:

(1) Arithmetic operators


(2) Comparison operators
(3) Logical operators
(4) Operators used to negate conditions

SQL Arithmetic Operators

SQL Arithmetic Operators are used to perform mathematical operations on the numerical
values.
Here is a list of all the arithmetic operators available in SQL.

Operator Description Example


+ Addition 10 + 20 = 30
- Subtraction 20 - 30 = -10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 5%2=1

SQL Comparison Operators

SQL Comparison Operators test whether two given expressions are the same or not. These
operators are used in SQL conditional statements while comparing one expression with
another and they return a Boolean value which can be either TRUE or FALSE. Here is a list
of all the comparison operators available in SQL.

Operator Description Example


= Equal to 5 = 5 returns TRUE
!= Not equal 5 != 6 returns TRUE
<> Not equal 5 <> 4 returns TRUE
> Greater than 4 > 5 returns FALSE
< Less than 4 < 5 returns TRUE
>= Greater than or equal to 4 >= 5 returns FALSE
<= Less than or equal to 4 <= 5 returns TRUE
!< Not less than 4 !< 5 returns FALSE
!> Not greater than 4 !> 5 returns TRUE

Prepared by: Mr.R.J. Patel P a g e | 20 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

SQL Logical Operators

SQL Logical Operators are very similar to comparison operators and they test for the truth of
some given condition. These operators return a Boolean value which can be either a TRUE or
FALSE.

Here is a list of all the logical operators available in SQL.

Operator Description

ALL TRUE if all of a set of comparisons are TRUE.

AND TRUE if all the conditions separated by AND are TRUE.

BETWEEN TRUE if the operand lies within the range of comparisons.

IN TRUE if the operand is equal to one of a list of expressions.

TRUE if the operand matches a pattern specially with


LIKE
wildcard.

NOT Reverses the value of any other Boolean operator.

OR TRUE if any of the conditions separated by OR is TRUE

Q.18 Define View, Index and synonym. [03]

Ans: View:

Views in SQL are considered as a virtual table. A view also contains rows and columns.

 To create the view, we can select the fields from one or more tables present in the
database.
 A view can either have specific rows based on certain condition or all the rows of a
table.

Syntax:

CREATE VIEW view_name AS SELECT column1, column2...... FROM table_name


WHERE condition;

Advantages of View:

1. Complexity: Views help to reduce the complexity. Different views can be created on the
same base table for different users.
2. Security: It increases the security by excluding the sensitive information from the view.

Prepared by: Mr.R.J. Patel P a g e | 21 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

3. Query Simplicity: It helps to simplify commands from the user. A view can draw data from
several different tables and present it as a single table.
4. Consistency: A view can present a consistent, unchanged image of the structure of the
database. Views can be used to rename the columns without affecting the base table.
5. Data Integrity: If data is accessed and entered through a view, the DBMS can automatically
check the data to ensure that it meets the specified integrity constraints.
6. Storage Capacity: Views take very little space to store the data.

Index: Indexes are used to retrieve data from the database more quickly than otherwise. The
users cannot see the indexes; they are just used to speed up searches/queries.

Two types of index are there: (1) Simple index (2) Unique Index

Syntax:

Creates an index on a table. Duplicate values are allowed: (simple index)

CREATE INDEX index_name ON table_name (column1, column2, ...);


CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:(unique index)

CREATE UNIQUE INDEX index_name ON table_name (column1, column2, ...);


Synonym: In SQL Server, the synonym is the database object that provides alternate name
(alias) to another database objects such as table, view, stored procedure, etc. in the local server
or a remote server.

Syntax:

CREATE SYNONYM <synonym> FOR <table_name or object>

Example: create synonym sym_stu for student;

This is will create another name for the table student.

Q.19 Write and Explain the command to create a sequence with all options.

Ans: Sequences in SQL are database objects that generate a sequence of unique integer values.
They are frequently used in databases because many applications require that each row in a
table must contain unique values and sequences provide an easy way to generate them.

Prepared by: Mr.R.J. Patel P a g e | 22 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Syntax:

CREATE SEQUENCE seq_name


INCREMENT BY n
START WITH n
MINVALUE n
MAXVALUE n
CYCLE
NOCACHE;
INCREMENT BY:

It represents the difference between current sequence value and the next sequence value.

STARTS WITH:

It specifies the first sequence number to be generated by oracle for a given sequence. If this
clause is excluded, then default is 1.

MINVALUE:

It specifies the minimum value to be allowed for a sequence. If this clause is excluded, then
default is 1.

MAXVALUE:

It specifies the maximum value to be allowed for a sequence. if this clause is excluded then
default is 9999999999999999999999999999.

CYCLE:

It specifies that whether the sequence will continue to generate unique numbers after reaching
its maximum value.

NOCYCLE:

It specifies that whether the sequence will not continue to generate unique numbers after
reaching its maximum value. NOCYCLE is the default.

CACHE:
It specifies that how many numbers oracle server will pre-allocate and keep in memory for a
sequence.

A sequence can be destroyed as described below.


Syntax:
DROP Sequence sequence_name

Prepared by: Mr.R.J. Patel P a g e | 23 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.20 Explain entity constraints with syntax and example. [ 07]

Ans: Integrity constraints are a set of rules. It is used to maintain the quality of information.

Entity integrity Contain (1) Not Null, Null (2) Check (3) primary key (4) Unique key

(1) Not Null & Null:


 There may be Records in table that do not contain any value for some
fields. In Oracle, Null values are stored in such fields. In other words, a
NULL value represents an unknown value.
 A NULL value indicates ‘not applicable’, ‘missing’, or ‘not known’.
 A NULL value distinct from zero or other numeric value for numerical
data.
 NULL value is also distinct from blank space for character data.
 A column, defined as a NOT NULL, cannot have a NULL value. In
other words, such column becomes a mandatory column and cannot be
left empty for any record

Syntax:
ColumnName datatype (size) NOT NULL / NULL
(2) Check: The CHECK constraint is used to implement business rules. This
constraint is also referred as business rule constraints. Business rules may vary
from system to system
Syntax:
columnName datatype (size) CHECK (CONDITION)
Example:
CREATE TABLE Orders
Prepared by: Mr.R.J. Patel P a g e | 24 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

(
order_id number (10),
amount number (10) CHECK (amount > 0)
)
(3) Primary key: A primary key is a set of one or more columns used to identify
each record uniquely in a column”. A single column primary key is called as
simple key, while a multi-column primary key is called a composite key
Syntax:
columnName datatype (size) PRIMARY KEY
(4) Unique key: A column, defined as a UNIQUE, cannot have duplicate values
across all records. In other words, such column must contain unique values.
Syntax:
columnName datatype (size) UNIQUE
Example:
CREATE TABLE Colleges (
college_id number (5) UNIQUE,
college_code VARCHAR(20) UNIQUE,
college_name VARCHAR(50)
);
Q.21 Explain foreign key with example: [4]

Ans: A foreign key is a set of one or more columns whose values are derived from another
table primary key or unique key.

The table in which a foreign key is defied is called foreign table, details table or child table.
The table in which primary key or unique key is defied is called primary table, master table or
parent table.

Syntax for foreign key at column level:

Columnname datatype (size) REFERENCES table name (column name)

[ON DELETE CASCADE OR ON DELETE SET NULL]

Example:

Create table account

Ano number (10) primary key, balance number (6), bname varchar2(20) REFERENCES
Branch(bname)

);

Prepared by: Mr.R.J. Patel P a g e | 25 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Where account is child table, Branch is parent or master table, bname is foreign key in
account table, bname is primary key in Branch table.

ON DELETE CASCADE OR ON DELETE SET NULL is optimal:

 If on delete cascade used with foreign key, then if delete command applies on Master
table(Branch) then corresponding record from child table(account) also deleted
automatically.
 If on delete set null option is used with foreign key, then if delete command applies on
Master table(Branch) then corresponding record from child table(account) also deleted
automatically and set to NULL.

Q.22 Define PL/SQL? Explain the advantages of PL/SQL over SQL. [03]

Ans: PL/SQL stands for Procedural Language/Structured Query Language. It is a combination of


SQL with procedural features of programming language.

Advantages of PL/SQL
PL/SQL is a completely portable, high-performance transaction processing language that offers the
following advantages:

Procedural Capabilities:
• PL/SQL provides procedural capabilities such as condition checking, branching and
looping.
• This enables programmer to control execution of a program based on some conditions
and user inputs.
2) Support to variables:
• PL/SQL supports declaration and use of variables.
• These variables can be used to store intermediate results of a query or some expression.
3) Error Handling:
• When an error occurs, user friendly message can be displayed.
• Also, execution of program can be controlled instead of abruptly terminating the program.
4) User Defined Functions:
• Along with a large set of in-build functions, PL/SQL also supports user defined functions
and procedures.
5) Portability:
• Programs written in PL/SQL are portable.
• It means, programs can be transferred and executed from any other computer hardware
and operating system, where Oracle is operational.

Prepared by: Mr.R.J. Patel P a g e | 26 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

6) Sharing of Code:
• PL/SQL allows user to store compiled code in database. This code can be accessed and
shared by different applications.

• This code can be executed by other programming language like JAVA.

Q.23 Explain implicit and explicit Cursors. [03]

Ans: When an SQL statement is processed, Oracle creates a memory area known as context
area. A cursor is a pointer to this context area. It contains all information needed for processing
the statement. In PL/SQL, the context area is controlled by Cursor.

There are two types of cursors:

 Implicit Cursors
 Explicit Cursors

1) PL/SQL Implicit Cursors

The implicit cursors are automatically generated by Oracle while an SQL statement is executed,
if you don't use an explicit cursor for the statement.

These are created by default to process the statements when DML statements like INSERT,
UPDATE, DELETE etc. are executed.

Oracle provides some attributes known as Implicit cursor's attributes to check the status of
DML operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and
%ISOPEN.

The following table specifies the status of the cursor with each of its attribute.

Attribute Description
Its return value is TRUE if DML statements affect at least one row or more
%FOUND
rows Otherwise it returns FALSE.
Its return value is TRUE if DML statements Otherwise it returns FALSE. It
%NOTFOUND
is a just opposite of %FOUND.
It always returns FALSE for implicit cursors, because the SQL cursor is
%ISOPEN
automatically closed after executing its associated SQL statements.
%ROWCOUNT It returns the number of rows affected by DML statements

2) PL/SQL Explicit Cursors

The Explicit cursors are defined by the programmers to gain more control over the context
area. These cursors 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.

Prepared by: Mr.R.J. Patel P a g e | 27 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Following is the syntax to create an explicit cursor:

Syntax of explicit cursor

Following is the syntax to create an explicit cursor:

1. CURSOR cursor_name IS select statement;

Steps:

You must follow these steps while working with an explicit cursor.

1. Declare the cursor to initialize in the memory.


2. Open the cursor to allocate memory.
3. Fetch the cursor to retrieve data.
4. Close the cursor to release allocated memory.

1) Declare the cursor:

It defines the cursor with a name and the associated SELECT statement.

Syntax for explicit cursor declaration

CURSOR name IS SELECT statement;

2) Open the cursor:

It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
SQL statements into it.

Syntax for cursor open: OPEN cursor_name;

3) Fetch the cursor:

It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:

Syntax for cursor fetch:

1. FETCH cursor_name INTO variable_list;

4) Close the cursor:

It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.

Syntax for cursor close:

1. Close cursor_name;

Prepared by: Mr.R.J. Patel P a g e | 28 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

PL/SQL Explicit Cursor Example

Create customers table and have records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000

Create procedure for cursor :

Execute the following program to retrieve the customer name and address.

1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers. address% type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers;
7. BEGIN
8. OPEN c_customers;
9. LOOP
10. FETCH c_customers into c_id, c_name, c_addr;
11. EXIT WHEN c_customers%notfound;
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
13. END LOOP;
14. CLOSE c_customers;
15. END;
16. /

Output:

1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL procedure successfully completed.

Q.24 Write a program to display numbers from 1 to 10 and their square values using
while LOOP. [04]

Prepared by: Mr.R.J. Patel P a g e | 29 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

1. DECLARE
2. i INTEGER: = 1;
3. BEGIN
4. WHILE i <= 10 LOOP
5. DBMS_OUTPUT.PUT_LINE (i || i*i);
6. i := i+1;
7. END LOOP;
8. END;

Q.25 Define Triggers. Explain types of Triggers with examples. [07]

Ans: A Trigger in Structured Query Language is a set of procedural statements which are
executed automatically when there is any response to certain events on the particular table in
the database. Triggers are used to protect the data integrity in the database.

The syntax for creating a trigger is −

CREATE [OR REPLACE] TRIGGER trigger_name


{BEFORE | AFTER}
{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
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Where,

 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an


existing trigger with the trigger_name.
 {BEFORE | AFTER} − This specifies when the trigger will be executed.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.

Prepared by: Mr.R.J. Patel P a g e | 30 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

 [OF col_name] − This specifies the column name that will be updated.
 [ON table_name] − This specifies the name of the table associated with the trigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old
values for various DML statements, such as INSERT, UPDATE, and DELETE.
 [FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would
fire. This clause is valid only for row-level triggers.

Type of trigger:

 After Statement trigger- executes trigger once before triggering statement


 After Row trigger-executes triggers multiple times after triggering statement.
 Before Statement trigger-executes trigger once before triggering statement.
 Before Row trigger- executes trigger once before triggering statement.

Row Level Triggers Statement Level Triggers


Row level triggers executes once for each Statement level triggers executes only once for
and every row in the transaction. each single transaction.
Used for enforcing all additional security on the
Specifically used for data auditing purpose.
transactions performed on the table.
“FOR EACH ROW” clause is present in “FOR EACH STATEMENT” clause is omitted
CREATE TRIGGER command. in CREATE TRIGGER command.
Example: If 1500 rows are to be inserted Example: If 1500 rows are to be inserted into a
into a table, the row level trigger would table, the statement level trigger would execute
execute 1500 times. only once.
Example

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This
trigger will display the salary difference between the old values and new values −
Prepared by: Mr.R.J. Patel P a g e | 31 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff: =: NEW. Salary -: OLD. Salary;
dbms_output.put_line ('Old salary: ' ||: OLD. Salary);
dbms_output.put_line ('New salary: ' ||: NEW. Salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

Trigger created.
Q.26 Explain System defined and user defined Exceptions Handling. [07]

Ans: 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 −

 System-defined exceptions
 User-defined exceptions

Syntax system defined for Exception Handling

The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others
THEN −

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
Prepared by: Mr.R.J. Patel P a g e | 32 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

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;

Syntax User defined for Exception Handling

DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
Example (system defined)

Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had
created and used in the previous chapters −

DECLARE
c_id customers.id%type: = 8;
c_name customerS.Name%type;
c_addr customers. address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
Prepared by: Mr.R.J. Patel P a g e | 33 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);


DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);

EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line ('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

No such customer!

PL/SQL procedure successfully completed.

The above program displays the name and address of a customer whose ID is given. Since there
is no customer with ID value 8 in our database, the program raises the run-time exception
NO_DATA_FOUND, which is captured in the EXCEPTION block.

Example (User defined)

The following example illustrates the concept. This program asks for a customer ID, when
the user enters an invalid ID, the exception invalid_id is raised.

DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers. address% type;
-- user defined exception
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;

Prepared by: Mr.R.J. Patel P a g e | 34 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

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;
/

When the above code is executed at the SQL prompt, it produces the following result −

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.


Q.27 Explain function and procedures in PL/SQL with proper example. [7]

Ans: A subprogram is a program unit/module that performs a particular task. These


subprograms are combined to form larger programs.

 Functions − These subprograms return a single value; mainly used to compute and
return a value.
 Procedures − These subprograms do not return a value directly; mainly used to
perform an action.

A procedure is created with the CREATE OR REPLACE PROCEDURE statement.

Syntax:

CREATE [OR REPLACE] PROCEDURE procedure_name

Prepared by: Mr.R.J. Patel P a g e | 35 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

[(parameter_name [IN | OUT | IN OUT] type [, ...])]

{IS | AS}
BEGIN
< procedure_body >
END procedure_name;

Where,

 procedure-name specifies the name of the procedure.


 [OR REPLACE] option allows the modification of an existing procedure.
 The optional parameter list contains name, mode and types of 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.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone procedure.

Example 1

This program finds the minimum of two values. Here, the procedure takes two numbers using
the IN mode and returns their minimum using the OUT parameters.

DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z: = x;
ELSE
z: = y;
END IF;
END;
BEGIN
a: = 23;
b: = 45;
findMin (a, b, c);
dbms_output.put_line (' Minimum of (23, 45): ' || c);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

Prepared by: Mr.R.J. Patel P a g e | 36 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Minimum of (23, 45): 23

PL/SQL procedure successfully completed.

Executing a Procedure:

To executes a procedure from SQL prompt

Exec procedure_name(parameter);

A standalone function is created using the CREATE FUNCTION statement. The simplified
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,

 function-name specifies the name of the function.


 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of 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.
 The function must contain a return statement.
 The RETURN clause specifies the data type you are going to return from the function.
 function-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone function.

Example

The following example illustrates how to create and call a standalone function. This function
returns the total number of CUSTOMERS in the customers table.

CREATE OR REPLACE FUNCTION totalCustomers


RETURN number IS
Prepared by: Mr.R.J. Patel P a g e | 37 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

total number (2): = 0;


BEGIN
SELECT count (*) into total
FROM customers;

RETURN total;
END;
/ When the above code is executed using the SQL prompt, it will produce the
following result −
Function created.

Calling a Function:

To execute from SQL prompt, it should be used with SELECT statement as given below

Syntax: SELECT function_name (parameter) from dual;

Destroying function and procedure:

Drop procedure procedure_name;

Drop function function_name;

Q.28 Write down Advantages and Disadvantages of Normalization. [07]

Ans.
Definition: Normalization.

In relational database design, the process of organizing data to minimize redundancy.


Normalization usually involves dividing a database into two or more tables without losing in
formation and defining relationships between the tables.

Advantages of Normalization:
1. Normalization reduces the unnecessary redundant data.
2. Data integrity is easily maintained within the database.
3. It makes database and application design processes much more flexible.

Disadvantages of Normalization:
1. Difficult and expansive
2. It requires a detailed database design
3. Maintenance overhead

Prepared by: Mr.R.J. Patel P a g e | 38 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.29 Explain 1NF, 2NF and 3NF with suitable examples.

Ans: Various normal forms are given below:

1. First Normal Form (1NF)


2. Second Normal Form (2NF)
3. Third Normal Form (3NF)

First Normal Form(1NF)


• A relation R is in first normal form (1NF) if and only if all domains contain
atomic values only.
• A relation R is in first normal form (1NF) if and only if it does not contain any
composite or multi valued attributes or their combinations.

Second Normal Form (2NF)


• A relation R is in second normal form (2NF) if and only if it is in 1NF and every nonprime
attribute of relation is fully dependent on the primary key.

Third Normal Form (3NF)


• A relation R is in third normal form (3NF) if and only if it is in 2NF and no any nonprime
attribute of a relation is transitively dependent on the primary key.
• An attribute C is transitively dependent on attribute A if there exist an attribute B such
that:
A → B and B → C.

Example:

Above relation has four attributes Cid, Name, Address, Contact_no. Here Address is
composite attribute which is further divided in to sub attributes as Society and City.
Another attribute Contact_no is multi valued attribute which can store more than one
Prepared by: Mr.R.J. Patel P a g e | 39 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

values. So
• Above relation is not in 1NF.

How to convert into 1NF.

First Approach:
• Determine maximum allowable values for multi-valued attribute.
• Insert separate attribute for multi valued attribute and insert only one value on one
attribute and other in other attribute.
• So, above table can be created as follows:

Second Approach:
• Remove multi valued attribute and place it in a separate relation along with the primary
key of a given original relation.
• So, above table can be created as follows:

Prepared by: Mr.R.J. Patel P a g e | 40 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Q.29 List and Explain Control structure in PL/SQL

Ans: PL/SQL Control Structures are used to control flow of execution. PL/SQL provides
different kinds of statements to provide such type of procedural capabilities.

The flow of control statements can be classified into the following categories:

 Conditional Control
 Iterative Control
 Sequential Control

Conditional Control:

Syntax:

IF < Condition > THEN


< Action >
ELSIF <Condition> THEN
< Action >
ELSE < Action >
END IF;
Example:

DECLARE
a Number := 30; b Number;
BEGIN
IF a > 40 THEN
b := a - 40;
DBMS_OUTPUT.PUT_LINE('b=' || b);
elsif a = 30 then
b := a + 40;
DBMS_OUTPUT.PUT_LINE('b=' || b);
ELSE
b := 0;
DBMS_OUTPUT.PUT_LINE('b=' || b);
END IF;
END;
/
Output:

Prepared by: Mr.R.J. Patel P a g e | 41 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Iterative Control:

Iterative control indicates the ability to repeat or skip sections of a code block.

(1) Simple loop:

Syntax:

Loop
< Sequence of statements >
End loop;

Example:
create file named it.sql

DECLARE
i number: = 0;
BEGIN
LOOP
dbms_output.put_line ('i = '||i);
i: =i+1;
EXIT WHEN i>=11;
END LOOP;

END;
/

Prepared by: Mr.R.J. Patel P a g e | 42 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Output:

(2) WHILE loop

The while loop executes commands in its body as long as the condtion remains true

Syntax:

WHILE < condition >


LOOP
< Action >
END LOOP
Example 1:

find reverse of given number using while loop

DECLARE
num Number (3): =123;
ans Number (3): =0;
i Number (3): =0;
BEGIN
WHILE num! = 0
LOOP
i: =mod(num,10);
ans: = (ans * 10) + i;
num: =floor(num/10);
END LOOP;
dbms_output.put_line ('reverse of given number is: ' || ans);
END;
/
Prepared by: Mr.R.J. Patel P a g e | 43 N.G. PATEL POLYTECHIC ISROLI
Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Output:

Example 2:

To print the odd numbers between 1 to 10 using the while loop.

DECLARE
num int: =1;
BEGIN
while (num <= 10) LOOP
dbms_output.put_line(''|| no);
num := num+2;
END LOOP;
END;
Output:

(3) The FOR Loop

The FOR loop can be used when the number of iterations to be executed are known.

Syntax:

FOR variable IN [REVERSE] start..end


LOOP
< Action >
END LOOP;

Prepared by: Mr.R.J. Patel P a g e | 44 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

The variable in the For Loop need not be declared. Also the increment value cannot be
specified. The For Loop variable is always incremented by 1.

Example:
DECLARE
i number;
BEGIN
FOR i IN 1 .. 10
LOOP
dbms_output.put_line ('i = '||i);
END LOOP;
END;
/
Output:

Sequential Control:

The GOTO Statement

The GOTO statement changes the flow of control within a PL/SQL block. This statement
allows execution of a section of code, which is not in the normal flow of control. The entry
point into such a block of code is marked using the tags «userdefined name».

Syntax:

GOTO jump;
....
<<jump>>
Example:

Prepared by: Mr.R.J. Patel P a g e | 45 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

DECLARE

BEGIN
dbms_output.put_line ('code starts');
dbms_output.put_line ('before GOTO statement');
GOTO down;
dbms_output.put_line ('statement will not get executed.');
<<down>>
dbms_output.put_line ('flow of execution jumped here.');
END;
/
Output:

Q.30 Explain set operator in RDBMS.

Ans: SQL supports few Set operations which can be performed on the table data.

1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

UNION Operation

UNION is used to combine the results of two or more SELECT statements. However it will
eliminate duplicate rows from its resultset. In case of union, number of columns and datatype
must be same in both the tables, on which UNION operation is being applied.

Prepared by: Mr.R.J. Patel P a g e | 46 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Syntax of Union SQL query will be,

SELECT * FROM First


UNION
SELECT * FROM Second;

UNION ALL

This operation is similar to Union. But it also shows the duplicate rows.

INTERSECT

Intersect operation is used to combine two SELECT statements, but it only retuns the records
which are common from both SELECT statements. In case of Intersect the number of columns
and datatype must be same.

Syntax of Intersect query will be,

SELECT * FROM First


INTERSECT
SELECT * FROM Second;

Prepared by: Mr.R.J. Patel P a g e | 47 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

MINUS

The Minus operation combines results of two SELECT statements and return only those in the
final result, which belongs to the first set of the result.

Syntax of Minus query will be,

SELECT * FROM First


MINUS
SELECT * FROM Second;

Q.31 List types and Explain following built function in SQL.

 Numeric Function
 Character Function
 Date Function
 Conversion Function

Numeric Function:

 ABS (): Returns the absolute value of a number


o SELECT Abs (-243.5) from dual; o/p 243.5
 POWER: Returns the value of a number raised to the power of another number
o SELECT POWER (4, 2) from dual; o/p 16
 ROUND: Rounds a number to a specified number of decimal places
o SELECT ROUND (235.415, 2) from dual; o/p 235.420
 SQRT: Returns the square root of a number
o SELECT SQRT (64) from dual; o/p 8.0

Prepared by: Mr.R.J. Patel P a g e | 48 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Character Function:

Function Input Argument Value Returned


First letter of each word is changed to
INITCAP ( s ) s = character string uppercase and all other letters are in
lower case.
LOWER ( s ) s = character string All letters are changed to lowercase.
UPPER ( s ) s = character string All letters are changed to uppercase.
Returns s1 right justified and padded
s1 and s2 are character strings and
LPAD ( s1, n [, s2] ) left with n characters from s2; s2
n is an integer value
defaults to space.
Returns s1 left justified and padded
s1 and s2 are character strings and
RPAD ( s1, n [, s2] ) right with n characters from s2; s2
n is an integer value
defaults to space.
Returns s with characters removed up
s is a character string and set is a
LTRIM ( s [, set ] ) to the first character not in set; defaults
set of characters
to space
Returns s with final characters removed
s is a character string and set is a
RTRIM ( s [, set ] ) after the last character not in set;
set of characters
defaults to space
s = character string, m = Returns a substring from s, beginning in
SUBSTR ( s, m [, n ] ) beginning position, n = number of position m and n characters long;
characters default returns to end of s.
LENGTH ( s ) s = character string Returns the number of characters in s.

Date Function:

Function Input Argument Value Returned

d = date, n =
ADD_MONTHS ( d, n ) Date d plus n months
number of months

Date of the last day of the month


LAST_DAY ( d ) d = date
containing d
Number of months by which e
MONTHS_BETWEEN ( d, e ) d and e are dates
precedes d
SYSDATE none Current date and time

Prepared by: Mr.R.J. Patel P a g e | 49 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Conversion Function:

Number m converted to
m = numeric value, fmt =
TO_CHAR ( m [, fmt ] ) character string as
format
specified by the format

Character string s
s = character string, fmt =
TO_NUMBER ( s [, fmt ] ) converted to a number as
format
specified by the format

Formats for TO_CHAR Function


Symbol Explanation

9 Each 9 represents one digit in the result

0 Represents a leading zero to be displayed

$ Floating dollar sign printed to the left of number

L Any local floating currency symbol

. Prints the decimal point

, Prints the comma to represent thousands

Date Conversion Functions

Function Input Argument Value Returned

d = date value, fmt = The date d converted to a string in the


TO_CHAR ( d [, fmt ] )
format for string given format

s = character string, fmt


TO_DATE ( s [, fmt ] ) String s converted to a date value
= format for date

Date Formats
Format
Description Range of Values
Code

DD Day of the month 1 - 31

DY Name of the day in 3 uppercase letters SUN, ..., SAT

Prepared by: Mr.R.J. Patel P a g e | 50 N.G. PATEL POLYTECHIC ISROLI


Subject Code: 4330702 Computer Engineering dept. Subject: RDBMS

Complete name of the day in uppercase, padded to SUNDAY, ...,


DAY
9 characters SATURDAY

MM Number of the month 1 - 12

MON Name of the month in 3 uppercase letters JAN, ..., DEC

Name of the month in uppercase padded to a length JANUARY, ...,


MONTH
of 9 characters DECEMBER

YY or
Two or four digit year 71 or 1971
YYYY

HH:MI:SS Hours : Minutes : Seconds 10:28:53

A suffix meaning that the ordinal number is to be


TH e.g. 1st, 2nd, 3rd, ...
added

Prepared by: Mr.R.J. Patel P a g e | 51 N.G. PATEL POLYTECHIC ISROLI

You might also like