Rdbms Solution
Rdbms Solution
Subject: RDBMS
SEMESTER:3
______________________________________________________________
Application of DBMS:
Telecom: There is a database to keeps track of the information regarding calls made,
network usage, customer details etc.
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.
DELETE:
SYNTAX –
If we want to delete the row of the table as per the condition then we use the WHERE
clause,
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 –
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
Q.3 Define information and data. List out the difference between them. [3]
Data is a collection of raw, unorganised facts and details like text, observations, figures,
symbols and descriptions of things etc.
What is Information?
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.
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;
Ans: The DDL Commands in Structured Query Language are used to create and modify the schema
of the database
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
(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.
ALTER is a DDL command which changes or modifies the existing structure of the
database, and it also changes the schema of database objects.
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:
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.
RENAME is a DDL command which is used to change the name of the database table.
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
Syntax
For example, if we want to insert multiple rows to the Employee table, we can use the
following command −
Example
DELETE
Syntax
For example, if we want to delete an entire row of employee id 002, we can use the following
command −
Example
UPDATE
Syntax
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
SELECT
Syntax
For example, if we want to select all rows from the Employee database, we can use the
following command −
Example
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:
Ans: SQL SAVEPOINT command create new save point. SAVEPOINT command save the
current point with the unique name in the processing of a transaction.
Syntax
SAVEPOINT savepoint_name;
Example
Table created.
Savepoint created.
1 row created.
Savepoint created.
1 row created.
Savepoint created.
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
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
Rollback complete.
NO NAME CODE
---------- ------------------------------------------ ------------
1 Opal e1401
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.
For Example:
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.
For Example:
Thus, when we use this command, the permissions of XYZ (like insert or query) on the
“student” database objects have been removed.
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]
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’.
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 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.
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.
Entities: An Entity is thing or object existing in the real world that is distinguishable from all
other objects.
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
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.
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.
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.
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:
(2) ROUND (): This function is used to return n rounded to integer places to the right of the
decimal point.
Syntax:
ROUND (n [, D])
Parameters:
Name Description
(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:
Example:
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 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.
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
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.
SELECT columns
FROM table1
ON table1.column = table2.column;
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.
SELECT columns
FROM table1
ON table1.column = table2.column;
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.
SELECT columns
ON table1.column = table2.column;
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
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
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
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
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 (): The SUM () is a Math function of Oracle. This function is used to sum the values
of given expressions.
Syntax
(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:
Output:
' 1340.6'
Output:
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.
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.
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.
Operator Description
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:
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.
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 a unique index on a table. Duplicate values are not allowed:(unique index)
Syntax:
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.
Syntax:
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.
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
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.
Example:
Ano number (10) primary key, balance number (6), bname varchar2(20) REFERENCES
Branch(bname)
);
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.
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]
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.
6) Sharing of Code:
• PL/SQL allows user to store compiled code in database. This code can be accessed and
shared by different applications.
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.
Implicit Cursors
Explicit 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
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.
Steps:
You must follow these steps while working with an explicit cursor.
It defines the cursor with a name and the associated SELECT statement.
It is used to allocate memory for the cursor and make it easy to fetch the rows returned by the
SQL statements into it.
It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:
It is used to release the allocated memory. The following syntax is used to close the above-
opened cursors.
1. Close cursor_name;
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]
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;
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.
Where,
[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:
+----+----------+-----+-----------+----------+
| 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
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]
System-defined exceptions
User-defined exceptions
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
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
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!
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.
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;
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 −
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.
Syntax:
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
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 −
Executing a Procedure:
Exec procedure_name(parameter);
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax:
Where,
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.
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
Ans.
Definition: Normalization.
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
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.
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:
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:
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:
Iterative Control:
Iterative control indicates the ability to repeat or skip sections of a code block.
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;
/
Output:
The while loop executes commands in its body as long as the condtion remains true
Syntax:
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:
DECLARE
num int: =1;
BEGIN
while (num <= 10) LOOP
dbms_output.put_line(''|| no);
num := num+2;
END LOOP;
END;
Output:
The FOR loop can be used when the number of iterations to be executed are known.
Syntax:
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 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:
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:
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.
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.
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.
Numeric Function
Character Function
Date Function
Conversion Function
Numeric Function:
Character Function:
Date Function:
d = date, n =
ADD_MONTHS ( d, n ) Date d plus n months
number of months
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
Date Formats
Format
Description Range of Values
Code
YY or
Two or four digit year 71 or 1971
YYYY