Beruflich Dokumente
Kultur Dokumente
By
Dinesh PV
Oracle supports this in/keep/out approach and provides c lever tools that
allow you considerable sophistication in how the data is captur ed, edited,
modif ied, and put in; how you keep it securely; and how you get it out to
manipulate and report on it.
Ancient Times: Hum an beings began to store inf ormation ver y long ago. In
the ancient t imes, elaborate database systems were developed by
government off ices, librar ies, hospitals, and business organizations, and
some of the basic pr inciples of these systems are still be ing used today.
1960s: Computer ized database started in the 1960s, when the use of
computers became a more cost -eff ective option f or private or ganizat ions.
There were t wo popular data models in this decade: a network model called
CODASYL and a hierarchical model called IMS. One database system that
proved to be a commercial success was t he SABRE system that was used by
IBM to help American Air lines manage it s reser vat ions data .
Heirarchical Model
In a hier archical model , data is organized into a tree- like structure, implying
a single parent f or each record. A sort f ield k eeps sibling records in a
particular order. Hier archical structures were widely used in the early
mainf rame database management system s, such as the Inf ormation
Management System (IMS) by IBM, and now describe the structure
of XML documents. This structure allows one one -to-many relationship
bet ween t wo t ypes of data. This structure is ver y ef f icient to describe many
relat ionships in the r eal wor ld; recipes, t able of contents, ordering of
paragraphs/ verses, any nest ed and sorted inf ormation.
This hierarchy is used as the physical order of records in stor age. Record
access is done by navigating downward t hrough the data structure
using pointers combined with sequential ac cessing. Because of this, the
hier archical structur e is inef f icient f or certain dat abase oper ations when a
f ull path (as opposed to upward link and sort f ield) is not also included f or
each record. Such limitations have been compensated f or in later I MS
ver sions by additional logical hierarchies imposed on the base physical
hier archy.
Network Model
The net work model expands upon the hier archical structure, allowing many-
to-many relat ionships in a tree - like struct ure that allows multiple parents. It
was most popular bef ore being replaced by the relational model, and is
def ined by the CODASYL specif icat ion.
The net work model organizes data using two f undamental concepts,
called records and sets. Records contain f ields ( which may be organized
hier archically, as in the programming language COBOL). Sets (not to be
conf used with mathematical sets) def ine one-to-many relat ionships bet ween
records: one owner, many members. A record may be an owner in any
number of sets, and a member in any number of sets.
A set consists of circular linked lists wher e one record t ype, the set owner or
parent, appears once in each circle, and a s econd record t ype, the
subordinate or child, may appear multiple times in each circle. In this way a
hier archy may be est ablished bet ween any t wo record t ypes, e.g., type A is
the owner of B. At the same time another set may be def ined where B is the
owner of A. Thus all the sets compr ise a general directed graph (ownership
def ines a direct ion), or network construct . Access to records is either
sequential (usuall y in each recor d t ype) or by navigation i n the circular
linked lists.
The net work model is able to represent redundancy in data more eff icient ly
than in the hierarchical model, and there can be more than one path f rom an
ancestor node to a descendant. The oper ations of t he net work model are
navigational in st yle: a program maintains a current posit ion, and navigates
f rom one record to another by f ollowing the relationships in which the record
participates. Records can also be located by supplying key values.
Although it i s not an essent ial f eature of the model, net work databases
generally implement the set relationships by means of pointer s that direct ly
address the locat ion of a record on disk. This gives excellent retrieval
perf ormance, at the expense of operations such as database loading and
reorganization.
Popular DBMS pr oducts that utilized it were Cincom Systems ' Total
and Cullinet's IDMS. IDMS gained a consider able customer base; in the
1980s, it adopted the relat ional model and SQL in addit ion t o its orig inal
tools and languages.
Most object databases (invented in the 1990s) use the navigational concept
to provide f as t navigation across net works of objects, generally using object
identif iers as "smart" point ers to related objects. Objectivit y/DB, f or
instance, implement s named one -to-one, one-to-many, many- to-one, and
many-to-many named relat ionships that can cross databases. Many object
databases also support SQL, combining the strengths of both models.
1970 to 1972: E. F. Codd published an important paper to propose the use of
a relat ional database model, and his ideas changed the way people thought
about databases. In his model, the database’s schema, or logical
organizat ion, is disconnect ed f rom physical inf ormation storage, and this
became the standar d principle f or database systems.
1970s: Two major relational dat abase system prot otypes were created
bet ween the years 1974 and 1977, and t hey wer e the Ingres, which was
developed at UBC, and System R, created at IBM San Jose.
Ingres used a quer y language known as QUEL, and it led to t he creat ion of
systems such as Ingres Corp., MS SQL Server, Sybase, W ang’s PACE, and
Britton-Lee. On the other hand, System R used the SEQ UEL query language,
and it contributed to the development of SQL/DS, DB2, Allbase, Oracle, and
Non- Stop SQL. It was also in this decade that Relational Database
Management System , or RDBMS, became a recognized term.
Early 1990s: Af ter a database industry shakeout, most of the sur viving
companies sold com plex database pr oducts at high prices. Ar ound this time,
new client tools f or application developm ent were released, and these
included the Oracle Developer, PowerBuilder, VB, and ot hers. A number of
tools f or personal pr oduct ivity, such as O DBC and Excel/Access, were also
developed. Protot ypes f or Object Database Management Syst ems, or
ODBMS, were cr eated in the early 1990s.
Mid 1990s: The advent of the Internet led to exponential growt h of the
database industry. Aver age desktop user s be gan to use client -server
database systems to access computer systems that contained legacy data.
Then there are many changes to Relati onal Dat abase like
1) Object Oriented database model
2) Dimensional mode l
3) Multival ve Model
W hat is a business?
Business is a collection of real world ent ities and its activities.
BUSI NESS
|
---------------------------------------------------------------------------------------------
| | | |
{emps depts Products/ customers} -----------> [entities/
Objects]
ser vices
Day-By- Day the business may impr ove , means need more number of
business resources and there is an incr ease in number of transacti ons. In
this case we need the automated Business syst em called DBMS, to maintain
business data and it s activities automat ically.
D AT A B ASE CONCEPTS :
D AT A:
Collection of inf ormation of any one Business ent it y is known as data.
[One line of inf ormation]
D AT A B ASE:
It is sof tware which stores and manages the collection of inf ormation of all
objects in the business.
Technically, it is collection of programs and each program is responsible f or
perf orming a specif ic task.
RDBMS:
Author of RDBMS I S E.F. CODD and he invented 12 Rules f or an RDBMS.
Collection of interrelated data of all inter related objects with in the business
is kno wn as RDBMS.
The relation bet ween the tables is implem ented by using Ref erential integrit y
constraints.
In any RDBMS
Data stored in the f orm of 2 -dimensional tables
A table is a collection of rows and colum ns.
A row is known as record (collection of columns)
A column is known as a f ield
Tables of Information
Oracle stores inf ormation in tables. Each of these tables has one or more
columns. The inf ormationis stor ed row after row. Each unique set of data
gets its own row.
Oracle avoids specialized, academ ic terminolog y in order to m ake the
product more
approachable. In research papers on relational theor y, a column may be
called an “attribut e,” a row may be called a “tuple” and a table may be
called an “entit y.”
For an end user, however, these terms are unnecessar y.
Prod_Dtls
PID PN AM E COST MFG WARRENTY
P001 Mobile 14000 22-oct-14 1 year
P003 Desktop 27000 14-may-15 3 years
P006 Laptop 35990 11-may-12` 2 years
P004 Tablet 12000 21-mar-13 1 year
P005 Smart phone 37000 10-oct-15 1 year
Comp_Dtls
Prod_Dtls
Pid Pname Cost Mfg Warrent y
Comp_Code
P001 Mobile 14000 22-oct-14 1 year Cmp1
P003 Desktop 27000 14-may- 3 years Cmp2
15
P006 Laptop 35990 11-may- 2 years Cmp1
12`
P004 Tablet 12000 21-mar-13 1 year Cmp1
P005 Smart 37000 10-oct-15 1 year Cmp2
phone
Advantages:
W e can maintain integrity among table data
W e can f etch accurate and complete data.
These rules can be applied on any dat abase syst em that manages stored
data using only its r elat ional capabilit ies. This is a f oundat ion rule, which
acts as a base f or all the other rules.
BUSINES
INDIA USA UK
USER
WEB PAGE WEB PAGE WEB PAGE
INTERFACES
OLTP
ORACLE SQL DB2
RDBMS
SERVER
EXTRACTION TRANSFORMATION
LOADING
OLAP
DATA WARE HOUSE RDBMS
REPORTING
OBIEE BO COGNOS SSRS TOOLS
Founding of Oracle
Oracle8 was released in 1997 as the obj ect -relat ional database,
support ing many new data t ypes. Addit ionally, Orac le8 supported
partit ioning of large tables.
Database instance
For each user connection to the inst ance, a client process r uns the
application.
Each client process is associated with its own server process.
The server process has its own pr ivat e session memor y, known as
the program global area (PG A) .
Oracle Instance and Database
A database can be considered f rom both a physical and logical perspect ive.
Physical dat a is data viewable at the oper ating system level. For example,
operat ing system utilities such as the Linux ls and ps can list database f iles
and processes. Logical data such as a table is meaningf ul only f or the
database. A SQL statement can list the t ables in an Oracle database, but an
operat ing system utilit y cannot.
In this section, you will be installing the Oracle Database and creating
an Oracle Home User account.
Expand the dat aba s e folder that you extracted in the previous section.
Double-click setup.
Click Yes in the User Account Control window to continue with the
installation.
In this OBE, we create and configure the database. Select the Create
and configure a database option and click Next.
The System Class window appears. Select Desktop Class or Server
Class depending on the t ype of system you are using. In this OBE, we
will perform the installation on a desktop/laptop. Select Desktop
class and click Next.
The Oracle Home User Selection window appears. Starting with Oracle
Database 12c Release 1 (12.1), Oracle Database on Microsoft Windows
supports the use of an Oracle Home User, speci fied at the time of
installation. This Oracle Home User is used to run the Windows services
for a Oracle Home, and is similar to the Oracle User on Oracle Database
on Linux. This user is associated with an Oracle Home and cannot be
changed to a different u ser post installation.
Note:
Select the Create New Windows User option. Enter the user name
as OracleHomeUser1 and password as Welcome1. Click Next.
field and then the balloon icon ( )to know more about the field.
Note that by default, the installer creates a container database along
with a pluggable database called " pdb orc l ". The pluggable database
contains the sample HR schema. Change the Global database name
to or cl . Enter the "Administrative password" as Oracle_1. This
password will be used later to log into administrator accounts such
as SYS and SYS TEM . Click Next.
The prereq uisite checks are performed and a Summary window appears.
Review the settings and click Install.
The Finish window appears. Click Close to exit the Oracle Universal
Installer.
Verifying the Installation
Navigate
to C: \a pp \ Ora cle Ho meUs er1 \pr odu ct \1 2.1. 0 \d bho me_ 1 folder.
This folder is the new "Oracle Home" created by the installer and
contains software files related to the database.
View the tnsnames.ora File
Navigate
to C: \a pp \ Ora cle Ho meUs er1 \pr odu ct \1 2.1. 0 \d bho me_ 1 \ NE TWOR K \
ADMI N . Double-click tnsnames.ora to view the network configuration
settings.
You see that a connect alias called " OR CL " has been created. This
" ORC L " alias points to the container database with the service name
" ORC L ".
Create a database connect alias called " P DBOR CL " and specify the
network configuration settings to access the pluggable database
" PDB ORC L " that we created during installation. Copy the following
code and paste it in the tnsnames.ora file. If necessary, modify the
host and port to match the values in the O RCL alias.
PDBO RCL =
(D ESC RIP TIO N =
(AD DRE SS = (P ROTO COL = TCP )( HO ST = lo cal hos t) (P ORT =
1521 ))
(CO NNE CT_ DA TA =
( SER VER = D EDIC ATE D)
( SER VIC E_ N A ME = pd bor cl)
)
)
Types of users: 2
W e can devide the users of data base as f ollows.
Parts of Oracle
1) SQL
2) PL/SQL
Oracle’s quer y langua ge has structure, just as English or any other language
has structure. It has rules of grammar and syntax, but they ar e basically the
normal rules of careful English speech and can be readily understood.
SQL * PLUS is a def ault client tool and acts as an interf ace bet ween
client and database.
SQL Def :
It is a collection of pre def ined commands and constructs wit h
syntactical rules .
Request processed on
Client SQL DB
Query
Output
1. Sql is a client tool to interact wi th ORACLE DB /any DB
2. Sql is to be installed in to the system whenever we have inst alled the
db sof twar e.
3. Client [Technical] requests should be submitted in the f orm of
"Queries".
4. Queries ar e executed by SQL ST MT EXECUTOR ( Oracle Db Engine )
5. Queries ar e executed against database and output will be displayed on
the Sql * plus window.
SQL COMMANDS
Types of SQL commands:
CREATE
ALTER
DROP
TRUNCATE
RENAME
These commands ar e u sed to enter new data/ chang ing exist ed data /
deleting the dat a f rom table.
INSERT
UPDATE
DELETE
Used to control the access of data base objects . These commands are used
by DBA (database administrator)
GRANT
REVO KE
5) TCL (TRANSACTION CONTROL LANGUAGE) CO MMANDS
N AVIG ATION:
This navigation is usef ul to open sql * plus window
Then it opens Sql command window, then submit user credent ials.
DBA ( Data Base Administrator) can CREATE and DELETE and manage user
accounts
NOTE:
User name is not case sensitive, but password is case sensit ive f rom oracle
11g onwards
username: system
password: manager
Hoststring: orcl / oracle -----> It is the database ser vice name.
In this window, the DBA has to writ e queries to create user account.
User created.
3) Giving permissions t o use the resources of data base
Grant succeeded.
username: dinesh
password: welcome
Hoststring: orcl
LOG ON PROCEDURE:
Or
Double click SqlPlus Command window
username: pv
password: welcome
hoststring: oracle / orcl
SQL>_
In the sql window, type the command EXIT. It disconnects t he current user
f rom the data base and it close the sql window.
Ex: SQL>EXIT;
1) Connect as DB A?
Connected.
SHOW USER;
SHOW CON_NAME;
Note:
If it is CDB$ROO T, THEN CH ANG E I T TO “PDBORCL” [ Pluggable
DataBase ].
D AT A MO DEL
For any OLTP RDBMS the data model is E-R ( Ent it y-Relat ionship ) Model.
Create an Ent it y-Relationship (ER) model is to visually r epresent the
structure of a business database, where data equates to ent it ies (or objects)
that are linked by def ined relat ionships expr essing dependencies and
requirements. By nat ure it is an abstract visualization, the f irst step in the
design process towards creating a logical and f unctional dat abase.
Ex : emp<-->dept;
company<-->product ;
prod<-->sales ;
1) CRE ATE
It is used to create any data base object like tables , views, indexes,
sequences, synonym s, users, f unctions, procedures, triggers, packages and
so on.
Naming Rules
Rules to f ollow bef ore specif ying names (Object names, Column Names and
Variable Names).
Ex: Emp123
Emp_o11
v) Pre def ined keywords (Reser ved W ords) are not allowed as names.
The data type represents the t ype of data to be entered into a column and
Db engine can assign memory f or the value entered into the column.
These data t ypes support alphabets, digits and any sym bol f rom
keyboard.
1) CH AR (size)
It is used to store f ixed length character strings. By def ault the size is
1 character, and max size is 2000 chars or byt es.
Ex: empid, pnr number, bank account numbers, Policy Numbers and so on
3) LONG
It is used to store variable length char data (similar to varchar 2 data type)
but max size is 2 GB
4)NCH AR(size)
It is similar to CHAR(SIZE) data t ype ,but it is used to support any Nat ional
char set.
The NUMBER dat at ype stores f ixed and f loat ing -point numbers. Numbers of
virtually any magnitude can be stored and are guaranteed por table among
dif f erent systems operating Oracle, up to 38 digits of precision.
2) NUMBER (Precision )
It is used to store numbers wit hout decim al point.
12.75
123.1
45621.08
99999.99
125
12560
100
0
10
999999
D ATE
The DATE datat ype stores point -in-time values (dates and t imes) in a
table. The DATE dat atype stores the year (including the cent ury), the mont h,
the day, the hours, the minut es, and the seconds (af ter midnight).
Oracle can store dat es in the Julian era, ranging f rom Januar y 1, 4712 BCE
through December 31, 4712 CE (Common Era). Unless BCE ('BC' in the
f ormat mask) is specif ically used, CE dat e entries are the default.
Oracle uses its own internal f ormat to store dates. Dat e data is stored in
f ixed- length f ields of seven byt es each, corresponding to century, year,
month, day, hour, minute, and second.
For input and output of dates, the standar d Oracle def ault dat e f ormat is DD -
MO N-YY, as below:
'13-NOV-92'
You can change this def ault date f orm at for an instance with the parameter
NLS_DATE_FORM AT . You can also change it during a user session with the
ALTER SESSION st atement. To enter dates that are not in standard Oracle
date f ormat, use the TO_DATE f unction with a f ormat mask:
Note:
Oracle stores t ime in 24 -hour f ormat --HH:MI:SS. By def ault, the time in a
date f ield is 00:00:00 A. M. (midnight) if no time port ion is entered. In a time -
only entr y, the date portion def aults to the f irst day of the current month. To
enter the time portion of a date, use the TO_DATE f unction with a f ormat
mask indicating the time port ion, as in
DD-MON-YY
DD Digits of date
MO N First 3 chars of month name
YY Last 2 digits of year
Ex: 12-may-13
Ex: 12/may/13 --It is not considered as a date f ormat --
1) R AW (size)
It is used to store binar y data like images, thumb impressions, logos
and so on.
Max size is 2000 byt es < 2 KB
2) LONG R AW
It is similar to RAW data t ype but max size is 2 GB
NOTE: Only one long raw type column is allowed per a table.
V) LOB--Large Objects
The LOB datat ypes BLOB, CLO B, NCLOB, and BFILE enable you to
store large blocks of unstructured data (such as text, graphic images, video
clips, and sound wavef orms) up to f our gigabytes in size. They provide
eff icient, random, piece - wise access to the data.
You can perf orm parallel queries (but not parallel DML or DDL) on LOB
columns.
LOB datat ypes diff er from LONG and LONG RAW datatypes in several ways.
For example:
A table can contain multiple LOB columns but only one LONG column.
A table containing one or more LOB columns can be partit ioned, but a
table containing a LONG column cannot be partit ioned.
The maximum size of a LOB is f our gigabytes, but the maximum size of
a LONG is t wo gigabytes.
LOBs support random access to data, but LONGs support only
sequential access.
LOB datat ypes (except NCLOB) can be at tributes of a user -def ined
object type but LO NG datatypes cannot.
Temporary LOBs that act like local variables can be used to perf orm
transf ormations on LOB data. Temporary internal LO Bs (BLOBs,
CLOBs, and NCLOBs) are cre ated in the user's temporar y tablespace
and are independent of tables. For LONG datat ypes, however, no
temporar y structures are available.
SQL statements def ine LOB columns in a table and LOB attr ibutes in a user -
def ined object type. W hen def ining LOBs in a table, you can explicit ly
specif y the tablespace and stor age char acterist ics f or each LOB.
LOB datat ypes can be stored inline ( within a table), out -of -line ( within a
tablespace, using a LOB locator), or in an external f ile (BFILE datat ypes).
LOB TYPES -- 3
The BFILE datat ype stores unstruct ured binar y data in operat ing -system f iles
outside the database. A BFILE column or attribute stor es a f ile locator that
points to an exter nal f ile containing the data. BFILEs can stor e up to f our
gigabytes of data.
BFILEs are read -only; you cannot modif y them. They support only random
(not sequential) reads, and they do not participate in transact ions. The
under lying operat ing system must maintain the f ile int egrity and durabilit y f or
BFILEs. The database administrator must ensure that the f ile exists and that
Oracle processes have operat ing -system read perm issions on the f ile.
Oracle uses a ROW ID datat ype to store t he addr ess (rowid) of every row in
the database.
A single datat ype called the universal row id , or UROW ID, s upports both
logical and physical rowids, as well as rowids of f oreign tables such as non -
Oracle tables accessed through a gateway.
A column of the UROW ID datatype can store all kinds of rowids. The value of
the CO MPATIBLE initialization paramet er must be set to 8.1 or higher to use
UROW ID columns.
Ex:
W rite a query to create emp_inf o table with columns eid, ename, sal, jdate,
desg, and gender wit h appropriat e data t ypes.
INSERT:
It is used to insert new recor ds in to the table. Assigns the values in to
corresponding columns in the column list. If there is no colum n list, the f irst
value is inserted into the f irst column def ined by
the CREATE TABLE statement, the second value is inserted into the second
column, and so on. There must be one value f or ea ch column in the column
list. The datatypes of the values being inserted must be compatible with the
datat ypes of corresponding columns in the column list.
Note:-
Character and date literals in the VALUES list must be enclosed by single
quotes ('). Numeric literals are not enclosed by quotes.
Syntax:
INSERT INTO <table_name>[(col1, col2,. ..., col n)]
VALUES ( val1, val2,. ....,val n);
Note:
i) If number of columns in the table and number of values inser ting in
to the table are equal, then no need to specif y c olumn names while
inserting records.
ii) Char, Varchar2 and date t ype values should be enclosed in Single
Quotes.
iii) If Number of inserting values are less than the number of columns
then we must specif y column names while insert ing records.
INSERT INTO bonus SELECT ename, job, sal, comm FRO M emp
W HERE comm > sal * 0.25;
...
INSERT INTO emp (empno, ename, job, sal, comm, deptno)
VALUES (4160, 'STURDEVIN', 'SECURITY GUARD', 2045, NULL, 30);
...
INSERT INTO dept
VALUES (m y_dept no, UPPER(my_dna me), 'CHICAGO');
Ex:
Insert into emp_inf o
Values('&eno', '&ename', '&sal', '&jdate', '&desg', '&gender');
1 row created.
1 row created.
sql > /
INSERT ALL
The Oracle INSERT ALL st atement is used to add multiple rows with a
singleINSERT statement . The rows can be inserted into one table or
multiple tables using only one SQL command.
Ex:
Say you have a table COLORS wi th this str ucture:
Name Type
---------------- ------------
NAME VARCHAR2(30)
CATEGORY VARCHAR2(10)
Ex:
insert all
into colors(name, category) values('yellow', 1)
into colors(name, category) values('red', 1)
into colors(name, category) values('blue', 1)
into colors(name, category) values('yellow', 2)
into colors(name, category) values('blue', 2)
select * from dual;
NULL V ALUES:
1) Implicit insertion:
If we miss a value in a column the n it is dynam ically maint ains a null value
at that place. To insert like this, we need to specif y column names while
using insert command.
2) Explicit insertion:
Ex:
Insert into emp_inf o
Values (888,'martin', 12000,'salesman',null,null,NULL,Null);
DESCCRIBE / DESC
DESC <Table_Name>;
or
desc emp_inf o;
Ex:
SQL> desc emp;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NOT NULL NUMBER(4)
ENAME VARCHAR2( 10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
CO MM NUMBE R(7,2)
DEPTNO NUMBER(2)
DEFAULT Keywor d
W e can create a table with DEFAULT Clause. W hile inserting data in to table
, we don’t need to enter any v alue in to def ault column. The column is
populated with the value supplied along with DEFAULT keyword.
Syntax:
Example:
Note:-
By Def ault the colum n value is “Hyderabad”.
If we submit a dif f erent value or Null value then the def ault column is
populated with given value.
SELECT
ENAME
----------
SMITH
ALLEN
W ARD
JONES
MARTIN
BLAKE
CLARK
SCOTT
KING
TURNER
ADAMS
ENAME
----------
JAMES
FORD
MILLER
14 rows selected.
SQL>
Ex:
SQL>
Ex:
Display employee join_dates, ename, designit ions and salar ies?
14 rows selected.
SQL>
From above examples , By def ault the column names are output titles in the
output.
W e can also change these output titles as f ollows.
“In this format w e can also maint ain spaces in the titles.”
9 rows selected
Syntax-2
Ex:
EMPNAME SALARY
---------- ----------
SMITH 800
ALLEN 1600
W ARD 1250
JONES 2975
MARTIN 1250
BLAKE 2850
CLARK 2450
SCOTT 3000
KING 5000
TURNER 1500
ADAMS 1100
14 rows selected.
SQL>
Syntax-3
Ex:
SQL> select empno as eid, ename as empnames f rom emp;
EID EMPNAMES
---------- ----------
7369 SMITH
7499 ALLEN
7521 W ARD
7566 JONES
7654 MARTIN
7698 BLAKE
7782 CLARK
7788 SCOTT
7839 KING
7844 TURNER
7876 ADAMS
EID EMPNAMES
---------- ----------
7900 JAMES
7902 FORD
7934 MILLER
14 rows selected.
SQL>
Assignments:
Create the f ollowing tables with your own assumpted relevant column names
and dat atypes.
Clauses
DISTINCT clause
ORDER BY clause
DISTINCT Clause
It will display dif f erent / unique values f rom the column and it will also
display unique recor ds f rom the table.
JOB
---------
CLERK
SALESMAN
PRESIDENT
MANAGER
ANALYST
SQL>
output:
Product ion
Sales
Finance
ORDER BY Clause
This clause is used t o display the column data or table data in ascending /
descending or sorting [ a to z] / reverse sorting [z -a] order.
Note:
i) By def ault it will display a to z data or ascending order dat a.
ii) In case of char data, if there exists upper and lower case data then
order by gives highest priorit y to the upper case data and next prior it y
goes to lower case data.
sample output:
ENAME
----------
ADAMS
ALLEN
BLAKE
CLARK
FORD ...
sample output:
ENAME
----------
W ARD
TURNER
SMITH
SCOTT
MILLER ...
sample output:
NOTE:
W e can also wr ite the column position number in the ORDER BY clause. The
column position num ber should be f rom the select column list, not f rom table
column list.
Here the f irst prior it y of o rder by clause given to f irst column, if f irst column
having duplicates then order by prior it y goes to second column and so on.
Ex: display sal and ename from emp based on order of salar ies?
sample output:
SAL ENAME
---------------------- ----------
800 SMITH
950 JAMES
1100 ADAMS
1250 W ARD------->
1250 MARTI N ---->
1300 MILLER
1500 TURNER
1600 ALLEN
2450 CLARK
2850 BLAKE
2975 JONES
3000 SCOTT ---->
3000 FORD ---->
5000 KING
Ex: display sal and ename from emp based on order of salar ies and
employee names?
sample output:
SAL ENAME
---------------------- ----------
800 SMITH
950 JAMES
1100 ADAMS
1250 MARTI N ------>
1250 W ARD -------->
1300 MILLER
1500 TURNER
1600 ALLEN
2450 CLARK
2850 BLAKE
2975 JONES
3000 FORD ------>
3000 SCOTT ----->
5000 KING
Ex:
Get employee data based on deptno order and f rom each dept least salr ied
emp to highest salar ied employee?
14 rows selected.
SQL>
OPERATORS
Arithmetic Operators:
+ - * /
These operat ors are used to perf orm Arit hmetic calculations on user's own
data and table data.
DU AL table
The DU AL table is a special one -row, one-column table present by def ault
inOracle and other database installat ions. In Oracle, the table has a single
VARCHAR2(1) colum n called DUMMY that has a value of 'X'. It is suit able f or
use in select ing a pseudo column such as SYSDATE or USER.
It is a system def ined table which contains only one column t o perf orm
calculations on user s own data.
500
10% of 90000
------------
9000
Ex: select 2000+(0.10*5000) -300 " Af ter calculat ion" f rom dual;
2200
select sal " Basic Sal", (0.02*sal) " TA" from emp;
select Sal " Basic", (0.02*Sal) " TA", (0.05*sal) "DA", (0.10*sal) "HRA",
(0.04*sal) " Comm" ,
(Sal + (0.02*Sal) + (0.05*sal) + (0.10*sal) + (0.04*sal) ) " Final
Salar y"
f rom emp;
output
14 rows selected.
SQL>
RELATIONAL OPERATORS: -
These are used to compare values by specif ying condit ions on the
columns.
WHERE clause:
In select quer y we can wr ite condit ions in this clause.
Syntax:
select cl1, cl2,......,cl -n / *
f rom table_name
where <conditions>
order by cl1, cl2,...,cln [asc/desc];
select sal " emp sal below 2000" f rom emp_inf o wher e sal < 2000;
emp sal below 2000
-------------------
800
1600
1250
1250
1500
1100
950
1300
SQL>
SQL>
Ex: Display employee details who joined bef ore 1st jan 1981?
SQL>
ASSIGNM ENTS:
Consider the below tables with est imated columns and then pr actise below
questions.
CUST_DTLS
CUST_Act_DTLS
ACT_TYPES_I NFO
PROD_DTLS
EMP
DEPT
BETWEEN
This operat or suppor ts specif ic range of values f rom a column . This is
applicable on NUMERIC, CHAR and DATE data t ype columns
Syntax:-1 BETWEEN
IN
This Operator supports specif ic list of values f rom a column.
This is applicable to Numeric, date & character data t ype columns.
Syntax:
IS NULL
This Operator is used to check the column value is null or not , if it is null
display output,
Otherwise it won’t display output.
Syntax: IS NULL
LIKE
The LIKE condit ions specif y a test involving pattern matching. W hereas the
equalit y oper ator (=) exactly matches one character value to another,
the LIKE conditions match a portion of one character value t o another by
searching the f irst value f or the pattern specif ied by the
second. LIKE calculates strings using characters as def ined by the input
character set.
LIKE:
It uses 2 symbols
EXAMPLES:
Ex: display salar ies bet ween 2000 and 3000 in ascending order?
select sal f rom emp where sal bet ween 2000 and 3000 order by sal;
SQL> select sal f rom emp where sal bet ween 2000 and 3000 order by sal;
SAL
----------
2450
2850
2975
3000
3000
SQL>
select * f rom emp where hir eda te bet ween '01 -jan-81' and '31 -dec-81';
or
select * f rom emp where hir edate like'%81';
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
74 9 9 A LL E N S A L ES M A N 7 6 98 2 0 - F E B- 81 1 6 00 300 30
75 2 1 W ARD S A L ES M A N 7 6 98 2 2 - F E B- 81 1 2 50 500 30
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 5 4 M ART I N S A LE S M A N 7 6 98 28 - S E P- 8 1 12 5 0 14 0 0 30
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
78 3 9 K ING P RE S ID E NT 17 - NO V- 8 1 5 0 00 10
78 4 4 T UR N ER S A LE S M A N 7 6 98 08 - S E P- 8 1 15 0 0 0 30
79 0 0 J A M E S C L ER K 7 69 8 0 3 - DE C- 81 9 50 30
79 0 2 F O R D A NA L YST 7 5 66 03 - D EC- 8 1 30 0 0 20
10 r o ws s e l ec t e d.
SQ L >
E M PNO EN A M E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
73 6 9 S MIT H C L ER K 7 90 2 1 7 - DE C- 80 8 00 20
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09- J UN - 8 1 2 45 0 10
78 7 6 A D AM S CL E R K 77 8 8 2 3 - MA Y- 8 7 1 10 0 20
79 0 0 J A M E S C L ER K 7 69 8 0 3 - DE C- 81 9 50 30
79 3 4 MI L L ER C L ER K 7 78 2 2 3 - J AN - 8 2 1 30 0 10
7 r o ws s el ec te d .
SQ L >
Ex: display employee names and salar ies who is getting any one of
f ollowing salar y?
1250,3000,5000
ENAME SAL
---------- ----------
W ARD 1250
MARTIN 1250
SCOTT 3000
KING 5000
FORD 3000
SQL>
10 rows selected.
SQL>
SAL
----------
800
950
SQL>
Ex: display names of emps begins s?
ENAME
----------
SMITH
SCOTT
SQL>
22-may-87
02-f eb-87
11-oct-87
Ex:
Execut e the f ollowing queries and ver if y the outputs
select * f rom emp where sal bet ween 1000 and 2000;
select * f rom emp where sal not bet ween 1000 and 2000;
select * f rom emp where hir edate bet ween '01 -jan-81' and '31 -dec-81' order
by hiredate;
select * f rom emp where hir edate not bet ween '01 -jan-81' and '31-dec-81'
order by hiredate;
--Display employee names begins with " J" and ends with "S" ?
select ename f rom emp where ename like'J%S';
--Display employee names,salar ies, hiredates joined inn the year " 81"?
select ename,sal,hir edate f rom emp where hiredate like'%81' ;
The f ollowing operat ors are the negation operators f or the above special
operators.
NO T BETWEEN
NO T LIKE
NO T IN
IS NO T NULL
10 r o ws s e l ec t e d.
SQ L >
select * f rom emp where hir edate NOT BETW EEN '01 -jan-14' and '31-
dec-14';
ASSIGNMENTS:
4) Display custom ers from the citites 'TEXAS ' and 'CHICAG O'?
These Operators are used to specif y Mult iple conditions in the where
clause.
Syntax:
SELECT cl1,cl2,....., / *
FRO M <table_name>
W HERE <cond-1> [ AND / OR ] <cond -2> [ AND / OR ] <cond -3> [
AND / OR ].......
ORDER BY cl1, cl2,. ..... [ ASC /DESC];
Ex: Display clerks and salesman details if their salar y at least 1000 and
atmost 1500?
Assignments:
Ex: Display tablet or mobile inf ormation if their cost min 10000 and max
15000?
Ex: Display product details if they were manuf actured in current year and
min cost 2000 and max cos t 10000?
CUST_ACT_DTLS
-------------
ACTNO ACT_TYPE ACT_OPEN_DT ACT_BAL CUST_ID
Ex: Display "male" customers f rom "texas" and "f emale" customer s f rom
"chicago"?
CUST_DTLS
---------
CUST_ID CUST_NAME CUST_CITY CUST_GENDER
CUST_MOBILE
EX:
Display employee details joined in 87 year or working under deptno 10?
Ex:
Display trading account details having min balance 10000 and savings
account details having min balance 100000?
DML COMMANDS
UPD ATE
It is used to update old values with new values within the table. By def ault it
updates all values in a column. W e can also update column values by
ver if ying condit ions.
Syntax:
update <table_nam e>
set colname1= value / expression,
colname2= value / expression,
colname3= value / expression
:
wher e <condit ion>;
Ex: update the salesman salar y wit h 20% incr ement , change their
designition as Sr. SALES who joined before 2005?
update emp
set sal=sal+(0. 20*sal),
job='Sr.SALES'
where job=' SALESMAN' AND hiredate < '01 -jan'05';
Ex: Update the customer account details with 25% addit ional interest?
Updat e cust_act_dt ls
Set act_bal= act_bal + (act_bal*0.25);
DELETE:
This command is used to delete the records f rom the table. By def ault it
deletes all the recor ds. W e can also delete the records condit ionally.
Syntax:
delete f rom <table_name> where <cond>;
Ex: delete employees inf ormation who is not getting any comm ission?
Note:
W e can get the back the deleted records / data wit hin the curr ent
session by using ROLLBACK.
DDL COMMANDS:-
CRE ATE
ALTER
DROP
TRUNC ATE
REN AME
ALTER:
This command is used to change the str ucture of the table by
syn:
alter table <table_name> ADD
(
<col_name> datat ype(size),
<col_name> datat ype(size),
:
:
);
iii) changing the datat ype and size (increasing / decreasi ng) of
column
Note:
A) If the column is empty then we can do the f ollowing
W e can change f rom any data t ype to any data t ype.
W e can change any size to any size .
3) DROP
This command is used to delete any dat a base object.
4) TRUNC ATE :
It deletes all the data f rom the table, it cannot deletes the partial data
f rom a table.
W e cannot get back or restore deleted data.
Ex: let us consider a table stud_dt ls with columns rno ,sname, fee
stud_dt ls
---------
rno sname f ee
Ex: change the above table to maintain course name f or each student?
Ex: change the above table to maintain gender and mobile number f or
each student?
Ex: f rom the above table delet e student mobile number column?
NOTE:
W e can also change the table name by using ALTER command as f ollows.
Generally, DML oper ations on table data are considered as tr ansact ions.
Transaction Control L anguage(TCL) commands are used to manage
transac tions in da tab ase.These a re used to manage the change s made b y DML
statements . It also all ows s ta tements to be grouped toge the r in to logical
transac tions.
1) COMMIT
It is used to make permanent the user tr ansact ions(DML operations)
on the table.
2) ROLLB ACK:
It is used to cancel t he user transaction.
3)S AVEPOINT
This command is used to save a s et of transact ions under a name
temporarily. So that if we want to rollback transactions to a save point we
can rollback up to a save point.
S AVEPOINT <name>;
Examples:
rollback;
commit;
select * f rom cust;
rollback;
select * f rom cust;
Ex-2:
savepoint s1;
savepoint s2;
rollback to s2;
rollback;
Oracle provides extensive secur it y f eatures in or der to saf eguard inf ormation
stored in its tables f rom unauthorized viewing and damage. Depending on a
user's status and responsibilit y, appropr iate rights on Oracle' s resources can
be assigned to the user by the DBA. The rights that allow t he use of some or
all of oracle's resour ces on the Ser ver ar e called PRI VILEGES.
Objects that are crea ted by a user are owned and controlled by that user. If
a user wishes to access any of the object s belonging to another user, the
owner of the object will have to give per missions f or such access. This is
called GR ANTING of PRIVILEGES.
Privileges once gi ven can be taken back by the owner of the object. This is
called REVOKING of PRIVILEGES.
GR ANT Statement:
Syntax:
eg:
GR ANT ALL
ON Student TO Mohd Imran
WITH GR ANT OPTI ON
eg:
The user Fareen has been given permission to view and modif y records in
the table Student.
To view the contents of the student table that belongs to Mohd Imran.
eg:
SELECT * FROM Mohd Imran. Student ;
Mohd Imran is the owner of the table, and he has given pr ivileges to other
user f or his table.
Each object privileges that is granted aut horized the grantee t o perf orm
some operat ion on t he object. A user can grant all the privileges or grant
only specif ic object privileges.
Al t er: Allows the grantee to change the table def inition with t he ALTER
TABLE command.
DELETE: Allows the grantee to remove the records f rom the table wit h the
DELETE command.
INDEX: Allows the grantee to create an index on the table with the
CREATE INDEX command.
INSERT: Allows the grantee to add records to the table with the INSERT
command.
SELECT: Allows the grantee to query the table with the SELECT command.
UPD ATE: Allows the grantee to modif y the records in the tables with the
UPDATE command.
Privileges once given can be denied to a user using the REVOKE command.
The object owner can revoke privileges granted to another user. A user of an
object who is not the owner, but has been granted the GRANT privileges,
has the power to REVOKE the pr ivileges f rom grantee.
Syntax:
REVOKE <Object_Privileges >
ON <Object_Name>
FROM <User_Name>
Eg:
REVOKE UPDATE
ON Student
FROM Fareen;
Ex: How do i cancel all previllages on all objects to the user -1?
CONSTR AI NTS:
Constraints ar e set of rules / business rules which will be def ined at
DDL level.
Constraints enf orce the data base to allow only valid values in to the
tables.
Constraints ensure t he user to f etch only valid / complete and accurate
data f rom the database.
Categories of Constraints: 3
1) Key Constraints
2) Domain Constraints
3) Referential Integrit y constraints
a) UNIQUE
It doesn’t allow duplicates but allows null values.
b) NO T NULL
It doesn’t allow null values but allows duplicates .
);
Ex: create a table student with columns rno, sname, course, f ee and
mobile
along with constraint s pk, nn, nn, nn and unique respect ively?
data:-
Note: Even af ter the key constraints on the table, still we have invalid
values.
W e can elim inate them by using DOM AIN constraints.
In oracle database, all constraints stored in a system def ined table called
USER_CONSTRAINTS .
Each constraint nam ed and numbered uniquely like, SYS_Cn (System
def ined Constraint).
Ex:
select constraint_name,constraint_t ype from USER_CONSTRAINTS where
table_name=' STUDENT';
CONSTRAINT_NAME CONSTRAINT_TYPE
------------------------------ ---------------
SYS_C007050 C --either Not null or Check
SYS_C007051 C
SYS_C007052 C
SYS_C007053 P --Primary key
SYS_C007054 U --Unique key
SYS_C007055 R –Foreign key
SYN: <col> datat ype(size) Constraint <User def ined name><act ual
constraint name>,
<col> datat ype(size) Constraint <User def ined name><act ual
constraint name>,
CONSTRAINT_NAME CONSTRAINT_TYPE
------------------------------ ---------------
NN_SNAME_STUDENT C
NN_COURSE_STUDENT C
NN_FEE_STUDENT C
CK_RNO_STUDENT C
CK_COURSE_STUDENT C
CK_FEE_STUDENT C
PK_RNO_STUDENT P
UK_MOBILE_STUDENT U
8 rows selected
DOMAIN constraints:
It is used to def ine a valid range / valid list of values on a column by using
the keyword CHECK.
CHECK uses 2 operators.
Syntax:
create table <table_name>
(
col1 datat ype( size) <constraint_name>,
col2 datat ype( size) <constraint_name>,
: : : :,
);
Ex: create the above table along with below domain constraints:
Recor ds:
CONSTRAINT_NAME CONSTRAINT_TYPE
------------------------------ ---------------
NN_SNAME_S_DTLS C
NN_COURSE_S_DT LS C
NN_FEE_S_DTLS C
CK_RNO_S_DTLS C
CK_COURSE_S_DT LS C
CK_FEE_S_DTLS C
PK_RNO_S_DTLS P
UK_MOB_S_DTLS U
Assignment:
DEPT
DNO DN AM E LOC
10 Product ion Hyder abad
20 Sales Hyder abad
30 Finance Chennai
EMP
Note:
By using above tables we are unable f etch the complete dat a of an object,
like, department nam e of any employee, number of emp loyees in dept and
etc.
1) Maintaining all the inf ormation in one big table [ DENORMALIZED DATA]
Note:
From the above table we will get the required inf ormation, but i t has
data duplicacy
it occupies more disk space
data retrieval time is ver y high.
2) NORMALIZATION:
The Process of dividing the above big table in to sub tables until the data
duplicacy is maximum reduced is called normalizat ion process.
Dividing the table int o sub tables based on repeated groups of data.
emp dept
--- ------------
eid ename sal dno dname loc
--- ----- ---- --- ------ ----
1 a 2000 10 product ion hyderabad
2 x 1200 10 product ion hyderabad
3 a 3400 10 product ion hyderabad
4 z 5000 10 product ion hyderabad
5 c 1000 20 sales hyderabad
6 s 1300 20 sales hyderabad
7 d 2300 20 sales hyderabad
8 x 1200 30 f in chennai
9 b 2200 30 f in chennai
Ex:
Emp Table:
DEPT table:
emp dept
--- ------------
eid ename sal dno dname loc
--- ----- ---- --- ------ ----
1 a 2000 10 product ion hyderabad
2 x 1200 20 sales hyderabad
3 a 3400 30 f in chennai
4 z 5000 PK
5 c 1000
6 s 1300
7 d 2300
8 x 1200
9 b 2200
PK
Implement ing relat ionships bet ween the t ables by using Pr imary key of
dept table , def ine the f oreign key column under emp table.
emp dept
--- ----
eid ename sal dno dno dname loc
--- ----- ---- ------- --- ------ ----
1 a 2000 10 10 product ion hyderabad
2 x 1200 10 20 sales hyderabad
3 a 3400 10 30 f in chennai
4 z 5000 10 PK
5 c 1000 20
6 s 1300 20
7 d 2300 20
8 x 1200 30
9 b 2200 30
PK FK
45KB
Advantages:
--Searching f or required data is as much as f ast
--And data retr ieval is f ast
--Max data duplicacy is eleminated.
--Occupy less Disk space.
This constraint is u sed to implement PHYSICAL relat ionship bet ween the
tables by using prim ary key of one table and we can def ine f oriegn key in
other table.
Foriegn key column contains only values from primary key. Foriegn
key contains duplicates and null values also.
--A table which cont ains primar y key is considere d as par ent
/ Master/Base table.
--A table which cont ains f oriegn key is known as child table / Detailed
table/ Derived table.
REFERENCES
we can use this keyword in the "creat ion of child table and to def ine f oriegn
key column".
Ex: create the f ollowing tables and Implement relationships accor dingly?
It allows deletion of parent table records even the parent is having childs. As
an eff ect the dependant child records ar e automatically deleted. This known
as “Maintaining Data Integrity among the tables. ”
ALTERING CONSTRAINTS
iii) Modif y constraints / changing exist ing constraints with new constraints
To do this ,F irst drop old constraint and then add new constr aints.
EN ABLI NG / DIS AB LING CONSTR AI NTS
W e can also tempor arily enable or disable constraints on the columns based
on business requirement.
Syn:- Enable constraint
NOTE:
Q: Can w e enable any constraint if a column havi ng invali d data
according to constraint?
Ans: YES ,w e can enable , but the column should be defined w ith
DIFFER ABLE ke yw ord.
MERGE statement
Syntax:
Example:
ID NAME SCORE
---------- --------------- ----------
1 Jack 540
2 Rose
3 W illiam 650
4 Caledon 620
5 Fabrizio 600
6 Thomas
7 Ruth 680
8 Spacer 555
ID NAME SCORE
---------- --------------- ----------
7 Ruth 690
8 Spicer 620
9 W allace 600
10 Lizzy
11 Brock 705
As you can see, the f ollowing act ions ar e requir ed on table STUDENT:
1 row f or id#7 to be corrected f or score: Ruth had scored 690, not 680.
1 row f or id#8 to be corrected f or name: the student is called Spicer, not
Spacer.
3 new rows (ids#9, 10,11) to be inserted into STUDENT table.
5 rows merged.
ID NAME SCORE
---------- --------------- ----------
1 Jack 540
2 Rose
3 W illiam 650
4 Caledon 620
5 Fabrizio 600
6 Thomas
7 Ruth 690
11 Brock 705
10 Lizzy
9 W allace 600
8 Spicer 620
11 rows selected.
Sure enough, 5 rows have got merged as expected – 2 updates + 3 inserts.
SET OPERATORS
The corresponding expr essions in the select lists of the component queries
of a compound quer y must match in number and must be in the same
datat ype group (such as numer ic or char acter).
Or
These operat ors will display combined data f rom multiple tables.
1) UNION
It will display combined data f rom multiple tables with out duplicates
2) UNION ALL
It will display combined data f rom multiple tables with duplicates
3) INTERSECT
It will display common data f rom multiple tables (From mult iple Select
stmts)
4) MINUS
It will display values f rom f irst select ion by eliminating values which
are repeat ing in second select ion
For example:
1) select * f rom s1
union
select * f rom s2;
output: {a,b,c,d,x, y, z}
2) select * f rom s1
union all
select * f rom s2;
3)select * f rom s1
intersect
select * f rom s2;
output: {c,b}
4)select * f rom s1
minus
select * f rom s2;
output: {a,d}
Sample Tables:
Note:
What are the limitations of set operators?
Ex:
select cname,mobile f rom cust_br1
union all
select cid f rom cust_br2;
select cname,mobile from cust_br1
*
ERROR at line 1:
ORA-01789: quer y block has incorrect number of result colum ns
Restrictions on the Set Operators The set operators ar e subj ect to the
f ollowing restrict ions:
Joins are used to display mult iple data t ypes of data f rom multiple
tables. A join is a quer y that combines rows f rom two or mor e tables, views,
or materialized views. Oracle Dat abase perf orms a join whenever mult iple
tables appear in the FRO M clause of the query. The select list of the query
can select any colum ns f rom any of these tables. If any t wo of these tables
have a column name in common, the n you must qualif y all ref erences to
these columns thr oughout the query with table names to avoid ambiguit y.
Types of joins: 4
i) CROSS JOIN
If two tables in a join query have no join conditi on, then Oracle Database
returns their Cartesian product . Oracle combines each row of one table with
each row of the other. A Cartesian product always generates many rows and
is rarely usef ul.
Example:
consider
s1={a,b,c,d} s2={d1,d2}
s1Xs2={(a,d1),(a,d2) ,(b,d1),(b,d2),.......}
syn:
select col1, col2,...,coln
f rom table1, table2,....
where <cond>
order by col1, col2,.. ..[ desc ];
Ex: Display employee names , salar ies and their department names?
…..
…..
…..
SMITH 800 OPERATIONS
ALLEN 1600 OPERATIONS
56 rows selected.
SQL>
Note:
In the above output some combinat ions are valid and remaining are invalid
according to physical table dat a.
Ex:
Get manager details and their dept details?
1 2 r o ws s e l e c t e d .
SQL>
“In the above output, bold faced lines are valid , and re maining are
invalid.”
So, Then in which case cross join will display only valid combination?
select ename,sal,job,per_id,per_incr,desc
f rom emp,Percent_incr_dtls
where job='manager' and per _incr='13%';
A cross join is known as equi join if we specif y join condition using '='
operator.
It will display only matched data f rom all tables.
A condit ion is known as join condition if it is specif ied bet ween primar y key
of one table and f oriegn key of other table.
Ex: display employee names , salar ies and corresponding depart ment
details?
select ename, sal,dept.deptno,dname, loc
f rom emp,dept
where emp. deptno=dept.deptno;
14 rows selected.
SQL>
Alias name is a temporar y name f or the table and it is valid with in the quer y.
Ex:
Display employee details and dept det ails f or all managers?
OUTPUT:
Ex:
Display all clerks det ails and their department names like hig hest salaried
clerk to least salaried clerk ?
Output:
SQL>
Examples :
CUST_DTLS Act_types
Cno PK Act_type PK
Cname Cust_act_Dtls Act_name
City Actno Act_desc
Gender Act_type
Mobile Act_Open_date
Act_bal
Cno
FK
FK
Ex:
Get customer details with account balance and account name?
Select cd.*,cad.act_bal,at.act_name
From cust_dtls cd, cust_act_dtls cad, act_types at
W here cd.cno=cad.cno
And
Cad.act_type=at.act_type;
OUTPUT:
7 rows selected.
SQL>
Ex:
Get product name,cost, warrenty, company name and sale date?
Select p.pname,p.cost,p.warr,c.cname,s.sale_dt
From prod_dtls p, comp_dtls c, sales s
W here c.cmpid=p.cmpid
And p.pid=s.pid;
INNER JOIN
Ex: display customer name and cit y, custom er actno,actt ype and bal,
act_name f or all cust omers?
select
cd.cname,cd.cit y,cad.actno,cad.act_t ype, cad.act_bal,at.act_name
f rom cust_dtls cd INNER JOIN cust_act_dtls cad
ON cd.cno=cad. cno
INNER JOIN act_types at
ON cad.act_t ype=at.act_type;
OUTPUT:
SQL>
SQL>
select t1.*,t2.*...
f rom t1,t2,t3, t4,t5
where
t1.col1=t2.col4
and
t2.col3=t3.col1
and
t3.col2=t4.col31
and
t4.col31=t5.col30;
select t1.*,t2.*...
f rom t1 Inner Join t2
ON
t1.col1=t2.col4 Inner Join t3
ON
t2.col3=t3.col1 Inner Join t4
ON
t3.col2=t4.col31 Inner Join t5
ON
t4.col31=t5.col30;
select e.*,d.*
f rom emp e, dept d
where job=' MANAGER'
AND
e.deptno=d.dept no;
or
select e.*,d.* f rom emp e inner join dept d
on e.deptno=d.deptno
where e.job=' MANAGER';
NOTE:
In the above query t he e and d are temporar y alias names f or the table
emp and dept respectively. And these alias nam es are valid f or current
query only.
Ex:
DISPLAY EMPLOYEE DETAILS AND DEPART MENT DETAILS W HO IS
W ORKING UNDER account ing and sales?
OUTPUT:
9 r o ws s e l e c t e d .
SQL>
Ex: Display product details along with its sales inf ormations from the year
2014?
Ex: Display cust omer det ails and the ir account details who is f rom the cit y
'CHICAGO'?
Ex: Display above inf ormation if the customer held DEMAT account and
with m in balance 100000?
Practical Examples:
Ex: W rite a query to display customer names, account names and respective
Act balances?
CNAME ACTNO
------------ -----------
Anil 20035201471
Kiran 20035201473
vinod 20035201472
vinod 20035201470
Madhu 20035201474
Rocky 20035201475
Ching Fu 20035201476
Assignment:
1) W rite a query to display employee names,salaries ,job tit les, hiredat e and
respect ive dept nam es based on salar y order?
2) W rite a query to display all "salesman and clerk" names,salar ies ,job
titles, hiredate and respect ive dept names based o n salar y and job tit le
order?
SELF JOIN
employee
--------
ename cit y
----- ------
kiran mumbai
hari hyd
madhu hyd
smith delhi
scott mumbai
allen hyd
soum ya chennai
john delhi
Ex: display emplyoee details who is living in a cit y where "john" is living?
e1 e2
--- ---
ename cit y ename
cit y
----- ------ ----- ------
kiran mumbai kiran mumbai
hari hyd hari hyd
madhu hyd madhu
hyd
smith delhi smith delhi(matched)
scott mumbai scott mumbai
allen hyd allen hyd
soum ya chennai soum ya chennai
john delhi-----(matched) john
delhi(matched)
goto f irst alias table and check the employee name "john"
If it is there then get his "cit y"
then the cit y f rom first alias table is compared with a ll cit y names in 2nd
alias table
If the cit y values are equal then get the records f rom second alias table.
(or)
select e2.*
f rom employee e1, employee e2
where e1.ename='john'
and
e1.cit y=e2.cit y;
output:
smith delhi
john delhi
output: If you display output f rom First alias table then y ou will get
Duplicate data
john delhi
john delhi
output:
OUTER JOINS
These are used to display all data f rom one table and only matched data
f rom other table.
An outer joi n extends the result of a simple join. An outer join returns all
rows that sat isf y the join condition and also returns some or all of those rows
f rom one table f or which no rows f rom the other sat isf y the join condition.
Display all the data f rom lef t table and only matched data f rom right
table.
Display complete dat a f rom right table and only matched data f rom lef t
table.
3) Full outer join / Full join:
Display
--matched data f rom both the tables
--unmatched data f rom lef t table
--unmatched data f rom right table
syn-1:
select col1, col2, col..... / *
f rom table_1 [lef t join / right join / f ull join] table_2
ON table1.pk=table2.fk;
Create a new table EMPCP from the table emp and delete deptno of emps
working under deptno 30?
Ex:
Display all employee details and if he is working under a dept then display
his department details also?
select e.*,d.*
f rom emp e left outer join dept d on e.deptno=d.deptno;
output:
1 4 r o ws s e l e c t e d .
SQL>
Ex:
Display all employee details and if he is working under a dept then display
his department details also?
1 4 r o ws s e l e c t e d .
SQL>
NO TE
Check the above out put , we are getting employees even they are not
working under any department, it is not possible using EQUI or Inner joins.
Ex:
Get all department details and also if a dept having emps then display its
emps details also?
select e.*, d.* f rom emp cp e right outer join dept d on
e.deptno=d.dept no;
ex:
1 0 r o ws s e l e c t e d .
SQL>
“Check above output for bold faced lines, these are dept have no emps,
still w e are getting the details, since the quer y is RIGHT OUTER JOIN. ”
Ex:
Get emp details and dept details using FULL OUTERJOIN?
1 6 r o ws s e l e c t e d .
SQL>
Ex: Display cust omer name, actno, act type and act nam e?
Ex: Display Female cust omers f rom CHICAGO, wit h their account s
inf ormation who have DEMAT account?
Ex: Display all customer details and if a customer having SALARY account
then display account details also?
Ex: Display all customer s personnel details and all accounts list of
inf ormation?
If a customer have an account then display his details along with his
account details?
NON-EQUI JOIN
An nonequi (or thet a) join is an inner join statement that uses an unequal
operat ion ( i.e: <>, >, <, !=, BETW EEN, etc.) to match rows f rom
dif f erent tables. The converse of an nonequi join is a equi join operat ion.
Ex:
S E LE C T e .e n a m e , e . s a l, s . g ra d e
2 F RO M e m p e , sa l g r a de s
3 W HE R E e . sa l B ET W E E N s . l o s a l A N D s . h i s al ;
N ATUR AL JOIN
The join is based on all the columns in the two tables that have the same
name and data t ypes.The join creates, by using the NATURAL JOIN
keywords.It selects rows f rom the two tables that have equal values in all
matched columns.W hen specif ying colum ns that are involved in the natural
join, do not qualif y the column name wit h a table name or table alias.
SQL: Syntax
FROM table1
Assignments
Syntax:
Execution process:
Here the execut ion process is always f rom innermost quer y to the outermost.
A sub quer y which depends on a value generated by outer query. Here the
execut ion process is as f ollows.
First Outer query has to be executed and generates some out put
values
Second based on these output values, sub query has to be executed
From sub quer y we have some output and it is passed to outer query
again
Then outer quer y has to be executed again.
Correlated subqueries reduce perf ormance.
Correlated subqueries are usef ul in rever se business processes.
EXAMPLES
Ex:
Display employee details who is working under ACCO UNTING ?
comp_dt ls
---------
comp_code comp_name comp_countr y
(PK)
|
|
V---------------------------------------------------------------------- ---------------
>
|
|
|
prod_dt ls |
--------- V
prodid prodname prodcost mfg warrent y
prod_comp_code
(PK) (FK)
C O MP _ C O D E C O MP _ N A ME CITY
---------- -------------------- ----------
I101 IBM N EW YO R K
W 20 2 W IPRO CHICAGO
D303 DELL TE X A S
S404 S A MS U N G KOREA
SQL>
PROD_CODE P R O D _ N A ME C O S T MF G W ARRENTY C O MP _ C O D E
---------- -------------------- ---------- --------- ---------- ----------
ILTPQS LAPTOP 45000 11 -FEB-12 4 YE A R S I101
I L T P XS LAPTOP 3 4 0 0 0 2 1 - MA R - 1 2 4 YE A R S I101
ILTPZS LAPTOP 40000 12 -FEB-13 7 YE A R S I101
W D TP G D E S K TO P 2 3 0 0 0 3 0 - O C T- 1 2 1 YE A R W 202
W CF L L L I G H TS 3400 22 -JAN-13 2 YE A R S W 202
D D T PW DESKTOP 2 7 0 0 0 1 3 - N O V - 1 2 5 YE A R S D303
D L TP G LAPTOP 46000 08 -JAN-13 2 YE A R S D303
D MB L Y MO B I L E 32000 10 -JAN-13 D303
S L TP C LAPTOP 34000 04 -DEC-12 6 MO N T H S S404
S L TP D LAPTOP 45000 09 -DEC-12 2 YE A R S S404
S MB L G L X Y MO B I L E 24000 10-JAN-12 1 YE A R S404
P R O D _ C O D E P R O D _ N A ME C O S T MF G W A R R E N T Y C O MP _ C O D E
---------- -------------------- ---------- --------- ---------- ----------
S MB L G L X G MO B I L E 21500 02 -FEB-13 1 YEAR S404
1 2 r o ws s e l e c t e d .
S Q L > S E L E C T * F R O M P R O D _ D TL S
2 W H E R E C O MP _ C O D E I N
3 (
4 S E L E C T C O MP _ C O D E F R O M C O MP _ D TL S
5 W H E R E C O MP _ N A M E I N ( ' I B M' , ' S A MS U N G ' )
6 );
P R O D _ C O D E P R O D _ N A ME C O S T MF G W A R R E N T Y C O MP _ C O D E
---------- -------------------- ---------- --------- ---------- ----------
ILTPQS LAPTOP 4 5 0 0 0 1 1 - F E B - 1 2 4 YE A R S I101
I L T P XS LAPTOP 3 4 0 0 0 2 1 - MA R - 1 2 4 YE A R S I101
ILTPZS LAPTOP 4 0 0 0 0 1 2 - F E B - 1 3 7 YE A R S I101
S L TP C LAPTOP 3 4 0 0 0 0 4 - D E C - 1 2 6 MO N T H S S 4 0 4
S L TP D LAPTOP 4 5 0 0 0 0 9 - D E C - 1 2 2 YE A R S S404
S MB L G L X Y MO B I L E 24000 10 -JAN-12 1 YEAR S404
S MB L G L X G MO B I L E 21500 02 -FEB-13 1 YEAR S404
7 r o ws s e l e c t e d .
Ex: display product details f rom the companies other than IBM, samsung?
S E L E C T * F R O M P R O D _ D TL S
W H E R E C O MP _ C O D E N O T I N
(
S E L E C T C O MP _ C O D E F R O M C O MP _ D TL S
W HE R E C O MP _ N A ME I N ( ' I B M' , ' S A MS U N G ' )
);
P R O D _ C O D E P R O D _ N A ME C O S T MF G W A R R E N T Y C O MP _ C O D E
---------- -------------------- ---------- --------- ---------- ----------
W CF L L LIGHTS 3 4 0 0 2 2 - J A N - 1 3 2 YE A R S W 202
W D TP G DESKTOP 2 3 0 0 0 3 0 - O C T- 1 2 1 Y E A R W 202
D MB L Y MO B I L E 32000 10 -JAN-13 D303
D L TP G L A P TO P 4 6 0 0 0 0 8 - J A N - 1 3 2 YE A R S D303
D D T PW DESKTOP 27000 13 -NOV-12 5 YEARS D303
CO MP_NAME
--------------------
DELL
W IPRO
CORREL ATED SUBQUERIES
These sub queries use 2 oper ators either EXISTS OR NOT EXISTS
EXISTS
It returns true if a sub query f etches at least one value. If it returns TRUE
then outer quer y will display the result.
Ex: display department details which is having at least one employee with
in it?
Ex: display department details which not having at least one employee
with in it?
Ex: Display company det ails f rom which we have no pr oducts at all?
no rows selected
Assignments:
ALL
The ALL comparison condition is used to compare a value to a list or subquery. It
must be preceded by =, !=, >, <, <=, >= and followed by a list or subquery.
When the ALL condition is followed by a list, the optimizer expands the initial
condition to all elements of the list and strings them together with AND operators, as
shown below.
EMPNO SAL
---------- ----------
7839 5000
SQL>
EMPNO SAL
---------- ----------
7839 5000
SQL>
When the ALL condition is followed by a subquery, the optimizer performs a two-step
transformation as shown below.
SELECT e1.empno, e1.sal
FROM emp e1
WHERE e1.sal > ALL (SELECT e2.sal
FROM emp e2
WHERE e2.deptno = 20);
EMPNO SAL
---------- ----------
7839 5000
SQL>
EMPNO SAL
---------- ----------
7839 5000
SQL>
EMPNO SAL
---------- ----------
7839 5000
SQL>
Assuming subqueries don't return zero rows, the following statements can be made
for both list and subquery versions:/p>
"x = ALL (...)": The value must match all the values in the list to evaluate to TRUE.
"x != ALL (...)": The value must not match any values in the list to evaluate to TRUE.
"x > ALL (...)": The value must be greater than the biggest value in the list to evaluate
to TRUE.
"x < ALL (...)": The value must be smaller than the smallest value in the list to
evaluate to TRUE.
"x >= ALL (...)": The value must be greater than or equal to the biggest value in the
list to evaluate to TRUE.
"x <= ALL (...)": The value must be smaller than or equal to the smallest value in the
list to evaluate to TRUE.
If a subquery returns zero rows, the condition evaluates to TRUE. In the following
example, the subquery returns zero rows, which means the whole expression "sal >
ALL (zero rows)" evaluates to TRUE, so all rows are displayed.
no rows selected
SQL>
EMPNO SAL
---------- ----------
7369 800
7900 950
7876 1100
7521 1250
7654 1250
7934 1300
7844 1500
7499 1600
7782 2450
7698 2850
7566 2975
7788 3000
7902 3000
7839 5000
SQL>
ANY
The ANY comparison condition is used to compare a value to a list or subquery. It
must be preceded by =, !=, >, <, <=, >= and followed by a list or subquery.
When the ANY condition is followed by a list, the optimizer expands the initial
condition to all elements of the list and strings them together with OR operators, as
shown below.
EMPNO SAL
---------- ----------
7566 2975
7698 2850
7782 2450
7788 3000
7839 5000
7902 3000
SQL>
EMPNO SAL
---------- ----------
7566 2975
7698 2850
7782 2450
7788 3000
7839 5000
7902 3000
SQL>
When the ANY condition is followed by a subquery, the optimizer performs a single
transformation as shown below.
EMPNO SAL
---------- ----------
7839 5000
7902 3000
7788 3000
7566 2975
7698 2850
7782 2450
7499 1600
7844 1500
SQL>
EMPNO SAL
---------- ----------
7839 5000
7902 3000
7788 3000
7566 2975
7698 2850
7782 2450
7499 1600
7844 1500
SQL>
Assuming subqueries don't return zero rows, the following statements can be made
for both list and subquery versions:
"x = ANY (...)": The value must match one or more values in the list to evaluate to
TRUE.
"x != ANY (...)": The value must not match one or more values in the list to evaluate
to TRUE.
"x > ANY (...)": The value must be greater than the smallest value in the list to
evaluate to TRUE.
"x < ANY (...)": The value must be smaller than the biggest value in the list to
evaluate to TRUE.
"x >= ANY (...)": The value must be greater than or equal to the smallest value in the
list to evaluate to TRUE.
"x <= ANY (...)": The value must be smaller than or equal to the biggest value in the
list to evaluate to TRUE.
If a subquery returns zero rows, the condition evaluates to FALSE. In the following
example, the subquery returns zero rows, which means the whole expression "sal >
ANY (zero rows)" evaluates to FALSE, so no rows are displayed.
no rows selected
SQL>
SOME
The SOME and ANY comparison conditions do exactly the same thing and are
completely interchangeable.
VIEWS
Views ar e known as logical tables. They represent the data of one of more
tables. A view derives its data f rom the tables on which it is based. These
tables are called base tables. Views can be based on actual tables or
another view also.
W hatever DML operations you perf ormed on a view they actually aff ect the
base table of the view. You can treat views same as any other table. You
can Quer y, Insert, Update and delete f rom vi ews, just as any other table.
Views ar e ver y powerf ul and handy since they can be treated j ust like any
other table but do not occupy the space of a table.
Request DATABASE
( query )------------->ENGINE--------------->-- ^---------------->DB
| | |
sql stmt executor | |
| | Data dictionar y( met a data)
pl/sql engine | |
| | |
|--------------------- Actual Dat a
|
-----------------------
| |
selecting f rom | |
table V |
1<------------------------- |
2<------------------------- |
3<------------------------- |
4<------------------------- |
: n hits to DB |
n<------------------------- |
|
|
|
output selecting f rom view |
<---------CACHE <----------------------------------------
<---------MEMO RY Only one HIT to the DB
<---------
<---------
:
<---------
View:
It is a database object contains logical copy of selected table data.
It can be created based on f requently using data.
It reduces number of hits to the dat abase.
It improves t he perf ormance of queries and database.
Types of View s: 5
Advantage: It will reduce wr it ing number of join queries again and again.
NO TE:
By def ault the Client user not having permission to creat e views. That
privillage is assigned by DBA.
Ex: wr ite a quer y to create a view which cont ains managers inf ormation
f rom emp table?
system
manager
orcl
grant succeeded
view created.
sample output:
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
ENAME SAL
---------- ----------
JONES 2975
BLAKE 2850
CLARK 2450
NOTE
sample hands-on:
sub table:
create tabl e emp_mgr as select * f rom emp where job=' MANAGER';
Ex:
select * f rom emp_mgr;
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
11 2 2 d in es h M AN A G E R 1 2 - M A Y- 1 3 4 5 00 700 40
create view vw _mgr_info as select * f rom emp where job=' MANAG ER';
Ex:
select * f rom vw_mgr_inf o;
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
11 2 2 d in es h M AN A G E R 1 2 - M A Y- 1 3 4 5 00 700 40
Ex:
ins ert into emp values(2233,'naresh',' MANAGER',NULL,'21 - MAY-
14',3400,200,10);
1 rows inserted.
Ex:
In the below sub table data we cannot see any new manager inf ormation.
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
11 2 2 d in es h M AN A G E R 1 2 - M A Y- 1 3 4 5 00 700 40
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
11 2 2 d in es h M AN A G E R 1 2 - M A Y- 1 3 4 5 00 700 40
22 3 3 n ares h M AN A G E R 2 1 - M A Y- 1 4 3 4 00 200 10
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ - - - - - - - - - -
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
11 2 2 d in es h M AN A G E R 1 2 - M A Y- 1 3 4 5 00 700 40
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- - ----- --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ ----------
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
E M P NO E N AM E JOB MG R H IR ED AT E S AL CO M M
DE PT NO
- - - - - - - - - - - --------- ------ --- - - - - - - - - - - ---- ----- - -- ------- ---- ------ ----------
75 6 6 J O N E S M AN AG E R 78 3 9 02 - A P R- 81 2 9 75 20
76 9 8 B L A K E M AN A G E R 7 83 9 0 1 - MA Y- 8 1 2 85 0 30
77 8 2 CL A R K M AN AG E R 78 3 9 09 - J UN - 8 1 2 45 0 10
EX AM PLES
Ex:
wr ite a quer y to maintain a view containing managers ename, sal, job, dept
name and dept loc?
ENAME DNAME
---------- --------------
JONES RESEARCH
BLAKE SALES
CLARK ACCOUNTING
3) Inline view
select * f rom emp where deptno=( select deptno f rom dept where
dname='ACCOUNTING');
SELECT *
FRO M ( SELECT deptno, count(*) emp_count
FROM emp
GROUP BY deptno ) emp,
dept
W HERE dept.deptno = emp.deptno;
Explanation:
deptno emp_count
------ ---------
10 4
20 6
30 7
20 REsearch Texas 6
30 Sales Dallas 7
Ex: display the employees who earn the highest salar y in each department ?
SELECT *
FRO M
( SELECT deptno, max(sal) maxsal
FROM emp
GROUP BY deptno ) b, emp a
W HERE
a.sal= b.maxsal
and
a.deptno = b.deptno;
output:
Ex:
FRO M employee
ON d.dept_id = emp_cnt.dept_id;
20 RESEARCH 5
30 SALES 6
Ex:
Display comp_codes, number of products f rom each company code and also
display company det ails?
ex:
A view can be created even if the def ining query of the view cannot be
executed, as long as the CREATE VIEW command has no syntax errors. W e
call such a view a view with errors.
For example,
if a view ref ers
--to a non-existent t able or
--an inval id column of an exist ing table, or
--if the owner of the view does not have the required privileges,
then the view can st ill be created and ent ered into the dat a dictionar y.
You can only create a view with errors by using the FORCE option of the
CREATE VIEW command:
Ex:
For data warehousing purposes, the mat erialized views com monly created
are aggregate views, single -table aggregate views, and join views.
In this article, we shall see how to create a Mater ialized View in Oracle and
discuss Ref resh Option of the view.
In replicat ion environments, the materi alized views commonly created are
primar y key, rowid, and subquer y mater ialized views.
The f ollowing statement creates the prim ary -key materialized view on the
table emp located on a remote database.
Note: W hen you create a materialized view using the FAST option you will
need to create a view log on the master tables(s) as shown below:
The f ollowing statement creates the rowi d materialized view on table emp
located on a remote database:
The f ollowing statement creates a subquery mater ialized view based on the
emp and dept tables loc ated on the remote database:
REFRESH CL AUSE
a. The ref resh method used by Oracle to ref resh data in materialized
view
b. W hether the view is primar y key based or row -id based
c. The time and inter val at which the view is to be ref reshed
The FAST ref reshes use the mater ialized view logs (as seen above) to send
the rows that have changed f rom master tables to the materialized view.
You should create a materialized view log f or the master table s if you specif y
the REFRESH FAST clause.
Mater ialized views are not eligible f or f ast refresh if the def ined subquer y
contains an analyt ic f unction.
The complete ref resh re -creates the entire materialized view. If you request
a complete ref resh, Oracle perf orms a complete ref resh even if a f ast ref resh
is possible.
Re f r e sh M eth od - F OR C E Cl au s e
Wh en y ou sp e ci fy a FOR C E cl au s e, O ra cl e wi l l pe rf o rm a fa st r ef r e sh i f on e
i s p o ssi bl e o r a c om pl et e r e f r esh oth e r w i se . If yo u d o n ot sp e ci fy a r ef r e sh
me th od (FAS T , C OM PL E T E , o r F OR C E) , F OR C E i s th e d e fau l t.
The START W ITH clause tells the database when to perf orm the f irst
replicat ion f rom the master table to the local base table. It should evaluate
to a f uture point in time. The NEXT clause specif ies the inter val bet ween
ref reshes
In the above example, the f irst copy of the materialized view is made at
SYSDATE and the interval at which the r ef resh has to be perf ormed is ever y
two days.
Summary
To alter the def inition of a view, you must replace the view using one of the
f ollowing methods:
A view can be dropped and then re-creat ed. W hen a view is dropped,
all grants of corresponding view pr ivileg es are revoked f rom roles and
users. Af ter the view is re -created, necessar y privileges must be
regranted.
A view can be replaced by redef ining it with a CREATE VIEW
statement that contains the OR REPLACE option. This option replaces
the current def inition of a view, but preserves the present securit y
author izat ions.
For example, assume that you creat e the ACCO UNTS_STAFF view, as given
in a previous example. You also grant sever al object privileges to roles and
other users. However, now you realize that you must redef ine the
ACCOUNTS_STAFF view to correct the department number specif ied in the
W HERE clause of the def ining query, because it should have been 30. To
preser ve the grants of object privileges t hat you have made, you can replace
the current version of the ACCO UNTS_STAFF view with the f ollowing
statement:
Replacing a view replaces the view's def init ion in the data dictionar y.
All under lying objects ref erenced by the view are not af f ected.
If previously def ined but not includ ed in t he new view def init ion, then
the constraint associated with the W ITH CHECK OPTION f or a view's
def init ion is dropped.
All views and PL/SQ L program units dependent on a replaced view
become invalid.
W hen a user attempts to ref erence an invalid view, Oracle ret urns an error
message to the user:
This error message is returned when a view exists but is unusable due to
errors in its query ( whether it had errors when originally cr eat ed or it was
created successf ully but became unusable later because underlying objects
were altered or dropped).
Dropping View s
Use the SQL command DROP VIEW to drop a view. For exam ple:
DROP VI EW Accounts_staff ;
Just as the index in t his manual helps you locate inf ormation f aster than if
there were no index, an Oracle Database index provides a f aster access path
to table data. You can use indexes without rewr iting any queries. Your
results ar e the same, but you see them more quickly.
Index is a table like object which maintains ordered data of the column
physically.
It reduces number of comparisons to make, to f etch the required data. It
f astens the search as much as f ast. It occupies physical disk space.
555.000.000
555.000.001
555.000.002
:
555.000.099-----> this is the last recor d in f irst data block of table no
555. (100 records)
555.001.000
555.001.001
555.001.002
: :
555.001.999------> this is the last record in second data block of table
no 555 ( 1000 records)
555.002.000
555.002.001
:
555.002.009------> this is the last record in the third data block of table
no 555 ex: salaries(table) Idx_sal(indexed table)
---------- ----------------------
1--9000 2--1000
2--1000 5--1000
3--2000 8--1000
4--9000 3--2000
5--1000 7--2000
6--2500 9--2000
7--2000 6--2500
8--1000 1--9000
9--2000 4--9000
10--9000 10-9000
6 salaries 6 records
B- Tree Indexes
B-trees, short f or balanced trees, are the most common type of database
index. A B-tree index is an or dered list of values divided into ranges. By
associat ing a key wit h a row or range of rows, B -trees provide excellent
retrieval perf ormance f or a wide range of queries, including exact match and
range searches.
Figure 3-1 illustrates the structure of a B -tree index. The example shows an
index on the department_id column, which is a f oreign key column in
the employees table.
TYPES OF INDEXES: 2
1) Simple index:
It is created on a table on single column.
In this index , the search criter ia is f rom right most leaf to lef t.
This index is pref erable to search f or highes t values f requently.
Ex: create a reverse index on sales transact ion table on sales am ount
column?
5) UNIQUE INDEX
If an index is cr eating on Unique column then it is known as unique index.
Note
By def ault the or acle engine create and maintains a def ault index on each
primar y key column of a table.
Note
In Oracle indexes inf ormation is maintained under a system def ined table
called USER_INDEXES
You can create multiple indexes on the same set of columns when the
indexes ar e dif f erent in some way. For example, you can cr eat e a B -tree
index and a bitmap index on the same set of columns.
W hen you have multiple indexes on the same set of columns, only one of
these indexes can be visible at a t ime, and any other indexes must be
invisible.
You might create dif ferent indexes on the same set of columns because they
provide the f lexibilit y to meet your requirements. You can also create
multiple indexes on t he same set of columns to perf orm application
migrations without dr opping an existing index and recreat ing it with dif f erent
attributes.
An invisible index is an index that is ignored by the opt imizer unless you
explicit ly set the OPTIMIZER_USE_INVI SIBLE_INDEXES init ialization
parameter to TRUE at the session or system level.
TABLESPACE users
NEXT 20k)
INVISIBLE;
USER_I NDEXES
USER_I NDEXES describes the indexes owned by the current user. This view
does not display the OW NER column.
CLUSTERS
To create a cluster in your schema, you must have the CRE ATE
CLUSTER system privilege and a quota f or the tablespace int ended to
contain the cluster or the UNLIMI TED TABLESP ACE system privilege.
To create a cluster in another user's schema you must have the CRE ATE
ANY CLUSTER syst em privilege, and the owner must have a quota f or t he
tablespace intended to contain the cluster or the UNLIMI TED
TABLESP ACE system privilege.
You create a cluster using the CRE ATE CLUSTER statement. The f ollowing
statement creates a cluster named emp_dept, which st ores
the emp and dept tables, clust ered b y thedeptno column:
To create a table in a clust er, you must have either the CRE ATE
TABLE or CRE ATE ANY TABLE system privilege. You do not need a
tablespace quota or the UNLIMITED TAB LESP ACE system privilege to create
a table in a cluster.
You create a table in a cluster using the CRE ATE TABLE stat ement with
the CLUSTER clause. The emp and dept tables can be cr eat ed in
the emp_dept cluster using the f ollowing statements:
CREATE TABLE em p (
. . .
Example:
dname varchar2(20) ,
loc varchar2(20)
ename varchar2(20),
sal number(5),
cluster emp_dept(deptno);
ALL_CLUSTERS
ALL_ CLU STE RS descri bes all clus ters acces sible to the curren t u ser.
Related Views
It is a data base obj ect which is used to generate sequent ial integers with
the specif ied inter val value.
Generally the sequences are used to generate primar y key values.
Note: by def ault the sequence starts with 1 and increment value is also 1.
Pseudo columns:
CURRVAL
----------
1
NEXTVAL
----------
Ex: update the cust_dtls table under that update the cust _srno column
with sequence values?
Ex: Insert new record in the table cust_dtls along with sequence values?
insert into cust_dt ls
values(4,'abc','hyd',6767676765,'F',null,srno1.next val);
**************
Hands-on:
results:
3 rows select ed
3 rows updated
ID NAME SRNO
---------------------- -------------------- ----------------------
6605 AJAY 1
6610 KIRAN 2
6615 MADHU 3
3 rows select ed
Ex:
ID DESCRIPTI ON
---------- ------------------------------
1 DESCRIPTION only
999 ID=999 and DESCRI PTION
ID=NULL and DESCRI PTION
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
description VARCHAR2(30)
);
3 rows selected.
SQL>
1 row created.
SQL>
Using BY DEFAULT allows you to use the identity if the column isn't
referenced in the insert statement, but if the column is referenced, the
specified value will be used in place of the identity. Attempting to
specif y the value NULL in this case results in an error, since identity
columns are always NOT NULL .
1 row created.
1 row created.
SQL>
1 row created.
1 row created.
1 row created.
ID DESCRIPTION
---------- ------------------------------
1 Just DESCRIPTION
999 ID=999 and DESCRIPTION
2 ID=NULL and DESCRIPTION
SQL>
Note:
System def ined view to get sequences inf ormation is “user _sequences”.
SYNONYMS
Use the CREATE SYNONYM statement to create a synonym, which is an
alternative name f or a table, view, sequence, oper ator, procedure, stored
f unction, package, materialized view, Java class schema object, user -
def ined object type, or another synonym. A syno nym places a dependency
on its target object and becomes invalid if the target object is changed or
dropped.
Types of Synonyms : 2
I ) Private synonym
It is a def ault synonym. and it is used by the owner only.
or
USER_SYNONYMS
It is a system def ined view, f rom where we can retr ieve the synonyms
inf ormation
PARTITIONS
Partitioning enables you to decompose very large tables and indexes into
smaller and more manageable pieces called partitions. Each partit ion is an
independent object with its own name and optionally its own storage
character ist ics.
Using smaller boxes has several advantages. W hen asked to retrieve the
f olders f or employees hired in June, the HR manager can retrieve the June
box. Furthermore, if any small box is tem porarily damaged, the other small
boxes remain available. Moving off ices also becomes easier because instead
of moving a single heavy box, the manager can move several small boxes.
From the perspec tive of an applicat ion, only one schema object
exists. DM L statements require no modif ication to access part itioned tables.
Partit ioning is usef ul f or many dif f erent types of database applicat ions,
particularly those that manage large volumes of data. Benef its include:
Increased availabilit y
The unavailabilit y of a partit ion does not entail the unavailabilit y of the
object. The query optimizer automatically removes unref erenced
partit ions f rom the query plan so queries are not aff ected when the
partit ions ar e unavailable.
A partit ioned object has pieces that can be managed either collect ively
or individually. DDL statements can manipulate part itions rather than
entire tables or indexes. Thus, you can break up resource - int ensive
tasks such as rebuilding an index or table. For example, you can move
one table partit ion at a time. If a probl em occurs, then only the
partit ion move must be redone, not the table move. Also, dropping a
partit ion avoids executing numerous DELETE statements.
Each partit ion of a table or index must have the same logical attributes, such
as column names, data t ypes, and const raints. For example, all part itions in
a table share the same column and constraint def initions, and all part itions
in an index share the same indexed columns. However, each partit ion can
have separate physical attributes, such as the tablespace to which it
belongs.
Partition Ke y
The partition key is a set of one or more columns that determ ines the
partit ion in which each row in a partit ioned table should go. Each row is
unambiguously assigned to a single partit ion.
In the sales table, you could specif y the time_id column as the key of a
range partition. The database assigns rows to partit ions based on whether
the date in this column f alls in a specif ied range. Oracle Database
automatically directs insert, update, and delete operations to the appropriate
partit ion by using the partit i on key.
Partitioning Strategies
Oracle Partitioning off ers several partit ioning strategies that control how the
database places dat a into partit ions. The basic strat egies are range, list, and
hash partitioning.
Range Partitioni ng
Suppose that you want to populate a partitioned table with the sales rows
shown in Example 4- 1.
You create time_r ange_sales as a part itioned table using the statement
in Example 4-2. The time_id column is the partit ion key.
The range partition key value determines the high value of the range
partit ions, which is called the transition point . In Figure 4-1,
the SALES_1998 partition contains rows with partit ioning key time_id values
less than the transit ion point 01-JAN- 1999.
List Partitioning
In list partitioning, the database uses a list of discrete values as the
partit ion key f or each partit ion. You can use list part itioning to control how
individual rows map to specif ic partit ions. By using lists, you can group and
organize related set s of data when the key used to identif y t hem is not
conveniently ordered.
Af terward, you load t he table with the rows f rom Example 4-1. Figure 4-
2 shows the row dist ribut ion in the t wo partitions. The database chooses the
partit ion f or each row based on the channel_id value according to the rules
specif ied i n the PARTITION BY LIST clause. Rows with a channel_id value of
2 or 4 are stored in t he EVEN_CHANNELS partit ions, while rows with
a channel_id value of 3 or 9 are stored in the ODD_CHANNELS partit ion.
Hash Partitioning
Assume that you create the partit ioned hash_sales table using the
statement in Examp le 4-4. The prod_id column is the partit ion key.
Af terward, you load t he table with the rows f rom Example 4-1. Figure 4-
3 shows a possible row distribution in the two partit ions. Note that the names
of these partitions ar e system -generated.
As you insert r ows, the database attempt s to randomly and evenly distribute
them across part itions. You cannot specif y the partit ion into which a row is
placed. The database applies the hash f unction, whose outcome determines
which part ition contains the row. If you chan ge the number of partitions, then
the database redistr ibutes the data over all of the partitions.
C ATEGORES: 2
i) Numeri c functions
Acts on numeric dat a
i) SUM(colname)
It will display addit ion of values f rom the column
output:
SUM(SAL)
----------
29025
Ex: Find the total invest ment amount f or the products f rom sony?
Ex: Find the total balance f rom the account t ypes SB and SAL?
Output:
SQL> select sum(act _bal)
2 f rom cust_act_dt ls
3 where act_t ype in('SB','SAL');
SUM(ACT_BAL)
------------
151000
output:
SQL> select avg(cost) AvgCostOf Product
2 f rom prod_dtls;
AVGCOSTOFPRODUCT
----------------
31241.6667
iii) M AX(colname)
Display higher value from the column.
output:
MAX(SAL)
----------
1600
iv) MIN(colname)
Display lower value f rom the column
SQL> select * f rom prod_dt ls where cost I N(select min(cost) f rom prod_dt ls
where pr od_name=' MO BILE');
v) COUNT( colname)
Display number of values f rom the colum n except null values
COUNT(CO MM)
-----------
4
vi) CO UNT(*)
Display number of records f rom a table.
Note:
" Aggregate functions executes on fiel d /column level dat a "
10 5
20 7
Expect ed output:
10 5
20 7
30 5
40 2
50 1
GROUP BY Clause:
It is used to group related data by considering distinct values f rom the
column. On each group the oracle engine executes the aggregate f u nction
and display result individually.
output:
deptno No. of emps
--------- -------------
30 6
20 7
10 5
Ex: f ind out number of emps working under each dept on order of deptno?
output: 10 5
20 7
30 6
Ex:
Find out number of customers f or each account t ype?
ACT_T No of customers
----- ----------------
SB 3
SAL 3
DEMAT 1
Ex:
Find number of emps under each job cat egory f or each dept number?
SQL>
Ex: f indout min sal f or each job categor y based on the order of job?
Ex: f indout number of emps under each dept getting morethan 5000 salar y
based on the order of deptno?
Ex: f ind out number of customers f rom each cit y based on order of city?
HAVING clause:
It is used to specif y conditions on group by output.
Ex: f ind out number of emps working under each dept on order of deptno
if a dept contains at least 10 emps?
output: 20 70
30 60
Examples:
OUTPUT:
DEPTNO EMPCOUNT
---------- ----------
30 6
20 5
10 2
DEPTNO EMPCOUNT
---------- ----------
30 6
20 5
JOB EMPCOUNT
--------- ----------
CLERK 4
SALESMAN 4
PRESIDENT 1
MANAGER 2
ANALYST 2
JOB EMPCOUNT
--------- ----------
PRESIDENT 1
MANAGER 2
ANALYST 2
1) ABS( n) [ ABSOLUTE ]
Display absolute value of n.
2) mod(m,n)
Display remainder value af ter m devides n.
3) pow er(m,n)
Display m power nth value
5) ROUND(m,n)
Display value “m ” which is rounded to the “n” number of decimal
places.
Bef ore displaying “n th” Decimal digit it will check " n+1 th” decimal
digit, if it is > or = 5 then “nth ” digit incr emented by 1.
7) FLOOR(n)
Display highest int eger value which is lessthan or equal to given
value.
8) CEIL(n)
Display lowest int eger value which is greater than or equal to given
value.
65
2) LENG TH('str'/col)
Display number of chars f rom the given string or column values
Ex:
Get all employee names and also each name length?
select ename, length(ename) " length of name" f rom emp;
3) LOWER('str'/col)
Display the given string chars or column values in lower case.
Ex:
Get all employee names in lower case?
select lower(ename) f rom emp;
ENAME LOW ER(ENAM
---------- ----------
SMITH smith
ALLEN allen
W ARD ward
JONES jones
MARTIN martin
BLAKE blake
CLARK clark
SCOTT scott
KING king
TURNER turner
ADAMS adams
14 rows selected.
SQL>
hai
4) UPPER( 'str'/col)
Display given string chars or column values in upper case
W elcome To Oracle
Ex:
Get employee names with beginnin g char acter as capital?
INITCAP(EN
----------
Smith
Allen
W ard
Jones
Martin
Blake
Clark
Scott
King
Turner
Adams
INITCAP(EN
----------
James
Ford
Miller
14 rows selected.
6) SUBSTR('str'/col,m,n) (substring)
Display a substring from the given string. Here the substring started
with "m" th char and through "n" number of chars.
Ex: display second occur ance of 'e' f rom the begining of string?
output:- 11
10) TRIM('str'/col)
Display given string by eleminating blank spaces bef ore and af ter the
string.
Ex:
select trim(' welcome to ') " trim" || initcap('oracle')
f rom dual;
:welcome to Oracle
:welcome to Oracle
Ex:
select rtrim(' welcome to '), initcap(' oracle') f rom
dual;
******page 1
CONCAT returns char1 concatenated wit h char2. Both char1 and char2 can
be any of the datat ypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB,
or NCLOB. The string returned is in the same character set as char1. Its
datat ype depends on the datat ypes of the arguments.
Ex:
SELE CT CON CAT (C ON CAT( las t_n ame , '' 's j ob cat ego ry i s ') ,
F ROM em plo ye es
Job
---- --- --- --- -- -- ---- --- --- --- -- -- ---- --- --- --- -- -- ---
Ex:
Get the below out put ?
14 rows selected.
SQL>
DATE FUNCTIONS
1) TO_D ATE('char fmt of date',dat e)
It will display any non -Oracle date f ormat value in oracle's dat e f ormat.
2) ADD_MONTHS(d,n)
Display a dat e value af ter adding " n " number of months to the
specif ied date
update the expdt f or all products like 24 months f rom the date of mfg?
3) MONTHS_BETWEEN(d1,d2)
4) L AST_D AY( d)
Display the date value of last day in the month.
it will display the dat e value of given weekdayname af ter the specif ied
date.
EXTRACT (
{ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND }
| { TIMEZONE_HOUR | TIMEZONE_MINUTE }
| { TIMEZONE_REGION | TIMEZONE_ABBR }
FROM { date_value | interval_value } )
Note
You can only extract YEAR, MONTH, and DAY f rom a DATE.
You can only extract TIMEZO NE_HOUR and TI MEZO NE_MINUTE f rom
a timestamp with a t ime zone dat atype.
Applies To
The EXTRACT function can be used in the following versions of
Oracle/PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i
EXTRACT(YEARFROMSYSDATE)
------------------------
2017
Description
Parameters or Arguments
date
format
Quarter Q
W eek WW
IW IW
W W
Minute MI
Applies To
Let's look at some Oracle TRUNC f unction examples and explore how to use
the TRUNC f unction in Oracle/PLSQL.
For example:
8) CURRENT_DATE function
Description
The Oracle/PLSQL CURRENT_DATE f unction returns the curr ent date in the
time zone of the current SQL session as set by the ALTER SESSION
command.
Syntax
The synt ax f or the CURRENT_DATE f unction in Oracle/PLSQ L is:
CURRENT_DATE
Parameters or Arguments
There are no par ameters or arguments f or the CURRENT_DAT E f unction.
Applies To
The CURRENT_DATE f unction can be used in the f ollowing versions of
Oracle/PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i
Example
The CURRENT_DATE f unction can be used in Oracle/ PLSQL.
If the f ollowing ALTER SESSION command was issued:
select CURRENT_DATE
f rom dual;
9/10/2005 10:58:24 PM
You then modif ied the session t ime zone with the f ollowing ALTER SESSI ON
command:
select CURRENT_DATE
f rom dual;
9/11/2005 3:58: 24 AM
The session time zone value has changed f rom -7:0 to -2:0, causing the
CURRENT_DATE f unction to return the current date as a value 5 hours
ahead.
9) CURRENT_TIMESTAMP
CURRENT_TI MESTAMP
Parameters or Arguments
There are no par ameters or arguments f or the CURRENT_TI MESTAMP
f unction.
Note
A sim ilar f unction to the CURRENT_TI MESTAMP f unction is
the LOCALTIMESTAMP f unction .
The diff erence bet ween these t wo f unctions is that the
CURRENT_TI MESTAMP f unction returns a TIMESTAMP W ITH TIME
ZONE value while the LOCALTI MESTAMP f unction returns a
TIMESTAMP value.
Applies To
The CURRENT_TIMESTAMP f unction can be used in the f ollowing ver sions
of Oracle/PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i
Example
The CURRENT_TIMESTAMP f unction can be used in Oracle/ PLSQL.
If the f ollowing ALTER SESSION command was issued:
select CURRENT_TIMESTAMP
f rom dual;
You then modif ied the session t ime zone with the f ollowing ALTER SESSION
command:
select CURRENT_TIMESTAMP
f rom dual;
The session time zone value has changed f rom -7:0 to -2:0, causing the
CURRENT_TI MESTAMP f unction to retur n the current dat e and time as a
value 5 hours ahead.
10) LOCALTIMESTAMP
The Oracle/PLSQL LOCALTI MESTAMP f unction returns the current date and
time in the time zone of the current SQL session as set by the ALTER
SESSION command. It returns a TIMESTAMP value.
Syntax
The synt ax f or the LOCALTI MESTAMP f unction in Oracle/ PLSQL is:
LOCALTI MESTAMP
Parameters or Arguments
There are no par ameters or arguments f or the LOCALTI MESTAMP f unction.
Note
A sim ilar f unction to the LOCALTIMESTAMP f unction is
the CURRENT_TI MESTAMP f unction .
The diff erence bet ween these t wo f unctions is that the
LOCALTI MESTAMP f unction returns a TIMESTAMP value while
the CURRENT_TI MESTAMP f unction returns a TIMESTAMP W ITH
TIME ZO NE value.
Applies To
The LOCALTI MESTAMP f unction can be used in the f ollowing versions of
Oracle/PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i, Oracle 8i
Example
Let's look at some Oracle LO CALTI MEST AMP f unction examples and explore
how to use the LOCALTI MESTAMP f unction in Oracle/PLSQL.
For example:
If the f ollowing ALTER SESSION command was issued:
select LOCALTIMESTAMP
f rom dual;
10-Sep-05 10.58.24 PM
You then modif ied the session t ime zone with the f ollowing ALTER SESSION
command:
select LOCALTIMESTAMP
f rom dual;
10-Sep-05 03.58.24 AM
The session time zone value has changed f rom -7:0 to -2:0, causing the
LOCALTI MESTAMP f unction to return the current date and tim e as a value 5
hours ahead .
11) SYSTIMESTAMP
The Oracle/PLSQL SYSTI MESTAMP f unction retur ns the current syst em date
and time ( including fractional seconds and time zone) on your local
database.
Syntax
The synt ax f or the SYSTI MESTAMP f unction in Oracle/PLSQL is:
SYSTI MESTAMP
Parameters or Arguments
There are no par ameters or arguments f or the SYSTI MESTAMP f unction.
Applies To
The SYSTI MESTAMP f unction can be used in the f ollowing versions of
Oracle/PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i
Example
Let's look at some Oracle SYSTIMESTAMP f unction examples and explore
how to use the SYST I MESTAMP f unction in Oracle/PLSQL.
For example:
The var iable called v_time will now contain the date and time ( including
f ractional seconds and time zone) at the moment the command is executed.
The SYSTI MESTAMP f unction might return a value like this:
You can also choose to use the TO_CHAR f unction with the SYSTI MESTAMP
f unction.
For example:
4141.550774
You could also use the SYSTI MESTAMP f unction in any SQL statement.
For example:
1) TO_NUM BER(chardata,[numberdata])
Ex: salaries
--------
$1200
$11005 (char type dat a)
$107069.12
1) substr(sal, 2)
1200
11005 ( chardata )
107069.12
2)to_number(substr( sal,2))
3) sum(to_number(substr(sal,2)))
Ex:
price_list target_f ormat
--------- ---------------
100.78 00,00,100.78
1200.12 00,01,200.12
5463.00 (number type data) 00,05,463.00
(char f ormat)
100700.00 01,00,700.00
1223501.01 12,23,501.01
DD digits of month
Day Dayname
day dayname
DAY DAYNAME
Mon 3-chars of month wit h begining char capit al
MO N "
mon "
month f ull month name( in lower case)
MO NTH f ull month name( caps)
Month f ull month name with begining char capital
yy last 2 digits of year
YY "
yyyy complete year number
Ex:
input output
sysdate 27 September 20 14
SAMPLE EXECUTIONS:
TO_CHAR( SYSDATE,'DDMO
---------------------
28 f ebruary 2015
TO_CHAR( SYSDATE
---------------
28 f eb 2015
TO_CHAR( SYSDATE
---------------
28 FEB 2015
TO_CHAR( SYSDATE
---------------
28 Feb 2015
TO_CHAR( SYSDATE,'DDDAYMO
------------------------
28 saturday Feb 2015
SQL> select to_char(sysdate,'dd Day Mon yyyy') f rom dual;
TO_CHAR( SYSDATE,'DDDAYMO
------------------------
28 Satur day Feb 2015
TO_CHAR( SYSDATE,'DDDAYMO
------------------------
28 SATURDAY Feb 2015
4) CAST
Applies To
The CAST f unction can be used in the f ollowing versions of Oracle/ PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i
Example
Let's look at some Oracle CAST f unction examples and explor e how to use
the CAST f unction in Oracle/PLSQL.
For example:
This would convert the date ( ie: 22-Aug-2003) into a var char 2(30) value.
5) TO_TIMESTAMP
Parameters or Arguments
string1
The string that will be converted to a tim estamp.
format_mask
Optional. This is the f ormat that will be used to convert string1 to a
timestamp. It can be one or a combination of the f ollowing values
Parameter Explanation
YYYY 4-digit year
MM Month (01-12; JAN = 01).
MO N Abbreviat ed name of month.
Name of month, padded with blanks to length of 9
MO NTH
characters.
DD Day of month (1 -31).
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
Applies To
The TO_TIMESTAMP f unction can be used in the f ollowing versions of
Oracle/PLSQL:
Oracle 12c, Oracle 11g, Oracle 10g, Oracle 9i
Example
Let's look at some Oracle TO_TIMESTAMP f unction examples and explore
how to use the TO_TI MESTAMP f unction in Oracle/PLSQL.
For example:
would return '13 -DEC-03 10. 13.18.000000000 AM' as a timest amp value.
Ex:
SELECT last _name, commission_pct,
(CASE commission_pct
W HEN 0.1 THEN 'Low'
W HEN 0.15 THEN 'Aver age'
W HEN 0.2 THEN 'High'
ELSE 'N/A' END ) Commission
FRO M
employees
ORDER BY
last_name;
Ex:
select case when sal<1000 then ' low'
when sal > =1000 and sal <2000 then ' Medium'
else 'High'
end
f rom emp;
CO ALESCE function
The COALESCE f unction takes t wo or more compatible arguments and
returns the f irst argument that is not null.
The result is null only if all the argument s are null.
If all the parameters of the f unction call are dynam ic , an error occurs.
Syntax
CO ALESCE ( expression, expression [, expression]* )
The f unction must have at least t wo arguments.
Example
create tabl e w ith three different integer t ypes
create tabl e temp(smallintcol smallint, bigintcol bigint, intcol integer);
0 row s inserted/updated/deleted
3 row s selected
3 row s selected
3 row s selected
3 row s selected
DEF AULT Values Using Sequences
In Oracle 12c, it is now possible to specif y
the CURRVAL and NEXTVAL sequence pseudo columns as the def ault
values f or a column.
CREATE TABLE t1 (
id NUMBER DEFAULT t1_seq.NEXTVAL,
descript ion VARCHAR2( 30)
);
ID DESCRIPTI ON
---------- ------------------------------
1 DESCRIPTION only
999 ID=999 and DESCRI PTION
ID=NULL and DESCRI PTION
LAG
The LAG f unction is used to access data f rom a previous row. The f ollowing
query returns the salary f rom the previous row to calculate the dif f erence
bet ween the salar y of the current row and that of the previous row. Not ice
that the ORDER BY of the LAG f unction is used to or der the data by salar y.
SELECT empno,
ename,
job,
sal,
LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_prev,
sal - LAG(sal, 1, 0) OVER (ORDER BY sal) AS sal_dif f
FRO M emp;
SQL>
LEAD
The LEAD f unction is used to return data from the next row. T he f ollowing
query returns the salary f rom the next row to calculate the dif f erence
bet ween the salar y of the current row and the f ollowing row.
SELECT empno,
ename,
job,
sal,
LEAD(sal, 1, 0) OVER (ORDER BY sal) AS sal_next,
LEAD(sal, 1, 0) OVER (ORDER BY sal) - sal AS sal_diff
FRO M emp;
SELECT empno,
deptno,
sal,
RANK() OVER ( PARTITION BY dept no ORDER BY sal) "rank"
FRO M emp;
SQL>
W hat we see here is where t wo people have the same salar y t hey are
assigne d the same r ank. W hen multiple rows share the same rank the next
rank in the sequence is not consecutive.
DENSE_RANK
The DENSE_RANK function acts like the RANK f unction except that it
assigns consecutive ranks.
SELECT empno,
deptno,
sal,
DENSE_RANK() OVER (PARTITION BY deptno ORDER BY sal) "rank"
FRO M emp;
SQL>
SELECT empno,
deptno,
sal,
MIN(sal) KEEP (DENSE_RANK FIRST ORDER BY sal) OVER
(PARTITION BY dept no) "Lowest",
MAX(sal) KEEP (DENSE_RANK LAST ORDER BY sal) OVER
(PARTITION BY dept no) "Highest"
FRO M emp
ORDER BY deptno, sal;
SQL>
NVL
The NVL f unction allows you to replace null values with a def ault value. If
the value in the f irst parameter is null, the f unction returns the value in the
second parameter. If the f irst parameter is any value other than null, it is
returned unchanged.
W e know that COL1 in the test table cont ains n ull in all rows except the f irst.
Using the NVL f unction we replace the null values with 'ZERO' .
ID OUTPUT
---------- ----------
1 ONE
2 ZERO
3 ZERO
4 ZERO
SQL>
DECODE
The DECO DE f unction is not specif ically f or handling null values, but it can
be used in a sim ilar way to the NVL f unct ion, as shown by the f ollowing
example.
SQL> SELECT id, DECODE(col1, NULL, 'ZERO', col1) AS out put FRO M
null_test_tab ORDER BY id;
ID OUTPUT
---------- ----------
1 ONE
2 ZERO
3 ZERO
4 ZERO
SQL>
NVL2
The NVL2 f unction accepts three parameters. If the f irst parameter value is
not null it returns the value in the second parameter. If the f irst parameter
value is null, it returns the thir d paramet er.
The f ollowing query shows NVL2 in act ion.
SQL>
The f irst row in the test table has a not null value in COL1, so the value of
COL2 is ret urned. All other rows cont ains null in COL1, so the value of COL3
is returned.
COALESCE
The COALESCE f unction was introduced in Oracle 9i. It accepts two or more
parameters and retur ns the f irst non -null value in a list. If all parameters
contain null values, it returns null.
ID OUTPUT
---------- ----------
1 ONE
2 TW O
3 THREE
4 THREE
SQL>
NULLIF
The NULLI F f unction was introduced in Oracle 9i. It accepts two paramet ers
and returns null if both parameters are eq ual. If they are not equal, the f irst
parameter value is r eturned.
In our test table the values of COL3 and COL4 are equal in row 4, so we
would only expect null ret urned f or that row using the f ollowing query.
SQL> SELECT id, NULLIF(col3, col4) AS output FRO M null_t est_tab ORDER
BY id;
ID OUTPUT
---------- ----------
1 THREE
2 THREE
3 THREE
4
SQL>
PL/SQL
Oracle Da tabase can also sto re p rogram u nits wri tten in Ja va . A Ja va sto red
procedure is a Ja va me thod published to SQL and s to red in th e database for
general use . You can call exis ting PL/SQL programs from Ja va a nd Ja va
programs from PL/SQL.
pl/sql program
It is a collection of programming stmts and with sql concepts ( queries ) to
perf orm user required tasks .
W hat is pl/sql?
Pl/sql is a collect ion of User def ined objects like Programs, procedur es,
Funct ions, Triggers, Types, Packages and so on.
Advantages:
Multiple queries ar e executed par llelly.
It reduces number of hits to the dat abase.
In pl/sql user can cr eate the objects according to his requirements.
It increases n/ w performance.
Modularit y ( dividing a big task into smaller modules )
Enhansibilit y ( It can easily accept the f uture changes )
Reusabilit y
2 Categories of Programs
i) Anonymous Blocks ( Programs )
ii) Sub Pr ograms (Stored Procedures and Functions)
i) Anonymous Blocks
It is a program which is not saved inside t he DataBase.
It contains declarat ion stmts. Used to declare variables. So t hese var iables
get memory space f rom the database eng ine based on their datatype and
size.
Syntax:
var _name DATATYPE(size);
BEGIN block
Assignment st atements
Syntax-1:
BY USING ASSIGNMENT OPERATOR
Ex: v_eno:=7654;
Ex:
declare
x int;
y int;
z int;
begin
x:=100;
y:=200;
z:= x+ y;
Syntax-2:
By Using SELECT Query w ith INTO keyw ord
EXCEPTION Block
It is used to display user f riendly error messages instead of system
generated error messages.
END;
Indicates end of program.
NOTE:
By def ault any program or procedur e should not display output. To display
output,
begin
dbms_out put.put_line ('welcome to oracle pl/sql');
end;
Ex: wr ite a pr ogram to display addit ion , average, max and min of 3000
and 5000?
DECLARE
X INT;
Y INT:=5000;
S INT;
A NUMBER(7, 2);
MX INT;
MN INT;
BEGIN
X:=3000;
S:=X+Y;
A:=S/2;
SELECT GREATEST(X,Y) INTO MX FRO M DUAL;
SELECT LEAST(X,Y) INTO MN FRO M DUAL;
DBMS_OUTPUT.PUT_LINE(' SUM=');
DBMS_OUTPUT.PUT_LINE(S);
DBMS_OUTPUT.PUT_LINE('AVERAGE=' );
DBMS_OUTPUT.PUT_LINE(A);
DBMS_OUTPUT.PUT_LINE('HIGHER VALUE=');
DBMS_OUTPUT.PUT_LINE( MX);
DBMS_OUTPUT.PUT_LINE('Least VALUE=');
DBMS_OUTPUT.PUT_LINE( MN);
END;
/
sample execution:
SUM=
8000
AVERAG E=
4000
HIGHER VALUE=
5000
MIN VALUE=
3000
NOTE:
How can i display a normal mesg af ter that the value of var iable immediately
in the same line?
DECLARE
X INT;
Y INT:=5000;
S INT;
A NUMBER(7, 2);
MX INT;
MN INT;
BEGIN
X:=3000;
S:=X+Y;
A:=S/2;
SELECT GREATEST(X,Y) INTO MX FRO M DUAL;
SELECT LEAST(X,Y) INTO MN FRO M DUAL;
DBMS_OUTPUT.PUT_LINE(' SUM=' ||s);
--DBMS_OUTPUT.PUT_LINE( S);
DBMS_OUTPUT.PUT_LINE('AVERAGE=' ||a);
--DBMS_OUTPUT.PUT_LINE ( A);
DBMS_OUTPUT.PUT_LINE('HIGHER VALUE=' ||m x);
--DBMS_OUTPUT.PUT_LINE( MX);
DBMS_OUTPUT.PUT_LINE(' MI N VALUE='||mn);
--DBMS_OUTPUT.PUT_LINE( MN);
END;
/
sample execution:
2) Dynamic programs
Generates dif f erent output values based on dif f erent input values. In
this case the program can accept runtim e input values.
Ex: wr ite a pr ogram to display the employee inf ormation of empID 7654?
declare
veno int:=7654;
vname var char2( 20);
vsal number(5);
vjob var char2( 20);
vhiredate date;
vcomm number(4);
vdeptno number(3);
BEGIN
select ename,sal,job,hiredate,comm,dept no INTO
vname, vsal, vjob, vhir edate, vcomm,vdeptno
f rom emp
where empno= veno;
dbms_out put.put_line(' Inf o of 7654');
dbms_out put.put_line(' ---------------');
dbms_out put.put_line(vname);
dbms_out put.put_line(vsal);
dbms_out put.put_line(vjob);
dbms_out put.put_line(vhir edate);
dbms_out put.put_line(vcomm);
dbms_out put.put_line(vdeptno);
END;
/
sample output:
Inf o of 7654
MARTIN
1250
SALESMAN
28-SEP-81
1400
30
Ex:
declare
veno int:=7654;
vname var char2( 20);
vsal number(5);
vjob var char2( 20);
vhiredate date;
vcomm number(4);
vdeptno number(3);
BEGIN
select ename,sal,job,hiredate,comm,dept no INTO
vname, vsal, vjob, vhir edate, vcomm,vdeptno
f rom emp
where empno= veno;
dbms_out put.put_line(' Inf o of Emp id: 7654');
dbms_out put.put_line('======================================
=======');
dbms_out put.put_line('Name of emp: '||vname);
dbms_out put.put_line('Salar y of emp: '||vsal);
dbms_out put.put_line('Designit ion of emp: '||vjob);
dbms_out put.put_line('Join date of emp: '||vhir edate);
dbms_out put.put_line('Commission of emp: '||vcomm);
dbms_out put.put_line('Deptno of emp: '||vdeptno);
dbms_out put.put_line('======================================
=======');
END;
/
output:
Inf o of 7654
=============================================
Name of emp: MART IN
Salar y of emp: 1250
Designit ion of e mp: SALESMAN
Join date of emp: 28 -SEP-81
Commission of emp: 1400
Deptno of emp: 30
=============================================
DECLARE
VCITY VARCHAR2( 20):='Delhi';
CUST_CNT INT;
BEGIN
SELECT COUNT(*) INTO CUST_CNT FROM CUST_DTLS W HERE
CITY=VCITY;
DBMS_OUTPUT.PUT_LINE(' NUMBER OF CUSTOMERS FROM '||VCITY||' =
'||CUST_CNT);
END;
Ex:
W rite a program to display number of male customers and number of f emale
customers?
declare
male_cnt int;
f emale_cnt int;
begin
select count(*) into male_cnt f rom cust_dtls where gender='M';
select count(*) into f emale_cnt f rom cust_dtls where gender='F';
dbms_out put.put_line(' Number of m ales= '||male_cnt);
dbms_out put.put_line(' Number of Females='||f emale_cnt);
end;
Assignments:
2) W rite a program to display the cit y and mobile number of customer id "
cust-5"?
3) W rite a program to display the locat ion of department " RESEARCH "?
Dynamic Programs
By using & (Substitution ) operator we will make a program as a dynamic
program.
Instead of assigning a constant value in to a variable , W hile the execution
of the program, the program has to take a value f rom the end user and that
value stored it into a var iable.
var name:=&varname;
Ex: wr ite a pr ogram to display the details of employee f or the given
empno?
declare
v_eno number(4);
v_ename var char2( 20);
v_sal number(5);
v_j ob var char2( 20);
v_hiredate date;
v_comm int;
v_mgr_code int;
v_dept no int;
BEGIN
v_eno:='&v_eno';
select ename,sal,job,hiredate,comm,mgr,deptno I NTO
v_ename, v_sal, v_job,v_hiredate, v_comm,v_mgr_code,
v_dept no
f rom emp
where empno= v_eno;
dbms_out put.put_line(v_eno||' Employee inf ormation ');
dbms_out put.put_line
('=====================================================');
dbms_out put.put_line
('EMPNAME : EMP- SALARY : EMP-DESG : EMP- JOINDATE : comm :
manager code : deptno');
dbms_out put.put_line
('=====================================================');
dbms_out put.put_line
(v_ename||' '||v_sal||' '||v_job||' '||v_hir edate||'
'||v_comm ||' '||v_mgr_code||' '||v_deptno);
dbms_out put.put_line
('=====================================================');
end;
declare
v_eno number(4);
r emp%rowt ype;
BEGIN
v_eno:='&v_eno';
select * INTO r f rom emp
where empno= v_eno;
dbms_out put.put_line(v_eno||' Employee inf ormation ') ;
dbms_out put.put_line
('=====================================================');
dbms_out put.put_line
(r.ename||' '||r.sal||' '||r.job||' ' ||r.mgr||' '||r.hiredate||' '||r.comm||'
'||r.deptno);
dbms_out put.put_line
('=====================================================');
end;
output:
output:
7788 inf or mation
=====================================================
SCOTT 3000 ANALYST 19-APR-87
=====================================================
Ex: W rite a program to display the number of emps in the given deptno?
declare
vdno number(2);
e_count int;
begin
vdno:=&vdno;
select count(empno) into e_count f rom emp where deptno= vdno;
dbms_out put.put_line(' number of emps in Department : '||vdno||' : =
'||e_count);
end;
output:
number of emps in 20 = 5
Ex:
number of emps in 30 = 6
Ex:
wr ite a pr ogram to display the dept details under which the employee is
working with given id?
declare
veno number(4);
vdno number(4);
vdname var char2( 20);
vloc var char2( 20);
begin
veno:=&veno;
select * into vdno, vdname, vloc f rom dept
where deptno=(sel ect deptno f rom emp where empno= veno);
dbms_out put.put_line(' department details of employee : '||veno);
dbms_out put.put_line(vdno||' '||vdname||' '||vloc);
end;
Ex output:
department details of employee : 7902
20 RESEARCH DALLAS
Ex output:
department details of employee : 7788
20 RESEARCH DALLAS
Assignment
5)
W RITE A PROGRAM TO DISPLAY NUMBER OF PRODUCTS HAVI NG
W ARRENTY MANUFACTURED I N THE YEAR 2014?
DECLARE
nop int;
begin
select count(*) into nop f rom prod_dtls
where mf g between '01 -jan-14' and '31-dec-14'
and
warrent y is not null;
dbms_out put.put_line(' NUmber of products having warrent y= '|| nop);
end;
------------------------------------------------------------------------------------------------
Ex
wr ite a program to display customer account details f or the given customer
name?
declare
vcname varchar2(20);
vactno number(12);
vacttype varchar2(10);
vopendate date;
vactbal number;
vccode varchar2( 10);
begin
vcname:='&vcname';
select actno,act_t ype,act_open_date,act _bal,cust_code into
vactno, vactt ype,vopendate, vact bal, vccode
from cust_act_dtls
where cust _code =(select cno f rom cust_dt ls where cname=vcname);
Note:
%TYPE
In the above the %TYPE is taking the data type and size of the column
DEPTNO f rom the table EMP and these t hings will be applicable to the
var aible.
%ROWTYPE
Used to declare a Table Based RECORD TYPE var iable, which will supports
all columns f rom that table.
syn:
var _name tablename%ROW TYPE;
EMPREC
Syntax:
record_var_name . colname;
Ex:
W rite a program to display the inf ormation of employee f or the given
employee id?
declare
veno emp.empno%t ype; --Dynam ic declaration of variable
e_rec emp%rowt ype; --Declaring table based record t ype var iable
begin
veno:=&veno;
select * into e_rec f rom emp where empno=veno;
dbms_out put.put_line(' given employee id: '||veno);
dbms_out put.put_line(' Inf ormation of '||veno);
dbms_out put.put_line
(e_rec.ename||' ' ||e_rec.sal||' ' ||e_rec.job||' ' ||e_rec.hiredate||'
'||e_rec.comm ||' ' ||e_rec.deptno);
end;
Ex:
wr ite a pr ogram to d isplay the inf ormation of product f or the given product
id?
declare
vpid prod_dt ls.pid%t ype;
p_rec prod_dt ls%rowt ype;
begin
vpid:='&vpid';
select * into p_rec f rom prod_dt ls where pid= vpid;
dbms_out put.put_line(' inf ormation of prodid: ' ||vpid);
dbms_out put.put_line(p_rec.pname||' '||p_rec.cost ||' '||p_rec.mf g||'
'||p_rec. warrent y||' ' ||p_rec.prod_comp_id);
end;
Ex
wr ite a pr ogram to display the inf ormation of a customer f or the given
customer number ?
declare
vcustid cust_dt ls.cust id%t ype;
cust_rec cust_dt ls%rowt ype;
begin
vcustid:='&vcust id';
select * into cust_rec f rom cust_dtls where custid= vcust id;
dbms_out put.put_line(' given customer id: '||vcustid);
dbms_out put.put_line(' customer name=' ||cust_rec.custname);
dbms_out put.put_line(' customer cit y=' ||cust_rec.custcit y);
dbms_out put.put_line(' customer gender ='||cust_rec.custgender);
dbms_out put.put_line(' customer mobile
number=' ||cust _rec.custmobile);
end;
declare
vcustid customers_br 1.cid%type;
cust_rec customers_br 1%rowt ype;
begin
vcustid:='&vcust id';
select * into cust_rec f rom customers_br 1 where cid= vcust id;
/* dbms_out put.put_line(' given customer id: '||vcustid);
dbms_out put.put_line(' customer name=' ||cust_rec.cname);
dbms_out put.put_line(' c ustomer cit y=' ||cust_rec.cit y);
dbms_out put.put_line(' customer gender ='||cust_rec.gender);
dbms_out put.put_line(' customer mobile number=' ||cust _rec. mobile); */
dbms_output.put_line('GIVEN ID:' ||vcustid);
dbms_output.put_line(' ---------------------- ---------------------------------------- ');
dbms_output.put_line('NAME CITY GENDER MOBILE -
NUMBER' );
dbms_output.put_line(' --------------------------------------------------------------- ');
dbms_output.put_line(cust_rec .cname||' '||cust_rec.cit y||'
'||cust_rec.gender ||' '||cust_rec.mobile);
end;
SUB PROGRAMS
PROCEDURES
FUNCTIONS
Procedures and f unctions f ollow the basic PL/SQL block structure, which
consists of the f o llowing elements:
The general f orm of a PL/SQL block f ollows. Note also that each st ored
program unit has a header that names the unit and ident if ies it as either a
f unction, procedure, or a package.
A named pr ogram which is stored / creat ed under the data base is known
stored procedure.
It is also known as a subprogram to perf orm a task or set of tasks.
Features of a Procedure: -
a) Static Procedure
It will not contains any argument variables and it wont take any
values f rom the user at runtime.
Always display same output.
b) Dynamic procedure
A procedure with arg ument variables is known as dynamic
procedure.
It will take runtime input values f rom the user and display
dif f erent output values f or diff erent users.
i) Procedure specification
It contains creat ion of procedure inf ormation like proc_name and
argument list
Syntax:
/*Procedure specifi cation*/
/* Procedure body */
<declaration stmts>;
BEGIN
<assignment stmts>;
<data processing stmts>;
<output stmts>;
EXCEPTION
<error handling stmts>;
END <proc_name>;
Proc_name(arg_val1,arg_val2,. . . . .);
STATIC PROCEDURE
Ex: wr ite a pr ocedure which is f inding number of emps working under dept
30?
BEGIN
proc_ecount _30; --Procedure calling stmt
dbms_out put.put_line(' calling procedur e is f inished');
dbms_out put.put_line(' Program Execution is f inished');
end;
DYNAMIC PROCEDURES
SAMPLE EXECUTIONS:
EXEC PROC_2(10);
EXEC PROC_2(20);
EXEC PROC_2(30);
ex:
declare
vdno int;
begin
vdno:=&vdno;
proc_ecount _did( vdno); --Procedure calling statement
dbms_out put.put_line(' Exec Finished');
end;
For the f ollowing program we need to create 2 procedures called p_add and
p_mult i.
declare
x int;
y int;
begin
x:=&x;
y:=&y;
dbms_out put.put_line(' adding '||x ||' and '||y);
Dbms_output.put_line(' Making a call to P_ADD pr ocedure');
p_add( x, y);
dbms_out put.put_line(' Multiplicat ion of '||x||' and ' ||y);
dbms_out put.put_line(' make a call to P_MULTI procedure');
p_mult i( x, y);
dbms_out put.put_line(' 2 tasks s uccessf ully completed');
end;
STATIC PROCEDURE:
Ex: wr ite a pr ocedure to display the cust omer details and his account
details f or the custid "cust -5"?
DYNAMIC PROCEDURE:
Ex:
wr ite a pr ocedure to display the cust omer details and his account details f or
the GIVEN custid ?
Ex:
wr ite a pr ocedure to display the employee details and dept details f or the
empno 7902?
DYNAMIC PROCEDURES:
EX: wr ite a procedur e to display the det ails of employee f or the given
employee id?
||emp_rec.job||','||em p_rec.hiredate);
end proc_5;
sample output:
Ex: wr ite a pr ocedure to display the cust omer mobile number and name of
the given custid if he is male and f rom the cit y delhi?
Ex:
wr ite a pr ocedure to display number of emps working under given depar tment
name?
Ex:
wr ite a pr ocedure to display the number of customers f rom the given cit y with
given gender?
Ex:
wr ite a pr ocedure to display the number of accounts of given account t ype?
Ex:
);
Ex: r emprec; /* Here Oracle engine reser ves only 3 column length
memory */
Ex:
W rite a procedure to display the name,sal,job,hiredat e,deptno f or the given
employee id?
rec emprec;
begin
select ename,sal,job,hiredate,deptno into rec
f rom emp where empno= veno;
dbms_out put.put_line(' Ename=' ||rec.name);
dbms_out put.put_line(' EmpSal=' ||rec.esal);
dbms_out put.put_line(' Emp Job Title='||r ec.desg);
dbms_out put.put_line(' Emp join date=' ||r ec.jdate);
dbms_out put.put_line(' Emp Dept No=' ||r ec. dno);
end p_emp;
Advantages:
Ex: W rite a procedur e to display the nam e,sal,job, dno,dname, loc f or the
given employe e id?
Ex:
W rite a procedure to di splay the name,cost and warrent y of the product f or
the given product id?
Ex:
W rite a procedure to display pname,cost,mfg,exp,companyName,Dealer
address, phonenumber f or the given product id?
Ex:
wr ite a pr ocedure to display customer name, actno,act balance and act name
f or the given custom er id?
rec custrec;
begin
select cd.cname,cad.actno,at.act_name,cad.act_bal I NTO rec
f rom cust_dtls cd Inner join cust _act_dtls cad
ON cd.cno=cad.cust_code
Inner Join act_types at
ON cad.act_type=at.act_t ype
W HERE cd.cno= vcid;
1) simple if
It is having only true part. If the condit ion is true the it execut es the
stmts.
Syntax:
if (condit ion) then
stmt;
stmt;
:
end if ;
2) if -- then-- else
It is having both true and f alse parts. If the condition is true then it
executes the true part and if the condition was f ailed then it execute s
the f alse part.
Syntax:
if (condit ion) then
stmt;
stmt;
:
ELSE
stmt;
stmt;
:
end if ;
3) COMPUND IF
Syntax:
if (cond-1) then
stmts;
stmts;
if (cond-2) then
stmt;
stmts;
:
else
stmt;
:
end if ; --closing of cond -2
else
stmt;
:
end if ; --closing of cond -1
4) ELSIF construct
checking if condit ion with in else part of other if .
Syntax:
if (cond) then
stmts;
:
else
if ( cond) then
stmts;
:
else
stmts;
:
end if
stmts;
stmts;
:
end if ;
or
if (cond) then
stmt;
stmt;
:
ELSIF(cond) then
stmt;
stmt;
else
stmts;
:
END IF;
Ex:
Creat ing a procedur e to display biggest of 2 integers with simple if logic?
Ex:
Creat ing a procedur e to display biggest of 2 integers with if -then-else logic?
exec proc_bigint_2(20,10);
exec proc_bigint_2(100,100);
Ex:
Creat ing a procedur e to display biggest of 2 integers with Elsif logic?
exec proc_bigint_3(4,5);
exec proc_bigint_3(5,5);
exec proc_bigint_3(14,5);
Ex:
W rite a program to display biggest of integers if any one given value is null?
IF (a>b) THEN
DBMS_OUTPUT.PUT_LINE('FI RST VALUE IS BIG');
elsif (a=b) then
dbms_output.put_line(' Values are equal');
else
DBMS_OUTPUT.PUT_LINE(' Second VALUE IS BIG');
END IF;
DBMS_OUTPUT.PUT_LINE('end of execution');
END PROC_BIGINT_4;
Ex:
wr ite a pr ocedure to f ind which t ype of customers( either male customers or
f emale customers) less in count, f rom the given cit y?
Ex:
wr ite a pr ocedure to f ind the higher number of customers f rom the given 2
cities?
Ex:
wr ite a pr ocedure to f ind the total balance amount in the given account type?
Ex:
W rite a procedure to display the number of products f rom the given 2
company names and f ind out f rom which company we have less number of
products?
Ex:
W rite a procedure to display the number of mobile products f rom the given 2
company names?
Ex:
W rite a procedure to display the total number of customers opted f or given
account type?
Ex:
wr ite a pr ocedure to display the higher total f unds f rom the given 3 t ypes of
accounts?
LOOPS
Loops are used to execute the set of st atements repeatedly.
Types: 3
1) simple loop
Syntax:
LOOP
stmt;
stmt;
:
EXIT W HEN(condition);
stmt;
stmt;
:
END LOOP;
2) FOR LOOP
Syntax:
FOR <varname> IN [ REVERSE ] range_of _values
LOOP
stmt;
stmt;
:
END LOOP;
Ex: f or x in 1..5
loop
dbms_out put.put_line(x);
end loop;
output:
1
2
3
4
5
Ex: f or x in REVERSE 1. .5
loop
dbms_out put.put_line(x);
end loop;
OUTPUT:
5
4
3
2
1
3) WHILE LOOP
Syntax:
WHILE ( cond )
loop
stmt;
stmt;
:
end loop;
x int:=1;
begin
--x:=1;
dbms_out put.put_li ne(' By using simple loop');
dbms_out put.put_line(' -----------------------');
loop
dbms_out put.put_line(x);
x:= x+1;
exit when( x > 10);
end loop;
DBMS_OUTPUT.PUT_LINE(' END OF SI MPLE LOOP');
DBMS_OUTPUT.PUT_LINE(' ');
f or y in 1..10
loop
dbms_out put.put_line(y);
end loop;
DBMS_OUTPUT.PUT_LINE(' END OF FOR LOOP');
DBMS_OUTPUT.PUT_LINE(' ');
f or y in REVERSE 1. .10
loop
dbms_out put.put_line(y);
end loop;
DBMS_OUTPUT.PU T_LINE(' END OF FOR LOOP');
DBMS_OUTPUT.PUT_LINE(' ');
Ex: wr ite a pr ocedure to display sequent ial even numbers f rom given
number TO GIVEN NUMBER?
Ex: wr ite a pr ocedure to insert the records lik e radius, pi value and area
values into the table "circle"
f or the radius range 1 to 10?
sample output:
10 rows selected
Ex: wr ite a pr ocedure to display reverse num ber f or the given number?
EX:
ERRORS LI KE:
01422. 00000 - "exact f etch returns more than requested number of rows"
....
NOTE:
General programs or procedur es cannot be able to display m ult iple
records f rom a table or multiple values f rom a column.
Exception handlers:
i) TOO_MANY_ROW S
It can be raised when the select stmts is selecting data f rom multiple
records.
ii) NO_DATA_FOUND
It can be raised if there is no matched data f rom the table.
iv) CURSOR_ALREADY_OPEN
It can be raised if we are trying to open a cursor which is alr eady
opened.
v) VALUE_ERROR
It can be raised if there is incom patibilit y bet ween declar ed variable
and recieving value by that variable.
EXAMPLE PROCEDURES:
Ex:
W rite a procedure to display employee names and job f or the given salar y?
EXEC PROC_NO_EXCEP(5000);
EXEC PROC_NO_EXCEP(800);
EXEC PROC_NO_EXCEP(10000);
VNAME EMP.ENAME%TYPE;
VJOB EMP.JOB%TYPE;
BEGIN
SELECT ename,job INTO vname, vjob f rom emp where sal= vsal;
dbms_out put.put_line('Name of emp: '||vname||' ; Job of emp: '||vj ob);
dbms_out put.put_line(' End of procedure ');
EXCEPTION
W HEN TOO_MANY_ROW S THEN
DBMS_OUTPUT.PUT_LINE(' SAL IS DUPLICATED');
DBMS_OUTPUT.PUT_LINE(' END OF TOO_M ANY_ROW S--Except ion');
W HEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('REQUIRED SAL IS NOT AVAILABLE');
DBMS_OUTPUT.PUT_LINE(' END OF NO DATA FOUND');
end proc_excep;
Ex:
W rite a procedure to display the employee details who is working with
given designit ion?
sample outputs:
Ex: wr ite a pr ocedure to display customer account det ials f or the given
customer id?
If customer have multiple account or n o account or no custid then
display corresponding message?
2) User defined exceptions / Unnamed Exceptions
Here user has to manage the exceptions. User has to RAISE the
except ion if he is expecting any error. The exception is to raised by
using exception var iable name. The exception variable is acts as and
EXCEPTION HANDLER in exception block.
ii) Raise the except ion using the keywor d RAISE in begin block
Ex: wr ite a pr ocedure to display the commission of the employee for the
given employee id?
create or replace procedure pr oc_emp_comm( veno
emp.empno%t ype)
is
vcomm emp.comm%type;
comm_miss except ion; /* Declaring Exception t ype variable , Then is
acting as except ion Handler.*/
begin /* we can def ine exception handler in exception
block */
select comm into vcomm f rom emp where empno= veno;
sample output:
ex: wr ite a pr ocedure to display the mf g, exp and warrent y of the given
product id?
If any one is null then display corresponding message?
1. exception_nam e
2. error_num ber
Example Code
user-named_exp.sql
SQL>edit user-named_exp
DECLARE
myex EXCEPTION;
PRAGMA EXCEPTION_INIT(myex,-20015);
n NUMBER := &n;
BEGIN
FOR i IN 1..n LOOP
dbms_output.put.line(i);
IF i=n THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
dbms_output.put.line('loop finish');
END;
/
Example Result
SQ L >@ us e r- n am ed _e xp
n n um ber & n = 5
1
2
3
4
5
l oo p f in is h
P L/ SQ L pr oc e d ur e s uc c es s f u l l y op er at i o n.
RAISE_APPLICATION_ERROR
Example Code
raise_app_error.sql
SQL>edit user-named_exp
DECLARE
myex EXCEPTION;
n NUMBER := &n;
BEGIN
FOR i IN 1..n LOOP
dbms_output.put.line(i);
IF i=n THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
RAISE_APPLICATION_ERROR(-20015, 'loop finish');
END;
/
CURSORS
query------> sql stmt executor --> Oracle engine --> oracle DB-- > DD-->actual
data-->
----> temp memory area ( CURSOR ) --->cache memor y-----> CLIENT
[ from view ]
In the above the required data can be pr ocessed in the temporar y memory
area ( cursor ), and t hen displayed to the client . This is the case if we are
selecting the data f rom the table.
CURSORS
It is a temp memory area, is used to perform intermediate operations bef ore
output displayed to t he client.
Types of cursors: 2
1) Implicit cursors
A cursor which is used by sql quer y. This type can be assigned and
managed by DB engine.
Properties:
2) Explicit cursors
These are declar ed and def ined and managed by user. Gener ally we
can use explicit cursors to display mult iple records f rom
the table through programs or procedures.
Ex: cursor c_mgr is select * f rom emp where job=' MANAG ER';
This f etch operation should be done repeatedly unt il all recor ds are
processed in, the cursor.
Ex: LOOP
FETCH c_mgr INTO REC;
stmt;
stmt;
EXIT W HEN (c_mgr%NOTFOUND);
stmt;
stmt;
END LOOP;
Ex: wr ite a pr ocedure to display the employee details f rom given deptno?
If we ar e f etching data f rom multiple tables mult iple recor ds, then we
need to declare cursor based record var iable . It supports all columns f rom
the cursor.
Ex: wr ite a pr ocedure to display the emp loyee details of given job?
begin
open c_emp;
dbms_out put.put_line(' the given job tit le: '||vjob);
dbms_out put.put_line('all '||vj ob||' inf ormation');
LOOP
FETCH c_emp INTO r;
exit when (c_emp%notf ound);
dbms_out put.put_line(r.empno||' ' ||r.ename||' ' ||r.job||' ' ||r.sal||'
'||r.hiredate||' ' ||r.deptno);
end loop;
close c_emp;
end proc_emp_inf o_ with_givenjob;
sample output:
Ex: wr ite a pr ocedure to display the employee names and salar ies, their
department names and locations?
NOTE:
cursor type var iable will supports all columns with in the cursor. No
matter the columns are f rom which table.
sample output:
E MP - N A ME E MP - S A L A R Y D e p a r t m e n t n a m e department-Location
========= ========== =============== ===================
S MI T H 800 RESEARCH DALLAS
ALLEN 1600 SALES CHICAGO
WARD 1250 SALES CHICAGO
JONES 2975 RESEARCH DALLAS
MA R TI N 1250 SALES CHICAGO
BLAKE 2850 SALES CHICAGO
CLARK 2450 A C C O U N TI N G N EW YO R K
SCOTT 3000 RESEARCH DALLAS
KING 5000 A C C O U N TI N G N EW YO R K
TURNER 1500 SALES CHICAGO
A D A MS 1100 RESEARCH DALLAS
J A ME S 950 SALES CHICAGO
FORD 3000 RESEARCH DALLAS
MI L L E R 1300 A C C O U N TI N G N EW YO R K
dinesh 3400 O P E R A TI O N S BOSTON
----------------------------------------------------------------------------------------------------------------
rec c_acts%rowt ype; /* Declar ing a cursor based variable , supports all
columns f rom cursor */
begin
open c_acts;
dbms_out put.put_line(' Customers and their Accounts inf ormation ');
dbms_out put.put_li ne('CustName---custCit y--- Account No: Account Bal
Account Name');
dbms_out put.put_line(' ----------------------------------------------------------------- ');
loop
f etch c_acts into rec;
EXIT when (c_acts%notf ound);
dbms_out put.put_line(rec.cname||' ----' ||r ec.cit y||' ---' ||rec.actno||'
'||rec. Act_bal||' '||r ec.act_name);
end loop;
close c_acts;
end proc_cust _act_inf o;
CREATE OR REPLACE
PROCEDURE get_emp_rs (p_deptno IN emp.deptno%TYPE,
p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT ename,
empno,
deptno
FROM emp
WHERE deptno = p_deptno
ORDER BY ename;
END GetEmpRS;
/
Funct ion also contains 2 parts. i.e Specif icat i on and Body like procedur e.
Syntax
create or replace function <f unc_name> ( argvar datat ype, argvar
datat ype...... )
RETURN <datat ype>
IS
<declaration stmts>;
begin
<assignment stmts>;
<data processing stmts>;
<output stmts>;
Except ion
<error handling stmts>;
......
RETURN( value/ var_name);
END <f unc_name>;
Note:
A Funct ion can be called through any SELECT or PROGRAM or Procedure.
declar e
s1 int;
s2 int;
r int;
begin
s1:=&s1;
s2:=&s2;
dbms_output.put_line(' calling f unction f rom a procedure thr ough
program');
dbms_output.put_line(' ');
p_add(s1,s2); /* Procedure calling stmt */
dbms_output.put_line(' completed');
dbms_output.put_line(' ------');
dbms_output.put _line(' calling f unction f rom program directly');
r:=f _add(s1,s2); /* f unction calling stmt */
dbms_output.put_line(' result='||r);
dbms_output.put_line(' completed');
end;
Example:
declare
a int;
b int;
output int;
begin
a:=&a;
b:=&b;
output:=f _add(a,b);
dbms_out put.put_line(' result f rom f unction='||output);
end;
Ex: wr ite procedur e to display esal,bonus value and f inal salar y ( basic
sal+ bonus)
f or the given employee id?
sal<1000 2%
>=1000 &< 2000 5%
>=2000 &<3000 10%
>=3000 &<5000 20%
>=5000 25%
Ex: write a procedur e to display the above output f or all emps with in given
job category?
It is a data base obj ect which logically groups the related obj ects. It reduces
the search t ime f or the required object according to required action.
It contains 2 parts
package created.
EX:package body
/* PROC_EMP_FSAL */
loop
f etch c into veno, vsal;
dbms_out put.put_line(' The salar y details of '||ven o);
b:=f unc_bonus( vsal); /* f unction calling stmt */
f sal:=vsal+b;
EXIT W HEN (C%NOTFOUND);
dbms_out put.put_line
( vsal||' '||b||' '||f sal);
END LOOP;
CLOSE C;
end proc_emps_f sal;
END PKG_EMP_FSAL;
How to dr op a package?
<5000 5%
>=5000 &<10000 10%
>=10000 &<20000 15%
>=20000 20%
Ex: wr ite a pr ocedure to display the f inal amount paid to the customer by
adding interest amount f or the principal amount?
Do the above pr ocess f or given customer id?
Do it f or all customers?
Do it f or given type of account holders?
Collections are used in some of the most important perf ormance optim izat ion
f eatures of PL/SQL, such as
BULK COLLECT. SELECT statements that retrieve mult iple rows with a
single f etch, increasing the speed of data retrieval.
FOR ALL. Inserts, updates, and deletes t hat use collect ions to change
multiple rows of data ver y quickly
Table functions. PL/SQL f unctions that r eturn collections and can be called
in the FRO M clause of a SELECT statem ent.
You can also use collect ions to work with lists of data in your program that
are not stored in database tables.
This article introduces you to collect ions and g ives you a solid f oundation in
both collection syntax and f eatures.
Collection Concepts and Term inology
Index value. The location of the data in a collect ion. Index values are
usually integers but f or one type of collection can also be strings.
Collections were f irst introduced in Oracle7 Ser ver and have been enhanced
in several ways through the years and across Oracle Database versions.
There are now thr ee types of collections t o choose f rom, each with its own
set of characterist ics and each best suited to a dif f erent circumstance.
Associati ve array. The f irst type of collection available in PL/SQL, this was
originally called a “PL/SQL table” and can be used only in PL/SQL blocks.
Associat ive arrays can be sparse or dense and can be indexed by integer or
string.
Nested table. Added in Oracle8 Database, the nested table can be used in
PL/SQL blocks, in SQL statements, and as the datat ype of columns in tables.
Nested tables can be sparse but are almost always dense. They can be
indexed only by integer. You can use the MULTISET operator to perf orm set
operat ions and to perf orm equalit y compariso ns on nested tables.
Varray. Added in Oracle8 Dat abase, the varr ay ( variable -size array) can be
used in PL/SQL blocks, in SQL statement s, and as the datat ype of columns
in tables. Varrays ar e always dense and indexed by integer. W hen a varray
type is def ined, you must specif y the maximum number of elements allowed
in a collect ion declar ed with that t ype.
You will rarely encounter a need f or a var ray ( How many times do you know
in advance the maximum number of elements you will def ine in your
collect ion?). T he associative array is the most commonly used collect ion
type, but nested tables have some power f ul, unique f eatures (such as
MULTISET operators) that can simplif y the code you need to wr ite to use
your collection.
Variable sized array. Array is able to stor e multiple values wit h same data
type at cont inuous m emory locations. Here we must specif y the size.
and the specif ied size is f ixed.
Ex: e1 empsal;
e2 empsal;
e1
|
-------------------------------------------------------------------------------
| | | | | | | | |.......20 locations
Ex: e1:=empsal(2300,3400,2000,1200,......);
e1
|
-------------------------------------------------------------------------------
|2300 |3400 |2000 |1200 | | | | |.......20 locations
Ex:
e1(3)
e1(1)
declare
x int:=1;
f or i in e1.f irst..e1.last
loop
dbms_out put.put_line(e1( x));
x:= x+1;
end loop;
declare
type esal is varray( 5) of number;
type enames is varr ay( 5) of varchar(10);
vsal esal;
vename enames;
x int:=1;
begin
Note:
The f ollowing are methods used along with Array t ype variables.
Collection Methods
A variet y of methods exist f or collections, but not all are relevant f or ever y
collect ion type.
MULTISET Conditions
Oracle provides MULTISET condit ions ag ainst collect ions, including the
f ollowing.
MULTISET UNION joins the t wo collect ions together, doing the equivalent of
a UNION ALL bet ween the t wo sets.
SET SERVEROUTPUT ON
DECLARE
TYPE t_tab IS TABLE OF NUMBER;
l_tab1 t_tab := t_tab(1,2,3,4,5,6);
l_tab2 t_tab := t_tab(5,6,7,8,9,10);
BEGIN
l_tab1 := l_tab1 MULTISET UNION l_t ab2;
SQL>
BULK COLLECT
It improves the perf ormance of database. It el iminates the context switching
bet ween program area and cursor area.
By using this we can take all values f rom the cursor at a time and
control coming to program area and save that collect ed values in t o array
type variable.
Ex:
W rite a procedure to Display all employee names with out BULK COLLECT
and varrays?
Ex: wr ite a pr ocedure to display employee names f rom emp using varr ays
and bulk collect ?
BULK COLLECT:
It reduces number of context switches f rom program Memor y to cursor
Memor y and vice ver sa. There by it is Increasing DB perf ormance.
vename enames;
vsal esal;
x int:=1;
begin
open c;
end proc_names_sal;
exec proc_names_sal;
sample output:
Associat ive
|
----------------------------------------------------------
| | | | ........ N is size( NO specif ication
of size)
Ex:
asso(1)
asso(abc)
Ex: W rite a procedur e to display employee names and salar ies using
Associat ive arrays, bulk collect?
/* creating array t ype structures f or storing employee names and salar ies */
open c;
end proc_name_sal;
exec proc_name_sal;
sample output:
Ex:
W rite a procedure to display all product names,cost using bulk collect and
associat ive Arrays?
----> To def ine a PL/ SQL type f or nested tables, use the
Ex: Display empid,enam e and salar ies of all emps with given job?
emp_rec e_arr;
x int:=1;
begin
open c_emp;
f etch c_emp bulk collect into emp_r ec;
close c_emp;
dbms_out put.put_line( 'Inf ormation of '||vjob||'s');
dbms_out put.put_line(' -----------------------------------------');
f or i in 1..emp_rec.count
loop
dbms_out put.put_line (emp_rec( x).eid||';' ||emp_rec( x).nam e||';'||emp_rec( x).s
alar y);
x:= x+1;
end loop;
end proc_empjob_rec;
SET SERVEROUTPUT ON
DECLARE
TYPE countr y_r ec IS RECORD (
iso_code VARCHAR2(5),
name VARCHAR2(50)
);
countr y_arr
1 2| 3
----------------------------------------------------------------------------------------
| | | |.....
| | |
FOR i IN 1 .. 4
LOOP
IF v_countr y(i). iso_code = 'DE' THEN
DBMS_O UTPUT.PUT_LINE('ISO code "DE" = ' || v_countr y(i).name);
END IF;
END LOOP;
END;
/
Ex:
SET SERVEROUTPUT ON
DECLARE
TYPE countr y_t ab I S TABLE OF VARCHAR2( 50)
INDEX BY VARCHAR2(5);
END;
SET SERVEROUTPUT ON
DECLARE
TYPE countr y_t ab I S TABLE OF VARCHAR2( 50)
INDEX BY VARCHAR2(5);
END;
IN Parameter
Ex:
CREATE OR REPLACE PROCEDURE W ELCO ME AS
SITE CHAR(80) := 'FYICenter.com';
PROCEDURE W ELCO ME_PRINT(S IN CHAR) AS
BEGIN
DBMS_O UTPUT.PUT_LINE('W elcome to ' || S);
-- S := 'Google.com'; -- Not allowed
END;
BEGIN
W ELCOME_PRINT('MySpace.com');
W ELCOME_PRINT(SITE);
END;
/
OUT Parameter
Ex:
/* calling Program */
declare
veid emp.empno%t ype;
vsal emp.sal%t ype;
begin
veid:=&veid;
proc_e_sal( veid, vsal);
dbms_out put.put_line(' emp salar y= ' ||vsal);
end;
begin
select ename into vename f rom emp wher e empno= veno;
dbms_out put.put_line(' Vename value ret urned to Calling Program');
end proc_ename_out;
declare
veid int;
empname var char2( 20);
Begin
veid:=&veid;
--Procedure calling stmt
Proc_ename_out( veid,empname);
dbms_out put.put_line('name of '||veid|| ' is ' ||empname);
end;
IN OUT Paramet er
Ex:
iii)Trigger action
It implements or repr esent the logic or f unctionalit y of the trigger, that
is what it is doing f or dml operat ion.
Types of triggers: 12
At row level
FOR E ACH ROW --It enable the trigger execution f or each record inside the
table.
The f ollowing are record level triggers
At statement level --Trigger is execut ed only once f or any number aff ected
records f or a dml operation.
:NEW--It represents the new values into a column[ insert & Af ter update ]
:OLD--It represents t he old values f rom a column [ Bef ore update & bef ore
delete ]
Syntax:
create or replace trigger <trig_name>
[bef ore / af ter]
[ insert / updat e /delete ] of <col1>,<col2>......
on <table name>
FOR EACH ROW
declare
------
------
BEGIN
------------
------------
------------
END <trig_name>;
trigger created.
Ex: table
ENAME CITY
-------------------- --------------------
Kiran Delhi
madhu Delhi
DINESH HYD
smith texas
Ex: wr ite a tr igger to insert or update the data of employee in upper case?
begin
if inserting then
opname:=' inserted';
insert into emp_audit_New
values(:new.ename,:new.cit y,opname,sysdate);
end if ;
if updating then
opname:='Bef ore Update -oldvalues';
insert into emp_audit_Changed values
(:old.ename,:old.cit y,opname,sysdate);
if deleting then
opname:='delet ing';
insert into emp_audit_delete values
(:old.ename,:old.cit y,opname,sysdate);
end if ;
end trig_emp_Audit;
sample examples:
ENAME CITY
---------- ----------
A CHENNAI
b chennai
s blore
X DALLAS
Y TEXAS
1 row deleted.
NOTE:
system table: USER_TRIGGERS
CASE statement:
The CASE statement begins with the keyword CASE. The keyword is
f ollowed by a select or.
The select or expression can be arbitrar ily complex. For example, it can
contain f unction calls. Usually, however, it consists of a single variable. The
selector expression is evaluated only once. The value it yields can have any
PL/SQL dat at ype other than BLOB, BFILE, an object type, a PL/SQL record,
an index-by-t able, a varr ay, or a nested table.
The select or is f ollowed by one or more W HEN clauses, which are checked
sequentially.
The value of the selector determines which clause is executed. If the value
of the selector equals the value of a W HEN -clause expr ession, that W HEN
clause is executed.
If the CASE statement selects the implicit ELSE clause, PL/SQL raises the
predef ined exception CASE_NOT_FOUND. So, there is always a def ault
action, even when you omit the ELSE clause.
SYNTAX:
CASE select or
W HEN expr ession1 THEN sequence_of _statements1;
W HEN expr ession2 THEN sequence_o f _statements2;
...
W HEN expr essionN THEN sequence_of _statementsN;
[ELSE sequence_of _statementsN+1;]
END CASE;
Example:
declare
grade char;
begin
dbms_out put.put_line(' Select anyone Grade f rom the f ollowing');
dbms_out put.put_line(' A B C D F');
grade:='&grade';
CASE grade
W HEN 'A' THEN dbms_output.put_line( 'Excellent');
W HEN 'B' THEN dbms_output.put_line( 'Ver y Good');
W HEN 'C' THEN dbms_output.put_line( 'Good');
W HEN 'D' THEN dbms_output.put_line( 'Fair');
W HEN 'F' THEN dbms_ output.put_line( 'Poor');
ELSE dbms_out put.put_line('Invalid grade select ion');
END CASE;
END;
PL/SQL also pr ovides a se arched CASE statement, which has the f orm:
CASE
W HEN search_condit ion1 THEN sequence_of _statements1;
W HEN search_condit ion2 THEN sequence_of _statements2;
...
W HEN search_condit ionN THEN sequence_of _statementsN;
[ELSE sequence_of _statementsN+1;]
END CASE;
The searched CASE statement has no selector. Also, its W HEN clauses
contain search conditions that yield a Boolean value, not expressions that
can yield a value of any t ype. An example f ollows:
CASE
W HEN grade = 'A' THEN dbms_output.put_line('Excellent');
W HEN grade = 'B' THEN dbms_output.put_line('Ver y Good' );
W HEN grade = 'C' THEN dbms_output.put_line('Good');
W HEN grade = 'D' THEN dbms_output.put_line('Fair');
W HEN grade = 'F' THEN dbms_outp ut.put_line('Poor');
ELSE dbms_out put.put_line(' No such grade');
END CASE;
Ex: wit h out FORALL
It is used to improve the perf ormance while doing dml operat ion inside
the loop.
Instead of f or loop we are using FORALL keyword.
DECLARE
aa_subset subset_aat;
BEGIN
END;
/
UTL_FILE Example
In the above query utl_f ile_dir is the logical name f or the path
‘E:\PLSQL’.W e can mention the logical name utl_f ile_dir inside the program
in uppercase within single quotes (utl_f ile_dir is mapped to t he dir ector y
‘E:\PLSQL’)W e can create any number of logical path names( DBA
director ies) in or acle 10g.
Example 1:
The follow ing is the procedure to read a text file in the file system and
inserting the text file contents(row s) into a table that is present in
oracle 10g dat abase .
ENAME VARCHAR2(15)
JOB VARCHAR2(15)
MG R NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
no rows selected
This PL/ SQL procedure w ill insert data(row s) from the text file called
‘input.txt’ to the database table emp12 in scott schema.
Connected.
USER is “SCOTT”
f _line varchar2(2000);
f _dir varchar2(250);
Comma2 varchar(10) ;
Comma3 varchar(10) ;
Comma4 varchar(10) ;
Comma5 varchar(10) ;
f _empno emp.empno%type;
f _ename emp.ename%type;
f _job emp.job%type;
f _mgr emp.mgr%type;
f _hiredate emp.hiredate%type;
begin
f _dir := ‘E:\PLSQL’;
loop
begin
-–using a loop cont inuously get the f ile’s content using get_line f unction
except ion
exit;
end;
-–and use the locat ions to get the f ield f rom the line.
insert into emp12 VALUES (f _empno,f _ename,f _job,f _mgr,f _hiredate,f _sal);
end loop;
commit;
end;
Step 4) check the emp12 table that the row s from external text file gets
inserted or not.
Example 2:
This PL/ SQL Procedure w rite the contents of the database table ‘emp’
in the scott schema to a text file called ‘emp_table.txt’ in the w indow s
directory ‘E: \ PLSQ L’
Connected.
USER is “SCOTT”
cursor empc is
line varchar2(300);
begin
line:=
‘============================================================
======================================’;
rpad(employ.ename, 20,’ ‘) ||
rpad(employ.job,20,’ ‘) ||
rpad(employ.hiredat e,30,’ ‘) ||
rpad(employ.sal,30,’ ‘) ||
end loop;
end;
/
Procedure creat ed.
begin
Example 2:
begin
f or employ in empc
loop
stmt := rpad(employ. empno,10, ’ ‘) ||
rpad(employ.ename, 20,’ ‘) ||
rpad(employ.job,20,’ ‘) ||
rpad(nvl(to_char(em ploy.mgr),’ ‘),30, ’ ‘) ||
rpad(employ.hiredat e,30,’ ‘) ||
rpad(employ.sal,30,’ ‘) ||
rpad(nvl(to_char(em ploy.comm),’ ‘),25, ’ ‘) ||
rpad(employ.deptno, 8,’ ‘);
utl_f ile.PUTF(f ile1, stmt);
utl_f ile.new_line(f ile1);
end loop;
utl_f ile.f close(f ile1);
end;
/
Procedure creat ed.
SQL> execut e writ e_f ile;
PL/SQL procedur e successf ully completed.
Step 2) Af ter execut ion of the above procedure a new f ile emp_table.t xt is
created in the locat ion ‘E: \PLSQL’ as shown in the below scr eenshot.
Step 3)Open the text document emp_table.txt to view the out put.
SQL * LOADER
SQL*Loader loads data f rom external f iles into tables of an Oracle database.
It has a powerf ul dat a parsing engine that puts litt le lim itation on the f ormat
of the data in the dat af ile. You can use SQL*Loader to do the f ollowing:
Load data across a net work if your data f il es are on a diff erent system
than the dat abase.
Load data f rom multiple dataf iles dur ing the same load session.
Load data into mult iple tables dur ing the same load session.
Specif y the character set of the data.
Selectively load data (you can load recor ds based on the records'
values).
Manipulate the data bef ore loading it, using SQL f unctions.
Generate unique seq uential key values in specif ied columns.
Use the operat ing system's f ile system to access the dataf iles.
Load data f rom disk, tape, or named pipe.
Generate sophisticat ed error reports, which greatly aid
troubleshooting.
Load ar bitrar ily com plex object -relat ional data.
Use secondar y dataf iles f or loading LOBs and collections.
A typical SQL*Loader session takes as input a control f ile, which controls the
behavior of SQL*Loader, and one or more dataf iles. The output of
SQL*Loader is an Oracle database ( wher e the data is loaded) , a log f ile, a
bad f ile, and potentially, a discard f ile.
SQL*Loader is invoked when you specif y the sqlldr command and, opt ionally,
parameters that establish session characteristics.
In situat ions where you always use the same parameters f or which the
values seldom chang e, it can be more eff icient to specif y parameters using
the f ollowing methods, rather than on the command line:
Parameters specif ied on the command line overr ide any par ameter values
specif ied in a param eter f ile or OPTIONS clause.
Although not precisely def ined, a control f ile can be said to have three
sections.
The second section consists of one or more INTO TABLE blocks. Each of
these blocks contains inf ormation about t he table into which the data is to be
loaded, such as the t able name and the columns of the table.
The third sect ion is optional and, if present, contains input data.
The synt ax is f ree -f ormat (statements can extend over mult iple lines).
It is case insensitive; however, strings enclosed in single or double
quotation marks are taken literally, including case.
In control f ile syntax, comments ext end f rom the two hyphens ( --) that
mark the beginning of the comment to the end of the line. The optional
third sect ion of the control f ile is interpr eted as data rather than as
control f ile syntax; consequent ly, comments in this sect ion ar e no t
supported.
The keywords CONSTANT and ZONE have special meaning to
SQL*Loader and are theref ore reserved. To avoid potent ial conf licts,
Oracle recommends that you do not use either CONSTANT or ZONE as
a name f or any tables or columns.
Note:
If data is specif ied inside the control f ile ( that is, INFILE * was specif ied in
the control f ile), then the data is inter pret ed in the stream record f ormat with
the def ault record terminator.
This example specif ies that SQL*Loader should interpret the particular
dataf ile as being in f ixed record f ormat where ever y record is n bytes long.
Example 6-1 shows a control f ile that specif ies a dataf ile tha t should be
interpr eted in the f ixed record f ormat. The dataf ile in the example contains
f ive physical records. Assuming that a period (.) indicates a space, the f irst
physical recor d is [001,...cd,.] which is exactly eleven byt es ( assuming a
single-byte character set). The second record is [0002,f ghi, \n] f ollowed by
the newline charact er (which is the eleventh byte), and so on. Note that
newline characters are not required with t he f ixed record f ormat.
Note that the length is always interpreted in bytes, e ven if character -length
semantics are in ef f ect f or the f ile. This is necessar y because the f ile could
contain a mix of f ields, some of which are processed with character -length
semantics and other s which are pr ocessed with byte - length semantics.
See Charact er -Length Semant ics .
load data
inf ile 'example.dat' "f ix 11"
(col1, col2)
example.dat:
00003,lmn,
1, "pqrs",
0005,uvwx,
In this example, n specif ies the number of bytes in the record length f ield.
If n is not specif ied, SQL*Loader assumes a length of 5 bytes.
Specif ying nlarger than 40 will result in an error.
Example 6-2 shows a control f ile specif ication that tells SQL*Loader to look
f or data in the dataf ile example.dat and to expect var iable record f ormat
where the record length f ields ar e 3 bytes long. The example. dat dataf ile
consists of three physical records. The f irst is specif ied to be 009 (that is, 9)
byt es long, the second is 010 bytes long (that is, 10, including a 1 -byte
newline), and the third is 012 bytes long (also including a 1 -byte newline).
Note that newline characters are not required with the var iable recor d
f ormat. This example also assumes a sing le -byte charact er set f or the
dataf ile.
The lengths are always interpr eted in byt es, even if charac ter-length
semantics are in ef f ect f or the f ile. This is necessar y because the f ile could
contain a mix of f ields, some processed with char acter -length semantics and
others processed with byte -length semant ics. See Character -Length
Semant ics.
(col1 char(5),
col2 char(7))
example.dat:
009hello,cd,010wor ld,im,
If the character set specif ied with the NLS_LANG paramet er for your session
is diff erent from the character set of the dataf ile, character st rings are
converted to the character set of the dataf ile. This is done bef ore
SQL*Loader checks f or the def ault recor d terminator.
Hexadecimal strings are assumed to be in the character set of the dataf ile,
so no conversion is perf ormed.
Example 6-3 illustrates loading data in stream record f ormat where the
terminator string is specif ied using a char acter string, '|\n'. The use of the
backslash character allows the character string to specif y the nonpr intable
line f eed character.
load data
(col1 char(5),
col2 char(7))
example.dat:
Logical Records
SQL*Loader organizes the input dat a int o physical recor ds, according to the
specif ied record f ormat. By def ault a physical record is a logical recor d, but
f or added f lexibilit y, SQL*Loader can be instructed to combine a number of
physical recor ds i nto a logical record.
Most control-f ile f ield specif icat ions claim a particular part of the logical
record. This mapping takes the f ollowing f orms:
The byte position of the data f ield's beginning, end, or bot h, can be
specif ied. This specif ication f orm is not the most f lexible, but it
provides high f ield -setting perf ormance.
The strings delimit ing (enclosing and/or t erminat ing) a particular data
f ield can be specif ied. A delim ited data f ield is assumed to st art where
the last data f ield ended, unless the byte position of the start of the
data f ield is specif ied.
The byte off set and/or the length of the data f ield can be specif ied.
This way each f ield starts a specif ied number of bytes f rom where the
last one ended and continues f or a specified length.
Length-value datat ypes can be used. In t his case, the f irst n number of
byt es of the data f ield contain inf ormation about how long the rest of
the data f ield is.
The SQL*Loader control f ile is a text f ile t hat contains data def inition
language (DDL) instr uctions. DDL is used to control the f o llowing aspects of
a SQL*Loader session:
In general, the control f ile has three main sections, in the f ollowing order:
2 LOAD DATA
4 BADFILE 'sample.bad'
5 DISCARDFILE 'sample.dsc'
6 APPEND
7 INTO TABLE em p
9 TRAILING NULLCOLS
10 (hiredate SYSDATE,
NULLIF deptno=BLANKS,
":comm * 100"
In this sample control f ile, the numbers that appear to the lef t would not
appear in a real cont rol f ile. They are keyed in this sample to the
explanat or y notes in the f ollowing list:
1. This is how comments are entered in a control f ile. See Comments in
the Control File .
2. The LOAD DATA statement tells SQL*Loader that this is the beginning
of a new data load. See Appendix A f or syntax inf ormation.
3. The INFILE clause specif ies the name of a dataf ile containing data
that you want to load. See Specif ying Dataf iles .
4. The BADFILE clause specif ies the name of a f ile int o which r ejected
records are placed. See Specif ying the Bad File .
5. The DISCARDFILE clause specif ies the name of a f ile into which
discarded records ar e placed. See Specif ying the Discar d File .
6. The APPEND clause is one of the options you can use when loading
data into a table that is not empt y. See Loading Data into Nonempt y
Tables.
7. The INTO TABLE clause enables you to identif y tables, f ields, and
datat ypes. It def ines the relat ionship bet ween records in the dataf ile
and tables in the dat abase. See Specif ying Table Names .
8. The W HEN clause specif ies one or more f ield condit ions. SQL*Loader
decides whether or not to load the data based on these f ield
conditions. See Loading Recor ds Based on a Condit ion .
9. The TRAILING NULLCOLS clause tells SQL*Loader to treat any
relat ively posit ioned columns that are not present in the recor d as null
columns. See Handling Short Recor ds wit h Missing Data .
10. The remainder of the control f ile contains the f ield list, which
provides inf ormation about column f ormats in the table being loaded.
Comments in th e Control File
Comments can appear anywhere in the command sect ion of the f ile, but they
should not appear within the data. Precede any comment with two hyphens,
f or example:
--This is a comment
All text to the right of the double hyphen is ignor ed, unt il the end of the line.
C:\Program Files\Oracle\temp>sqlldr
scott/tiger@127.0.0.1/pdb1 data=dependents.txt
control=dataload.txt
ORACLE QUESTIONS
1) Can we create a New table with any old table struct ure ?
A: Yes we can. That is while creation of new table ,use any f alse condit ion
as below
example.
Ex:
create table emp_new
as
select * f rom emp_old where 1= 2;
A: Yes we can add a constraint without checking exist ing dat a ,by using
NO VALIDATE CONSTRAI NT.
[ But bef ore doing above , the table created with DIFFERABLE column. On
this column
we can add NO VALIDATE constraint ]
A: select distinct *
f rom(select sal, dense_rank() over(order by sal desc ) rank from emp)
where rank=n
Note: In the above exam ple , n value is any integer value like 1,2,3,4.. . .
7) W hat is the dif f erence bet ween TRUNCATE and DELETE operations?
A: Truncate command delete all the recor ds f rom the table per manently.
Delete command delete all or some of records f rom the table , but we can
restore
deleted records using rollback.
8) W hat is the dif f erence bet ween Inner j oin and Correlated j oin?
A: Inner join will display only matched data f rom both tables according to
join
condit ion.
OUTER join will display complete data f rom any one table and only
matched dat a
according to join condition.
9) W e are not allowed to perf orm one dml operation on CO MPOSITE VIEW ,
what is that?
A: No .
12) W hat is the use index , why it is and what is the diff erence bet ween
view and index?
A: Index is a data base object which cont ains ordered data f rom column
,physically.
Index is usef ul to search f or the required data as much as f ast.
A: Group by clause internally makes logical groups based on dist inct values
f rom column.
14) what is the dif f erence bet ween HAVI NG and W HERE clauses?
A: Bulk collect reduce the CONTEXT SW ITCH bet ween cursor area and
program area.
so it improves perf ormance of pl/sql pr ogram.
23) How can i see the so urce code of any database object?
A: select
dbms_metadata.get_ddl('object_t ype','Object_name')
f rom dual;
3) W hat is the output from below quer y, if emp table has 10 records?
a) No output
b) 1000 pr inted one t ime
c) 1000 pr inted 1000 times
d) 1000 pr inted 10 times
a) YES
b) NO
c) SO ME TI MES
d) None of above
a) UPDATE
b) INSERT
c) MERGE
d) UPSERT
7) W hat is the dif f erence bet ween Inner j oin and Outer join?
a) Innerjoin get all data f rom all tables & Outer join
get only data f rom one table
b) Inner join get matched data f rom all tables based on join condition
& Outer join gets all data f rom one table and get matched data
from other table
c) Inner join get un - matched dat a and outer join get matched data.
d) none of above
a) YES
b) NO
13) Can i use HAVING clause wit hout GROUP BY clause in a query?
a) YES
b) NO
a) SUBSTR()
b) INSTR()
c) LTRI M()
d) RTRI M()
a) %ROW TYPE
b) TYPE
c) %CURSORTYPE
d) %TYPE
a) yes
b) NO
c) May be
d) None
SQL FAQs
1. Explain: a.) Integrit y Constraints
It can be called as a declarative way in order to def ine a business rule f or a
table's column
2) Index
- It can be called as an opt ional structur e which is associated with a table f or
direct access to the rows
- Index can be creat ed f or one or more columns in a table
3) Extent
- It can be def ined as a specif ic number of contiguous data blocks in single
allocation.
- It is used to store a specif ic t ype of inf ormation.
7) W hat is a view?
- It is virtual table which is def ined as a stored proced ure based on one or
more tables.
8) W hat are the varoius com ponents of physical database str ucture of Oracle
database?
Oracle dat abase comprises of three kinds of f iles:
- Dataf iles,
- Redo log f iles,
- Control f iles.
14) W hat suggestions do you have to reduce the net work traffic?
Following are some of the actions which can be taken to reduce the net work
traff ic:
- Use snapshots to r eplicate data.
- Use remote procedure calls.
- Replicate data in distribut ed environment.
15) W hat is a sub query? W hat are its var ious types?
- Sub Quer y also ter med as Nest ed Quer y or Inner Quer y is used to get data
f rom multiple tables.
- A sub quer y is added in the where clause of the main query.
Ans:
% ROW TYPE is used when a quer y retur ns an ent ire row of a table or view.
TYPE RECORD, on t he other hand, is used when a quer y ret urns column of
dif f erent tables or views.
Eg. TYPE r_emp is RECORD (sno smp.smpno%type,sname smp sname
%type)
e_rec smp ROW TYPE
Cursor c1 is select smpno,dept f rom smp;
e_rec c1 %ROW TYPE
Ans:
Cursor is a named pr ivate ar ea in SQL f rom which inf ormation can be
accessed. They are r equired to process each row individually f or queries
which return multiple rows.
Ans:
Cursor declares %ROW TYPE as loop index implicit ly. It then opens a cursor,
gets rows of valu es f rom the active set in f ields of the record and shuts when
all records are processed.
Eg. FOR smp_rec IN C1 LOOP
totalsal=totalsal+sm p_recsal;
ENDLOOP;
Ans:
A PL/SQL pr ogram unit associated with a particular database table is called
a database trigger. It is used f or :
1)Audit data modif ications.
2)Log events transparently.
3)Enf orce complex business rules.
4) Maintain replica tables
5)Der ive column values
6)Implement Complex secur ity author izat ions
Ans:
Error handling part of PL/SQL block is called Exception. They have t wo types
: user_def ined and predef ined.
Ans:
ZERO_DIVIDE
CURSOR_ALREADY_OPEN
VALUE_ERROR
Ans:
It is a procedure of package DBMS_STANDARD that allows issuing of
user_def ined error m essages f rom database trigger or stored sub -program.
8) Show how f unct ions and pr ocedures are called in a PL/SQ L block.
Ans:
Funct ion is called as a part of an expression.
total:=calculate_sal( ‘b644’)
Procedure is called as a statement in PL/SQL.
calculate_bonus(‘b644’);
Ans:
A syntax error can be easily detected by a PL/SQL compiler. For eg,
incorrect spelling.
A runtime error is handled with the help of exception -handling section in an
PL/SQL block. For eg, SELECT INTO statement, which does not return any
rows.
Ans:
For a CO MMIT statement, the f ollowing is true:
Other users can see the data changes made by the transaction.
The work done by the transact ion becom es permanent.
A ROLLBACK statem ent gets issued when the transact ion ends, and the
f ollowing is true.
The work done in a transit ion is undone as if it was never issued.
It undoes all the work done by the user in a transact ion. W ith
SAVEPOINT, only part of transaction can be undone.
Ans:
A cursor is implicit by def ault. The user cannot control or pr ocess the
inf ormation in this cursor.
If a query returns multiple rows of data, the program def ines an explicit
cursor. This allows t he applicat ion to pr ocess each row sequentially as the
cursor returns it.
Ans:
DECLARE stat ement is used by PL/SQL anonymous blocks such as with
stand alone, non -stored procedures. If it is used, it must com e f irst in a
stand alone f ile.
13) How many triggers can be applied to a table?
Ans:
A maximum of 12 triggers can be applied to one table.
Ans:
SQLCODE returns the value of the number of error f or the last encountered
error whereas SQLERRM returns the message f or the last error.
Ans:
the %ISOPEN cursor status variable can be used.
Ans:
Cursor_Already_Open
Invaid_cursor
Ans:
NVL converts NULL to another specif ied value.
var:= NVL( var2,’Hi’);
IS NULL and IS NOT NULL can be used to check specif ically t o see whether
the value of a var iable is NULL or not.
Ans:
No, SQL*Plus does not have a PL/SQL Engine embedded in it . Thus, all
PL/SQL code is sent direct ly to database engine. It is much m ore eff icient as
each statement is not individually stripped off .
Ans:
A triggering statement or event.
A restrict ion
An act ion
Ans:
%ISOPEN : Checks if the cursor is open or not
%ROW COUNT : The number of rows that are updat ed, deleted or f etched.
%FOUND : Checks if the cursor has f etched any row. It is true if rows are
f etched
%NOT FOUND : Checks if the cursor has f etched any row. It is True if rows
are not f etched.
21) How would you r ef erence column values BEFORE and AFTER you have
inserted and deleted triggers?
Ans:
Using the keyword “new.colum n name”, the triggers can ref erence col umn
values by new collection. By using the keyword “old.column name”, they can
ref erence column vaues by old collect ion.
Ans:
SYSDATE ref ers to the current ser ver system date. It is a pseudo column.
USER is also a pseudo column but ref ers to current user logged onto the
session. They are used to monit or chang es happening in the table.
Ans:
ROW ID is the logical address of a row, it is not a physical c olumn. It
composes of data block number, f ile num ber and row number in the data
block. Thus, I/O time gets minimized retrieving the row, and r esults in a
f aster query.
Ans:
Fetching a cursor reads Result Set row by ro w.
Ans:
Closing a cursor clears the private SQL area as well as de -allocates memor y
Ans:
Anonym ous blocks are unnamed blocks that are not stored anywher e but
sub-programs are compiled and stored in database. They are compiled at
runtime.
Ans:
DECODE and CASE statements are ver y similar, but CASE is ext ended
ver sion of DECODE. DECO DE does not allow Decision making statement s in
its place.
select decode(totalsal=12000, ’high’,10000,’medium ’) as decode_tesr f rom
smp where smpno in (10,12,14,16);
This statement retur ns an error.
You can watch my youtube training videos using below link.
THANK YOU
DINESH