Oracle 9

download Oracle 9

of 57

Transcript of Oracle 9

  • 8/6/2019 Oracle 9

    1/57

    Oracle

    Create Command

    Create command is used to create a Table or a relation.

    Syntax: Create table tablename (Field1 datatype, Field1 datatype,., Field n datatype)

    SQL> create table emp (eno number (8), ename varchar2 (20), esal number (10));

    Table created.

    Describe Command

    Describe command is used to see the description of a table.

    Syntax: Desc tablename

    SQL> desc emp;

    Name Null? Type

    ------------------------------- -------- ----

    ENO NUMBER(8)

    ENAME VARCHAR2(20)ESAL NUMBER(10)

    Insert command

    Insert command is used to insert the values in a table.

    Syntax: insert into tablename values (value1, value2,.., value n)

    insert into emp values(1,shyam,5000);

    SQL> insert into emp values (&eno,'&ename',&esal);

    Enter value for eno: 1

    Enter value for ename: suresh

    Enter value for esal: 20000old 1: insert into emp values(&eno,'&ename',&esal)

    new 1: insert into emp values(1,'suresh',20000)

    1 row created.

    SQL> /

    Enter value for eno: 2

    Enter value for ename: ajayEnter value for esal: 15000

    old 1: insert into emp values(&eno,'&ename',&esal)

    new 1: insert into emp values(2,'ajay',15000)

    1 row created.

    SQL> /Enter value for eno: 3Enter value for ename: vijay

    Enter value for esal: 18000old 1: insert into emp values(&eno,'&ename',&esal)

    new 1: insert into emp values(3,'vijay',18000)

    1 row created.

    SQL> /

  • 8/6/2019 Oracle 9

    2/57

    Enter value for eno: 4

    Enter value for ename: arun

    Enter value for esal: 17

    old 1: insert into emp values(&eno,'&ename',&esal)

    new 1: insert into emp values(4,'arun',17)

    1 row created.Select Command

    Select command is used to view the table.

    Syntax:

    Select columnname from emp

    Select columnname1, columnname2, columnname3 from emp

    Select * from emp

    SQL> select * from emp;

    ENO ENAME ESAL

    --------- -------------------- ---------

    1 suresh 20000

    2 ajay 15000

    3 vijay 180004 arun 17

    Update Command

    Update command is used to update the values of a table.

    Syntax: update tablename set columnname=value where columnname=value

    SQL> update emp set esal=17000 where eno=4;

    1 row updated.

    SQL> select * from emp;

    ENO ENAME ESAL--------- -------------------- ---------

    1 suresh 20000

    2 ajay 15000

    3 vijay 18000

    4 arun 17000

    Alter Command :

    Alter command is used to alter the structure of a table. Alter command has three attributes namely add,

    modify and drop.

    Add: Adding a column in a table.

    Modify: Modify the size of a column.

    Drop: Dropping a column of a table.

    Syntax: Add Column

    Alter table tablename add (column datatype)

    SQL> alter table emp add (city varchar2 (15));

    Table altered.

    SQL> select * from emp;

  • 8/6/2019 Oracle 9

    3/57

    ENO ENAME ESAL CITY

    --------- -------------------- --------- ----------

    1 suresh 20000

    2 ajay 15000

    3 vijay 180004 arun 17000

    SQL> update emp set city='CHD 'where eno=1;

    1 row updated.

    SQL> update emp set city='CHD 'where eno=2;

    1 row updated.

    SQL> update emp set city='AMBALA' where eno=3;

    1 row updated.

    SQL> update emp set city='banur' where eno=4;

    1 row updated.

    SQL> select * from emp;

    ENO ENAME ESAL CITY

    --------- -------------------- --------- -----------

    1 suresh 20000 CHD

    2 ajay 15000 CHD

    3 vijay 18000 AMBALA

    4 arun 17000 banur

    SQL> desc emp;Name Null? Type

    ------------------------------- -------- ----

    ENO NUMBER(8)

    ENAME VARCHAR2(20)

    ESAL NUMBER(10)CITY VARCHAR2(15)

    Syntax: Modify Column

    Alter table tablename modify (column datatype)

    SQL> alter table emp modify(city varchar2(20));

    Table altered.

    SQL> desc emp;

    Name Null? Type

    ------------------------------- -------- ----

    ENO NUMBER(8)

    ENAME VARCHAR2(20)

    ESAL NUMBER(10)

    CITY VARCHAR2(20)

  • 8/6/2019 Oracle 9

    4/57

    Syntax: Drop Column

    Alter table tablename drop column columnname

    SQL> alter table emp drop column city ;

    Table altered.

    SQL> desc emp;

    Name Null? Type

    ------------------------------- -------- ----

    ENO NUMBER(8)

    ENAME VARCHAR2(20)ESAL NUMBER(10)

    Delete Command

    Delete command is used to delete a row from a table.

    Syntax: Delete from tablename where cloumnname=value

    SQL> delete from emp where eno=3;

    1 row deleted.SQL> select * from emp;

    ENO ENAME ESAL CITY

    --------- -------------------- --------- --------------------

    1 suresh 20000 CHD

    2 ajay 15000 CHD

    4 arun 17000 banur

    Truncate command:

    Truncate command is used to truncate or empty or delete all rows of a table.Syntax:Truncate table tablename

    SQL> truncate table emp;

    Table truncated.

    SQL> select * from emp;

    no rows selected

    SQL> desc emp;

    Name Null? Type

    ------------------------------- -------- ----ENO NUMBER(8)

    ENAME VARCHAR2(20)ESAL NUMBER(10)

    CITY VARCHAR2(20)

    Drop Command:

    Drop command is used to drop the structure of a table permanently.

    Syntax: Drop table tablename

  • 8/6/2019 Oracle 9

    5/57

    SQL> drop table emp;

    Table dropped.

    SQL> desc emp;

    ERROR:ORA-04043: object emp does not exist

    Slash Command(/) :

    Slash command is used to rerun the previous command.

    SQL> create table employee(eno number(8),ename varchar2(20),esal number(10));

    Table created.

    SQL> insert into employee values(&eno,'&ename',&esal);

    Enter value for eno: 1

    Enter value for ename: arun

    Enter value for esal: 12000

    old 1: insert into employee values(&eno,'&ename',&esal)new 1: insert into employee values(1,'arun',12000)

    1 row created.

    SQL> /

    Enter value for eno: 2

    Enter value for ename: raani

    Enter value for esal: 14000

    old 1: insert into employee values(&eno,'&ename',&esal)

    new 1: insert into employee values(2,'raani',14000)

    1 row created.

    SQL> /

    Enter value for eno: 3

    Enter value for ename: raaj

    Enter value for esal: 15000

    old 1: insert into employee values(&eno,'&ename',&esal)new 1: insert into employee values(3,'raaj',15000)

    1 row created.

    SQL> /

    Enter value for eno: 4

    Enter value for ename: harpreet

    Enter value for esal: 17000old 1: insert into employee values(&eno,'&ename',&esal)

    new 1: insert into employee values(4,'harpreet',17000)

    1 row created.

    SQL> select * from employee

    ENO ENAME ESAL

    --------- -------------------- ---------

  • 8/6/2019 Oracle 9

    6/57

    1 arun 12000

    2 raani 14000

    3 raaj 15000

    4 harpreet 17000

    COLUMN ALIASES:-

    SQL> select empno "employee no",ename "employee name",edep "employee department" from emp1;

    employee no employee name employee department

    ------------------ ------------------------ ----------------------------------

    10 Amit HR

    20 Sumit Mkt

    30 Harish Finance

    40 Avneet sales50 Neha Admin

    60 Rajat Prod6 rows selected.OPERATORS:-

    1. ARITHMETIC OPERATOR:-

    SQL> select empno,ename,esalary*12 "Annual Salary" from emp1;

    EMPNO ENAME Annual Salary------------- -------------- ----------------------

    10 Amit 120000

    20 Sumit 144000

    30 Harish 276000

    40 Avneet 180000

    50 Neha 192000

    60 Rajat 288000

    6 rows selected.

    SQL> select * from emp1;

    EMPNO ENAME EDEP ESALARY EADD ELOC

    -------------- -------------- ---------- -------------- ------------ ---------------

    10 Amit HR 10000 #1276,sec-12b chd

    20 Sumit Mkt 12000 #897/a amb

    30 Harish Finance 23000 #986 Mohali

    40 Avneet sales 15000 #908 Pkl50 Neha Admin 16000 #765,d Pat

    60 Rajat Prod 24000 #127,b Banur

    6 rows selected.

    2. COMPARISON/RELATIONAL OPERATOR:-

    SQL> select * from emp1 where empno!=20;

    EMPNO ENAME EDEP ESALARY EADD ELOC

    ----------- ----------- ----------- -------------- ----------------- -----------------

  • 8/6/2019 Oracle 9

    7/57

    10 Amit HR 10000 #1276,sec-12b chd

    30 Harish Finance 23000 #986 Mohali

    40 Avneet sales 15000 #908 Pkl

    50 Neha Admin 16000 #765,d Pat

    60 Rajat Prod 24000 #127,b Banur

    A) BETWEEN:-

    SQL> select * from emp1 where esalary between 10000 and 20000;

    EMPNO ENAME EDEP ESALARY EADD ELOC

    ----------- ------------- ---------- -------------- -------------------- --------------10 Amit HR 10000 #1276,sec-12b chd

    20 Sumit Mkt 12000 #897/a amb

    40 Avneet sales 15000 #908 Pkl

    50 Neha Admin 16000 #765,d Pat

    B) IN:-

    SQL> select * from emp1 where edep in('HR','Sales');

    EMPNO ENAME EDEP ESALARY EADD ELOC------------- ------------- -------- ------------- -------------------- ---------------

    10 Amit HR 10000 #1276,sec-12b chd

    C) LIKE:-

    SQL> select * from emp1 where ename like 'A%'

    EMPNO ENAME EDEP ESALARY EADD ELOC---------- -------------- ---------- ------------ ----------------- ------------------

    10 Amit HR 10000 #1276,sec-12b chd

    40 Avneet sales 15000 #908 Pkl

    3. LOGICAL OPERATOR:-

    A) AND OPERATOR:-

    SQL> select * from emp1 where esalary=23000 and edep='Finance';

    EMPNO ENAME EDEP ESALARY EADD ELOC

    ------------- ------------ ---------- ----------- ---------- ---------------30 Harish Finance 23000 #986 Mohali

    B) OR OPERATOR:-

    SQL> select * from emp1 where esalary=15000 or edep='HR';

    EMPNO ENAME EDEP ESALARY EADD ELOC

    ------------- ------------- --------- --------- ----------------- ---------------10 Amit HR 10000 #1276,sec-12b chd

    40 Avneet sales 15000 #908 Pkl

  • 8/6/2019 Oracle 9

    8/57

    4. SET OPERATORS:-

    We created two tables emp1 and emp2 with the following enteries:-

    SQL> select * from emp2;

    EMPNO ENAME ESALARY----------- ----------- ------------

    70 Mohit 9000080 Roshan 25000

    90 Ajay 17000

    30 Harish 23000

    SQL> select * from emp1;

    EMPNO ENAME EDEP ESALARY EADD ELOC

    -------------- -------------- ---------- -------------- ------------ ---------------

    10 Amit HR 10000 #1276,sec-12b chd

    20 Sumit Mkt 12000 #897/a amb

    30 Harish Finance 23000 #986 Mohali

    40 Avneet sales 15000 #908 Pkl

    50 Neha Admin 16000 #765,d Pat60 Rajat Prod 24000 #127,b Banur

    6 rows selected.

    A) UNION:-

    SQL> select empno from emp1 union select empno from emp2;

    EMPNO

    ---------10

    20

    3040

    50

    60

    70

    8090

    9 rows selected.

    B) UNION ALL:-

    SQL> select empno from emp1 union all select empno from emp2;

    EMPNO--------------

    1020

    30

    40

    50

    60

    70

    80

  • 8/6/2019 Oracle 9

    9/57

    90

    30

    10 rows selected.

    C) INTERSECT:-

    SQL> select empno from emp1 intersect select empno from emp2;

    EMPNO

    ---------

    30

    D) MINUS:-

    SQL> select empno from emp1 minus select empno from emp2;

    EMPNO

    ---------

    10

    2040

    5060

    CONSTRAINTS:-

    Constraints are the rules and regulations which we impose on our table fields.They are used to maintain the

    consistency of the database.We have three categories of constraints:

    1. Domain Level Constraint : NOT NULL , CHECK

    2. Entity Integrity Constraint: PRIMARY KEY, UNIQUE

    3. Referential Integrity Constraint: FOREIGN KEY

    1) DOMAIN LEVEL CONSTRAINT:-

    We are inserting a null value in ename field of emp2 table.

    SQL> insert into emp2 values(100,'',8000);

    1 row created.

    SQL> select * from emp2

    EMPNO ENAME ESALARY

    ------------ ------------ -----------

    70 Mohit 9000080 Roshan 25000

    90 Ajay 17000

    30 Harish 23000

    100 8000

    Now we implement a NOT NULL constraint on emp2 table.Constraint can be applied at the time of table

    creation. So by dropping the table emp2 and creating it again implementing a NOT NULL constraint:

    NOT NULL:-Create table emp2(empno number(3),ename varchar2(30) constraint emp_en_nn not null,esalary

    number(10));

    Table Created.

  • 8/6/2019 Oracle 9

    10/57

    CHECK:-

    Check constraint can be applied at the time of table creation and at the time of alteration as well.

    At the time of creation:

    Create table emp2(empno number(3),ename varchar2(30),esalary number(10) constraint emp_sal_chkcheck(esalary>5000));

    Table Created.

    At the time of alteration:

    SQL> alter table emp2 add constraint emp_sal_chk check(esalary>5000);

    Table altered.

    B) ENTITY INTEGRITY CONSTRAINTS:-

    Entity Integrity constraints can also be created at both times at the time of creation and at the time of

    alteration of a table.

    UNIQUE:-

    SQL> alter table emp add constraint emp_dn_uq unique(dname);

    Table altered.

    PRIMARY KEY:-

    SQL> alter table emp add constraint emp_eno_pk primary key(eno);alter table emp add constraint emp_eno_pk primary key(eno)

    *

    ERROR at line 1:

    ORA-02437: cannot enable (SCOTT.EMP_ENO_PK) - primary key violated

    C) REFERENTIAL INTEGRITY CONSTRAINTS:-

    FOREIGN KEY:-SQL> alter table emp add constraint emp_dno_fk foreign key(dno) references dep(dno);

    Table altered.

    SQL FUNCTIONS:-

    We have Single row functions and Group functions in SQL.

    Single row functions are further divided into following categories:

    1. Character Functions

    2. Numeric Functions

    3. Date Functions

    4. Miscellaneous Functions5. Conversion Functions

    Let us discuss them

    SINGLE ROW FUNCTIONS:-A) Character Functions:-

    i) INITCAP:-

    It makes the first Charcter of the string as capital.

    SQL> select empno,initcap(ename),esalary from emp1;

    EMPNO INITCAP(ENAME) ESALARY

    --------- -------------------- ---------

    10 Amit 10000

  • 8/6/2019 Oracle 9

    11/57

    20 Sumit 12000

    30 Harish 23000

    40 Avneet 15000

    50 Neha 16000

    60 Rajat 24000

    6 rows selected.

    Ii) LOWER:-

    It converts the field into lowercase.

    SQL> select empno,lower(ename),esalary from emp1;

    EMPNO LOWER(ENAME) ESALARY--------- -------------------- ---------

    10 amit 10000

    20 sumit 12000

    30 harish 23000

    40 avneet 15000

    50 neha 16000

    60 rajat 24000

    6 rows selected.

    iii) UPPER:-

    It converts the field into uppercase.

    SQL> select empno,upper(ename),esalary from emp1;

    EMPNO UPPER(ENAME) ESALARY

    --------- -------------------- ---------

    10 AMIT 10000

    20 SUMIT 1200030 HARISH 23000

    40 AVNEET 15000

    50 NEHA 1600060 RAJAT 24000

    6 rows selected.

    iv) LTRIM:-It trims the given set of characters from a string from left.

    SQL> select ltrim ('amit','am') from emp1 where empno=10;

    LT

    --

    it

    1 rows selected.

    v)RTRIM:-It trims the given set of characters from a string from right.

    SQL> select rtrim ('amit','it') from emp1 where empno=10;

    RT

    --

    am

  • 8/6/2019 Oracle 9

    12/57

    1 rows selected.

    vi)TRANSLATE:-

    It replaces a character by a single character.

    SQL> select empno,translate('neha','a','u') from emp1 where empno=50;

    EMPNO TRAN--------- ----

    50 nehu

    1 rows selected.

    vii)REPLACE:-It replaces a character by multiple characters.

    SQL> select empno, replace('sumit','i','ee') from emp1 where empno=20;

    EMPNO REPLAC

    --------- ------

    20 sumeet

    1 rows selected.

    viii)LENGTH:-It counts the number of characters in a string.

    SQL> select empno,length(ename) from emp1;

    EMPNO LENGTH(ENAME)

    --------- -------------

    10 4

    20 5

    30 640 6

    50 4

    60 5

    6 rows selected.

    ix) SUBSTR:-

    It fetches the given substring from a string.SQL> select substr('HELLOWORLD',4,5) from dual;

    SUBST

    -----

    LOWOR

    x) LPAD:-

    SQL> select lpad('amit',10,'*') from dual;

    LPAD('AMIT

    ----------

    ******amit

    1 rows selected.

    xi) RPAD:-

  • 8/6/2019 Oracle 9

    13/57

    SQL> select rpad('amit',10,'*')from dual;

    RPAD('AMIT

    ----------------amit******

    1 rows selected.

    xii) CONCAT:-

    SQL> select concat('hello','world') from dual;

    CONCAT('HE

    ----------

    Helloworld

    xiii) INSTR:-

    SQL> select instr('hello','e') from dual;

    INSTR('HELLO','E')

    ------------------2

    B) NUMERIC FUNCTIONS:-

    i) ABS():-

    SQL> select abs(-31) from dual;

    ABS(-31)

    -------------

    31

    ii) CEIL():-

    SQL> select ceil(100.23) from dual;

    CEIL(100.23)

    ------------

    101

    iii) FLOOR():-

    SQL> select floor(100.23) from dual;

    FLOOR(100.23)

    -------------

    100

    iv) POWER():-

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

  • 8/6/2019 Oracle 9

    14/57

    POWER(2,3)

    ----------

    8

    v) MOD():-

    SQL> select mod(10,3) from dual;

    MOD(10,3)

    ---------

    1

    vi) ROUND():-

    SQL> select round(23.467235,2) from dual;

    ROUND(23.467235,2)

    ------------------

    23.47

    vii) TRUNCATE():-

    SQL> select trunc(23.461235,2) from dual;

    TRUNC(23.461235,2)

    ------------------

    23.46

    viii) SQRT():-

    SQL> select sqrt(4) from dual;

    SQRT(4)

    ---------

    2

    C) DATE FUNCTIONS:-

    i. ADD_MONTHS:-

    SQL> select add_months(sysdate,6) from dual;

    ADD_MONTH

    ---------

    29-MAY-10

    ii. SYSDATE:-

    SQL> select sysdate from dual;

    SYSDATE

    ---------29-NOV-09

    iii. MONTHS_BETWEEN:-

    SQL> select months_between(sysdate,'15-oct-09') from dual;

    MONTHS_BETWEEN(SYSDATE,'15-OCT-09')

    -----------------------------------

  • 8/6/2019 Oracle 9

    15/57

    1.4819736

    iv. LAST_DAY:-

    SQL> select last_day('14-jul-09') from dual;

    LAST_DAY(

    ---------31-JUL-09

    v. NEXT_DAY:-

    SQL> select next_day(sysdate,'Sunday') from dual;

    NEXT_DAY(---------

    06-DEC-09

    D) MISCELLANEOUS FUNCTIONS:-

    i. UID:-

    SQL> select uid from dual;

    UID

    ---------20

    ii. USER:-

    SQL> select user from dual;

    USER

    ------------------------------

    SCOTT

    E) CONVERSION FUNCTIONS:-

    i. TO_CHAR():-

    SQL> select to_char(sysdate) from dual;

    TO_CHAR(S---------

    29-NOV-09

    ii. TO_NUMBER():-

    SQL> select to_number('123') from dual;

    TO_NUMBER('123')

    ----------------123

    iii. TO_DATE():-

    SQL> select to_date('29-NOV-09') from dual;

    TO_DATE(S

    ---------

    29-NOV-09

  • 8/6/2019 Oracle 9

    16/57

  • 8/6/2019 Oracle 9

    17/57

    1 A 10

    2 B 20

    3 C 30

    4 D 10

    5 E 20

    SQL> select * from dep;DNO DNAME DLOC

    --------- --------------- ----------

    10 HR Chd

    20 MKT Moh

    30 SALES Banur

    Implementing equii join on both tables:

    SQL> select emp.eno,emp.enmae,emp.dno,dep.dname from emp,dep where emp.dno=dep.dno;

    ENO ENMAE DNO DNAME

    --------- --------------- --------- ---------------

    1 A 10 HR

    4 D 10 HR

    2 B 20 MKT5 E 20 MKT

    3 C 30 SALES

    2. NON-EQUII JOIN

    Lets have a look at both the tables i.e. emp2 and salgrade table.

    SQL> select * from emp2;

    ENO ENAME ESAL

    --------- ---------- ---------1 A 5500

    2 B 6500

    3 C 140004 D 2200

    5 E 25000

    SQL> select * from salgrade;

    GRADE LOSAL HISAL--------- --------- ---------

    1 700 1200

    2 1201 1400

    3 1401 2000

    4 2001 3000

    5 3001 9999

    Implementing non equii join on both tables:SQL> select e.eno,e.ename,e.esal,s.grade from emp2 e,salgrade s where e.esal between s.losal and s.hisal;

    ENO ENAME ESAL GRADE--------- ---------- --------- ---------

    4 D 2200 4

    1 A 5500 5

    2 B 6500 5

    3. OUTER JOIN

    SQL> select * from emp;

  • 8/6/2019 Oracle 9

    18/57

    ENO ENMAE DNO

    --------- --------------- ---------

    1 A 10

    2 B 20

    3 C 304 D 10

    5 E 206 F 70

    SQL> insert into dep values (40,'ADMIN','Pkl');

    1 row created.

    SQL> select * from dep;DNO DNAME DLOC

    --------- --------------- ----------

    10 HR Chd

    20 MKT Moh

    30 SALES Banur

    40 ADMIN Pkl

    i. LEFT OUTER JOINReturn all rows from the left table, even if there are no matches in the right table.

    SQL> select eno,enmae,emp.dno,dname from emp,dep where emp.dno(+)=dep.dno;

    ENO ENMAE DNO DNAME

    --------- --------------- --------- ---------------

    1 A 10 HR

    4 D 10 HR

    2 B 20 MKT

    5 E 20 MKT

    3 C 30 SALESADMIN

    6 rows selected.

    ii. RIGHT OUTER JOIN:-

    SQL> select eno,enmae,emp.dno,dname from emp,dep where emp.dno=dep.dno(+);

    Return all rows from the right table, even if there are no matches in the left table.

    ENO ENMAE DNO DNAME--------- --------------- --------- ---------------

    1 A 10 HR

    4 D 10 HR

    2 B 20 MKT

    5 E 20 MKT

    3 C 30 SALES

    6 F 70

    6 rows selected.

    ii. FULL OUTER JOIN:-

    SQL> select eno,enmae,emp.dno,dname from emp,dep where emp.dno(+)=dep.dno and

    emp.dno=dep.dno(+)

    Return rows when there is a match in one of the tables.

    ENO ENMAE DNO DNAME

    --------- --------------- --------- ---------------

  • 8/6/2019 Oracle 9

    19/57

    1 A 10 HR

    4 D 10 HR

    2 B 20 MKT

    5 E 20 MKT

    3 C 30 SALES6 F 70

    ADMIN7 rows selected.

    4. SELF JOIN:-

    Joins the table with itself.

    SQL> select * from emp3;

    ENO ENAME DESIGNATION MGR--------- ---------- --------------- -------

    1 A Peon 3

    2 B Clerk 5

    4 D Peon 3

    3 C Manager

    5 E Manager

    6 F Clerk 3

    6 rows selected.

    SQL> select e1.eno,e1.ename,e1.designation,e2.ename from emp3 e1,emp3 e2 where e1.mgr=e2.eno;

    ENO ENAME DESIGNATION ENAME

    --------- ---------- --------------- ----------

    1 A Peon C

    4 D Peon C6 F Clerk C

    2 B Clerk E

    SUB QUERIES

    Nested queries are known as sub queries.

    SQL> select * from emp2;

    ENO ENAME ESAL

    --------- ---------- ---------

    1 A 55002 B 6500

    3 C 14000

    4 D 2200

    5 E 25000

    QUERY1 : SELECT THE ENAMES FROM THE EMP TABLE WHOSE SALARY ARE GREATER

    THAN THE SALARY OF EMP WHOSE ENO IS 2.

    SQL> select ename from emp2 where esal>(select esal from emp2 where eno=2);

    ENAME

    ----------

    C

  • 8/6/2019 Oracle 9

    20/57

    E

    QUERY2 : SELECT THE DETAILS OF EMP WHOSE SALARY IS EQUAL TO THE MINIMUMSALARY.

    SQL> select eno,ename,esal from emp2 where esal=(select min(esal)from emp2);

    ENO ENAME ESAL--------- ---------- ---------

    4 D 2200

    QUERY3 : SELECT THE 2ND MAXIMUM SALARY OF THE EMP TABLE.

    SQL> select max(esal) from emp2 where esal select * from emp1;

    EMPNO ENAME EDEP ESALARY EADD ELOC

    -------------- -------------- ---------- -------------- ------------ ---------------

    10 Amit HR 10000 #1276,sec-12b chd

    20 Sumit Mkt 12000 #897/a amb

    30 Harish Finance 23000 #986 Mohali

    40 Avneet sales 15000 #908 Pkl

    50 Neha Admin 16000 #765,d Pat60 Rajat Prod 24000 #127,b Banur

    1. SIMPLE VIEW:-

    SQL> create or replace view emp10 as select empno,ename,eadd from emp1;

    View created.

    SQL> select * from emp10;

    EMPNO ENAME EADD

    -------------- -------------- ---------- -------------- ------------ ---------------10 Amit #1276,sec-12b

    20 Sumit #897/a

    30 Harish #986

    40 Avneet #908

    50 Neha #765,d

    60 Rajat #127,b

    SQL> create or replace view emp10(empno,empname,empsal) as select empno,ename,esalary from emp1;

  • 8/6/2019 Oracle 9

    21/57

    View created.

    SQL> select * from emp10;

    EMPNO EMPNAME EMPSAL

    --------- -------------------- ---------10 Amit 10000

    20 Sumit 12000

    30 Harish 23000

    50 Neha 16000

    60 Rajat 24000

    2. COMPLEX VIEW

    SQL> select * from emp;

    ENO ENMAE DNO

    --------- --------------- ---------

    1 A 10

    2 B 20

    3 C 30

    4 D 105 E 20

    6 F 70

    6 rows selected.

    SQL> select * from dep;

    DNO DNAME DLOC

    --------- --------------- ----------

    10 HR Chd

    20 MKT Moh30 SALES Banur

    40 ADMIN Pkl

    SQL> create or replace view emp10 as select e.eno,e.enmae,e.dno,d.dname from emp e,dep d where

    e.dno=d.dno;

    View created.

    SQL> select * from emp10;

    ENO ENMAE DNO DNAME

    --------- --------------- --------- ---------------

    1 A 10 HR

    4 D 10 HR

    2 B 20 MKT

    5 E 20 MKT

    3 C 30 SALES

    DROP VIEWSQL> drop view emp10;

    View dropped.

    SQL> select * from emp10;

    select * from em0p10

    *

  • 8/6/2019 Oracle 9

    22/57

    ERROR at line 1:

    ORA-00942: table or view does not exist

    INDEX

    SQL> select * from dep;

    DNO DNAME DLOC

    --------- --------------- ----------

    10 HR Chd

    20 MKT Moh

    30 SALES Banur

    40 ADMIN Pkl

    SQL> create unique index i4 on dep(dname);

    Index created.

    SQL> insert into dep values(50,'HR','CHD');

    insert into dep values(50,'HR','CHD')

    *ERROR at line 1:

    ORA-00001: unique constraint (SCOTT.I4) violated

    SQL> insert into dep values(50,'HR1','Pat');

    1 row created.

    SQL> select * from dep;

    DNO DNAME DLOC--------- --------------- ----------

    10 HR Chd

    20 MKT Moh30 SALES Banur

    40 ADMIN Pkl

    50 HR1 Pat

    COMPOSITE INDEX

    SQL> create unique index d1 on dep (dno,dloc);

    Index created.

    SQL> select * from dep;

    DNO DNAME DLOC--------- --------------- ----------

    10 HR Chd20 MKT Moh

    30 SALES Banur

    40 ADMIN Pkl

    50 HR1 Pat

    DROP INDEX

  • 8/6/2019 Oracle 9

    23/57

    SQL> drop index d1;

    Index dropped.

    IMPLEMENTING PL/SQL

    PL/SQL Variables

    These are placeholders that store the values that can change through the PL/SQL Block.

    The General Syntax to declare a variable is:

    variable_name datatype [NOT NULL := value ];

    variable_name is the name of the variable.

    datatype is a valid PL/SQL datatype.

    NOT NULL is an optional specification on the variable.

    value or DEFAULT valueis also an optional specification, where you caninitialize a variable.

    Each variable declaration is a separate statement and must be terminated by asemicolon.

    For example, if you want to store the current salary of an employee, you can use a

    variable.DECLAREsalary number (6);

    * salary is a variable of datatype number and of length 6.

    When a variable is specified as NOT NULL, you must initialize the variable when it isdeclared.

    For example: The below example declares two variables, one of which is a not null.DECLAREsalary number(4);dept varchar2(10) NOT NULL := HR Dept;

    The value of a variable can change in the execution or exception section of the PL/SQL

    Block. We can assign values to variables in the two ways given below.

    1) We can directly assign values to variables.The General Syntax is:

    variable_name:= value;

    2) We can assign values to variables directly from the database columns by using aSELECT.. INTO statement. The General Syntax is:SELECT column_nameINTO variable_nameFROM table_name

  • 8/6/2019 Oracle 9

    24/57

    [WHERE condition];

    Example: The below program will get the salary of an employee with id '1116' and

    display it on the screen.

    DECLARE

    var_salary number(6);var_emp_id number(6) = 1116;

    BEGINSELECT salaryINTO var_salaryFROM employeeWHERE emp_id = var_emp_id;dbms_output.put_line(var_salary);dbms_output.put_line('The employee '

    || var_emp_id || ' has salary ' || var_salary);END;/

    Scope of Variables

    PL/SQL allows the nesting of Blocks within Blocks i.e, the Execution section of an outer

    block can contain inner blocks. Therefore, a variable which is accessible to an outer

    Block is also accessible to all nested inner Blocks. The variables declared in the innerblocks are not accessible to outer blocks. Based on their declaration we can classify

    variables into two types.

    Localvariables - These are declared in a inner block and cannot be referenced by

    outside Blocks.

    Globalvariables - These are declared in a outer block and can be referenced by its

    itself and by its inner blocks.

    For Example: In the below example we are creating two variables in the outer block and

    assigning thier product to the third variable created in the inner block. The variable'var_mult' is declared in the inner block, so cannot be accessed in the outer block i.e. it

    cannot be accessed after line 11. The variables 'var_num1' and 'var_num2' can be

    accessed anywhere in the block.1> DECLARE2> var_num1 number;3> var_num2 number;4> BEGIN5> var_num1 := 100;

    6> var_num2 := 200;7> DECLARE8> var_mult number;9> BEGIN10> var_mult := var_num1 * var_num2;11> END;12> END;13> /

  • 8/6/2019 Oracle 9

    25/57

    PL/SQL Constants

    As the name implies a constantis a value used in a PL/SQL Block that remains

    unchanged throughout the program. A constant is a user-defined literal value. You can

    declare a constant and use it instead of actual value.

    For example: If you want to write a program which will increase the salary of the

    employees by 25%, you can declare a constant and use it throughout the program. Nexttime when you want to increase the salary again you can change the value of the constant

    which will be easier than changing the actual value throughout the program.

    The General Syntax to declare a constant is:constant_name CONSTANT datatype := VALUE;

    constant_name is the name of the constant i.e. similar to a variable name.

    The word CONSTANTis a reserved word and ensures that the value does notchange.

    VALUE- It is a value which must be assigned to a constant when it is declared.

    You cannot assign a value later.

    For example, to declare salary_increase, you can write code as follows:

    DECLAREsalary_increase CONSTANT number (3) := 10;

    You mustassign a value to a constant at the time you declare it. If you do not assign a

    value to a constant while declaring it and try to assign a value in the execution section,you will get a error. If you execute the below Pl/SQL block you will get error.

    DECLAREsalary_increase CONSTANT number(3);

    BEGINsalary_increase := 100;dbms_output.put_line (salary_increase);

    END;

    Conditional Statements in PL/SQL

    As the name implies, PL/SQL supports programming language features like conditionalstatements, iterative statements.

    The programming constructs are similar to how you use in programming languages likeJava and C++. In this section I will provide you syntax of how to use conditional

    statements in PL/SQL programming.

  • 8/6/2019 Oracle 9

    26/57

  • 8/6/2019 Oracle 9

    27/57

    declarenum1 number:=#begincase num1when 1 thendbms_output.put_line(One);when 2 thendbms_output.put_line(two);end case;end;/OrDeclareNum:=2;BeginCase numWhen 1 thenDbms_output.put_line(Sunday);ElseDbms_output.put_line(Wrong);

    End case;End;/

    Iterative Statements in PL/SQL

    An iterative control Statements are used when we want to repeat the execution of one or

    more statements for specified number of times. These are similar to those in

    There are three types of loops in PL/SQL: Simple Loop

    While Loop For Loop

    1) Simple Loop

    A Simple Loop is used when a set of statements is to be executed at least once before the

    loop terminates. An EXIT condition must be specified in the loop, otherwise the loop will

    get into an infinite number of iterations. When the EXIT condition is satisfied the processexits from the loop.

    The General Syntax to write a Simple Loop is:

    LOOPstatements;EXIT;{or EXIT WHEN condition;}

    END LOOP;

    These are the important steps to be followed while using Simple Loop.

    1) Initialise a variable before the loop body.

    2) Increment the variable in the loop.

  • 8/6/2019 Oracle 9

    28/57

    3) Use a EXIT WHEN statement to exit from the Loop. If you use a EXIT statement

    without WHEN condition, the statements in the loop is executed only once.

    e.g

    declare

    ctr number(2):=0;

    begin

    dbms_output.put_line(the loop begins);

    loop

    ctr:=ctrl+1;

    exit when ctr>10;

    dbms_output.put_line(Loop number:||ctr);

    end loop;

    end;

    /

    2) While Loop

    A WHILE LOOP is used when a set of statements has to be executed as long as a

    condition is true. The condition is evaluated at the beginning of each iteration. The

    iteration continues until the condition becomes false.

    The General Syntax to write a WHILE LOOP is:WHILE LOOP statements;

    END LOOP;

    Important steps to follow when executing a while loop:

    1) Initialise a variable before the loop body.2) Increment the variable in the loop.

    3) EXIT WHEN statement and EXIT statements can be used in while loops but it's not

    done oftenly.

    e.g

  • 8/6/2019 Oracle 9

    29/57

    declare

    ctr number(2):=1;

    begin

    dbms_output.put_line(The while loop begin);

    while ctr

  • 8/6/2019 Oracle 9

    30/57

  • 8/6/2019 Oracle 9

    31/57

    3. If neither condition1 nor condition2 are true, then statements3 isexecuted.

    SQL> set echo onSQL>SQL> DECLARE

    2 v_a Number := 50 ;3 v_b Number;4 BEGIN5 IF v_a > 40 THEN6 v_b := v_a - 40;7 DBMS_OUTPUT.PUT_LINE('Hours b worked = ' || v_b);8 ELSE9 v_b := 0;10 END IF;11 END;12 /

    Hours b worked = 10

    PL/SQL procedure successfully completed.

    Use IF THEN ELSE IFset serveroutput onSQL> set echo onSQL>SQL> DECLARE2 v_Score Number := 85; --Percentage3 v_LetterGrade Char(1);4 BEGIN5 IF v_Score >= 90 THEN6 v_LetterGrade := 'A';7 ELSIF v_Score >= 80 THEN8 v_LetterGrade := 'B';

    9 ELSIF v_Score >= 70 THEN10 v_LetterGrade := 'C';11 ELSIF v_Score >= 60 THEN12 v_LetterGrade := 'D';13 ELSE14 v_LetterGrade := 'E';15 END IF;16 DBMS_OUTPUT.PUT_LINE('Your Letter Grade is: ' || v_LetterGrade

    );17 END;18 /

    Your Letter Grade is: B

    PL/SQL procedure successfully completed.

    We have created a table order_master with the following fields:

    SQL> select * from order_master;

    ONO ITEM QUANTITY DDATE OSTATUS

    ---- ----- ------ ---- --------- --------- ----------

  • 8/6/2019 Oracle 9

    32/57

    1 pancil 100 15-NOV-09 p

    2 pen 500 29-OCT-09 d

    3 ink 400 25-OCT-09 d

    4 eraser 900 12-NOV-09 p

    Write a PL/SQL Block to implement IF statement

    SQL> declare2 os varchar2(10);

    3 begin

    4 select ostatus into os from order_master where ono=1;

    5 if(os='p') then

    6 update order_master set ddate=sysdate+15 where ono=1;

    7 else8 update order_master set ddate=sysdate where ono=1;

    9 end if;

    10end;

    11 /

    PL/SQL procedure successfully completed.

    SQL> select * from order_master;

    ONO ITEM QUANTITY DDATE OSTATUS

    --------- ----- ----- --------- --------- ----------

    1 pancil 100 06-DEC-09 p2 pen 500 29-OCT-09 d

    3 ink 400 25-OCT-09 d

    4 eraser 900 12-NOV-09 p

    Write a PL/SQL Block to implement Simple Loop

    SQL> declare

    2 a number:=1;

    3 begin4 loop

    5 a:=a+1;

    6 dbms_output.put_line(a);

    7 exit when(a>5);

    8 end loop;

    9 end;

    10 /

    PL/SQL procedure successfully completed.

    Write a PL/SQL Block to implement while Loop

    SQL> declare

    2 a number:=1;

    3 begin

    4 while(a>5)

    5 loop

  • 8/6/2019 Oracle 9

    33/57

    6 a:=a+1;

    7 dbms_output.put_line(a);

    8 end loop;

    9end;

    10/

    PL/SQL procedure successfully completed.

    Exception Handling in PL/SQL

    SQL> select * from emp;

    ENO ENAME ESAL

    ------ --- ---------- ---------

    1 navneet 12000

    2 navjot 140003 permod 15000

    4 harish 18000

    DATABASE WITH PL/SQL

    declare

    vsal number;

    begin

    select esal into vsal from emp6 where ename='&ename';dbms_output.put_line(vsal);

    end;

    /To display the name and location of dept

    declare

    vdname varchar2(10);vloc varchar2(10);

    begin

    select dname,loc into vdname,vloc from dept where deptno='&deptno';

    dbms_output.put_line(vdname||' '||vloc);end;

    /

    Working with attribute:- %type and %rowtype attribute are used to avoid the erro whichmight occure due to some mistake while declaring a variable.

    Suppose you want to display the total sal of emp

    declare

    vsal emp.sal%type;

    beginselect sal into vsal from emp where empno='&empno';

    dbms_output.put_line('The total sal is'||to_char(vsal));

    end;

    /To display the record in row wise

    declare

    drec dept%rowtype;

  • 8/6/2019 Oracle 9

    34/57

    begin

    select * into drec from dept where deptno='&deptno';

    dbms_output.put_line(drec.dname||' '||drec.loc);end;

    /

    To increase the salary based on their jobsdeclare

    erec emp%rowtype;

    vraise number;begin

    select * into erec from emp where ename='&ename';

    if erec.job='CLERK' then

    vraise:=500;elsif erec.job='SALESMAN' then

    vraise:=1000;

    end if;

    update emp set sal=sal+vraise where empno=erec.empno;end;

    /Exceptions:- Exceptions are nothing but error handlers.It help to us about take care of any

    error that may have occurred in the executable part of the block.

    Some common exception are:

    1. Pre defined exception2. User defined exc

    E.g of pre defined exc.

    NO_DATA_FOUND

    TOO_MANY_ROWS

    ZERO_DIVIDE

    VALUE_ERROR

    E.G

    declare

    vsal emp.sal%type;begin

    select sal into vsal from emp where empno='&empno';

    dbms_output.put_line('The total sal is'||to_char(vsal));

    exceptionwhen no_data_found then

    dbms_output.put_line('No such emp exists in the table:');

    end;

    /

    Too_many_rows

    declare

    vsal emp.sal%type;

  • 8/6/2019 Oracle 9

    35/57

    begin

    select sal into vsal from emp where empno='&empno';

    dbms_output.put_line('The total sal is'||to_char(vsal));exception

    TOO_MANY_ROWS then

    dbms_output.put_line('too many rows ...:');

    end;

    /Write a PL/SQL Block to implement Inbuilt exception-No data found and too many rows

    SQL>declare

    2 name emp.ename %type;3 empno emp.eno %type;

    4 salary emp.esal %type;

    5 begin

    6 empno:=&eno;

    7 select ename,esal into name,salary from emp where eno=empno;

    8 dbms_output.put_line('employee name is:' ||name);

    9 dbms_output.put_line('employee salary is:' || salary);10 EXCEPTION11 when no_data_found then

    12 dbms_output.put_line('there is no data for this employee no.');

    13 when too_many_rows then

    14 dbms_output.put_line('too many rows are there for this end');

    15 end;

    16 /

    Enter value for eno: 4

    old 6: empno:=&eno;new 6: empno:=4;

    employee name is:harish

    employee salary is:18000

    PL/SQL procedure successfully completed.

    SQL> /

    Enter value for eno: 12

    old 6: empno:=&eno;

    new 6: empno:=12;there is no data for this employee no.

    Write a PL/SQL Block to implement a user defined exception

    SQL> select * from order_master;

    ONO ITEM QUANTITY DDATE OSTATUS--------- ---------- --------- --------- ---------

    1 pancil 100 06-DEC-09 p

    2 pen 500 29-OCT-09 d

    3 ink 400 25-OCT-09 d4 eraser 900 12-NOV-09 p

    SQL> declare

    2 d1 order_master.ddate %type;

    3 o_pending Exception;

  • 8/6/2019 Oracle 9

    36/57

    4 begin

    5 select ddate into d1 from order_master where ono=4;

    6 if(d1 select * from emp;

    ENO ENAME ESAL

    --------- ---------- ---------

    1 navneet 12000

    2 navjot 14000

    3 permod 150004 harish 18000

    SQL> declare

    2 no emp.eno %type;

    3 begin

    4 delete from emp where eno=&no;

    5 if SQL %found then

    6 dbms_output.put_line('record found');7 else

    8 dbms_output.put_line('record is not found');

    9 end if;

    10 end;

    11 /

    Enter value for no: 2

    old 4: delete from emp where eno=&no;

    new 4: delete from emp where eno=2;

    record found

    PL/SQL procedure successfully completed.

    SQL> select * from emp;

    ENO ENAME ESAL

    --------- ---------- ---------

    1 navneet 12000

    3 permod 15000

    4 harish 18000

    Write a PL/SQL Block to implement the attribute: %rowcount

  • 8/6/2019 Oracle 9

    37/57

    SQL> declare

    2 no emp.eno %type;

    3 begin

    4 update emp set esal=24000 where eno=&no;

    5 if SQL %found then6 dbms_output.put_line(SQL %rowcount);

    7 end if;8 end;

    9 /

    Enter value for no: 1

    old 4: update emp set esal=24000 where eno=&no;

    new 4: update emp set esal=24000 where eno=1;

    1

    PL/SQL procedure successfully completed.

    SQL> select * from emp;

    ENO ENAME ESAL

    --------- ---------- ---------

    1 navneet 240003 permod 15000

    4 harish 18000

    Explicit Cursor:

    SQL> select * from employee;

    ENO ENAME ESAL ECITY DNO DNAME

    --------- -------------------- --------- --------------- --------- -------------------

    1 rahul 12000 CHD 110 ADMIN

    2 manpreet 4500 patiala 120 MKT3 reena 23000 panchkula 130 HR

    4 sabiha kour 41000 CHD 130 HR

    5 gopal 14500 CHD 120 MKT7 jaspreet 42000 patiala 150 FIn

    6 rows selected.

    SQL> declare2 no employee.eno %type;

    3 name employee.ename %type;

    4 salary employee.esal %type;

    5 cursor emp_crsr is select eno,ename,esal from employee;

    6 begin

    7 open emp_crsr;

    8 loop

    9 fetch emp_crsr into no,name,salary;10 if(salary>15000)then

    11 update employee set esal=10000 where esal

  • 8/6/2019 Oracle 9

    38/57

    PL/SQL procedure successfully completed.

    Cursor For loop

    SQL> select * from emp;

    ENO ENAME ESAL

    --------- ---------- ---------1 arpeta 12000

    2 arun 15000

    3 harish 20000

    4 rahul 14000

    5 ranjeet 45000

    SQL> declare

    2 cursor emp_crsr

    3 is4 select * from emp;

    5 begin

    6 for e1 IN emp_crsr

    7 loop

    8 if(e1.esal declare

    2 cursor emp_cursor(p_depno number,p_job varchar2)

    3 is

    4 select eno,ename,esal from employi where dno=p_depno and job=p_job;

    5 begin

    6 open emp_cursor (10,'clerk');

    7 if(emp_cursor %found)then

    8 dbms_output.put_line('record fetch');

    9 end if;10 close emp_cursor;

    11 end;

    12 /

    PL/SQL procedure successfully completed.

  • 8/6/2019 Oracle 9

    39/57

    What are Cursors?

    A cursor is a temporary work area created in the system memory when a SQL statement

    is executed. A cursor contains information on a select statement and the rows of dataaccessed by it. This temporary work area is used to store the data retrieved from the

    database, and manipulate this data. A cursor can hold more than one row, but can processonly one row at a time. The set of rows the cursor holds is called the active set.

    There are two types of cursors in PL/SQL:

    Implicit cursors:

    These are created by default when DML statements like, INSERT, UPDATE, and

    DELETE statements are executed. They are also created when a SELECT statement that

    returns just one row is executed.

    Explicit cursors:

    They must be created when you are executing a SELECT statement that returns more

    than one row. Even though the cursor stores multiple records, only one record can be

    processed at a time, which is called as current row. When you fetch a row the current row

    position moves to next row.

    Both implicit and explicit cursors have the same functionality, but they differ in the way

    they are accessed.

    Implicit Cursors:

    When you execute DML statements like DELETE, INSERT, UPDATE and SELECT

    statements, implicit statements are created to process these statements.

    Oracle provides few attributes called as implicit cursor attributes to check the status of

    DML operations. The cursor attributes available are %FOUND, %NOTFOUND,%ROWCOUNT, and %ISOPEN.

    For example, When you execute INSERT, UPDATE, or DELETE statements the cursor

    attributes tell us whether any rows are affected and how many have been affected.When a SELECT... INTO statement is executed in a PL/SQL Block, implicit cursorattributes can be used to find out whether any row has been returned by the SELECT

    statement. PL/SQL returns an error when no data is selected.

    The status of the cursor for each of these attributes are defined in the below table.

  • 8/6/2019 Oracle 9

    40/57

    Attributes Return Value Example

    %FOUND The return value is TRUE, if the DML

    statements like INSERT, DELETE and

    UPDATE affect at least one row and ifSELECT .INTO statement return at least

    one row.

    SQL%FOUND

    The return value is FALSE, if DML

    statements like INSERT, DELETE andUPDATE do not affect row and if

    SELECT.INTO statement do not return a

    row.

    %NOTFOUND The return value is FALSE, if DMLstatements like INSERT, DELETE and

    UPDATE at least one row and if SELECT

    .INTO statement return at least one row.

    SQL%NOTFOUND

    The return value is TRUE, if a DML statementlike INSERT, DELETE and UPDATE do not

    affect even one row and if SELECT .INTO

    statement does not return a row.

    %ROWCOUNT Return the number of rows affected by the

    DML operations INSERT, DELETE,

    UPDATE, SELECT

    SQL%ROWCOUNT

    For Example: Consider the PL/SQL Block that uses implicit cursor attributes as shownbelow:

    DECLARE var_rows number(5);BEGINUPDATE employeeSET salary = salary + 1000;IF SQL%NOTFOUND THENdbms_output.put_line('None of the salaries where updated');

    ELSIF SQL%FOUND THENvar_rows := SQL%ROWCOUNT;dbms_output.put_line('Salaries for ' || var_rows || 'employees are

    updated');END IF;

    END;

    In the above PL/SQL Block, the salaries of all the employees in the employee table are

    updated. If none of the employees salary are updated we get a message 'None of thesalaries where updated'. Else we get a message like for example, 'Salaries for 1000

    employees are updated' if there are 1000 rows in employee table.

  • 8/6/2019 Oracle 9

    41/57

    Explicit Cursors

    An explicit cursor is defined in the declaration section of the PL/SQL Block. It is created

    on a SELECT Statement which returns more than one row. We can provide a suitablename for the cursor.

    The General Syntax for creating a cursor is as given below:

    CURSOR cursor_name IS select_statement;

    cursor_name A suitable name for the cursor.

    select_statement A select query which returns multiple rows.

    How to use Explicit Cursor?

    There are four steps in using an Explicit Cursor.

    DECLARE the cursor in the declaration section.

    OPEN the cursor in the Execution Section.

    FETCH the data from cursor into PL/SQL variables or records in the ExecutionSection.

    CLOSE the cursor in the Execution Section before you end the PL/SQL Block.

    1) Declaring a Cursor in the Declaration Section:

    DECLARECURSOR emp_cur ISSELECT *FROM emp_tblWHERE salary > 5000;

    In the above example we are creating a cursor emp_cur on a query which returns therecords of all the

    employees with salary greater than 5000. Here emp_tbl in the table which contains

    records of all theemployees.

    2) Accessing the records in the cursor:

    Once the cursor is created in the declaration section we can access the cursor in the

    executionsection of the PL/SQL program.

    How to access an Explicit Cursor?

  • 8/6/2019 Oracle 9

    42/57

    These are the three steps in accessing the cursor.

    1) Open the cursor.

    2) Fetch the records in the cursor one at a time.3) Close the cursor.

    General Syntax to open a cursor is:

    OPEN cursor_name;

    General Syntax to fetch records from a cursor is:

    FETCH cursor_name INTO record_name;

    ORFETCH cursor_name INTO variable_list;

    General Syntax to close a cursor is:

    CLOSE cursor_name;

    When a cursor is opened, the first row becomes the current row. When the data is fetchedit is copied to the record or variables and the logical pointer moves to the next row and it

    becomes the current row. On every fetch statement, the pointer moves to the next row. If

    you want to fetch after the last row, the program will throw an error. When there is morethan one row in a cursor we can use loops along with explicit cursor attributes to fetch all

    the records.

    Points to remember while fetching a row:

    We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created inthe PL/SQL Block.

    If you are fetching a cursor to a PL/SQL Record, the record should have the same

    structure as the cursor.

    If you are fetching a cursor to a list of variables, the variables should be listed in thesame order in the fetch statement as the columns are present in the cursor.

    General Form of using an explicit cursor is:

    DECLAREvariables;records;create a cursor;

    BEGINOPEN cursor;FETCH cursor;process the records;

    CLOSE cursor;END;

  • 8/6/2019 Oracle 9

    43/57

    Lets Look at the example below

    Example 1:

    1> DECLARE2> emp_rec emp_tbl%rowtype;

    3> CURSOR emp_cur IS4> SELECT *5> FROM6> WHERE salary > 10;7> BEGIN8> OPEN emp_cur;9> FETCH emp_cur INTO emp_rec;10> dbms_output.put_line (emp_rec.first_name || ' ' ||emp_rec.last_name);11> CLOSE emp_cur;12> END;

    In the above example, first we are creating a record emp_rec of the same structure as of

    table emp_tbl in line no 2. We can also create a record with a cursor by replacing the

    table name with the cursor name. Second, we are declaring a cursor emp_cur from aselect query in line no 3 - 6. Third, we are opening the cursor in the execution section in

    line no 8. Fourth, we are fetching the cursor to the record in line no 9. Fifth, we are

    displaying the first_name and last_name of the employee in the record emp_rec in line no

    10. Sixth, we are closing the cursor in line no 11.

    What are Explicit Cursor Attributes?

    Oracle provides some attributes known as Explicit Cursor Attributes to control the dataprocessing while using cursors. We use these attributes to avoid errors while accessing

    cursors through OPEN, FETCH and CLOSE Statements.

    When does an error occur while accessing an explicit cursor?

    a) When we try to open a cursor which is not closed in the previous operation.

    b) When we try to fetch a cursor after the last operation.

    These are the attributes available to check the status of an explicit cursor.

    Attributes Return values Example

    %FOUND TRUE, if fetch statement returns atleast one row.

    Cursor_name%FOUND

    FALSE, if fetch statement doesnt

    return a row.

    %NOTFOUND TRUE, , if fetch statement doesntreturn a row.

    Cursor_name%NOTFOUND

    FALSE, if fetch statement returns at

  • 8/6/2019 Oracle 9

    44/57

    least one row.

    %ROWCOUNT The number of rows fetched by the

    fetch statement

    Cursor_name%ROWCOUNT

    If no row is returned, the PL/SQLstatement returns an error.

    %ISOPEN TRUE, if the cursor is already open in

    the program

    Cursor_name%ISNAME

    FALSE, if the cursor is not opened in

    the program.

    Using Loops with Explicit Cursors:

    Oracle provides three types of cursors namely SIMPLE LOOP, WHILE LOOP and FOR

    LOOP. These loops can be used to process multiple rows in the cursor. Here I will

    modify the same example for each loops to explain how to use loops with cursors.

    Cursor with a Simple Loop:1> DECLARE2> CURSOR emp_cur IS3> SELECT first_name, last_name, salary FROM emp_tbl;4> emp_rec emp_cur%rowtype;5> BEGIN6> IF NOT sales_cur%ISOPEN THEN7> OPEN sales_cur;8> END IF;9> LOOP10> FETCH emp_cur INTO emp_rec;11> EXIT WHEN emp_cur%NOTFOUND;12> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name13> || ' ' ||emp_cur.salary);14> END LOOP;15> END;16> /

    In the above example we are using two cursor attributes %ISOPEN and %NOTFOUND.

    In line no 6, we are using the cursor attribute %ISOPEN to check if the cursor is open, if

    the condition is true the program does not open the cursor again, it directly moves to lineno 9.

    In line no 11, we are using the cursor attribute %NOTFOUND to check whether the fetchreturned any row. If there is no rows found the program would exit, a condition whichexists when you fetch the cursor after the last row, if there is a row found the program

    continues.

    We can use %FOUND in place of %NOTFOUND and vice versa. If we do so, we need to

    reverse the logic of the program. So use these attributes in appropriate instances.

  • 8/6/2019 Oracle 9

    45/57

    Cursor with a While Loop:

    Lets modify the above program to use while loop.

    1> DECLARE2> CURSOR emp_cur IS3> SELECT first_name, last_name, salary FROM emp_tbl;4> emp_rec emp_cur%rowtype;5> BEGIN6> IF NOT sales_cur%ISOPEN THEN7> OPEN sales_cur;8> END IF;9> FETCH sales_cur INTO sales_rec;10> WHILE sales_cur%FOUND THEN11> LOOP12> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name13> || ' ' ||emp_cur.salary);15> FETCH sales_cur INTO sales_rec;

    16> END LOOP;17> END;18> /

    In the above example, in line no 10 we are using %FOUND to evaluate if the first fetchstatement in line no 9 returned a row, if true the program moves into the while loop. In

    the loop we use fetch statement again (line no 15) to process the next row. If the fetch

    statement is not executed once before the while loop the while condition will return falsein the first instance and the while loop is skipped. In the loop, before fetching the record

    again, always process the record retrieved by the first fetch statement, else you will skip

    the first row.

    Cursor with a FOR Loop:

    When using FOR LOOP you need not declare a record or variables to store the cursor

    values, need not open, fetch and close the cursor. These functions are accomplished by

    the FOR LOOP automatically.

    General Syntax for using FOR LOOP:

    FOR record_name IN cusror_nameLOOP

    process the row...

    END LOOP;

    Lets use the above example to learn how to use for loops in cursors.

    1> DECLARE2> CURSOR emp_cur IS3> SELECT first_name, last_name, salary FROM emp_tbl;4> emp_rec emp_cur%rowtype;5> BEGIN

  • 8/6/2019 Oracle 9

    46/57

    6> FOR emp_rec in sales_cur7> LOOP8> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name9> || ' ' ||emp_cur.salary);10> END LOOP;11>END;12> /

    In the above example, when the FOR loop is processed a record emp_recof structure

    emp_cur gets created, the cursor is opened, the rows are fetched to the record emp_rec

    and the cursor is closed after the last row is processed. By using FOR Loop in yourprogram, you can reduce the number of lines in the program.

    Create a cursor for updateCreate a following table:CREATE TABLE product (2 product_name VARCHAR2(25) PRIMARY KEY,3 product_price NUMBER(4,2),

    4 quantity_on_hand NUMBER(5,0),5 last_stock_date DATE6 );

    DECLARE2 CURSOR product_cur IS3 SELECT * FROMproduct4 FOR UPDATE OF product_price;5 BEGIN6 FOR product_rec IN product_cur7 LOOP8 UPDATE product9 SET product_price = (product_rec.product_price * 0

    .97)10 WHERE CURRENT OF product_cur;11 END LOOP;12 END;13 /

    What is a Stored Procedure?

    A stored procedure or in simple a proc is a named PL/SQL block which performs one

    or more specific task. This is similar to a procedure in other programming languages. A

    procedure has a header and a body. The header consists of the name of the procedure and

    the parameters or variables passed to the procedure. The body consists or declarationsection, execution section and exception section similar to a general PL/SQL Block. A

    procedure is similar to an anonymous PL/SQL Block but it is named for repeated usage.

    We can pass parameters to procedures in three ways.1) IN-parameters

    2) OUT-parameters

    3) IN OUT-parameters

  • 8/6/2019 Oracle 9

    47/57

    A procedure may or may not return any value.

    General Syntax to create a procedure is:

    CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]IS

    Declaration sectionBEGIN

    Execution sectionEXCEPTIONException section

    END;

    IS - marks the beginning of the body of the procedure and is similar to DECLARE in

    anonymous PL/SQL Blocks. The code between IS and BEGIN forms the Declaration

    section.

    The syntax within the brackets [ ] indicate they are optional. By using CREATE OR

    REPLACE together the procedure is created if no other procedure with the same nameexists or the existing procedure is replaced with the current code.

    The below example creates a procedure employer_details which gives the details of theemployee.

    1> CREATE OR REPLACE PROCEDURE employer_details2> IS3> CURSOR emp_cur IS4> SELECT first_name, last_name, salary FROM emp_tbl;5> emp_rec emp_cur%rowtype;6> BEGIN

    7> FOR emp_rec in sales_cur8> LOOP9> dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name10> || ' ' ||emp_cur.salary);11> END LOOP;12>END;13> /

    How to execute a Stored Procedure?

    There are two ways to execute a procedure.

    1) From the SQL prompt.

    EXECUTE [or EXEC] procedure_name;

    2) Within another procedure simply use the procedure name.

    procedure_name;

  • 8/6/2019 Oracle 9

    48/57

    NOTE: In the examples given above, we are using backward slash / at the end of the

    program. This indicates the oracle engine that the PL/SQL program has ended and it can

    begin processing the statements.

    Stored Procedures in PL/SQL

    A stored procedure has three categories of parameter modes: IN mode, OUT mode, IN OUT mode

    Write a procedure to implement IN Mode:

    SQL> select * from emp;

    ENO ENAME ESAL

    --------- ---------- ---------

    1 arpeta 12000

    2 arun 15000

    3 harish 20000

    4 rahul 140005 ranjeet 45000

    SQL> create or replace procedure raise_salary(no IN emp.eno % type)

    2 is begin

    3 update emp set esal=esal+1000 where eno=no;

    4 end raise_salary;

    5 /

    Procedure created.

    SQL> execute raise_salary(2);

    PL/SQL procedure successfully completed.

    SQL> select * from emp;

    ENO ENAME ESAL

    --------- ---------- ---------1 arpeta 12000

    2 arun 16000

    3 harish 20000

    4 rahul 14000

    5 ranjeet 45000

    Write a procedure to implement OUT Mode:

    SQL> create or replace procedure emp_detail(no IN emp.eno %type, name OUT emp.ename %type,

    salary OUT emp.esal %type)T emp.esal %type)

    2 is

    3 begin4 select ename,esal into name,salary from emp where eno=no;

    5 end emp_detail;

    6 /

    Procedure created.

  • 8/6/2019 Oracle 9

    49/57

    SQL> declare

    2 no emp.eno %type;

    3 name emp.ename %type;

    4 salary emp.esal%type;5 begin

    6 no:=&eno;7 emp_detail(no,name,salary);

    8 dbms_output.put_line('employee name is: '||name);

    9 dbms_output.put_line('employee salary is: '||salary);

    10* end;

    SQL> /

    Enter value for eno: 3old 6: no:=&eno;

    new 6: no:=3;

    employee name is: harish

    employee salary is: 20000

    PL/SQL procedure successfully completed.

    Write a procedure to implement IN OUT Mode:

    Format a phone number using a procedure. Phone number is having a format like 022-2567890.The

    first three digit/ characters are of area code. Fetch the area code from a phone number given using a

    format procedure code.

    SQL> create or replace procedure format_phone(p in out varchar2(10));

    2 is

    3 begin

    4 p:=substr(p,1,3);

    5 end format_phone;

    6 /

    Procedure created.

    SQL> declare

    2 p varchar2(10);

    3 begin

    4 p:=&p;

    5 dbms_output.putline("Phoneno Is: "||p);

    6 format_phone(p);

    7 dbms_output.putline("Area Code Is: "||p);

    8 end;

  • 8/6/2019 Oracle 9

    50/57

    9 /

    Enter value for p: 1722665626

    old 4: p=&p;

    new 4: p=1722665626;

    Phoneno Is: 1722665626

    Area Code Is: 172

    PL/SQL procedure successfully completed.

    Functions in PL/SQL

    Write a function to get the salary of employee.

    SQL> select * from emp;

    ENO ENAME ESAL--------- ---------- ---------

    1 arpeta 14000

    2 arun 16000

    3 harish 20000

    4 rahul 18000

    5 ranjeet 45000

    SQL> create or replace function getsal(no emp.eno %type)

    2 return number;

    3 is

    4 sal number;

    5 begin

    6 select esal into sal from emp where eno=no;7 return sal;8 end getsal;

    9 /

    PL/SQL procedure successfully completed.

    Function:

    A function is similar to a procedure except that a function must return a value.

    You create a function using the CREATE FUNCTION statement.

    The simplified syntax for the CREATE FUNCTION statement is as follows:

    The simplified syntax for the CREATE FUNCTION statement is as follows:CREATE [OR REPLACE] FUNCTION function_name[(parameter_name [IN | OUT | IN OUT] type [, ...])]RETURN type{IS | AS}BEGIN

    function_bodyEND function_name;

  • 8/6/2019 Oracle 9

    51/57

    where

    1. OR REPLACE specifies the function that is to replace an existing function if present.2. type specifies the PL/SQL type of the parameter.

    3. The body of a function must return a value of the PL/SQL type specified in the RETU

    Describe a user-defined function

    create table employees(2 empno NUMBER(4)3 , ename VARCHAR2(8)4 , init VARCHAR2(5)5 , job VARCHAR2(8)6 , mgr NUMBER(4)7 , bdate DATE8 , msal NUMBER(6,2)9 , comm NUMBER(6,2)10 , deptno NUMBER(2) ) ;

    create or replace function emp_count(p_deptno in number)2 return number is3 cnt number(2) := 0;4 begin5 select count(*) into cnt6 from employees e7 where e.deptno = p_deptno;8 return (cnt);9 end;10 /

    CREATE OR REPLACE a functionCREATE OR REPLACE FUNCTION ss_thresh2 RETURN NUMBER AS3 x NUMBER(9,2);4 BEGIN5 x := 65400;6 RETURN x;7 END ss_thresh;8 /

    Function created.

    SQL> BEGIN2 DBMS_OUTPUT.PUT_LINE('ss_thresh ' || ss_thresh());3 END;4 /

    ss_thresh 65400

    Calling a Function

  • 8/6/2019 Oracle 9

    52/57

    CREATE OR REPLACE FUNCTION circle_area (p_radius IN NUMBER) RETURN NUMBER AS2 v_pi NUMBER := 3.14;3 v_area NUMBER;4 BEGIN5 v_area := v_pi * POWER(p_radius, 2);6 RETURN v_area;7 END circle_area;8 /

    Function created.

    SQL>SQL> select circle_area(12) fromdual;

    CIRCLE_AREA(12)

    Calling a Function to a table.

    CREATE OR REPLACE FUNCTION average_salary RETURN NUMBER AS2 v_average_salary NUMBER;3 BEGIN4 SELECT AVG(salary)5 INTO v_average_salary6 FROMemployee;7 RETURN v_average_salary;8 END average_salary;9 /

    Function created.

    SQL>

    SQL> select average_salary fromdual;

    AVERAGE_SALARY--------------

    4071.7525

    Packaage:- A package is a schema object that groups logically related PL/SQL types,

    variables, and subprograms. Packages usually have two parts, a specification and a body;

    sometimes the body is unnecessary. The specification (spec for short) is the interface to

    the package. It declares the types, variables, constants, exceptions, cursors, andsubprograms that can be referenced from outside the package. The body defines the

    queries for the cursors and the code for the subprograms.

    You can think of the spec as an interface and of the body as a "black box." You candebug, enhance, or replace a package body without changing the package spec.

  • 8/6/2019 Oracle 9

    53/57

    To create package specs, use the SQL statement CREATEPACKAGE. If necessary, a CREATE

    PACKAGE BODY statement defines the package body.

    The spec holds public declarations, which are visible to stored procedures and othercode outside the package. You must declare subprograms at the end of the spec after all

    other items (except pragmas that name a specific function; such pragmas must follow thefunction spec).

    The body holds implementation details and private declarations, which are hidden fromcode outside the package. Following the declarative part of the package body is the

    optional initialization part, which holds statements that initialize package variables and

    do any other one-time setup steps.

    1. Packages encapsulate related functionality into one self-contained unit.

    2. Packages are typically made up of two components: a specification and a body.3. The package specification contains information about the package.

    4. The package specification lists the available procedures and functions.5. These are potentially available to all database users.

    6. The package specification generally doesn't contain the code.

    7. The package body contains the actual code.

    CREATE OR REPLACE PACKAGE command:

    Example of a PL/SQL Package

    The example below packages a record type, a cursor, and two employment procedures.The procedure hire_employee uses the sequence empno_seq and the function SYSDATE

    to insert a new employee number and hire date.

    CREATE OR REPLACE PACKAGE emp_actions AS -- specTYPE EmpRecTyp IS RECORD (emp_id INT, salary REAL);CURSOR desc_salary RETURN EmpRecTyp;PROCEDURE hire_employee (

    ename VARCHAR2,job VARCHAR2,mgr NUMBER,sal NUMBER,comm NUMBER,

    deptno NUMBER);PROCEDURE fire_employee (emp_id NUMBER);

    END emp_actions;/

    CREATE OR REPLACE PACKAGE BODY emp_actions AS -- bodyCURSOR desc_salary RETURN EmpRecTyp IS

    SELECT empno, sal FROM emp ORDER BY sal DESC;PROCEDURE hire_employee (

    ename VARCHAR2,

  • 8/6/2019 Oracle 9

    54/57

    job VARCHAR2,mgr NUMBER,sal NUMBER,comm NUMBER,deptno NUMBER) IS

    BEGININSERT INTO emp VALUES (empno_seq.NEXTVAL, ename, job,

    mgr, SYSDATE, sal, comm, deptno);END hire_employee;

    PROCEDURE fire_employee (emp_id NUMBER) ISBEGIN

    DELETE FROM emp WHERE empno = emp_id;END fire_employee;

    END emp_actions;/

    Creating Packages and call its functions

    After the specification is created, you create the body of the package.

    The body of a package is a collection of schema objects that was declared in the

    specification.

    If you perform any initialization in the package body, it is executed once when the

    package is initially referenced.

    To reference the package's subprograms and objects, you must use dot notation.

    The Syntax for Dot Notation

    package_name.type_namepackage_name.object_namepackage_name.subprogram_name

    SQL> -- create demo tableSQL> create table Employee(2 ID VARCHAR2(4 BYTE) NOT NULL,3 First_Name VARCHAR2(10 BYTE),4 Last_Name VARCHAR2(10 BYTE),5 Start_Date DATE,6 End_Date DATE,7 Salary Number(8,2),8 City VARCHAR2(10 BYTE),9 Description VARCHAR2(15 BYTE)10 )11 /

    Table created.

    SQL>

  • 8/6/2019 Oracle 9

    55/57

    SQL> -- prepare dataSQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values ('01','Jason', 'Martin', to_date('19960725','YYYYMMD3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values('02','Alison', 'Mathews', to_date('19760321','YYYYMMD3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values('03','James', 'Smith', to_date('19781212','YYYYMMD3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date,

    2 values('04','Celia', 'Rice', to_date('19821024','YYYYMMD3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values('05','Robert', 'Black', to_date('19840115','YYYYMMD3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values('06','Linda', 'Green', to_date('19870730','YYYYMMD

    3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values('07','David', 'Larry', to_date('19901231','YYYYMMD3 /

    1 row created.

    SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, 2 values('08','James', 'Cat', to_date('19960917','YYYYMMD3 /

    1 row created.

    SQL>SQL>SQL>SQL> -- display data in the tableSQL> select * fromEmployee2 /

  • 8/6/2019 Oracle 9

    56/57

    ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION---- ---------- ---------- --------- --------- ---------- ---------- ------------01 Jason Martin 25-JUL-96 25-JUL-06 1234.56 Toronto Programmer02 Alison Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester03 James Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester04 Celia Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager

    05 Robert Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester06 Linda Green 30-JUL-87 04-JAN-96 4322.78 New York Tester07 David Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager08 James Cat 17-SEP-96 15-APR-02 1232.78 Vancouver Tester

    8 rows selected.

    SQL>SQL>SQL>SQL>SQL> CREATE OR REPLACE PACKAGE inv_pck_spec as2 FUNCTION inv_count(qty integer) RETURN integer;3 PROCEDURE inv_adjust(qty integer);

    4 END inv_pck_spec;5 /

    Package created.

    SQL>SQL> CREATE OR REPLACE PACKAGE BODY inv_pck_spec is2 FUNCTION inv_count(qty integer)RETURN integer is3 new_qty integer;4 BEGIN5 new_qty:= qty*6;6 INSERT into employee (id,salary) values ('01',new_qty);7 RETURN(new_qty);

    8 END inv_count;910 PROCEDURE inv_adjust(qty integer) is11 BEGIN12 DELETE fromemployeeWHERE salarySQL> --call inv_pck_spec.inv_count(2);SQL>SQL> call inv_pck_spec.inv_adjust(2000);

    Call completed.

    SQL>SQL> select * fromemployee;

  • 8/6/2019 Oracle 9

    57/57

    ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY DESCRIPTION---- ---------- ---------- --------- --------- ---------- ---------- ------------02 Alison Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester03 James Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester04 Celia Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager

    05 Robert Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester06 Linda Green 30-JUL-87 04-JAN-96 4322.78 New York Tester07 David Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager01 new

    7 rows selected.

    SQL>SQL>SQL>SQL> -- clean the tableSQL> drop table Employee2 /

    Table dropped.