You are on page 1of 121

HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023

Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

CONTENTS ____________________________________

PART-1 =====DBMS PAGE.NO


Introduction to DBMS……………………………………………………………………….

Advantages……………………………………………………………………………………

Data Abstraction……………………………………………………………………………..

Data Models…………………………………………………………………………………..

DataBase Facilities………………………………………………………………………….

Structure of a DBMS……………………………………………………………………..…

Different Type of Keys…………………………………………………………………..…

PART-2 =====SQL.

What is SQL…………………………………………………………………………………..

SQL Statements……………………………………………………………………………..

1.DDL , 2.DML , 3.DCL , 4.TCL , 5.DRL

Differences between DDL , DML & DCL


commands…………………………………………………………………………………….

SQL (ALL) commands………………………………………………………………………

(i)SQL*PLUS commands

(ii)PL/SQL commands

(iii)SQL commands

DATA TYPES of SQL………………………………………………………………………

OPERATIONS OF THE SQL STATEMENTS……………………………………………

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


1.DDL , 2 DML , 3 TCL & 4.DRL

Built Functions………………………………………………………………………………

*Number Function , *Character Function , *Date Function & *Group Function

Set Operators………………………………………………………………………………

Sub Queries (OR) Nested Queries……………………………………………………..

Views…………………………………………………………………………………………
Advantages

Sequence……………………………………………………………………………………

Index…………………………………………………………………………………………

Differences between SQL & PL/SQL………………………………………………….

Dynamic SQL………………………………………………………………………………

Embedded SQL……………………………………………………………………………

PART-3 =====PL/SQL.

Introduction to PL/SQL………………………………………………………………….

Advantages…………………………………………………………………………………

Block Structure……………………………………………………………………………

Variable & Constraints…………………………………………………………………..

DataTypes of PL/SQL……………………………………………………………………

Architecture………………………………………………………………………………

Trigger……………………………………………………………………………………..

Advantages of trigger………………………………………………………………….

Cursor………………………………………………………………………………………

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

SQL , PL/SQL PROGRAMS

Create a table to represent SB _account of a bank consisting of


1. account_no,customer_name & bal_amount. Write a PL/SQL block to
implement deposit & withdraw.Withdraw shoult not be allowed if the
balance goes below Rs.1000.

Create the following Two tables:


2.
College_info, consisting of field s :-
(college_code,college_name,address) Faculty_info,
consisting of fields :-(college_code,faculty_code ,faculty_name
,qualification, experiences_in_no_of_years,address.) The field
college_code is foreign key. (A)Design a
form to accept the data from the user.
(B)Generate queries ti do th following:
( i)List all those faculty members whose experience is greater than or
equal to 10years & have M.TECH degree.
(ii) List all those faculty members,who have atleast 10years of experience
but,do not have M.TECH degree.

Create the following tables for Library Information system:


3.
BOOK:(book_no,title,publisher,author,status) . STATUS could be
issued,present in the library,sent for binding and cannot be issued.
Write a trigger which sets the status of a book to “cannot be issued”,if it
is a published 20years back.

4. Create the BOOK table as in the 3rd program add one field as
(data_of_purchase), AND Status could be as same as in that table.
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those books which are new arrivals.The books which are
acquired during the last 6 months are categorized as new arrivals.
(ii) List all those books that cannot be issued and purchased 20 years
back (or) ago.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Create the following tables:-
5.
Student(roll_no,name date_of_birth,course_id)
Cource(cource_id,name,fee,duration).
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those students who are greater than 18 years of age and have
opted for MCA cource.
(ii) List all those cources whose fee is greater than that of MCA cource.

Create the following tables:-


6.
Item(item_code,item_name,qty_in_stock,reorder_level)
Supplier(supplier_code,supplier_name,address)
Can_supply(supplier_code,item_code)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those suppliers who can supply the given item.
(ii) List all those items which cannot be supplied by given company.

Create the following tables:-


7. Branch(branch_id,branch_name,customer_city,customer_id)
Customer(customer_id,customer_name,customer-city,branch_id).
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i)List all those customers who live in the same city as the branch in
which they have account.
(ii) List all those customers who have an account in a given branch city.

Create the following tables:-


8. BOOK(book_number,title,publisher,year,data_of_purchase,status)
MEMBER(member_id,member_name,number_of_books_issued,max_limit
).
BOOK_ISSUE(book_number,member_id,data_of_issue)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those books which are due from the students to be returned. A

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


book is considered to be due ,if it has been issued 15 days back and yet
not returned.
(ii) List all those members who cannot be issued any more books.

Create the following tables:-


9.
BOOK(book_number,title,publisher,year,data_of_purchase,status)
MEMBER(member_id,member_name,number_of_books_issued,max_limit
,status)
BOOK_ISSUE(book_number,member_id,data_of_issue,due_date)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Write a PL/SQL to list all those students who are defaulters. A
student is consider to be a defaulter if he has not returned a book even
after due_date.
(C) Write a trigger to set the status of the status of students to “black
listed” if they have taken book but not returned even after one(1) year.

Create the following tables:-


10. Student(roll_no,s_name,category,district,state)
Student_rank(roll_no,marks,rank)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List names of the students who are having the same rank but they
should reside in different districts.
(ii) List details of students they belongs to same category with same rank.

Create the following tables:-


11. Student(roll_no,name date_of_birth,course_id)
Cource(cource_id,name,fee,duration).
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those students who are between18-to-19 years of age and have
opted for MCA course.
(ii) List all those courses in which number of students are less than 10.

Create the following tables:-


12. Student(roll_no,name date_of_birth,course_id).
Cource(cource_id,name,fee,duration,status).

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Write PL/SQL procedure to do the following:-
Set the status of course to “not offered” in which the number of
candidates is less than 5.

13. Create the following tables:-


Item(item_code,item_name,qty_in_stock,reorder_level)
Supplier(supplier_code,supplier_name,address)
Can_supply(supplier_code,item_code)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Write PL/SQL procedure to do the following:-
Generate a report to list the items whose qty-in-stock is less than or
equal to their reorder-levels.

Create the following tables:-


14.
Item(item_code,item_name,qty_in_stock,reorder_level)
Supplier(supplier_code,supplier_name,address,status)
Can_supply(supplier_code,item_code)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Write PL/SQL procedure to do the following:-
Set the status of the supplier to “important”,if the supplier can supply
more then than five(5) items.

Create the following tables:-


15.
Student(roll_no,s_name,subject_opted)
Subject_rank(subject_code,subject_name,faculty_code,specialization)
Faculty(faculty_code,faculty_name,specialization)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Write PL/SQL procedure to do the following:-
Set the status of the student to “not offered”,if the subject is not opted by
atleast 5 students.

Create the following tables:-


16. Student(roll_no,s_name,subject_opted)
Subject_rank(subject_code,subject_name,faculty_code,specialization)
Faculty(faculty_code,faculty_name,specialization)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Write PL/SQL procedure to do the following:-
Set the status of the student to “not offered”,if the subject is not offered
by any of the faculty members.

Create the following tables:-


17. Student(roll_no,s_name,subject_opted)
Subject_rank(subject_code,subject_name,faculty_code)
Faculty(faculty_code,faculty_name,specialization)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) Find the number of students who have enrolled for the subject
“DBMS”.
(ii) Find all those subjects which are not offered by any faculty members.

Create the ABOVE tables of program no.18 to do the following :-


18. (A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) Find the number of students who have enrolled for the subject “OS”.
(ii) Find all those subjects who opted for more than 5 subjects.

Create the ABOVE tables of program no.18 to do the following :-


19. (A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) Find the number of students who have “not” enrolled for the subject
“DBMS”.
(ii) Find all those subjects which are offered by MORE than one(1)
faculty members.

Create the following tables:-


20.
Student(roll_no,marks,category,state)
Student-rank(roll_no,marks,rank)
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those students who have come from “tamilnadu” state and

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


secured a rank above 100.
(ii) L ist all those students who come from “andhra pradesh” state and
belong to given category who have secured a rank above 100.

Introduction to DBMS

A database management system (DBMS) consists of an interrelated


data and a set of programs to access that data. The collection of data is
usually referred to as database. The primary goal of a database is to
provide an environment that is both convenient and efficient to use in
retrieving and storing database information.
Database systems are designed to manage large bodies of
information. The management of data involves both the definition of
structures for the storage of information and provision of mechanisms for
the manipulation of information. In addition, the database system must
provide for the safety of the information stored, despite system crashes or
attempts at unauthorized access. If data is stored among several users, the
system must avoid possible anomalous results.

Database systems overcomes the problems faced in file-


oriented system. The database system are controlled by the Database
Administrator (DBA)
(OR)
OR
What is database?
A database is a logically coherent collection of data with some inherent meaning,
representing some aspect of real world and which is designed, built and populated
with data for a specific purpose.
(OR)
OR
It is a collection of programs that enables user to create and maintain a database. In
other words it is general-purpose software that provides the users with the processes
of defining, constructing and manipulating the database for various applications.

Advantages of DBMS:

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

 Reduces Data redundancy (duplicity) and inconsistency of data.

 Provides data sharing facilities.

 Provides Data Integrity and Security.

 Provides Data Independence.

 Resolves concurrent access anomalies.

DATA ABSTRACTION:

A database management system provides users with an abstract view


of data, i.e. the system hides certain details of how the data is stored and
maintained. This concern has lead to the design of complex data structures
for the representation of data in the database. Its complexity is hidden from
the users through several levels of abstraction in order to simplify the
interaction between the user and the system.

Physical Level:

The lowest level of abstraction describes the data is actually stored


in the database.

Conceptual Level:

The next-higher level of abstraction describes what data are


actually stored in the database and the relationship that exists between
them. This level is used by DBA, who must decide what information is to be
kept in the database.

View Level:

The highest level of abstraction describes only a part of the entire


database.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


DATA MODELS:

A data model can be defined as a collection of tools for


describing data and the relationship between them.Data models can be
classified into the following groups.

 Object oriented logical models.


 Record based logical models.
 Physical data models.

Object oriented logical models:

They are used in describing data at the conceptual and view levels.
Some of the widely known models are

 Entity Relationship model(ER model): is based on real world


perception which consists of collection of basic objects
called ‘Entities’ and ‘relationships’ among these objects.
 Object oriented model: is based on collection of objects.
An object contains instance variables within the object. An
object also contains bodies of code that operate on the
object, called methods.

Record based logical models:


They are used in describing data at the conceptual and view levels. As
the database is structured in fixed-format records of several types, they are
called as record based logical models.
Some of the widely known models are:

 Relational model: represents data and relationships among data


by a collection of tables, each of which has a number of columns with
unique names.
 Network model: represents data by collection of records and
relationships among data are represented by links which are viewed
as pointers.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


 Hierarchical model: represents data by collection of records, which
are organized as trees rather than arbitrary graphs and relationships
among data are represented by links which are viewed as pointers.
 Physical models: They are used in describing data at the lowest
level.

DATABASE FACILITIES:

Two main types of facilities are provided by a DBMS:

 Data definition facility or Data definition language (DDL).

 Data manipulation or Data manipulation language (DML).

Data definition language (DDL):

A database scheme is specified by a set of definitions which are


expressed by a special language called Data definition language
(DDL).The result of compilation of DDL statements is a set of tables
which are stored in a special file called Data Dictionary.
The storage structures and access methods used by the
database system are specified by a set of definitions in a special type of
DDL called Data storage and definition language. The result of
compilation of these definitions is a set of instructions to specify the
implementation details of the database schemes which are usually
hidden from others.

Data manipulation language (DML):

A Data manipulation language (DML) is a language that


enables users to access or manipulate data efficiently.
Data manipulation means
1. Retrieval of information stored in the database.
2. Insertion of new information into the database.
3. Deletion of information from the database.
4. Modification of data stored in the database.
There two types of DMLS:

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


1. Procedural DMLs requires a user to specify what data is
need and how it get it.
2. Non Procedural DMLs requires a user to specify what
data is needed without specifying how to get it.

Query is a statement requesting the retrieval of information.


A portion of a DML that involves retrieval is called query
language.

STRUCTURE OF A DBMS:

The major components of this system are

Data definition language compiler:

The DDL compiler converts data definition statements


into a set of tables. These tables contain metadata concerning the
database.

Data Manager:

The data manager is the central software component of the


DBMS.Its function is to convert operation queries coming from query
processor or indirectly or an application program from the user’s logical
view to physical file system. The data manager is responsible for
interfacing the file system.

File Manager:
It is responsible for the structure of files and managing the file space and
also for locating the block containing required record, requesting this block
from the disk manager, and transmitting the required record to the data
manager.

Disk manager:

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


The disk manager transfers the block containing the data requested by the
file manager without the concern of physical characteristics of the
underlying storage media.

Query Processor:
The query processor is used to interpret the online user’s query and covert
it into an efficient series of operations in a form capable of being sent to the
data manager for execution. It uses data dictionary to find the structure of
the relevant portion of the database and uses this information in modifying
the query.

Data Files:
Data files contain data portion of the database.

Data Dictionary:
A data dictionary is a file that contains metadata. i.e. data about data. This
file is consulted before actual data is read or deleted in the database
system.
Different types of Keys:
Attribute: An object or an entity is characterized by its properties or
attributes, they can also be referred as field.

1. Primary key: An attribute to identify a record uniquely without


allowing any null values to be entered into it is called Primary key.

Ex: empno attribute in the employee table and deptno attribute in dept
table.

2. Foreign key: An attribute which is a primary key in its own table and
is used as a reference in another table is called foreign key.
3. Super Key: A primary key with a combination of other attributes for
unique identification is called super key. In other words primary key is
a minimum super key.
Ex: Empno along with ename is super key.

4. Candidate Key: The super key for which no proper subset is a super
key such a minimal super key is a candidate key.
Ex: Ename is a candidate key

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


.
STRUCTURED QUERY LANGUAGE(SQL)

What is SQL?
ANS:-
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to
perform tasks such as update data on a database, or retrieve data from a database. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL
Server, Access, Ingres, etc. Although most database systems use SQL, most of them also have
their own additional proprietary extensions that are usually only used on their system. However,
the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop"
can be used to accomplish almost everything that one needs to do with a database. This tutorial
will provide you with the instruction on the basics of each of these commands as well as allow
you to put them to practice using the SQL Interpreter.
(OR)

SQL is the official standard language used to access data held in the
databases.
SQL organizes data as tables , indexes , views etc. SQL is the
tool for organizing , managing and retrieving data stored in the
database.
SQL provides various features like portability , client-
server architecture ,dynamic data definition , multiple views of data etc.

(OR)

SQL , commonly expanded as Structured Query Language, is a computer language


designed for the retrieval and management of data in relational database management
systems, database schema creation and modification, and database object access control
management.[1][2]

SQL (Structured Query Language) is a standard interactive and programming language for
getting information from and updating a database. Although SQL is both an ANSI and an ISO
standard, many database products support SQL with proprietary extensions to the standard
language. Queries take the form of a command language that lets you select, insert, update,
find out the location of data, and so forth. There is also a programming interface.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Procedural extensions
SQL is designed for a specific purpose: to query data contained in a relational database. SQL
is a set-based, declarative query language, not an imperative language such as C or BASIC.
However, there are extensions to Standard SQL which add procedural programming
language functionality, such as control-of-flow construct.

(OR)
(Structured Query Language) Pronounced "S-Q-L" or "see-quill," a language used to
interrogate and process data in a relational database. Originally developed by IBM for its
mainframes, all database systems designed for client/server environments support SQL. SQL
commands can be used to interactively work with a database or can be embedded within a
programming language to interface to a database. Programming extensions to SQL have turned
it into a full-blown database programming language, and all major database management
systems (DBMSs) support the language.

ANSI standardized SQL, but most database management systems (DBMSs) have some
proprietary enhancement, which if used, makes SQL non standard. Moving an application from
one SQL database to another may require tailoring to convert some command.

SQL Statements:

SQL statements are divided into


1. Data Definition language(DDL)
2. Data Manipulation Language(DML)
3. Data Control Language (DCL)
4. Transaction Processing Language (TPL)
5. Data Retrieval Language (DRL)
Data Definition Language (DDL): These statements define the
structure of the database. DDL consists of create, alter and drop
statements.

Data Manipulation Language (DML): These statements are basically


required to manipulate the records of the tabled consists of insert, delete,
and update statements.

Data Control Language (DCL): These statements are basically required


to control the tables among several users by giving access or by taking
back the access to the tables. DCL consists of grant and revoke
statements.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Transaction control language (TCL): These statements are basically
related to various transactions like insert, delete, and update.

Data retrieval language (DRL): These statements are basically required


to retrieve the records for the table. DRL consists of select statements.

What are the difference between DDL, DML


and DCL commands?
DDL
Data Definition Language (DDL) statements are used to define the database structure or schema. Some
examples:

o CREATE - to create objects in the database


o ALTER - alters the structure of the database
o DROP - delete objects from the database
o TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed
o COMMENT - add comments to the data dictionary
o RENAME - rename an object

DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some
examples:

o SELECT - retrieve data from the a database


o INSERT - insert data into a table
o UPDATE - updates existing data within a table
o DELETE - deletes all records from a table, the space for the records remain
o MERGE - UPSERT operation (insert or update)
o CALL - call a PL/SQL or Java subprogram
o EXPLAIN PLAN - explain access path to data
o LOCK TABLE - control concurrency

DCL
Data Control Language (DCL) statements. Some examples:

o GRANT - gives user's access privileges to database


o REVOKE - withdraw access privileges given with the GRANT command

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


TCL
Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

o COMMIT - save work done


o SAVEPOINT - identify a point in a transaction to which you can later roll back
o ROLLBACK - restore database to original since the last COMMIT
o SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

‹ SQL up Difference between TRUNCATE, DELETE and DROP commands › »

DML statements can be rollbacked where DDL are autocommit.

DML commands can't be


DML commands can't be rollback when a DDL command is executed immediately after
a DML. DDL after DML means "auto commit". The changes will return on disk not on
the buffer. If the changes return on the buffer it is possible to rollback not from the
disk.

Let me tell you the difference between DDL,DML,TCL and DCL:

DDL COMMANDS:
CREATE,ALTER,DROP AND TRUNCATE ARE CALLED DDL COMMANDS. They are called
Data Definition since they are used for defining the data. That is the structure of the
data is known through these DDL commands.

DML COMMANDS:
DML commands are used for data manipulation. Some of the DML commands
insert,select,update,delete etc. Even though select is not exactly a DML language
command oracle still recommends you to consider SELECT as an DML command.

TCL:
For revoking the transactions and to make the data commit to the database we use
TCL. Some of the TCL commands are:
1. ROLLBACK
2. COMMIT

ROLLBACK is used for revoking the transactions until last commit.


COMMIT is used for commiting the transactions to the database.
Once we commit we cannot rollback. Once we rollback we cannot commit.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Commit and Rollback are generally used to commit or revoke the transactions that are
with regard to DML commands.

DCL:
Data Control Language is used for the control of data. That is a user can access any
data based on the priveleges given to him. This is done through DATA CONTROL
LANGUAGE. Some of the DCL Commands are:
1. GRANT
2. REVOKE.

SQL statements are often divided into three categories:

DML (Data Manipulation Language). These SQL statements are used to retrieve and
manipulate data. This category encompasses the most fundamental commands
including DELETE, INSERT, SELECT, and UPDATE. DML SQL statements have only minor
differences between SQL variations. DML SQL commands include the following:

o DELETE to remove rows.


o INSERT to add a row.
o SELECT to retrieve row.
o UPDATE to change data in specified columns.

DDL (Data Definition Language). These SQL statements define the structure of a
database, including rows, columns, tables, indexes, and database specifics such as
file locations. DDL SQL statements are more part of the DBMS and have large
differences between the SQL variations. DML SQL commands include the following:

o CREATE to make a new database, table, index, or stored query.


o DROP to destroy an existing database, table, index, or view.
o DBCC (Database Console Commands) statements check the physical and logical
consistency of a database.

DCL (Data Control Language). These SQL statements control the security and
permissions of the objects or parts of the database(s). DCL SQL statements are also
more part of the DBMS and have large differences between the SQL variations. DML
SQL commands include the following:

o GRANT to allow specified users to perform specified tasks.


o DENY to disallow specified users from performing specified tasks.
o REVOKE to cancel previously granted or denied permissions.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

ALL SQL COMMAND DETAILS

The commands are listed in the following order:  SQL*Plus commands,

PL/SQL commands, and then SQL commands.

SQL*PLUS COMMANDS:=

     @                        @@                     /

     ACCEPT                   APPEND                 BREAK

     BTITLE                   CHANGE                 CLEAR

     COLUMN                   COMPUTE                CONNECT

    COPY                     DEFINE                 DEL

    DESCRIBE                 DISCONNECT             EDIT

    EXECUTE                  EXIT                   GET

    HELP                     HOST                   INPUT

    LIST                     PAUSE                  PRINT

    PROMPT                   REMARK                 RUN

    RUNFORM                  SAVE                   SET

    SHOW                     SPOOL                  SQLPLUS

    START                    TIMING                 TTITLE

    UNDEFINE                 VARIABLE               WHENEVER OSERROR

    WHENEVER SQLERROR

PL/SQL COMMANDS (Statements):=

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


    CLOSE Statement          EXIT Statement         FETCH Statement

    GOTO Statement           IF Statement           LOOP Statement

    NULL Statement           OPEN Statement         RAISE Statement

    RETURN Statement

SQL COMMANDS:=

The SQL commands are divided into these categories:

    * Data Definition Language commands

    * Data Manipulation Language commands

    * Transaction Control commands

    * Session Control commands

    * System Control commands

SQL Data Definition Language commands include the following:

    ALTER CLUSTER            ALTER SEQUENCE         COMMENT

    ALTER DATABASE           ALTER SNAPSHOT         CREATE CLUSTER

    ALTER FUNCTION           ALTER SNAPSHOT LOG     CREATE CONTROLFILE

    ALTER INDEX              ALTER TABLE            CREATE DATABASE

    ALTER PACKAGE            ALTER TABLESPACE       CREATE DATABASE LINK

    ALTER PROCEDURE          ALTER TRIGGER          CREATE FUNCTION

    ALTER PROFILE            ALTER USER             CREATE INDEX

    ALTER RESOURCE COST      ALTER VIEW             CREATE PACKAGE

    ALTER ROLE               ANALYZE                CREATE PACKAGE BODY

    ALTER ROLLBACK SEGMENT   AUDIT                  CREATE PROCEDURE

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


    CREATE PROFILE           DROP ROLE

    CREATE ROLE              DROP ROLLBACK SEGMENT

    CREATE ROLLBACK SEGMENT  DROP SEQUENCE

    CREATE SCHEMA            DROP SNAPSHOT

    CREATE SEQUENCE          DROP SNAPSHOT LOG

    CREATE SNAPSHOT          DROP SYNONYM

    CREATE SNAPSHOT LOG      DROP TABLE

    CREATE SYNONYM           DROP TABLESPACE

    CREATE TABLE             DROP TRIGGER

    CREATE TABLESPACE        DROP USER

    CREATE TRIGGER           DROP VIEW

    CREATE USER              GRANT

    CREATE VIEW              NOAUDIT

    DROP CLUSTER             RENAME

    DROP DATABASE LINK       REVOKE

    DROP FUNCTION            TRUNCATE

    DROP INDEX               UPDATE

    DROP PROCEDURE

    DROP PROFILE

SQL Data Manipulation Language commands include the following:

    DELETE

    EXPLAIN PLAN

    INSERT

    LOCK TABLE

    SELECT

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

SQL Transaction Control commands include the following:

    COMMIT

    ROLLBACK

    SAVEPOINT

    SET TRANSACTION

SQL Session Control commands include the following:

    ALTER SESSION

    SET ROLE

SQL System Control command (only one command):

    ALTER SYSTEM

Data Types in SQL:

1.Varchar2(size):
It is a variable length string with a max length of ‘size’ bytes.
2. Char (size):
It specifies a fixed length character string. Max size is 255
3. Number (n):
It specifies integer type of data with max of n digits.
4.Number(p,s):
It specifies floating number with p as total no of digits and specifies the
number of digits to the right of decimal points.

5. Date: It specifies the date in DD-MM-YY format.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Data definition language (DDL):

Create statement: It is used to create and define a table.

Syntax:

Create table <table name>

(<field-name1> <data type> [column constraints],


<field-name2> <data type> [column constraints],
.
.
.
<field-name n> <data type> [column constraints]) ;

Column constraints :

1. Primary Key: It will not allow null and duplicate values corresponding
to that column.
2. Not Null : It will allow null values corresponding to that column
3. Unique: It will not allow duplicate values corresponding to that
column.
4. Check: It will impose the constraints based on the condition being
mentioned on the column.
5. Reference( foreign key): It will impose the constraints based on the
condition being mentioned on the column
6. Reference (foreign key): It will refer to other column values that are
acting as primary key in other table.
7. On delete cascade: It will delete the values in the column in one
table, corresponding values in other table will be deleted
automatically, and it will work only references only.

Example 1:

Create a table employee with employee no as primary key, name


field not be left empty, salary greater than 2000,job field not to be left
empty,deptno is foreign key taken from dept table.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Example 2:

Create dept table with deptno as primary key and dept


name as not null.
SQL>Create table Dept
(Deptno number(3) primary key,
Dname varchar2(10) not null);

Example 3: Create a customer table.


SQL>Create table Customer
(Cust_id number(5) primary key,
First_name varcahr2(20) not null,
Last_name varchar2(20) not null,
Address varchar2(40),
City varchar2(20),
State varchar2(20),
Phone_no number(9) unique);

Table Level Constraints:


Imposing constraints after declaring all the columns of the table, then
we call it as table level constraints.

Example 4: Create project table.

SQL>Create table Project

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


(Emp_id number(5),
Proj_id number(5),
Payment number(8),
Primary key(Emp_id,Proj_id);

Create with Select:

To create a table from taking the records from existing table. When
creating a table based on existing table then it is going to transfer only not
null constraint, other constraints will not be transferred.

Example 1:
SQL>Create table Emp
As select Empno, Ename, Salary from Employee;

Create with select using where clause:

Example 2: Create a table empno containing the details in deptno 10 only

SQL>Create table Empd


As select * from Employee
Where deptno=10;
Alter Statement: It is used to alter the definition of a table in the database

Syntax:

Alter table<table_name>
Add column_name data_type <column_constraint>
[Modify column_name data_type <column_constraint>];

Add: is used when ever you want to add a new column to the table.

Example 1: Adding Phno as a new field into Employee table

SQL>Alter table Employee


Add(Phno number(7));

Example 2: Adding empno as primary key to Emp table

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

SQL>Alter table Emp


Add(Primary key(empno));
Modify: is used to change the size of the column of the same data
type.Modify will not decrease the column size.Whenever it comes to
increase in the size of column it is going to allow only when the field is
empty.

Example 1:

Modify the salary field by increasing its size.


SQL>Alter table Emp
Modify(sal number(9,2));

Droping the Constraints:


Example1:
Dropping Primary key constraint we must see that no
references are there from other tables.

SQL>Alter table Emp


Drop Primary key;
Drop command: is used to drop the table.

Syntax:
Drop table<table_name>;

Example 1: Dropping emp table.

SQL>Drop table emp;


Describe command: is used to display the structure of the table.Desc can
also be used

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Data Manipulation Language (DML):

Insert command: is used to add rows(or records) to the table. The number

and sequence should match that of columns in the table.If the number of
data values is less, then specify the column names into which data is being
entered. To insert null values, NULL can be used.
Syntax:
Insert into<table_name>values(datavalue_1,
………..,datavalue_n);

Insert into<table_name>(column_1,column_3)
Values(datavalue_1,datavalue_3);

Example 1: Insert 100th record into employee table.

SQL>insert into employee


Values(100,’James’,6000,’17-Mar-03’);
Example 2: Inserting 101th record into employee table with salary and date
Of joining as null values.

SQL>Insert into employee


Values(101,’James’,null,null);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Example 3: Inserting 1001th record into employee table with only empno
and name.
SQL>Insert into employee(empno,ename)
Values(1001,’John’);
Insert with select: is used to transfer the data from one table to another
table.
Syntax:
Insert into<table_name>
Select <field_name_1>,……<field_name_n> from <table_name>
Where<condition>;
Example 1:

SQL>Insert into emp


Select empno,ename,sal from employee
Where deptno=10;

Delete Command: is used to delete the records from the specified table.
Syntax:
Delete <table_name>
Where<condition>;
Example 1: Deleting the employee holding empno1001

SQL> Delete employee where empno = 1001;

Example 2 : Delete all the records of the employee table

SQL> Delete employee;

Example 3: Delete the employees who are working as clerks.

SQL> Delete employee where job =’clerk’

Update command: is used to modify the records of the table

Syntax:
Update <table_name>
Set <field_name> = <value> ,
.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


.
.
Where <condition> ;

Example1: Increase all the employees salary by Rs. 500


SQL> update employee set sal=sal+500;

Example2: Give an increment of 20% salary and commission by 5%of


salary
SQL> update employee set sal = sal* 1.2, comm = (sal* 0.05) +comm;

Example3: Promote the manager as director of the company

SQL> update employee set job =’director ‘ where job= ‘manager’;

Example4: Give an increment of 10% salary whose salary is less than Rs.
1000
SQL> update employee set sal = sal*1.1 where sal <1000;

Transaction control language(TCL);

The DML transactions will not be saved implicitly based on the following
reasons.

1. Improper shut down


2. System crash
3. When working under SQL environment DML transactions will not
saved.
To handle DML transactions explicitly we require a set of commands which
are commit, roll back and save point.

Commit command: is used to save all the transactions up to the last


command explicitly.

SQL> insert into employee( empno, ename) values (200, ‘smith’);


SQL> commit ;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Roll back command: is used to undo the transactions up to the last
commit.

SQL> Rollback;

Savepoint: is used to minimize roll back only to certain transactions

Example:

SQL> insert ………


SQL> savepoint ins;
SQL> update …….
SQL> savepoint upd
SQL> delete ….
SQL> savepoint del;
SQL> Rollback;
SQL> commit;
SQL> Rollback to del;(Once you commit and then give rollback, will
remove all save points)

Autocommit command: is used to make all DML transactions to save


implicitly after the execution of the command.

SQL> set autocommit on;


SQL> set autocommit off;

To see the status of autocommit we use show command.


SQL> show autocommit;

Data Retrieval language(DRL);

Select command: is used to retrieve the records from the table.

Syntax:
Select < field_name_1>, …….. , <field_name_n> from <table_name>

where <condition> ;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Example 1: To display the deptno,dname,loc.

Example 2: To display all the employee details,who are working as


manager.
SQL>Select * from emp where job-‘manager’;

Logical Operators:

 And
 Or
 Not
Example 1: To display the employee information who are working in deptno
10 and salary greater than 2000.
SQL>select * from emp
Where deptno=10 and sal>2000;
Example 2: To display the employee information who are working as
manager corresponding to deptno 20.
SQL>select * from emp
Where job=’manager’ and depno=20;
Example 3: To display the employee information who are working in
deptno 10,20.
SQL>select * from emp
Where deptno=10 or dept=20;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Example 4: To display the employee information who are working as
managers corresponding to deptno 10 as well as the employees who are
receiving salary more than 2000 corresponding to deptno 20.

SQL>select * from emp


Where job=’manager’ and deptno=10;

Special Operators:

 Is null
 In
 Between
 like

 is null: is used to check the null values corresponding


to the column.

Example 1: To display the employee information who are not receiving any
commission.

SQL>select * from emp


Where comm Is null;
 Between: Whenever we want to frame the condition in the range of
values then we use the between operator.

Example1: To display the employee information whose salary is greater


than 1000 and less than 2000.

SQL>select * from emp


Where sal between 1000 and 2000;
Example 2: To display the employee information for those who are working
for deptno 10 with their first alphabet of the name is coming in the range of
‘e’ to ‘j’.

SQL>select * from emp


Where deptno=10 and(ename between ‘E’ and ‘J’);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


 In: When you have multiple conditions among which any one has to
be
selected we use in operator.
Example 1: To display the employee details who are working as
managers ,clerks ,analyst.
SQL>select * from emp
Where job in(‘manager’,’clerk’,’analyst’);
Example 2:To display the employee who are working in the deptno
10,20,30.
SQL>select * from emp
Where deptno in (10,20,30);

 Like: is used when you want to frame a condition based on a


particular pattern, for which we need wild card characters, which are
‘%’ and ‘_’.
‘%’ is used to replace any no.of characters in the pattern.
‘_’ is used to replace only single characters in the pattern.

Example 1: To display the employee details whose names are ending with
‘s’.
SQL>select * from emp
Where ename like’%s’;

Example 2: To diplay the employee names have onlay 5 characters.


SQL>select * from emp
Where ename like’_____’;

Example 3: To display the employee details whose name has ‘a’ as second
character and ‘r’ as last character.
SQL>select * from emp
Where ename like’_a%r’;

Special operators with not:

Example1: To display the employee information who are receiving any


commission.
SQL>select * from emp

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Where comm. Is not null;

Example 2:To display employee information for whose who are working as
managers and receiving salary other than the range 2000 to 3000.
SQL>select * from emp
Where job=’manager’ and sal not between 2000 and 3000;

Example 3:To display the employee details who are working in dept other
than 20,30.
SQL>select * from emp
Where deptno not in (20,30);

Example 4:To display the employee details who are working in deptno
10,20 for their names not ending with ‘s’.
SQL>select * from emp
Where deptno in(10,20) and ename not like ‘%s’;

In built functions: Are classified into five types

o Number Functions
o Character Functions

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


o Date functions
o Group functions

Group Functions:

1. Sum(expr) 2. avg(expr) 3. count(expr)


4.count(*) 5. Max(expr) 6. min(expr)

1. Sum(expr): Is used to find total sum of the attribute or field


mentioned.
Example 1: Find the sum of total salary being paid to all the employees
of the organizations.
SQL>select sum(sal) from emp;
Example 2: Find the sum of salary and commission paid to the
employees of deptno 10.
SQL>select sum(sal+comm.) from emp
Where deptno=10;

2. avg(expr): Is used to find the average of the attribute being


mentioned.
Example: Find the average amount salary being paid to each employee.
SQL>select avg(sal) from emp;

3.Count(*): Is used to count the no.of records in the table,where the


empty record is also counted.
Example 1: find the no.of employees working in the organization.

SQL>select count(*) from emp;


Example 2:find the no.of employees working as managers and clerks in
the organization.
SQL>select count(*) from emp
Where job in(‘manager’,’clerk’);

4.count(expr): Is used to count the no.of records will the expr is


satisfied.If a record has a null value it will not count that
record.
Example 1: Find the no.of employees who are receiving the commission.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


SQL>select count(comm.) from emp;
Example 2: Find the no.of employees who are receiving the commission
corresponding to deptno.10,20.
SQL>select count(comm) from emp
Where deptno=10 or deptno=20;
5.max(expr): Is used to find the maximum value for the mentioned
numerical attribute.
Example 1: Find the employees who is paid the highest salary.
SQL>select max(sal) from emp;

6.min(expr): Is used to find the minimum value for the mentioned numerical
attribute.
Example: find the employees who is paid the least salary.
SQL>select min(sal) from emp;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Numerical Functions:

 abs(n)
 sqrt(n)
 power(n)
 mod(n)

1.abs(n): Is used to find the absolute value of n.dual is dummy table for
Temporary manipulation.

SQL>select abs(-5) from dual;

2.sqrt(n): Is used to find the square root of n.

SQL>select sqrt(36) from dual;

3.power(n): Is used to find the value of m to the power of n.

SQL>select power(3,2) from dual;


4.mod(m,n): Is used to find the remainder after dividing m by n.
SQL>select mod(5,2) from dual;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

CHARACTER FUNCTIONS:

 Length(str)
 Concate(str1,str2)
 Substr(str,pos,n)
 Ascii(char)
 Chr(n)

1. length(str): Returns the length of the string mentioned.

SQL>select length(‘student’) from dual;

2. concat(str1,str2): Joints string1 and string2 ot form a new string.

SQL>select concat(‘aaaa’,’bbbb’) from dual;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

3. substr(str,pos,n): Returns the substring from the string from position


pos cut n characters.

SQL>select substr(‘student’,3,4) from dual;

4. ascii(char): Returns the ascii value of the mentioned character.

SQL>select ascii(‘a’) from dual;

5.chr(n): Returns the character for the ascii value n mentioned.

SQL>select chr(68) from dual;

6.lower(str): Converts the given string into lower case.

SQL>select lower(‘AAAA’) from dual;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

8. upper(str): Converts the given string into upper case.

SQL>select upper(‘dddd’) from dual;

DATE FUNCTIONS:

1. add months(date,n): To add or remove given n months to the given


data.Sysdate gives the system date.

SQL>select sysdate from dual;


SQL>select add_month(sysdate,3) from dual;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

2. months between(date1,date2): Returns the no.of months between


the two dates mentioned.Date1 is maximum value and date2 is
minimum value.The output of this function is either float or integer
value.

SQL>select months_between(’29-oct-03’,’29-apr-03’)
from dual;

3. Last day(date): Returns the last day in the month specified by the date
mentioned.

SQL>select last_day(sysdate) from dual;

Group by clause: Is used to group a set of repeated values corresponding


to a particular column for which we want to apply group function.

Example 1: To display the deptno. And total salary in each dept.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


SQL>select deptno,sum(sal) from emp
Group by deptno;
Example 2: To display the dept’s highest,lowest salary and no.of
employees in each dept.

SQL>select deptno,max(sal),min(sal),count(*) from


emp group by deptno;

Example 3: To display the no.of employees receiving commission


corresponding to deptno 10,20 with their deptno.

SQL>select deptno,count(comm.) from


Emp where deptno=10 or deptno=20
Group by deptno;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Having Clause: Is used when we want to frame the condition of salary is
greater than cannot be used with where clause.

Example 1: To display the deptno.s for which total amount of salary is


greater than 10,000.
SQL>select deptno,sum(sal) from emp
Group by deptno
Having sum(sal)>10000;

Example 2: To display the deptno.s along with their total salary for
which total salary is greater than 10,000 corresponding to deptno 10,20.
SQL>select deptno,sum(sal) from emp
Where deptno in (10,20)
Group by deptno
Having sum(sal)>10000;

Example 3 : To display the job’s along with the no.of employees


working ,provided the highest salary corresponding to the job is greater
than 3000 as well as the no.of employees working is more than 3.
SQL>select job,count(*) from emp
Where deptno in (10,20,30)
Group by job
Having max(sal)>2000 and count(*)>2;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Order by clause: Is used when we want to display the data in a sorted


order.
1. Ascending order |asc| (default ordering)
2. Descending |desc|

Example 1: To display the employee information in the ascending order


of the empno.
SQL> select * from emp
Oreder by empno;

Example 2: To display the employee information in the descending


order of the salary.
SQL>select * from emp
Order by sal desc;

Example 3: To display the employee information in the ascending order


of the deptno,descending order of salary.
SQL>select * from emp
Order by deptno,sal desc;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Example 4: To display the depts along with their total payment


corresponding to deptno 10,20,30 for which n0.of employees are
working is more than 2 and display based on the descending order of
total salary.

SQL>select deptno,sum(sal) from emp


Where deptno in (10,20,30)
Group by deptno
Having count(*)>2
Order by sum(sal) desc;

SET OPERATORS:

 Union
 Intersection
 Minus

1. union: Is used to take distinct rows from more than one select
statement.By using union all the duplication is not removed.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Example 1: To display in deptno the job’s. 10 or 20.
SQL>select job from emp
Where deptno=10
Union
Select job from emp
Where deptno=20;

Example 2: To display the job’s from emp.


SQL>select job from emp
Where deptno=10
Union all
Select job from emp
Where deptno=20;

2.intersect: Is used to take common rows from more than one select
statement.
Example 1: To dispalyb the job’s in deptno. 10 and 20.
SQL>select job from emp
Where deptno=10
Intersect
Select job from emp
Where deptno=20;

Example 2:To disaply the job’s in deptno. 10 and (20 or 30).


SQL>select job from emp
Where deptno=10
Intersect
(select job from emp
Where deptno=20
Union
Select job from emp
Where deptno=30);

2. minus: Is used to select the rows from more than first select
statement which are not in the second statement.

Example 1: To display the job’s in deptno.10 and not in 20.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


SQL>select job from emp
Where deptno=10
Minus
Select job from emp
Where deptno=20;
Example 2: To list the jobs which are unique to dept 10 as compare to 20
and 30.
SQL>(select job from emp
Where deptno=20
Union
Select job from emp
Where deptno=30)
Minus
(select job from emp
Where deptno=10);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

SUB QUERIES(or)NESTED QUERIES: when we are using more than one


select statement to perform particular operation then we will be calling it as
a subquery.In subquery the inner statement will be executed first and only
noce as compared to the outer statement.

Syntax: select -----------


From<table name>
Where(select ------);

Example 1: To display all the employee’s information whose salary is


greater than Smith’s salary.

SQL>select * from emp


Where sal>(select sal from emp
Where ename=’SMITH’);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Example 2: To display all the employee’s information who is receiving the


highest salary.
SQL>select * from employee
Where sal=(select max(sal) from emp);

Example 3: To display all the employee’s information whose job is same


like Smith at the same time salary greater than Allen.

SQL>select * from emp


Where job=(select job from emp where
ename=’SMITH’)
And sal>(select sal from emp
Where ename=’ALLEN’);

Example 4:To display all the employee’s information who is receiving


salary greater than average salary of all the employee’s.

SQL>select * from emp


Where sal>(select avg(sal) from emp);

Example 5:To display the manager no.alng with the no.of employee’s
working under him should be maximum no.of employees compared with
the other members.

SQL>select mgr,count(*) from emp


Group by mgr
Having count(*)=(select max(count(*) from
Emp group by mgr);

Example 6: To display the employee information under which maximum


no.of employee’s working.

SQL>select * from emp


Where empno=(select mgr from emp
Group by mgr)
Having count(*)=(select max(count(*) fom
emp group by mgr);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Example 7: To disaply all the employee’s information who is receiving the


second highest salary.

SQL>select * from emp


Where sal=(select max(sal) from emp where
Sa<(select max(sal) from emp));
When the subquery is returning more than one value to frame the condition
we have to use all or any.

Example 8: To display the employee information whose salary is greater


than all the employees salaries of deptno 20.

SQL>select * from emp


Where sal>all(select sal from emp
Where deptno=20);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Views: Views can be defined as a virtual table because it doesn’t exist by


itself,unless you are having one or more ordinary table on which it will be
based or dependent.The table on which view is based is called as base
table of the view.It is possible to insert,update and delete the data in the
view in the same way as in the table.

Advantages of views:

 Providing the security for the table.


 By giving limited access to your table to other users.
 Complicated queries can be generated by using views a normal
simple table creation.

Creation of view:

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Syntax: create view <view name>


As select ------ from <table name>;

Example 1: To create a view for emp table with empno,name,salary.

SQL>craerte view empview


As select empno,ename,sal from emp;

Example 2: To create a view for emp table for dept 10.

SQL>create view d10view


As select * from emp
Where deptno=10;

Insert into view:

Example 1: Insert a new record into view empview.

SQL>insert into empview


Values(101,’WILLIAM’,2000);

Viewing the contents of d10view:

Example: To display the contents of d10view.

SQL>select * from d10view;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Replace: Replace option is used whenever you want to over write the
existing select statement with new select statement.

Example: To create empview with empno,name,salary and deptno.

SQL>replace view empview


As select empno,ename,sal,deptno from emp;

With check option: When ever you want to restrict the user to insert thr
records which are satisfying the where condition of the view then we use
with check option.

Syntax: create view <view name>


As select-----from <table name>
Where <condition>
With check option;
Example : create a view for employee details of deptno. 20

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

SQL>create view d20view


As select * from emp
Where deptno=20
With check option;
If you try to enter deptno other than 20,it will not be accepted into the view.

Sequences: Whenever you want to create a object which is going to


generate the numbers in a particular order (i.e. interval) then we will be
calling a sequence.

Syntax: create sequence <seq.Name>


Start with <no.>
Increment by <interval>
Maxvalue <n>
Minvalue <n>
Cache
Cycle;
Whenever you want to generate the next number of the sequence then we
will be using nextval and when you want to see the current position of the
sequence we use currval.

Example: SQL>create sequence eno


Start with 5
Increment by 1
Minvalue 5
Maxvalue 15
Cache 5
Cycle;
This is going to create a sequence with name eno starting with
5,incrementing by 1,minimum value is 5,maximum value is 15,cache is 5
and with cycle.

Altering the sequence: whenever you want to change any options relatedt

To existing sequence then we will be using Alter.


Note:start with cannot be changed using Alter.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Syntax: alter sequence <seq.name>
<options to be changed>;
Example: SQL>alter sequence eno
Increment by 2
Minvalue 10
Maxvalue 100;

Drop sequence: Whenever you want to drop a sequence we use drop


statement.
Syntax: drop sequence <seq.name>

Example: SQL>drop sequence eno;

INDEX: Whenever you to retrieve the records faster corresponding to one


condition then we will be using Indexing concept.
Before going to index,identify the fields which will be
using mostly in the where clause then indx on those fields.Apply index
when there are more than 500 records are present in a table.
There are 3 types of indexes Simple index, Unique index
and Concatenated index.
Syntax: SQL>create index <index name> on <table name>(<field
name>);

1. Simple index: Is used when indexing is based on the column of the


table.

Example 1: SQL>create index idept on emp(deptno);


Example 2: SQL>create index iename on emp(ename):

2. Unique index: Is used when indexing is based on implementing


unique constraint along with indexing.

Example : SQL>create unique index iph on emp(phno);

3. concatenated index: Is used when indexing is based on more than


one column as a combination.

Example: SQL>create index ds on emp(deptno,sal);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Delete index: drop statement is used

Example: SQL>drop index idept;

What Is The Difference Between SQL and PL/SQL?


There are so many variants of SQL that it is hard sometimes to figure out what to use. Here is a
short article that briefly explains the difference between SQL and PL/SQL. LET SEE!

What is SQL?

SQL (pronounced “sequal”) stands for Structured Query Language. Withe SQL, you can view
data - called Data Definiton Language or DDL and manipulate data - called Data Manipulation
Languate or DML. All of the above are just a fancy way to say that with SQL, the user can both
view and alter records in the database. To help , here are a couple of queries:

DDL or View

SELECT * FROM employees

View all of the records in the employee table

DML or Manipulate

UPDATE employees SET employeefirstname = ‘John’ WHERE employeeid = 101

Find the record for employee ID 101 and change the first name to John

What is PL/SQL?

The official answer is from the PL/SQL User Guide:


PL/SQL, Oracle’s procedural extension of SQL, is an advanced fourth-generation programming
language (4GL). It offers software-engineering features such as data encapsulation, overloading,
collection types, exceptions, and information hiding. PL/SQL also supports rapid prototyping
and development through tight integration with SQL and the Oracle database.
Huh? That is what I thought at the beginning. But at a high level, all this means is that it can do
all of the things that regular SQL can do, but also, it is procedural and can be used like a

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


programming language (C++, Java, etc.) For instance, you can use loops and If . . . Then
statements in your PL/SQL statements (Programs).

Here is a definition of PL/SQL from Lewis Cunningham (an Oracle database expert):

“If I wanted to create my own, very short, definition of PL/SQL it would be this: PL/SQL is the
Oracle native programming language that provides database-centric application development. It
can natively call static SQL and provides multiple methods of calling dynamic SQL.

DIFFER:

SQL is a data oriented language for selecting and manipulating sets of data. PL/SQL is a
procedural language to create applications. You don’t normally have a “SQL application”. You
normally have an application that uses SQL and a relational database on the back-end. PL/SQL
can be the application language just like Java or PHP can. SQL may be the source of data for
your screens, web pages and reports. PL/SQL might be the language you use to build, format and
display those screens, web pages and reports.

What Is Dynamic SQL?


Most PL/SQL programs do a specific, predictable job. For example, a stored procedure might
accept an employee number and salary increase, then update the sal column in the emp table. In
this case, the full text of the UPDATE statement is known at compile time. Such statements do not
change from execution to execution. So, they are called static SQL statements.

However, some programs must build and process a variety of SQL statements at run time. For
example, a general-purpose report writer must build different SELECT statements for the various
reports it generates. In this case, the full text of the statement is unknown until run time. Such
statements can, and probably will, change from execution to execution. So, they are called
dynamic SQL statements.

Dynamic SQL statements are stored in character strings built by your program at run time. Such
strings must contain the text of a valid SQL statement or PL/SQL block. They can also contain
placeholders for bind arguments. A placeholder is an undeclared identifier, so its name, to which
you must prefix a colon, does not matter. For example, PL/SQL makes no distinction between
the following strings:

'DELETE FROM emp WHERE sal > :my_sal AND comm < :my_comm'
'DELETE FROM emp WHERE sal > :s AND comm < :c'

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


To process most dynamic SQL statements, you use the EXECUTE IMMEDIATE statement. However,
to process a multi-row query (SELECT statement), you must use the OPEN-FOR, FETCH, and CLOSE
statements.

(OR)

Dynamic SQL is an extended form of


embedded SQL that allows more generalpurpose
application. Dynamic SQL is used
when part or all of the SQL statement is
unknown at compile-time
• EXECUTE IMMEDIATE
• PREPARE and EXECUTE
• Placeholders can be used to pass values to
EXECUTE/FETCH statements

The Need for Dynamic SQL


You need dynamic SQL in the following situations:

 You want to execute a SQL data definition statement (such as CREATE), a data control
statement (such as GRANT), or a session control statement (such as ALTER SESSION). In
PL/SQL, such statements cannot be executed statically.
 You want more flexibility. For example, you might want to defer your choice of schema
objects until run time. Or, you might want your program to build different search
conditions for the WHERE clause of a SELECT statement. A more complex program might
choose from various SQL operations, clauses, etc.
 You use package DBMS_SQL to execute SQL statements dynamically, but you want better
performance, something easier to use, or functionality that DBMS_SQL lacks such as
support for objects and collections.

(OR)
OR

Dynamic SQL:
􀂄 Static SQL
• Allowing access to the database using the

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


normal interactive SQL statements, with
minor modifications in some cases.
• The pattern of database access is fixed
and can be ‘hard-coded’ into the program.
􀂄 Dynamic SQL
• There are many situations where the
pattern of database access is not fixed and
is known only at runtime

The basic difference between the two types of


embedded SQL is Static SQL does not allow host
variables to be used in place of table names or
column names
• For example, in static SQL we can not write:
• EXEC SQL BEGIN DECLARE SECTION
char TableName[20];
EXEC SQL END DECLARE SECTION;
EXEC SQL INSERT INTO :TableName
VALUES (“S1”, “Simth”, 24)
• EXEC SQL DECLARE cursor1 CURSOR FOR
SELECT * FROM :TableName

Problems
• “*” indicates that all columns from the table,
TableName, but the number of columns will
vary with the choice of table.
• Data types of the columns will vary between
tables
• But if we do not know the number and data
type, we can not use FETCH statement
Dynamic SQL can overcome these problems
and allow more general-purpose software to
be developed.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


The EXECUTE IMMEDIATE
Statement:
􀂄 For example,
Static SQL:
EXEC SQL BEGIN DECLARE SECTION
float increment;
EXEC SQL END DECLARE SECTION
EXEC SQL UPDATE staff SET salary=salary+:increment
WHERE staffNo=“SL21”
Dynamic SQL:
EXEC SQL BEGIN DECLARE SECTION;
char buffer[100];
EXEC SQL END DECLARE SECTION;
sprintf (buffer, “ UPDATE staff SET salary = salary + %f
WHERE staffNo=‘SL21’ ”, increment);
EXEC SQL EXECUTE IMMEDIATE :buffer;

Examples of Dynamic SQL for Records, Objects, and Collections

As the following example shows, you can fetch rows from the result set of a dynamic multi-row
query into a record:

DECLARE
TYPE EmpCurTyp IS REF CURSOR;
emp_cv EmpCurTyp;
emp_rec emp%ROWTYPE;
sql_stmt VARCHAR2(200);
my_job VARCHAR2(15) := 'CLERK';
BEGIN
sql_stmt := 'SELECT * FROM emp WHERE job = :j';
OPEN emp_cv FOR sql_stmt USING my_job;
LOOP
FETCH emp_cv INTO emp_rec;
EXIT WHEN emp_cv%NOTFOUND;
-- process record
END LOOP;
CLOSE emp_cv;
END;

The next example illustrates the use of objects and collections. Suppose you define object type
Person and VARRAY type Hobbies, as follows:

CREATE TYPE Person AS OBJECT (name VARCHAR2(25), age NUMBER);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


CREATE TYPE Hobbies IS VARRAY(10) OF VARCHAR2(25);

Embedded SQL
Embedded SQL statements
ISO standard specifies embedded support for Ada, C,
COBOL, Fortran, Pascal, PL/1.

Types of embedded SQL:


• Static embedded SQL, where the entire
SQL statement is known when the
program is written
• Dynamic embedded SQL, which allows
all or part of the SQL statement to be
specified at runtime
• Dynamic SQL provides increased
flexibility and helps produce more
general-purpose software

Simple Embedded SQL Statements


􀂄 Simplest types of embedded SQL statements
are those that do not produce any query
results
• Non-select statement, INSERT, UPDATE,
DELETE, CREATE TABLE.

Some comments for the example


Embedded SQL statements start with
keyword EXEC SQL
Embedded SQL statements end with a
terminator that’s dependent on host language
• C, PL/1, Ada ----”;”
• COBOL ---- END-EXEC

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


An embedded SQL statement can appear
anywhere that an executable host language
statement can appear
The embedded statements are same as ISQL

Processing Programs with Embedded SQL:-

Embedded SQL Application


Running:-

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Retrieving data Using Embedded SQL


Embedded SQL divides queries into two
groups:
• Single-row queries, where the query result
contains at most one row of data
• Multi-row queries, where the query result may
contain an arbitrary number of rows, which
may be zero, one, more.

PL/SQL (Procedural Language using sql)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


PL/SQL can be called the extension of SQL where it is going to support the
SQL statement along with the processing statement we will be calling it as
Procedural Language.
(OR)
PL/SQL is Oracle's Procedural Language
extension to SQL.
PL/SQL has many programming
language features.
Program units written in PL/SQL can be
stored in compiled form.
PL/SQL code is portable across all
operating systems that support Oracle.
PL/SQL does not support DDL and DCL.

PL/SQL Block
A PL/SQL block contains logically
related SQL and PL/SQL statements.
Three sections in a typical PL/SQL block:
declaration (optional): declare
identifiers (variables and constants).
execution (required): execute SQL and
PL/SQL statements.
exception (optional): perform error
handling.

Execute PL/SQL Program


Save the program in a file: sample1.sql
Execute the program in SQL*Plus
SQL> start sample1
Enable output to the screen:
SQL> set serveroutput on
or place set serveroutput on at the
beginning of the PL/SQL program.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


(OR)

In Oracle Tools:

When it contains the PL/SQL engine, an application development tool can process PL/SQL
blocks and subprograms. The tool passes the blocks to its local PL/SQL engine. The engine
executes all procedural statements at the application site and sends only SQL statements to
Oracle. Thus, most of the work is done at the application site, not at the server site.

Furthermore, if the block contains no SQL statements, the engine executes the entire block at the
application site. This is useful if your application can benefit from conditional and iterative
control.

Frequently, Oracle Forms applications use SQL statements merely to test the value of field
entries or to do simple computations. By using PL/SQL instead, you can avoid calls to the Oracle
server. Moreover, you can use PL/SQL functions to manipulate field entries.

Advantages of PL/SQL

PL/SQL is a completely portable, high-performance transaction processing language that offers


the following advantages:

 Support for SQL


 Support for object-oriented programming
 Better performance
 Higher productivity
 Full portability
 Tight integration with Oracle
 Tight security

Understanding the Main Features of PL/SQL

A good way to get acquainted with PL/SQL is to look at a sample program. The program below
processes an order for a tennis racket. First, it declares a variable of type NUMBER to store the
quantity of tennis rackets on hand. Then, it retrieves the quantity on hand from a database table
named inventory. If the quantity is greater than zero, the program updates the table and inserts
a purchase record into another table named purchase_record. Otherwise, the program inserts an
out-of-stock record into the purchase_record table

With PL/SQL, you can use SQL statements to manipulate Oracle data and flow-of-control
statements to process the data. You can also declare constants and variables, define procedures

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


and functions, and trap runtime errors. Thus, PL/SQL combines the data manipulating power of
SQL with the data processing power of procedural languages.

Block Structure

PL/SQL is a block-structured language. That is, the basic units (procedures, functions, and
anonymous blocks) that make up a PL/SQL program are logical blocks, which can contain any
number of nested sub-blocks. Typically, each logical block corresponds to a problem or
subproblem to be solved. Thus, PL/SQL supports the divide-and-conquer approach to problem
solving called stepwise refinement.

A block (or sub-block) lets you group logically related declarations and statements. That way,
you can place declarations close to where they are used. The declarations are local to the block
and cease to exist when the block completes.

The following FIGURE shows, a PL/SQL block has three parts: a declarative part, an executable
part, and an exception-handling part. (In PL/SQL, a warning or error condition is called an
exception.) Only the executable part is required.

The order of the parts is logical. First comes the declarative part, in which items can be declared.
Once declared, items can be manipulated in the executable part. Exceptions raised during
execution can be dealt with in the exception-handling part.

Variables and Constants

PL/SQL lets you declare constants and variables, then use them in SQL and procedural
statements anywhere an expression can be used. However, forward references are not allowed.
So, you must declare a constant or variable before referencing it in other statements, including
other declarative statements.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Declaring Variables

Variables can have any SQL datatype, such as CHAR, DATE, or NUMBER, or any PL/SQL datatype,
such as BOOLEAN or BINARY_INTEGER. For example, assume that you want to declare a variable
named part_no to hold 4-digit numbers and a variable named in_stock to hold the Boolean
value TRUE or FALSE. You declare these variables as follows:

part_no NUMBER(4);
in_stock BOOLEAN;

You can also declare nested tables, variable-size arrays (varrays for short), and records using the
TABLE, VARRAY, and RECORD composite datatypes.

Assigning Values to a Variable

You can assign values to a variable in three ways. The first way uses the assignment operator
(:=), a colon followed by an equal sign. You place the variable to the left of the operator and an
expression (which can include function calls) to the right. A few examples follow:

tax := price * tax_rate;


valid_id := FALSE;
bonus := current_salary * 0.10;
wages := gross_pay(emp_id, st_hrs, ot_hrs) - deductions;

The second way to assign values to a variable is by selecting (or fetching) database values into it.
In the example below, you have Oracle compute a 10% bonus when you select the salary of an
employee. Now, you can use the variable bonus in another computation or insert its value into a
database table.

SELECT sal * 0.10 INTO bonus FROM emp WHERE empno = emp_id;

The third way to assign values to a variable is by passing it as an OUT or IN OUT parameter to a
subprogram. As the following example shows, an IN OUT parameter lets you pass initial values to
the subprogram being called and return updated values to the caller:

DECLARE
my_sal REAL(7,2);
PROCEDURE adjust_salary (emp_id INT, salary IN OUT REAL) IS ...
BEGIN
SELECT AVG(sal) INTO my_sal FROM emp;
adjust_salary(7788, my_sal); -- assigns a new value to my_sal

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Declaring Constants

Declaring a constant is like declaring a variable except that you must add the keyword CONSTANT
and immediately assign a value to the constant. Thereafter, no more assignments to the constant
are allowed. In the following example, you declare a constant named credit_limit:

credit_limit CONSTANT REAL := 5000.00;

The above mention parts are now defining:

PL/SQL is divided into 3 parts


1.Declaration part: Declaring the variables.
2.Execution part: corresponding to the task all the statements are to
be written here.
3.Exception part: Errors are to be handled properly.

DBMS output.put line(string): Is a function used to print message on


the screen.before using this function set serveroutput on.
SQL>set serveroutput on;
%type: Is used in declaring whenever we want to assign the same
datatype and size of one variable to another variable.

Example: sall emp.sal%type;/*sall is of same type&size as that of sal field


in emp table*/

Syntax: Declare
: /*Declaring block*/
Begin
: /*Execution block*/
Exception
: /*Exception block*/
End;

Example: Write a PL/SQL block which finds area of a circle.

SQL>ed area
Declare

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


R number(2):=10;
Pi constant number(4,3):=3.14;
A number(7,2);
Begin
A:=Pi*R*R;
DBMS_output.put_line(‘area is=’||to_char(a));
End;
/
SQL>@area; /* To execute the PL/SQL block*/

PL/SQL Boosts Performance:

PL/SQL Datatypes
Every constant, variable, and parameter has a datatype (or type), which specifies a storage
format, constraints, and valid range of values. PL/SQL provides a variety of predefined
datatypes. For instance, you can choose from integer, floating point, character, Boolean, date,
collection, reference, and LOB types. In addition, PL/SQL lets you define your own subtypes.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Predefined Datatypes
A scalar type has no internal components. A composite type has internal components that can be
manipulated individually. A reference type holds values, called pointers, that designate other
program items. A LOB type holds values, called lob locators, that specify the location of large
objects (graphic images for example) stored out-of-line.
Number Types
Number types let you store numeric data (integers, real numbers, and floating-point numbers),
represent quantities, and do calculations.
BINARY_INTEGER
You use the BINARY_INTEGER datatype to store signed integers. Its magnitude range is -2**31 ..
2**31. Like PLS_INTEGER values, BINARY_INTEGER values require less storage than NUMBER
values. However, most BINARY_INTEGER operations are slower than PLS_INTEGER operations.
BINARY_INTEGER Subtypes
A base type is the datatype from which a subtype is derived. A subtype associates a base type
with a constraint and so defines a subset of values. For your convenience, PL/SQL predefines the
following BINARY_INTEGER subtypes:
NATURAL
NATURALN
POSITIVE
POSITIVEN
SIGNTYPE

NUMBER
The syntax follows:
NUMBER[(precision,scale)]

To declare fixed-point numbers, for which you must specify scale, use the following form:
NUMBER(precision,scale)

NUMBER Subtypes
You can use the following NUMBER subtypes for compatibility with ANSI/ISO and IBM types or
when you want a more descriptive name:
DEC
DECIMAL
DOUBLE PRECISION
FLOAT
INTEGER
INT
NUMERIC
REAL
SMALLINT

PLS_INTEGER
You use the PLS_INTEGER datatype to store signed integers. Its magnitude range is -2**31 ..
2**31. PLS_INTEGER values require less storage than NUMBER values.
Character Types

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Character types let you store alphanumeric data, represent words and text, and manipulate
character strings.
CHAR
You use the CHAR datatype to store fixed-length character data.
The syntax follows:
CHAR[(maximum_size [CHAR | BYTE] )]

CHAR Subtype
The CHAR subtype CHARACTER has the same range of values as its base type.
LONG and LONG RAW
You use the LONG datatype to store variable-length character strings. The LONG datatype is like
the VARCHAR2 datatype, except that the maximum size of a LONG value is 32760 bytes.
You use the LONG RAW datatype to store binary data or byte strings. LONG RAW data is like LONG
data, except that LONG RAW data is not interpreted by PL/SQL. The maximum size of a LONG RAW
value is 32760 bytes.
RAW
You use the RAW datatype to store binary data or byte strings. another.
The RAW datatype takes a required parameter that lets you specify a maximum size up to 32767
bytes. The syntax follows:
RAW(maximum_size)

ROWID and UROWID


Internally, every database table has a ROWID pseudocolumn, which stores binary values called
rowids. Each rowid represents the storage address of a row. A physical rowid identifies a row in
an ordinary table. A logical rowid identifies a row in an index-organized table.
Physical Rowids
SQL> SELECT rowid, ename FROM emp WHERE empno = 7788;

might return the following row:


ROWID ENAME
------------------ ----------
AAAAqcAABAAADFNAAH SCOTT

Logical Rowids
Logical rowids provide the fastest access to particular rows..
VARCHAR2
The syntax follows:
VARCHAR2(maximum_size [CHAR | BYTE])

VARCHAR2 Subtypes
The VARCHAR2 subtypes below have the same range of values as their base type. For example,
VARCHAR is just another name for VARCHAR2.
STRING
VARCHAR
DSINTERVAL_UNCONSTRAINED .

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


PL/SQL Architecture

The PL/SQL compilation and run-time system is an engine that compiles and executes PL/SQL blocks and
subprograms. The engine can be installed in an Oracle server or in an application development tool such
as Oracle Forms.

In either environment, the PL/SQL engine accepts as input any valid PL/SQL block or subprogram. Figure
shows the PL/SQL engine processing an anonymous block. The PL/SQL engine executes procedural
statements but sends SQL statements to the SQL engine in the Oracle database.

PL/SQL Engine

THE PL/SQL ENGINE(Processing)

//****>
THE PL/SQL ENGINE(Processing)==//

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


TRIGGER: Triggers are procedures that are sotored in the database not
in the complied form and implicitly fired when an event
occurs.Traditionally,triggers guarantee that when a specific operation is
performed related actions are performd.Triggers support the execution of a
Pl/SQL block when an INSERT<UPDATE,or DELETE occurances on a
table view.
(OR)

Trigger:-
A trigger is an event-driven block of
PL/SQL code.
An event could be an insertion of a tuple
into a table, a deletion of an existing tuple
from a table, and an update of a table.
A trigger fires (executes, activates) when
an event occurs.
Triggers are useful for enforcing various
integrity constraints and business rules.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Advantages of Triggers:

 Applying Complex Bussiness rules.


 Security.
 Auditing.

Syntax: Create or replace trigger <trigger name>


Before/after insert or delete or update on <table name> for each
row.
Begin
:
:
End;

Example 1: Create a database Trigger corresponding to emp table which


is not going to allow the user to insert the employee’s salary more than
5000.

SQL>ed t1
Create or replace trigger eins
Before insert on emp for each row
Begin
If:new.sal>5000 then
Raise_application_erroe(-20001,’salary above 5000’);
End if;
End;
/

SQL>@t1

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

Example 2: Create a database Trigger on dept table which prevents the


user from updating the deptno or deleting a row from the dept table if
dependent rows are existing in the emp table( i.e. if there are any
employee’s belonging to that department).

SQL>ed t2
Create or replace trigger updel
Before update or delete on dept for each row
Begin
Declare
No number(4);
If updating or deleting then
Select count(*) no from emp
Where deptno=:new.deptno;
If (no>1) then
Raise_application_erroe(-20001,’Records existing
in emp table’);
End if;
End if;
End;
/

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


SQL>@ t2
(OR)

Triggers:
Trigger: procedure that starts automatically if
specified changes occur to the DBMS.

Three parts:

Event (activates the trigger)


Condition (tests whether the triggers should run)
Action (what happens if the trigger runs)

Triggers: Example
CREATE TRIGGER youngSailorUpdate
AFTER INSERT ON SAILORS
REFERENCING NEW TABLE NewSailors
FOR EACH STATEMENT
INSERT
INTO YoungSailors(sid, name, age, rating)
SELECT sid, name, age, rating
FROM NewSailors N
WHERE N.age <= 18.
(OR)

Triggers are stored procedures which are fired when data is modified in an underlying table.
They can evaluate data being added to a table for validation purposes, or can make changes
in that or other fields depending on the value of that data. You can use them even to
execute a separate stored procedure, or to roll back a data modification or an entire
transaction.

Triggers are created in the Enterprise Manager, or in the Query Analyzer through the object
browser. There are also templates for triggers in the Query Analyzer (Edit|Insert Trigger).
Triggers can be created with the following syntax:

CREATE TRIGGER trigger_name


ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] }
[ WITH APPEND ]

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[…n]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ … n ]
}]
sql_statement [ … n ]
}
}

There are two types of triggers: AFTER and INSTEAD OF. After triggers AFTER TRIGGERS
fire after the data is changed, either by insert, delete, or update. If the data is
inappropriate, as defined in the trigger, the modification can be rolled back to where it was
before the data was modified. After triggers AFTER TRIGGERS cannot be placed on views,
and cannot be used on more than one table. Also, the text, ntext, and image columns
cannot be referenced in an after trigger. AFTER TRIGGERS.

After triggers AFTER TRIGGERS can be nested to 32 levels deep, and can be called
recursively, again to 32 levels.

Instead of INSTEAD OF triggers make the validation before the modification. However,
Instead of INSTEAD OF triggers CAN can be used on views. They do not allow recursion, and
you can only have one Instead of INSTEAD OF trigger per table. And you cannot use an
Instead of INSTEAD OF trigger with a cascade.

Cursors
Oracle uses work areas to execute SQL statements and store processing information. A PL/SQL
construct called a cursor lets you name a work area and access its stored information. There are
two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data
manipulation statements, including queries that return only one row. For queries that return more
than one row, you can explicitly declare a cursor to process the rows individually. An example
follows:

DECLARE
CURSOR c1 IS
SELECT empno, ename, job FROM emp WHERE deptno = 20;
(OR)

Cursor in PL/SQL
Consider an SQL query returning

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


multiple rows.
How to save the result of the query?
Save the result into a big array.
• No easy way to estimate the size of the result.
• The result could be too large for any memorybased
array.
Save one-row-at-a-time: This is the SQL
approach.
Define a cursor:
cursor cursor_name is
select_statement;
Example: cursor c1 is
select cid, cname, city
from customers;
The query defining the cursor is not
executed at the declaration time.
Working with Cursor
open cursor_name;
fetch cursor_name
into record_or_variable-list;
close cursor_name;
Open causes the query defining the
cursor to be executed.
Cursor FOR Loops

In most situations that require an explicit cursor, you can simplify coding by using a cursor FOR
loop instead of the OPEN, FETCH, and CLOSE statements. A cursor FOR loop implicitly declares its
loop index as a record that represents a row fetched from the database. Next, it opens a cursor,
repeatedly fetches rows of values from the result set into fields in the record, then closes the
cursor when all rows have been processed. In the following example, the cursor FOR loop
implicitly declares emp_rec as a record:

DECLARE
CURSOR c1 IS
SELECT ename, sal, hiredate, deptno FROM emp;
...
BEGIN
FOR emp_rec IN c1 LOOP
...
salary_total := salary_total + emp_rec.sal;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


END LOOP;

To reference individual fields in the record, you use dot notation, in which a dot (.) serves as the
component selector.

Cursor Variables

Like a cursor, a cursor variable points to the current row in the result set of a multi-row query.
But, unlike a cursor, a cursor variable can be opened for any type-compatible query. It is not tied
to a specific query. Cursor variables are true PL/SQL variables, to which you can assign new
values and which you can pass to subprograms stored in an Oracle database. This gives you more
flexibility and a convenient way to centralize data retrieval.

Typically, you open a cursor variable by passing it to a stored procedure that declares a cursor
variable as one of its formal parameters. The following procedure opens the cursor variable
generic_cv for the chosen query:

PROCEDURE open_cv (generic_cv IN OUT GenericCurTyp,choice NUMBER) IS


BEGIN
IF choice = 1 THEN
OPEN generic_cv FOR SELECT * FROM emp;
ELSIF choice = 2 THEN
OPEN generic_cv FOR SELECT * FROM dept;
ELSIF choice = 3 THEN
OPEN generic_cv FOR SELECT * FROM salgrade;
END IF;
...
END;

/*PL/SQL program for checking if a number is prime or not*/

SQL>ed prime.sql
Declare
N number:=&n;
I number:=2;
R number(3):=0;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Begin
While(i<=n/2)
Loop
R:=mod(n,i);
If r=0 then
Exit;
End if;
I:=i
1;
End loop;
If r=1 then
Dbms_output.put_line(‘prime’);
else
dbms_output.put_line(‘not prime’);
end if;
end;
/

SQL>@ prime;

OUTPUT:

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(1)

AbdulQader(SQL)> create table sb_account(acc_no number(20),cust_name


varchar2(17),bal_amount number(6,2));
Table created.

For inserting the values:-


SQL> insert into sb_account values(&acc_no,'&cust_name',&bal_amount);
Enter value for acc_no: 111
Enter value for cust_name: SHAIK ABDUL QADER
Enter value for bal_amount: 17000
old 1: insert into bank values(&acc_no,'&cust_name',&bal_amount)
new 1: insert into sb_account values(123456,'SHAIK ABDUL QADER',15000)
1 row created.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


SIMILARLY,create some 5 to10 rows.

PL/SQL CODE:-
CODE
declare
2 ano number(10);
3 cn varchar2(35);
4 ba number(10);
5 re number(10) :=1000;
6 dep number(10);
7 wit number(10);
8 msg varchar2(50);
9 d3 varchar2(50);
10 begin
11 ano :=&accountno;
12 select acc_no,cust_name,bal_amount into ano,cn,ba from sb_account where
acc_no=ano;
13 dep :=&enter_for_deposit;
14 update sb_account set bal_amount=dep where acc_no=ano;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


15 if re < dep
16 then
17 wit :=&withdraw;
18 dep := dep-wit;
19 if dep < 1000
20 then
21 d3 :='your account doesnot have suffisient bal';
22 else
23 update sb_account set bal_amount=dep where acc_no=ano;
24 d3 :='your transaction has sucessfully completed';
25 end if;
26 else
27 msg :='YOU CANNOT WITHDRAWN DUE TO INSUFFICIENT BALANCE';
28 end if;
29 dbms_output.put_line(d3);
30* end;

Output;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(2)

AbdulQader(SQL)>CREATE TABLE COLLEGE_INFO(COLLEGE_CODE


NUMBER(5)PRIMARY KEY,COLLEGE_NAME
VARCHAR2(20),ADDRESS VARCHAR2(25));

Table created.

AbdulQader(SQL)>CREATE TABLE FACULTY_INFO(COLLEGE_CODE


NUMBER(5)REFERENCES
COLLEGE_INFO(COLLEGE_CODE),FACULTY_CODE
NUMBER(5),FACULTY_NAME VARCHAR2(25),QUALIFICATION

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


VARCHAR2(10),EXP_IN_NO_YEARS NUMBER(5,2),ADDRESS
VARCHAR2(25));

Table created.

( A)

ACCEPTING THE DATA FROM A FORM:-

(B) GENERATE THE QUERE FROM SQL MODE:-


(i) SELECT FACULTY_NAME ,
EXP_IN_NO_YEARS,QUALIFICATION FROM FACULTY_INFO WHERE
EXP_IN_NO_YEARS>=10 AND QUALIFICATION='MTECH';

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(ii) SELECT FACULTY_NAME,EXP_IN_NO_YEARS,QUALIFICATION


FROM FACULTY_INFO WHERE EXP_IN_NO_YEARS>=10 AND
QUALIFICATION!='MTECH';

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(3)

AbdulQader(SQL)> CREATE TABLE LIBRARY(BOOK_NO


NUMBER(5)PRIMARY KEY,TITLE VARCHAR2(20),PUBLISHED
NUMBER(5),AUTHOR VARCHAR2(20),STATUS VARCHAR2(20));

Table created.

TRIGGER:-
AbdulQader(SQL)> create or replace trigger LIBtrigger before INSERT OR DELETE OR
UPDATE on LIBRARY for each row
declare
sta varchar2(25);
pub number(5);
begin
select published,status into pub,sta from library where published>1;
if pub>=20 then
sta :='cannot be issued';
insert into LIBRARY value('sta') WHERE PUBLISHED>=20;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


end if;
if pub<20
then
sta :='&below5years';
insert into LIBRARY value('sta') WHERE PUBLISHED<5;
sta :='&below10years';
insert into LIBRARY value('sta') WHERE PUBLISHED<10;
sta :='&below19years';
insert into LIBRARY value('sta') WHERE PUBLISHED<=19;
END IF;
END;
/

PROGRAM---
---(4)

AbdulQader(SQL)> create table book1(book_no number(5),title


varchar2(15),publisher varchar2(15),author varchar2(25),status
varchar2(15),date_of_purchase date);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

QUEREIS:-
(i)

(ii)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(5)

AbdulQader(SQL)> CREATE TABLE STUDENT(ROLL_NO


NUMBER(15)PRIMARY KEY,S_NAME
VARCHAR2(25),DATE_OF_BIRTH date,COURCE_ID NUMBER(10));
Table created.

AbdulQader(SQL)> CREATE TABLE COURCE(COURCE_ID


NUMBER(5),NAME VARCHAR2(10),FEE NUMBER(10),DURATION
VARCHAR2(10));
Table created.

ACCEPTING THE DATA FROM A FORM:-

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

QUEREIS:-
(i)
AbdulQader(SQL)>SELECT S_NAME,ROLL_NO,DATE_OF_BIRTH
FROM STUDENT WHERE DATE_OF_BIRTH<='31-DEC-1991';

(ii)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


AbdulQader(SQL)> select cource_id,name,fee from cource where
fee>26700;

PROGRAM---
---(6)

AbdulQader(SQL)>create table item(item_code number(5),item_name


varchar2(20),qty_in_stock number(10),reorder_level number(7));
Table created.
AbdulQader(SQL)>create table supplier(supp_code
number(5),supp_name varchar2(25),address varchar2(25));
Table created.
AbdulQader(SQL)>create table can_supply(supp_code
number(5),item_code number(5));
Table created.

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


ACCEPTING THE DATA FROM A FORM:-

QUEREIS:-
(i)
AbdulQader(SQL)>SELECT SUPP_CODE,SUPP_NAME FROM
SUPPLIER WHERE SUPP_CODE IN(SELECT ITEM_CODE FROM ITEM
WHERE ITEM_CODE IN(ITEM_CODE));

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(ii)
AbdulQader(SQL)>select item_code,item_name from item where
item_code not in(select supp_code from supplier where
supp_code>100);

PROGRAM---
---(7)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


AbdulQader(SQL)>create table branch(branch_id
number(6),branch_name varchar2(25), cust_city varchar2(25),cust_id
number(5));
Table created.

AbdulQader(SQL)>create table customer(cust_id


number(5),cust_name varchar2(25),cust_city varchar2(25),branch_id
number(5));
Table created.

ACCEPTING THE DATA FROM A FORM:-

QUEREIS:-
(i)
AbdulQader(SQL)>SELECT CUST_ID,CUST_CITY,BRANCH_NAME
FROM BRANCH WHERE CUST_CITY=BRANCH_NAME;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(ii)
AbdulQader(SQL)>select cust_id,cust_name,cust_city from customer
where cust_city not in(select branch_name from branch where
branch_id>100);

PROGRAM---
---(8)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

AbdulQader(SQL)>create table book(book_no number(5),title


varchar2(15),publisher varchar2(15),status
varchar2(15),date_of_purchase date, year number(5));
Table created.

AbdulQader(SQL)>create table member(member_id number(5),name


varchar2(15),number_of_books_issued number(4),max_limit
number(5));
Table created.

AbdulQader(SQL)>create table book_issue(book_no


number(8),member_id number(6),date_of_issue number(12))
Table created.

ACCEPTING THE DATA FROM FORMS:

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

QUERIES:
(i)
AbdulQader(SQL)>SELECT BOOK_NO,TITLE,DATE_OF_PURCHASE
FROM BOOK WHERE DATE_OF_PURCHASE<'27-SEP-2009';

(ii)
AbdulQader(SQL)> select member_id,name,
number_of_books_issued,max_limit from member where
number_of_books_issued>5;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(9)

(a) All the data are same which we are previously seen(program-8).

(B)
declare
cursor prog IS select book_no,member_id,
date_of_issued,due_date from book_issued
where book_no>100;
book number(10);
mem number(10);
dateissued number(15);
duedate number(15);
begin
open prog;
DBMS_OUTPUT.PUT_LINE(' BOOK_NO MEMBER_ID DATE_OF_ISSUED
DUE_DATE ');
DBMS_OUTPUT.PUT_LINE('-------- ------------ --------------- ------------');
LOOP
FETCH PROG INTO book,mem,dateissued,duedate;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


exit when(Dateissued<=8);
dbms_output.put_line(book||' '||mem||' '||dateissued||' '||duedate);
end loop;
end;

PROGRAM---
---(10)

AbdulQader(SQL)> create table student11(roll_no


number(5)primary key,s_name varchar2(25), category
char(3),district varchar2(15),state varchar2(15));
Table created.

AbdulQader(SQL)>create table student_rank11(roll_no


number(5)references student11(roll_no),marks
number(5),rank number(5));
Table created.

(A)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(B)
(i)
AbdulQader(SQL)> SELECT
STUDENT11.S_NAME,STUDENT11.DISTRICT,STUDENT_RANK11.RAN
K FROM STUDENT11,STUDENT_RANK11
WHERE STUDENT11.ROLL_NO=STUDENT_RANK11.ROLL_NO AND
STUDENT_RANK11.RANK=505;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(ii)
select student11.roll_no, student11.s_name,
student11.category,student_rank11.rank from student11,
student_rank11 where student11.category='BC' and
student_rank11.rank=505 and
student11.roll_no=student_rank11.roll_no;
/

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(11)

AbdulQader(SQL)> create table student17(roll_no number(5),name


varchar2(25),age date,course_id number(5)primary key);
Table created..

AbdulQader(SQL)> create table course17(course_id


number(5)references student17(course_id),c_name char(6),fee
number(5,2),duration number(4));
Table created.

(A )
WE ARE ALREADY CREATED TABLES and FORM OF BOTH IN THE PROGRAM
OF--5.
Let us create (b),
(B )
(i)
AbdulQader(SQL)> SELECT STUDENT17.ROLL_NO,
STUDENT17.NAME,STUDENT17.AGE,COURSE17.COURSE_ID,COURS
E17.C_NAME FROM STUDENT17,COURSE17 WHERE
COURSE17.C_NAME='MCA' AND STUDENT17.AGE BETWEEN '01-
JAN-1991' ANd '31-DEC-1992';

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(12)

(A)WE ARE ALREADY SAW and CREATED IN THE PROGRAM OF---5; 5;


(B )
declare
C1 NUMBER(10);
COU VARCHAR2(10);
F NUMBER(10);
i varchar2(3);
a varchar2(15);
b varchar2(15);
D number(5);
begin
COU :='&COURCE';
select COURCE_ID,name,FEE,DURATION,status into C1,a,F,D,b from
cource where NAME=COU;
IF a='COU'
then
LOOP
A :=A+1;
EXIT WHEN I>10;
IF A<5
THEN
UPDATE COURCE SET STATUS='NOT OFFERED' WHERE NAME='COU';
DBMS_OUTPUT.PUT_LINE('OFFERED NOT ALLOWED WRITTEN TO
STATUS SUCCESSFULLY');
END IF;
END LOOP;
END IF;
END;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(13)

(A) WE ARE ALREADY SAW IN THE PROGRAM OF---6


6

(B) BEFORE PL/SQL CODE WRITTEN:-

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

declare
cursor progfourt is select
item_code,item_name,qty_in_stock,reorder_level from item where
item_code>100;
a number(5);
b number(5);
c number(5);
d varchar2(15);
begin
open progfourt;
DBMS_OUTPUT.PUT_LINE('ITEM_CODE ITEM_NAME QTY_IN_STOCK
REORDER_LEVEL');
DBMS_OUTPUT.PUT_LINE('---------- --------------- -------------- -------------');
LOOP
FETCH PROGFOURT INTO a,d,c,b;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


if c<=b
then
DBMS_OUTPUT.PUT_LINE( a||' '||d||' '||c||' '||b);
end if;
exit when progfourt%NOTFOUND;
end loop;
end; // AFTER PL/SQL CODE WRITTEN:-
/

PROGRAM---
---(14)

(A) WE CREATED FORM ALREADY IN THE PROGRAM NUMBER 5.

(B)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

declare
a number(10);
b varchar2(25);
c varchar2(25);
d varchar2(25);
begin
select supp_code,supp_name,address,status into a,b,c,d from supplier
where supp_code=111;
if a > 100
then
update supplier set status='IMPORTANT' where supp_code
in(111,222,333,444,555,666,777,888,999,1010);

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


end if;
end;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(15)

(A)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(B)

PL/SQL CODE:-
DECLARE
A NUMBER(5);
B NUMBER(10);
C VARCHAR2(25);
BEGIN
SELECT ROLL_NO,SUB_OPTED,STATUS INTO A,B,C FROM
STUDENT16 WHERE ROLL_NO=1;
IF B<=5
THEN
UPDATE STUDENT16 SET STATUS='NOT OFFERED' WHERE
SUB_OPTED<=5;
DBMS_OUTPUT.PUT_LINE('SUCCESSIVELY UPDATE TO STATUS');
DBMS_OUTPUT.PUT_LINE('NOT OFFERED WHERE SUB_OPTED
ATLEAST 5');

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


END IF;
END;
/

PROGRAM---
---(16)

AbdulQader(SQL)>CREATE TABLE SUBJECT(SUB_ID


NUMBER(5),SUB_NAME VARCHAR2(25),FACULTY_CODE VARCHAR2(20
),SPECIALIZATION VARCHAR2(20),STATUS VARCHAR2(20));
Table created.
AbdulQader(SQL)>INSERT INTO SUBJECT VALUES
(&SUB_ID,'&SUB_NAME','&FACULTY_CODE','&SPECIALIZATION');

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(A) we are already created form in the last program number 15.
(B)

Pl/sql code:-
DECLARE
A NUMBER(5);
B varchar2(20);
C VARCHAR2(25);
BEGIN
SELECT sub_id,faculty_code,STATUS INTO A,B,C FROM subject
WHERE sub_id=1;
IF A>0 --B='NOT OFFERED'
THEN
UPDATE Subject SET STATUS='NOT OFFERED' WHERE
faculty_code='NOT OFFERED';
END IF;
DBMS_OUTPUT.PUT_LINE('SUCCESSIVELY UPDATE TO STATUS');
DBMS_OUTPUT.PUT_LINE('NOT OFFERED WHERE faculty member
set not offered');
END;

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

PROGRAM---
---(17)

(A) Already created.

(B)
(i)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(ii)

PROGRAM---
---(18)

(A)Already created.
(B)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


(i)

(ii)

PROGRAM---
---(19)

(A)Already created.
(B)
(i)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(ii)

PROGRAM---
---(20)

AbdulQader(SQL)>create table student8(rno number(5)primary key,


marks number(5),category char(5),state varchar(25));

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )


Table created.

AbdulQader(SQL)>create table studentrank8(rno number(5)references


student8(rno),marks number(5),rank number(5));
Table created.

AndulQader(SQL)>select *from student8; select *from studentrank8;

RNO MARKS CATEG STATE RNO MARKS RANK


--------- ---------- ----- ---------------------- ---------- ---------- ----------
1 1000 oc andhra Pradesh 1 159 20
2 980 bc tamilnadu 2 666 500
3 250 bc tamilnadu 3 1000 99
4 1325 oc andhra Pradesh 4 450 450
5 555 oc tamilnadu 5 850 950
6 350 oc tamilnadu 6 750 255
7 654 bc andhra Pradesh 7 774 56
8 587 oc andhra pradesh 8 656 79
9 741 oc tamilnadu 9 850 129
10 959 bc tamilnadu 10 299 255
11 258 bc andhra Pradesh 11 598 366

11 rows selected. 11 rows selected.

(A)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(B)
(i)
AndulQader(SQL)>select studentrank8.rno,studentrank8.rank,
student8.state from studentrank8,student8 where
studentrank8.rno=student8.rno and studentrank8.rank>100 and
student8.state='tamilnadu';

(ii)
AndulQader(SQL)>select studentrank8.rno,studentrank8.rank,
student8.category,student8.state
from studentrank8,student8 where studentrank8.rank>100
and student8.category='bc' and student8.state='andhra pradesh';

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2


HYDERABAD NAME=“ Shaik Abdul Qader ” ROLL NO=060-09-023
Contact me=9700064061

Nizam Institute of Computer Sciences(NICS) ( SQL , PL/SQL PROGRAMMING )

(i) (ii)

DBMS=LAB-V{NOV/DEC-2009} M.C.A II/I ---DBMS(LAB)RECORD Page 2

You might also like