Upload
abdul-qader
View
241
Download
0
Embed Size (px)
Citation preview
8/8/2019 AbdulQader-MCA Dbms LAB
1/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 1
CCOONNTTEENNTTSS ____________________________________PPAARRTT--11 ==========DDBBMMSS PPAAGGEE..NNOO
Introduction to DBMS.
Advantages
Data Abstraction..
Data Models..
DataBase Facilities.
Structure of a DBMS..
Different Type of Keys..
PPAARRTT--22 ==========SSQQLL.
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
8/8/2019 AbdulQader-MCA Dbms LAB
2/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 2
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
PPAARRTT--33 ==========PPLL/SSQQLL.
Introduction to PL/SQL.
Advantages
Block Structure
Variable & Constraints..
DataTypes of PL/SQL
Architecture
Trigger..
Advantages of trigger.
Cursor
8/8/2019 AbdulQader-MCA Dbms LAB
3/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 3
1.
2.
3.
4.
SQL , PL/SQL PROGRAMS
Create a table to represent SB _account of a bank consisting of
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:
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:
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.
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.
8/8/2019 AbdulQader-MCA Dbms LAB
4/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 4
5.
6.
7.
8.
Create the following tables:-
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:-
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:-
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:-
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
8/8/2019 AbdulQader-MCA Dbms LAB
5/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 5
9.
10.
11.
12.
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:-
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 evenafter 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:-
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:-
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:-
Student(roll_no,name date_of_birth,course_id).
8/8/2019 AbdulQader-MCA Dbms LAB
6/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 6
13.
14.
15.
16.
Cource(cource_id,name,fee,duration,status).
(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.
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:-
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:-
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:-
Student(roll_no,s_name,subject_opted)
8/8/2019 AbdulQader-MCA Dbms LAB
7/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 7
17.
18.
19.
20.
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 appropriatevalidation 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:-
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 appropriatevalidation 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 :-
(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 :-
(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:-
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
8/8/2019 AbdulQader-MCA Dbms LAB
8/124
8/8/2019 AbdulQader-MCA Dbms LAB
9/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 9
Introduction to DBMS
AA database management system (DBMS) consists of an interrelateddata and a set of programs to access that data. The collection of data isusually referred to as database. The primary goal of a database is toprovide an environment that is both convenient and efficient to use inretrieving and storing database information.
Database systems are designed to manage large bodies ofinformation. The management of data involves both the definition ofstructures for the storage of information and provision of mechanisms forthe manipulation of information. In addition, the database system mustprovide for the safety of the information stored, despite system crashes orattempts at unauthorized access. If data is stored among several users, thesystem 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)(OORR)
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.
(OORR)
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 processesof defining, constructing and manipulating the database for various applications.
Advantages of DBMS:
Reduces Data redundancy (duplicity) and inconsistency of data.
Provides data sharing facilities.
8/8/2019 AbdulQader-MCA Dbms LAB
10/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 10
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 andmaintained. This concern has lead to the design of complex data structuresfor the representation of data in the database. Its complexity is hidden fromthe users through several levels of abstraction in order to simplify theinteraction between the user and the system.
Physical Level:
The lowest level of abstraction describes the data is actually storedin the database.
Conceptual Level:
The next-higher level of abstraction describes what data areactually stored in the database and the relationship that exists betweenthem. This level is used by DBA, who must decide what information is to bekept in the database.
View Level:
The highest level of abstraction describes only a part of the entiredatabase.
DATA MODELS:
8/8/2019 AbdulQader-MCA Dbms LAB
11/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 1
A data model can be defined as a collection of tools fordescribing 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 worldperception which consists of collection of basic objectscalled Entities and relationships among these objects.
Object oriented model: is based on collection of objects.An object contains instance variables within the object. Anobject also contains bodies of code that operate on theobject, 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 arecalled as record based logical models.
Some of the widely known models are:
Relational model: represents data and relationships among databy a collection of tables, each of which has a number of columns withunique names.
Network model: represents data by collection of records andrelationships among data are represented by links which are viewedas pointers.
Hierarchical model: represents data by collection of records, whichare organized as trees rather than arbitrary graphs and relationshipsamong data are represented by links which are viewed as pointers.
8/8/2019 AbdulQader-MCA Dbms LAB
12/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 12
Physical models: They are used in describing data at the lowestlevel.
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 areexpressed by a special language called Data definition language(DDL).The result of compilation of DDL statements is a set of tableswhich are stored in a special file called Data Dictionary.
The storage structures and access methods used by thedatabase system are specified by a set of definitions in a special type ofDDL called Data storage and definition language. The result ofcompilation of these definitions is a set of instructions to specify the
implementation details of the database schemes which are usuallyhidden from others.
Data manipulation language (DML):
A Data manipulation language (DML) is a language thatenables users to access or manipulate data efficiently.
Data manipulation means1. 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:1. Procedural DMLs requires a user to specify what data is
need and how it get it.
8/8/2019 AbdulQader-MCA Dbms LAB
13/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 13
2. Non Procedural DMLs requires a user to specify whatdata 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 querylanguage.
STRUCTURE OF A DBMS:
The major components of this system are
Data definition language compiler:
The DDL compiler converts data definition statementsinto a set of tables. These tables contain metadata concerning thedatabase.
Data Manager:
The data manager is the central software component of theDBMS.Its function is to convert operation queries coming from queryprocessor or indirectly or an application program from the users logicalview to physical file system. The data manager is responsible forinterfacing 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 datamanager.
Disk manager:The disk manager transfers the block containing the data requested by thefile manager without the concern of physical characteristics of theunderlying storage media.
8/8/2019 AbdulQader-MCA Dbms LAB
14/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 14
Query Processor:
The query processor is used to interpret the online users query and covertit into an efficient series of operations in a form capable of being sent to thedata manager for execution. It uses data dictionary to find the structure ofthe relevant portion of the database and uses this information in modifyingthe 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. Thisfile is consulted before actual data is read or deleted in the databasesystem.Different types of Keys:
Attribute: An object or an entity is characterized by its properties orattributes, they can also be referred as field.
1. Primary key: An attribute to identify a record uniquely withoutallowing any null values to be entered into it is called Primary key.
Ex: empno attribute in the employee table and deptno attribute in depttable.
2. Foreign key: An attribute which is a primary key in its own table andis used as a reference in another table is called foreign key.
3. Super Key: A primary key with a combination of other attributes forunique identification is called super key. In other words primary key isa minimum super key.
Ex: Empno along with ename is super key.
4. Candidate Key: The super key for which no proper subset is a superkey such a minimal super key is a candidate key.
Ex: Ename is a candidate key.
SSTRUCTURED QQUERY LLANGUAGE(SQL)
8/8/2019 AbdulQader-MCA Dbms LAB
15/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 15
Whhaattiiss SSQQLL??
ANS:-
SSQQLL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used tocommunicate with a database. According to ANSI (American National Standards Institute),it is
the standard language for relational database management systems. SQL statements are used toperform tasks such as update data on a database, or retrieve data froma database. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQLServer, Access, Ingres, etc. Although most database systems use SQL,most of themalso have
their own additionalproprietary 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 tutorialwillprovide 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 thedatabases.
SQL organizes data as tables , indexes , views etc. SQL is thetool for organizing , managing and retrieving data stored in thedatabase.
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 ofdata in relational database managementsystems, database schema creation and modification, and database object access controlmanagement.[1][2]
SQL (Structured Query Language) is a standard interactive and programming language forgetting information from and updating a database. Although SQL is both an ANSI and an ISOstandard, many database products support SQL with proprietary extensions to the standardlanguage. 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.
Procedural extensions
8/8/2019 AbdulQader-MCA Dbms LAB
16/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 16
SQL is designed for a specific purpose: to query data contained in a relational database. SQLis a set-based, declarative query language, not an imperative language such as C orBASIC.However, there are extensions to Standard SQL which add procedural programminglanguage functionality, such as control-of-flow construct.
(OR)
(Structured Query Language) Pronounced "S-Q-L" or "see-quill," a language used tointerrogate and process data in a relational database. Originally developed by IBM for itsmainframes, all database systems designed for client/server environments support SQL. SQLcommands can be used to interactively work with a database or can be embedded within aprogramming language to interface to a database. Programming extensions to SQL have turnedit into a full-blown database programming language, and all major database managementsystems (DBMSs) support the language.
ANSI standardized SQL, but most database management systems (DBMSs) have someproprietary enhancement, which if used, makes SQL non standard. Moving an application fromone SQL database to another may require tailoring to convert some command.
SQL Statements:
SQL statements are divided into1. 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 thestructure of the database. DDL consists of create, alter and dropstatements.
Data Manipulation Language (DML): These statements are basicallyrequired to manipulate the records of the tabled consists of insert, delete,and update statements.
Data Control Language (DCL): These statements are basically requiredto control the tables among several users by giving access or by takingback the access to the tables. DCL consists of grant and revokestatements.
8/8/2019 AbdulQader-MCA Dbms LAB
17/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 17
Transaction control language (TCL): These statements are basicallyrelated to various transactions like insert, delete, and update.
Data retrieval language (DRL): These statements are basically requiredto retrieve the records for the table. DRL consists of select statements.
WWhhaatt aarree tthhee ddiiffffeerreennccee bbeettwweeeenn DDDDLL,, DDMMLLaanndd DDCCLL ccoommmmaannddss??
DDL
Data Definition Language (DDL) statements are used to define the database structure or schema. Someexamples:
o CREATE - to create objects in the databaseo ALTER - alters the structure of the databaseo DROP - delete objects from the databaseo TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removedo COMMENT - add comments to the data dictionaryo RENAME - rename an object
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. Someexamples:
o SELECT - retrieve data from the a databaseo INSERT - insert data into a tableo UPDATE - updates existing data within a tableo DELETE - deletes all records from a table, the space for the records remaino MERGE - UPSERT operation (insert or update)o CALL - call a PL/SQL or Java subprogram
oEXP
LAIN
PLAN
- explain access path to datao LOCKTABLE - control concurrency
DCL
Data Control Language (DCL) statements. Some examples:
o GRANT - gives user's access privileges to databaseo REVOKE - withdraw access privileges given with the GRANT command
8/8/2019 AbdulQader-MCA Dbms LAB
18/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 18
TCL
Transaction Control (
TCL) statements are used to manage the changes made by D
ML statements.
It allowsstatements to be grouped together into logical transactions.
o COMMIT - save work doneo SAVEPOINT - identify a point in a transaction to which you can later roll backo ROLLBACK - restore database to original since the last COMMITo SETTRANSACTION - 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 aftera DML. DDL after DML means "auto commit". The changes will return on disk not onthe buffer. If the changes return on the buffer it is possible to rollback not from thedisk.
Let me tell you the difference between DDL,DML,TCL and DCL:
DDL COMMANDS:CREATE,ALTER,DROPAND TRUNCATEARECALLED DDL COMMANDS. They are calledData Definition since they are used for defining the data. That is the structure of thedata is known through these DDL commands.
DML COMMANDS:DML commands are used for data manipulation. Some of the DML commandsinsert,select,update,delete etc. Even though select is not exactly a DML languagecommand 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 useTCL. Some of the TCL commands are:1. ROLLBACK2. 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.
8/8/2019 AbdulQader-MCA Dbms LAB
19/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 19
Commit and Rollback are generally used to commit or revoke the transactions that arewith regard to DML commands.
DCL:Data Control Language is used for the control of data. That is a user can access anydata based on the priveleges given to him. This is done through DATACONTROLLANGUAGE. Some of the DCL Commands are:1. GRANT2. 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 commandsincluding DELETE, INSERT, SELECT, and UPDATE. DML SQL statements have only minordifferences 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 adatabase, including rows, columns, tables, indexes, and database specifics such as
file locations. DDL SQL statements are more part of the DBMS and have largedifferences 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 andpermissions of the objects or parts of the database(s). DCL SQL statements are alsomore part of the DBMS and have large differences between the SQL variations. DMLSQL 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.
8/8/2019 AbdulQader-MCA Dbms LAB
20/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 20
AALLLL SSQQLLCCOOMMMMAANNDDDDEETTAAIILLSS
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):=
8/8/2019 AbdulQader-MCA Dbms LAB
21/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 2
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
8/8/2019 AbdulQader-MCA Dbms LAB
22/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 22
ALTER ROLLBACK SEGMENT AUDIT CREATE PROCEDURE
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
8/8/2019 AbdulQader-MCA Dbms LAB
23/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 23
SELECT
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
DData TTypes 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 2553. 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 thenumber of digits to the right of decimal points.
8/8/2019 AbdulQader-MCA Dbms LAB
24/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 24
5. Date: It specifies the date in DD-MM-YY format.
Data definition language (DDL):
Create statement: It is used to create and define a table.
Syntax:
Create table
( [column constraints], [column constraints],...
[column constraints]) ;
Column constraints :
1. Primary Key:It will not allow null and duplicate values correspondingto that column.
2. Not Null : It will allow null values corresponding to that column3. 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 column6. 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 onetable, corresponding values in other table will be deletedautomatically, and it will work only references only.
Example 1:
8/8/2019 AbdulQader-MCA Dbms LAB
25/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 25
Create a table employee with employee no as primary key, namefield not be left empty, salary greater than 2000,job field not to be left
empty,deptno is foreign key taken from dept table.
Example 2:
Create dept table with deptno as primary key and deptname 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.
8/8/2019 AbdulQader-MCA Dbms LAB
26/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 26
Example 4: Create project table.
SQL>Create table Project(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. Whencreating a table based on existing table then it is going to transfer only notnull 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 EmpdAs select * from Employee
Where deptno=10;Alter Statement: It is used to alter the definition of a table in the database
Syntax:
Alter table Add column_name data_type [Modify column_name data_type ];
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
8/8/2019 AbdulQader-MCA Dbms LAB
27/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 27
SQL>Alter table Employee
Add(Phno number(7));
Example 2: Adding empno as primary key to Emp table
SQL>Alter table EmpAdd(Primary key(empno));
Modify: is used to change the size of the column of the same datatype.Modify will not decrease the column size.Whenever it comes toincrease 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 noreferences are there from other tables.
SQL>Alter table EmpDrop Primary key;
Drop command: is used to drop the table.
Syntax:Drop table;
Example 1: Dropping emp table.
SQL>Drop table emp;Describe command: is used to display the structure of the table.Desc canalso be used
8/8/2019 AbdulQader-MCA Dbms LAB
28/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 28
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 ofdata values is less, then specify the column names into which data is being
entered. To insert null values, NULL can be used.Syntax:Insert
intovalues(datavalue_1,..,datavalue_n);
Insert into(column_1,column_3)Values(datavalue_1,datavalue_3);
Example 1: Insert 100th record into employee table.
SQL>insert into employeeValues(100,James,6000,17-Mar-03);
Example 2: Inserting 101th record into employee table with salary and dateOf joining as null values.
SQL>Insert into employeeValues(101,James,null,null);
8/8/2019 AbdulQader-MCA Dbms LAB
29/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 29
Example 3: Inserting 1001th record into employee table with only empnoand name.
SQL>Insert into employee(empno,ename)Values(1001,John);
Insert with select: is used to transfer the data from one table to anothertable.Syntax:
Insert intoSelect , from Where;
Example 1:
SQL>Insert into empSelect empno,ename,sal from employeeWhere deptno=10;
Delete Command: is used to delete the records from the specified table.Syntax:
Delete Where;
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 Set = ,
8/8/2019 AbdulQader-MCA Dbms LAB
30/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 30
.
.
.Where ;
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%ofsalarySQL> 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.1000SQL> update employee set sal = sal*1.1 where sal insert into employee( empno, ename) values (200, smith);SQL> commit ;
8/8/2019 AbdulQader-MCA Dbms LAB
31/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 3
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 updSQL> 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 saveimplicitly 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>, .. , from
8/8/2019 AbdulQader-MCA Dbms LAB
32/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 32
where ;Example 1: To display the deptno,dname,loc.
Example 2: To display all the employee details,who are working asmanager.
SQL>Select * from emp where job-manager;
Logical Operators:
y And
y Or
y NotExample 1: To display the employee information who are working in deptno10 and salary greater than 2000.
SQL>select * from empWhere deptno=10 and sal>2000;
Example 2: To display the employee information who are working asmanager corresponding to deptno 20.
SQL>select * from empWhere job=manager and depno=20;
Example 3: To display the employee information who are working indeptno 10,20.
SQL>select * from empWhere deptno=10 or dept=20;
8/8/2019 AbdulQader-MCA Dbms LAB
33/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 33
Example 4: To display the employee information who are working asmanagers corresponding to deptno 10 as well as the employees who are
receiving salary more than 2000 corresponding to deptno 20.
SQL>select * from empWhere job=manager and deptno=10;
Special Operators:
Is null In
Between like
is null: is used to check the null values correspondingto the column.
Example 1: To display the employee information who are not receiving anycommission.
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 greaterthan 1000 and less than 2000.
SQL>select * from empWhere sal between 1000 and 2000;
Example 2: To display the employee information for those who are workingfor deptno 10 with their first alphabet of the name is coming in the range ofe to j.
SQL>select * from empWhere deptno=10 and(ename between E and J);
8/8/2019 AbdulQader-MCA Dbms LAB
34/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 34
In: When you have multiple conditions among which any one has tobe
selected we use in operator.Example 1: To display the employee details who are working as managers,clerks ,analyst.
SQL>select * from empWhere job in(manager,clerk,analyst);
Example 2:To display the employee who are working in the deptno10,20,30.
SQL>select * from empWhere deptno in (10,20,30);
Like: is used when you want to frame a condition based on aparticular 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 withs.
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 secondcharacter 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 anycommission.
8/8/2019 AbdulQader-MCA Dbms LAB
35/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 35
SQL>select * from empWhere comm. Is not null;
Example 2:To display employee information for whose who are working asmanagers and receiving salary other than the range 2000 to 3000.
SQL>select * from empWhere job=manager and sal not between 2000 and 3000;
Example 3:To display the employee details who are working in dept otherthan 20,30.
SQL>select * from emp
Where deptno not in (20,30);
Example 4:To display the employee details who are working in deptno10,20 for their names not ending with s.
SQL>select * from empWhere deptno in(10,20) and ename not like %s;
In built functions: Are classified into five types
o Number Functions
8/8/2019 AbdulQader-MCA Dbms LAB
36/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 36
o Character Functionso 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 employeesof the organizations.
SQL>select sum(sal) from emp;Example 2: Find the sum of salary and commission paid to theemployees of deptno 10.
SQL>select sum(sal+comm.) from empWhere 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 theempty 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 inthe organization.SQL>select count(*) from emp
Where job in(manager,clerk);
8/8/2019 AbdulQader-MCA Dbms LAB
37/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 37
4.count(expr): Is used to count the no.of records will the expr issatisfied.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.
SQL>select count(comm.) from emp;Example 2: Find the no.of employees who are receiving the commissioncorresponding to deptno.10,20.
SQL>select count(comm) from empWhere deptno=10 or deptno=20;
5.max(expr): Is used to find the maximum value for the mentionednumerical 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 numericalattribute.Example: find the employees who is paid the least salary.
SQL>select min(sal) from emp;
8/8/2019 AbdulQader-MCA Dbms LAB
38/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 38
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 forTemporary 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;
8/8/2019 AbdulQader-MCA Dbms LAB
39/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 39
4.mod(m,n): Is used to find the remainder after dividing m by n.SQL>select mod(5,2) from dual;
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.
8/8/2019 AbdulQader-MCA Dbms LAB
40/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 40
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;
3. substr(str,pos,n): Returns the substring from the string from positionpos 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;
8/8/2019 AbdulQader-MCA Dbms LAB
41/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 4
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 givendata.Sysdate gives the system date.
SQL>select sysdate from dual;SQL>select add_month(sysdate,3) from dual;
8/8/2019 AbdulQader-MCA Dbms LAB
42/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 42
2. months between(date1,date2): Returns the no.of months between
the two dates mentioned.Date1 is maximum value and date2 isminimum value.The output of this function is either float or integervalue.
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 datementioned.
SQL>select last_day(sysdate) from dual;
Group by clause: Is used to group a set of repeated values correspondingto a particular column for which we want to apply group function.
Example 1: To display the deptno. And total salary in each dept.
8/8/2019 AbdulQader-MCA Dbms LAB
43/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 43
SQL>select deptno,sum(sal) from emp
Group by deptno;Example 2: To display the depts highest,lowest salary and no.ofemployees in each dept.
SQL>select deptno,max(sal),min(sal),count(*) fromemp group by deptno;
Example 3: To display the no.of employees receiving commissioncorresponding to deptno 10,20 with their deptno.
SQL>select deptno,count(comm.) fromEmp where deptno=10 or deptno=20Group by deptno;
8/8/2019 AbdulQader-MCA Dbms LAB
44/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 44
Having Clause: Is used when we want to frame the condition of salary isgreater than cannot be used with where clause.
Example 1: To display the deptno.s for which total amount of salary isgreater than 10,000.
SQL>select deptno,sum(sal) from empGroup by deptnoHaving sum(sal)>10000;
Example 2: To display the deptno.s along with their total salary forwhich total salary is greater than 10,000 corresponding to deptno 10,20.
SQL>select deptno,sum(sal) from empWhere deptno in (10,20)Group by deptnoHaving sum(sal)>10000;
Example 3 : To display the jobs along with the no.of employeesworking ,provided the highest salary corresponding to the job is greaterthan 3000 as well as the no.of employees working is more than 3.
SQL>select job,count(*) from empWhere deptno in (10,20,30)
Group by jobHaving max(sal)>2000 and count(*)>2;
8/8/2019 AbdulQader-MCA Dbms LAB
45/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 45
Order by clause: Is used when we want to display the data in a sortedorder.
1. Ascending order |asc| (default ordering)2. Descending |desc|
Example 1: To display the employee information in the ascending orderof the empno.
SQL> select * from empOreder by empno;
Example 2: To display the employee information in the descendingorder of the salary.
SQL>select * from empOrder by sal desc;
Example 3: To display the employee information in the ascending order
of the deptno,descending order of salary.SQL>select * fromemp
Order by deptno,sal desc;
8/8/2019 AbdulQader-MCA Dbms LAB
46/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 46
Example 4: To display the depts along with their total payment
corresponding to deptno 10,20,30 for which n0.of employees areworking is more than 2 and display based on the descending order oftotal salary.
SQL>select deptno,sum(sal) from empWhere deptno in (10,20,30)Group by deptnoHaving count(*)>2Order by sum(sal) desc;
SET OPERATORS:
y Union
y Intersection
y Minus
1. union: Is used to take distinct rows from more than one selectstatement.By using union all the duplication is not removed.
8/8/2019 AbdulQader-MCA Dbms LAB
47/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 47
Example 1: To display in deptno the jobs. 10 or 20.
SQL>select job from empWhere deptno=10UnionSelect job from empWhere deptno=20;
Example 2: To display the jobs from emp.SQL>select job from emp
Where deptno=10
Union allSelect job from empWhere deptno=20;
2.intersect: Is used to take commonrows from more than one selectstatement.Example 1: To dispalyb the jobs in deptno. 10 and 20.
SQL>select job from empWhere deptno=10Intersect
Select job from empWhere deptno=20;
Example 2:To disaply the jobs in deptno. 10 and (20 or 30).SQL>select job from emp
Where deptno=10Intersect(select job from empWhere deptno=20
UnionSelect job from empWhere deptno=30);
2. minus: Is used to select the rows from more than first selectstatement which are not in the second statement.
8/8/2019 AbdulQader-MCA Dbms LAB
48/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 48
Example 1: To display the jobs in deptno.10 and not in 20.
SQL>select job from empWhere deptno=10MinusSelect job from empWhere deptno=20;
Example 2: To list the jobs which are unique to dept 10 as compare to 20and 30.
SQL>(select job from empWhere deptno=20
UnionSelect job from empWhere deptno=30)Minus(select job from empWhere deptno=10);
8/8/2019 AbdulQader-MCA Dbms LAB
49/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 49
SUB QUERIES(or)NESTED QUERIES: when we are using more than oneselect statement to perform particular operation then we will be calling it asa subquery.In subquery the inner statement will be executed first and onlynoce as compared to the outer statement.
Syntax: select -----------FromWhere(select ------);
Example 1: To display all the employees information whose salary isgreater than Smiths salary.
SQL>select * from empWhere sal>(select sal from emp
Where ename=SMITH);
8/8/2019 AbdulQader-MCA Dbms LAB
50/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 50
Example 2: To display all the employees information who is receiving the
highest salary.SQL>select * from employee
Where sal=(select max(sal) from emp);
Example 3: To display all the employees information whose job is samelike Smith at the same time salary greater than Allen.
SQL>select * from empWhere job=(select job from emp where
ename=SMITH)And sal>(select sal from empWhere ename=ALLEN);
Example 4:To display all the employees information who is receivingsalary greater than average salary of all the employees.
SQL>select * from empWhere sal>(select avg(sal) from emp);
Example 5:To display the manager no.alng with the no.of employeesworking under him should be maximum no.of employees compared withthe other members.
SQL>select mgr,count(*) from empGroup by mgrHaving count(*)=(select max(count(*) fromEmp group by mgr);
Example 6: To display the employee information under which maximumno.of employees working.
SQL>select * from empWhere empno=(select mgr from emp
Group by mgr)
8/8/2019 AbdulQader-MCA Dbms LAB
51/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 5
Having count(*)=(select max(count(*) fomemp group by mgr);
Example 7: To disaply all the employees information who is receiving thesecond highest salary.
SQL>select * from empWhere sal=(select max(sal) from emp where
Saselect * from empWhere sal>all(select sal from emp
Where deptno=20);
8/8/2019 AbdulQader-MCA Dbms LAB
52/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 52
Views: Views can be defined as a virtual table because it doesnt exist byitself,unless you are having one or more ordinary table on which it will bebased or dependent.The table on which view is based is called as basetable of the view.It is possible to insert,update and delete the data in theview 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.
8/8/2019 AbdulQader-MCA Dbms LAB
53/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 53
Creation of view:
Syntax: create view As select ------ from ;
Example 1: To create a view for emp table with empno,name,salary.
SQL>craerte view empviewAs select empno,ename,sal from emp;
Example 2: To create a view for emp table for dept 10.
SQL>create view d10viewAs select * from emp
Where deptno=10;
Insert into view:
Example 1: Insert a new record into view empview.
SQL>insert into empviewValues(101,WILLIAM,2000);
Viewing the contents of d10view:
Example: To display the contents of d10view.
SQL>select * from d10view;
8/8/2019 AbdulQader-MCA Dbms LAB
54/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 54
Replace: Replace option is used whenever you want to over write theexisting select statement with new select statement.
Example: To create empview with empno,name,salary and deptno.
SQL>replace view empviewAs select empno,ename,sal,deptno from emp;
With check option: When ever you want to restrict the user to insert thrrecords which are satisfying the where condition of the view then we usewith check option.
Syntax: create view As select-----from Where With check option;
8/8/2019 AbdulQader-MCA Dbms LAB
55/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 55
Example : createa view for employee details of deptno. 20
SQL>create view d20viewAs select * from empWhere deptno=20With 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 togenerate the numbers in a particular order (i.e. interval) then we will becalling a sequence.
Syntax: create sequence Start with Increment by Maxvalue Minvalue CacheCycle;
Whenever you want to generate the next number of the sequence then wewill be using nextval and when you want to see the current position of the
sequence we use currval.
Example: SQL>create sequence enoStart with 5Increment by 1Minvalue 5Maxvalue 15Cache 5Cycle;
This is going to create a sequence with name eno starting with5,incrementing by 1,minimum value is 5,maximum value is 15,cache is 5and with cycle.
Altering the sequence: whenever you want to change any options relatedt
To existing sequence then we will be using Alter.
8/8/2019 AbdulQader-MCA Dbms LAB
56/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 56
Note:start with cannot be changed using Alter.
Syntax: alter sequence ;
Example: SQL>alter sequence enoIncrement by 2Minvalue 10Maxvalue 100;
Drop sequence: Whenever you want to drop a sequence we use dropstatement.
Syntax: drop sequence
Example: SQL>drop sequence eno;
INDEX: Whenever you to retrieve the records faster corresponding to onecondition then we will be using Indexing concept.
Before going to index,identify the fields which will beusing mostly in the where clause then indx on those fields.Apply indexwhen 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 on ();
1. Simple index: Is used when indexingis based on the column of thetable.
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 implementingunique constraint along with indexing.
Example : SQL>create unique index iph on emp(phno);
8/8/2019 AbdulQader-MCA Dbms LAB
57/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 57
3. concatenated index: Is used when indexing is based on more thanone column as a combination.
Example: SQL>create index ds on emp(deptno,sal);
Delete index: drop statement is used
Example: SQL>drop index idept;
WWhhaatt IIss TThhee DDiiffffeerreennccee BBeettwweeeenn SSQQLL aanndd PPLL//SSQQLL??
There are so many variants of SQL that it is hard sometimes to figure out what to use. Here is ashort 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 ManipulationLanguate or DML. All of the above are just a fancy way to say that with SQL, the user canboth
view and alter records in the database. To help, here are a couple ofqueries:
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 answeris from the PL/SQL User Guide:
PL/SQL, Oraclesprocedural extension of SQL,is an advanced fourth-generation programminglanguage (4GL). It offers software-engineering features such as data encapsulation, overloading,
8/8/2019 AbdulQader-MCA Dbms LAB
58/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 58
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 doall of the things that regular SQL can do,but also,it is procedural and can be used like aprogramming language (C++, Java, etc.) Forinstance, 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 nativeprogramming language that provides database-centric application development. Itcan natively call static SQL and provides multiple methods of calling dynamic SQL.
DIFFER:
SQL is a data oriented language for selectingand manipulating sets of data. PL/SQL is a
procedural language to create applications. You dont normally have a SQL application. Younormally 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 maybe the source of data foryour screens, webpages and reports. PL/SQL might be the language you use to build, format and
display those screens, webpages and reports.
WWhhaatt IIss DDyynnaammiicc SSQQLL??
Most PL/SQL programs do a specific,predictable job. For example,a stored procedure might
accept an employee numberand 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 notchange from execution to execution. So, they are calledstatic SQL statements.
However, some programs must build andprocess a variety of SQL statements at run time. For
example,ageneral-purpose report writermust build different SELECT statements for the various
reports it generates. In this case, the full text of the statement is unknown until run time. Suchstatements 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 yourprogramat run time. Such
strings must contain the text ofa valid SQL statement or PL/SQL block. They can also containplaceholders forbind arguments. Aplaceholderis an undeclared identifier, so its name, to which
you must prefix a colon, does not matter. For example, PL/SQL makes no distinction betweenthe following strings:
8/8/2019 AbdulQader-MCA Dbms LAB
59/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 59
'DELETE FROM emp WHERE sal > :my_sal AND comm < :my_comm''DELETE FROM emp WHERE sal > :s AND comm < :c'
To process most dynamic SQL statements, you use the EXECUTEIMMEDIATE statement. However,
to process amulti-row query (SELECT statement), you must use the OPEN-FOR,FETCH,and CLOSEstatements.
(OORR)
Dynamic SQL is an extended form ofembedded SQL that allows more generalpurposeapplication. Dynamic SQL is used
when part or all of the SQL statement isunknown at compile-time EXECUTE IMMEDIATE PREPARE and EXECUTE Placeholders can be used to pass values toEXECUTE/FETCH statements
The Need for Dynamic SQL
You need dynamic SQL in the following situations:
y You want to execute a SQL data definition statement (such as CREATE),a data control
statement (such as GRANT), ora session control statement (such as ALTERSESSION). InPL/SQL, such statements cannot be executed statically.
y You want more flexibility. For example, you might want to defer your choice of schema
objects until run time. Or, you might want yourprogram to build different search
conditions for the WHERE clause ofaSELECT statement. A more complexprogrammight
choose from various SQL operations, clauses, etc.
y 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 assupport for objects and collections.
(OORR)
Dynamic SQL:
8/8/2019 AbdulQader-MCA Dbms LAB
60/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 60
Static SQL
Allowingaccess to the database using thenormal interactive SQL statements, with
minormodifications in some cases.
The pattern of database access is fixed
and canbe 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 ofembedded SQL is Static SQL does not allow hostvariables to be used in place of table names orcolumn names For example, in static SQL we can not write: EXEC SQL BEGIN DECLARE SECTIONchar TableName[20];EXEC SQL END DECLARE SECTION;EXEC SQL INSERT INTO :TableNameVALUES (S1, Simth, 24) EXEC SQL DECLARE cursor1 CURSOR FORSELECT * FROM :TableName
Problems * indicates that all columns from the table,
TableName, but the number of columns willvary with the choice of table. Data types of the columns will vary betweentables But if we do not know the number and datatype, we can not use FETCH statement
Dynamic SQL can overcome these problems
8/8/2019 AbdulQader-MCA Dbms LAB
61/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 6
and allow more general-purpose software tobe developed.
The EXECUTE IMMEDIATEStatement:
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=SL21Dynamic SQL:
EXEC SQL BEGIN DECLARE SECTION;
charbuffer[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 ofa 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';
BEGINsql_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;
8/8/2019 AbdulQader-MCA Dbms LAB
62/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 62
The next example illustrates the use of objects and collections. Suppose you define object type
Personand VARRAY type Hobbies,as follows:
CREATE TYPE Person AS OBJECT (name VARCHAR2(25), age NUMBER);CREATE TYPE Hobbies IS VARRAY(10) OF VARCHAR2(25);
EEmmbbeeddddeedd SSQQLL
Embedded SQL statements
ISO standard specifies embedded support for Ada, C,COBOL, Fortran, Pascal, PL/1.
TTyyppeess ooffeemmbbeeddddeedd SSQQLL:: Static embedded SQL, where the entire
SQL statement is known when the
programis written
Dynamic embedded SQL, which allows
all orpart of the SQL statement to be
specified at runtime
Dynamic SQLprovides increased
flexibility and helps produce more
general-purpose software
SSiimmppllee EEmmbbeeddddeedd SSQQLL SSttaatteemmeennttss
Simplest types of embedded SQL statements
are those that do not produce any queryresults Non-select statement, INSERT, UPDATE,DELETE, CREATE TABLE.
SSoommee ccoommmmeennttss ffoorrtthhee eexxaammpplleeEmbedded SQL statements start with
keyword EXEC SQL
8/8/2019 AbdulQader-MCA Dbms LAB
63/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 63
Embedded SQL statements end with aterminator thats dependent on host language
C, PL/1, Ada ----; COBOL ---- END-EXEC
An embedded SQL statement can appearanywhere that an executable host languagestatement can appear
The embedded statements are same as ISQL
PPrroocceessssiinngg PPrrooggrraammss wwiitthh EEmmbbeeddddeedd SSQQLL::--
EEmmbbeeddddeedd SSQQLL AApppplliiccaattiioonn
8/8/2019 AbdulQader-MCA Dbms LAB
64/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 64
RRuunnnniinngg::--
RReettrriieevviinngg ddaattaa UUssiinngg EEmmbbeeddddeedd SSQQLLEmbedded SQL divides queries into two
groups: Single-row queries, where the query resultcontains at most one row of data Multi-row queries, where the query result maycontain an arbitrary number of rows, whichmay be zero, one, more.
8/8/2019 AbdulQader-MCA Dbms LAB
65/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofComputerSciences(NICS) ( SQL , PL/SQL PROGRAMMING )
D B M S = L A B - V { N O V / D E C - 2 0 0 9 } M . C . A I I / I - - - DD BB MM SS (( LL AA BB )) RR EE CC OO RR DD Page 65
PPLL//SSQQLL ((PPrroocceedduurraall LLaanngguuaaggee uussiinngg ssqqll))
PL/SQL can be called the extension of SQL where it is going to support theSQL statement along with the processing statement we will be calling it asProcedural Language.
(OR)PL/SQL is Oracle's Procedural Languageextension to SQL.
PL/SQL has many programminglanguage 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.
PPLL//SSQQLL BBlloocckkA PL/SQL block contains logically
related SQL and PL/SQL statements.Three sections in a typical PL/SQL block:
declaration (optional): declareidentifiers (variables and constants).
execution (required): execute SQL andPL/SQL statements.
exception (optional): perform errorhandling.
Execute PL/SQL ProgramSave the program in a file: sample1.sqlExecute the program in SQL*Plus
SQL> start sample1Enable output to the screen:
SQL> set serveroutput onor place set serveroutput on at the
8/8/2019 AbdulQader-MCA Dbms LAB
66/124
HYDERABAD NAME= Shaaik Abduul Qaadeerr OLL NO=060-09-
Contact me=9700064061
NizamInstitute ofCompu