Está en la página 1de 88

ORACLE

What is Database: - Collection interrelated data organized in the form of Rows & Columns. Why Database System
1) To award the repetition of data that is to development program for each Application One Database File in required. Some of the data may be common between the file, but one Application may required the file ordered in a particular field and other Application is a need of the same file ordered on different field, i.e., though the same data in required by the Two Applications the data has to be stored in the different places.

2) Data redundancy leads to in consists of data.

What is DBMS :- (Database Management System) :- Collection of related if organized in a


structured way in the form of rows & columns.

Management -> Managing the data which includes,


1) addition, deletion, inserting, modification, updating, sorting & generating of Reports. 2) Provides security for accessing the data.

DBMS Useses 1) Application Programmers 2) end users (end) 3) DBA (Database Administrator)

1) Application Programmers -> Writes the Application programs that use the data base which operates on the data of the database which includes addition, deletion, modification etc. 2) End Users -> Interaction to the system either by invoking a Application a Program are writing Query is the database Queries Language. 3) DBA -> The DBA has to co-ordinate the functions of collecting information about the data to stored, designing and maintaining the database and security. Advantages Of DBMS

1) Retundancy can be Cntrolled -> Centralized control of data by DBA avoids the
unnecessary duplication of data and effetely reduces the total amount of data storage required. 2) Inconsistency can be Awarded -> As redundancy in reduced inconsistency of data can also be avoided to same entered the DBMS ensure that the database in inconsistent by ensuring automatically applications to any other entries. 3) Sharing of Data -> DataBase allows the sharing of data by any no. of Application programs or Users. 4) Security -> DBMS Guaranty that only the authorized persons can access the data from the

database that in different checks can be applied to different operation. 5) Integrity can be Maintained -> Data integrity means data contained in the database both accurate and contained. Data Models 1) File Based Model 2) Traditional Data Model 3) Semantic Data Models

Traditional Models 1) Hierarchal Model 2) NetWork Model 3) Relational Model

1) Hierarchal Model -> is from file based system. 2) NetWork Model -> is the set of hirarchel model. 3) Relational Model -> developed from the concept of relations.

SQL
SQL -> Structure Query Language to access the relation data based usually pronounced as Sequel. SQL is IVth Generation Language Developed by IBM, in 1970, but later it was incorporated by Oracle Corporation (1979). Features of SQL :1) SQL is a non-procedural language i.e., specify what you require but not how to get it. 2) SQL process set of records rather than single record at a time. 3) Provides Commands For a) Querying the data b) Inserting, deleting & modification of rows in a table. c) Altering, creating & deletion of data base Objects d) Controlling Access to the Database Objects -> These SQL Commands are available 1) Data Manipulation Language Command (DML) 2) Data Definition Language Command (DDL) 3) Data Control Language Command (DCL) 4) Transaction Processing Command (TPC) DML -> Insert, Delete, Update DDL -> Create, Alter, Drop DCL -> Grant, Revoke TPC -> Commit, RollBack, SavePoint

Writing of SQL Commands


1) Can be Written on One / More Lines. 2) Clauses are Generally Written on Separate Lines. 3) Command words can't be split across lines. 4) SQL commands are not case sensitive. 5) SQL commands are entered at SQL prompt on the Sub Sequence Lines are Numbered known as SQL Buffers. 6) At any Movement of Time only One Command can be Active. 7) Commands in a SQL Buffer can be Executed by Pressing ' / ' (slash). 8) Command should be entered with a Semicolon ( ; ).

Select Statement
is used to Query the Data from DataBase. Syntax:select *[col1.col2,.] from <tablename> [<cond.>]; Using Operators

select m1+m2+m3 total from student; select 2+3*4 from dual;


In Operator

select * from emp where ename in(james,smith,allen); Between Operator select * from emp where sal between 2000 and 4000; Not Between Operator ** To select records of employees who joined before 30-jun-81 and 31-dec-81 from emp select * from emp where hiredate not between 30-jun-81 and 31-dec-81; Is Null Operator select * from emp where comm. is null; Using Wild Card Characters (%,_ )

Like (%) Operator

To select records whose names have only 4 characters from emp table select * from emp where ename like S____; _(underscore) is used to replace any one character select * from emp where ename like _S%; Distinct Avoids duplicate rows select distinct job from emp; FUNCTIONS Date Functions
Related with Date type of Data. Sysdate -> It Returns Current Date & Time. select sysdate from dual;

Date Functions Using Arthematic Operations


Date + Number -> Adds No. of days to the date producing date. Date - Number -> Substracs No. of days from the date producing date. Date - Date -> Substracs One Date from another producing No. of Days. select sysdate,sysdate+7,sysdate - 7, sysdate - hiredate from emp; Months - Between -> Returns No. of Months between Date1 and Date2 result can be negative or positive. Syn:- months_between(date1, date2) select sysdate,months_between(hiredate, sysdate),months_between(' 01-Jan-04',' 31-Aug-03') from emp; Add-Months -> Adds n no. of months to date where n can be positive OR negative. Syn:Add_months(date,n) select sysdate,add_months(sysdate,2), add_months(sysdate, - 3) from emp; Next-Day -> Returns the date of next specified day of the week .

Syn:- Next_day(date,char) select sysdate,next_day(sysdate,'Monday' ) from dual; Last-Day -> Returns Last Day of the Month, that contents date. Syn:Last_day(date) select sysdate,last_day(sysdate),last_day(' 10-Mar-04' ) from dual; Round -> Returns first Day of the Year containing Date, if Date is in the half of the Year, otherwise returns the first Day of the following year. Syn:- round(date,year) select sysdate,round(sysdate,'year' ) from dual; Trunc -> Find the date of the first day of the Month containing Date, when char = 1 Syn:trunc(date,'char' )

-> if the character is equal to year it finds the First Day of the Year containing Date.
select sysdate,trunc(sysdate,'month' ),trunc(sysdate,'year' ) from dual;

Conversion Functions
To-Char -> If use to change or to convert number/Date to Character format, it is usually used to change from default date format to alternate date format. Syn:To_char(number of date,'format' ) select sysdate,to_char(sysdate,'dd/mm/yy' ) from dual; select to_char(sysdate,day,month,year) from dual; select to_char(sysdate,hh:mi:ss) from dual; select sysdate,to_char(sysdate,'dd month year' ) from dual; select to_char(345) from dual; To-Number -> Converts string data type to no. data type To_number(char) select to_number(345) from dual; select * from emp where sal >'4000' where sal > to_number('4000' );

To-Date -> Converts a string to date data type Converts the character value representing date into date value according to format specified, if format is

omited the date format is dd-mm-yy. Syn:To_date( 'char',' format' )

select to_date(15/8/1947,dd/mm/yyyy) from dual; select hiredate,to_date(hiredate,'month-yy-dd' ) from emp; select hiredate, to_date(hiredate,'month-spddth-yyy' ) from emp; * To print No. of Days between the Current Date to Worth Date. select sysdate - hiredate from emp; select sysdate to_date( '10-Apr-04' ) from dual; * To print No.of Days between to Dates. select to_date(' 10-Apr-03' ) ,to_date(' 10-Jul-04' ) from dual; FM (Fill Mode) -> It can be used sub place reading zeros for ddth format. select sysdate,to_char(sysdate,'fmday ddth mm yy' ) from dual; Extraction Of Time From Date select sysdate,to_char(sysdate,'HH:MI:SS' ) from dual; select sysdate,sal,to_char(sal,' $9,999.99' ) from emp; Suffix ---------th SP SPth (OR) th SP select sysdate,to_char(sysdate,' fm day ddspth yy' ) from dual; Prefix ---------FM

Number Functions
Operators on numeric type of data. round() -> To round the number to the specific no of decimal placeses. If no. of decimal is '0' no decimal places, no. of decimal is -1. If no. of decimal is nagitive round the no. to the left of it. Syn:round(no,no. of decimals)

select round(124.6894,2), round(124.6894),round(127.6894,-1) from dual; sqrt() -> Returns the sqrt of a no. Syn:sqrt(no)

select sqrt(25) from dual; mod() -> It has the remainder when first no. is devided is the second no. Syn:mod(no.1,no.2) select mod(25,5),25/5 from dual; abs() -> Return the absulate values a no. Syn:abs(no.) select abs(10),abs(-10) from dual; least() -> Find the smallest of the no's. Syn:least(no.1,no.2,...........) select least(3,6,4,8) from dual; retest() -> Syn:power() -> Ranges the no. to the nth Syn:power(x,y) select pow(2,4) from dual; power.

Ceil -> Smallest integer greater than or equal to a value select ceil(2,6), ceil(4,2) from dual; Floor -> Greatest integer less than or equal to a value select floor(2,6), floor(4,2) from dual; 2 4 3 5

Sign -> Returns -1 if the no. is <0, 1 if the no. is >0, 0 otherwise select sign(-3),sign(5), sign(0) from dual; -1 1 0

Trunc -> Truncates: the int part of a no. with ve precession, decimal part otherwise select trunk(99,26),trunk(99,26,-1),trunk(99,267,2) from dual; Sin -> Returns the sin value select sin(30*3.14/180) from dual; Cos -> Returns the cos value 99 90 99 , 27

select cos(30*3.14/180) from dual; Tan -> Returns the tan value select tan(30*3.14/180) from dual; LN -> Returns the natural logarithmic value select ln(2) from dual; Log -> Returns the logarithmic value as per the base value.
select log(10,2) from dual;

Miscellaneous Functions Vsize -> Returns no.of bytes to represent a value select vsize(100), vsize(santhosh) from dual; NVL -> Converts NULL to a specified value select sal + NVL(comm.,0) from emp; Output :- prints salary + comm.., if comm.. is null, it is converted to zero Decode -> Converts the values of the given column to other given mapping values. Executes as in if else loop select ename, decode(job,manager,boss) from emp where job=manager;
decode() -> Syn:decode(col / value, 'from string' , 'to string' [, 'from', 'to ' , .....], default) (OR) decode(col / expr, search1,result,[search2,result, .......] default]

Ex:- select job decode(job,'sales man','saleswoman','manager') from emp;

-> Column Or Expression is compared to each Search value and returns the value, if column Or expression
equals the search value, if no match is found decode function returns the default value, if the default value is omitted the null value is returned for unmatched values. Note :- Decode Function is used as an alternate to If Else Or Case construct.

* W.A.Q. To replace all tabs with salesman as saleswoman, managers with executive and others with persons.

select job,decode(job,'salesman','sales woman','manager','Exec','persons' ) from emp;

* W.A.Q. To increase the salary baseing on Job. select job,sal,decode(job,'CLERK',sal+sal*1.5/100, 'MANAGER',sal+sal*2/100, 'Salesman',sal+sal*3/100,sal+sal*4/100) from emp;

Ex: ** W.A.Q. To print names and jobs of managers and salesmen but salesman must be printed as sales person and manager must be printed as boss select ename,decode(job,salesman,salesperson,manager,boss) job from emp where job in(salesman,manager); User -> Returns the current user name Select user from dual; UID -> Returns user ID select Uid from dual Greatest -> returns greatest value in the values of a row select greatest(10,20,90,50) from dual; Least -> Returns smallest value in the values of a row select least (10,20,90,50) from dual;

String Functions
Length() -> To calculate the Length of String. Syn :- length(col / value) select length(ename),length('sharath') from emp;

Concat() -> It is used to concatenate of two strings. Syn :- concat(col1,col2)

select ename,job,concat(ename,job) Employee from emp;

Initcap-> Changes the first letters of words into uppercase select initcap(ename) from emp; Upper -> select upper(ename) from emp; Lower -> select lower(ename) from emp; Lpad -> Adds width minus string length no.of characters to the left select lpad(santhosh,10,*) from dual; Rpad -> Adds width minus string length no.of characters to the right select rpad(santhosh,10,*) from dual; Ltrim -> Removes all occurrences of the chars of a set till it faces an unmatched char starting from left select ltrim (abbas,ba) from dual; Rtim -> Removes all occurrences of the chars of a set till it faces an unmatched char starting from right select rtrim(softech,ch) from dual; Instr -> Finds the first occurrence of a char, (after nth position if given) select instr(softech,o), instr(softech computers,o,3) from dual; Substr -> Subtracts n chars from a given position select substr (softech,2,3) from dual; Replace -> Replaces the search string, if exists, with the given string. select replace (abcaabbcc,abc,xyz) from dual; Translate -> Replaces occurrences of each char of a search string with the each corresponding char of a given string

select translate (abcaabbcc,abc,xyz) from dual; Soundex -> Finds values whose pronunciation matches with as that of a given string select ename from emp where soundex (ename) = soundex(James); Chr -> returns character corresponding to a no. select char (65), char (67) from dual; Ascii -> Returns ASCII value select ascii(A) from dual; Group Functions
These process sets of rows. Sum() -> Returns the sum of values of column. Syn :- sum(col) Ex:- select sum(sal) from emp; max() -> Returns the max of values of column. Syn :- max(col) Ex:- select max(sal) from emp; average() -> Returns the Mean of values of column. Syn :- average(col) Ex:- select avg(sal) from emp; min() -> Returns the minimum values of column. Syn :- min(col) Ex:- select min(sal) from emp; count() -> Returns the count of values of column. Syn :- count(col) Ex:- select count(empno) from emp; * Ex:W.A.Q. to Count No.Of Employees working in a selected deptno.

select count(*) from emp where deptno=&dno; stddev -> Finds standard deviation

of the values of a column

select stddev(sal) from emp;


Variance -> Finds variance of the values

of a column

select variance(sal) from emp;


SORTING : Using Order By Clause: Ex:- To list the employee details in ascending order according to salary select * from emp order by sal; W.A.Q. To list the employee details in descending order according to names select * from emp order by ename desc; W.A.Q. To list the employee details in ascending order according to names. If there is a matching name, then sort by empno select * from emp order by ename, empno; W.A.Q. To list the employee details in ascending order according to their experience select ename, job, months_between(sysdate, hiredate)/12 from emp order by 3; Order by 3 indicates sorting according to third column i.e. experience in years

Group By Class
It is used to display the query result into small of groups. Mainly this class is used on the column whose values are repeated. Syn :- select * [ (col1,col2, .....)] from <table name> group by (col1, col2, ....); * Ex :W.A.Q. to find the max sal with job wise. select job, max(sal) from emp group by job; W.A.Q. to count the no. of employees deptno wise. select deptno,count(*) from emp group by deptno;

W.A.Q. To list the unique jobs in emp table

select job from emp group by job; W.A.Q. To list the department number and number of clerks in each department select deptno, count(*) from emp where job = CLERK group by deptno; W.A.Q. To list the jobs and number of employees in each job. The result should be in ascending order according to the number of employees. select job,count(*) from emp group by job order by job; * (20)

Having Clause
having clause restricts the set of rows where as where clause restricts individual course. Syn :- select * [ (col1,col2, ....)] from <table name> having cond(s); * Ex:- W.A.Q. to display the department no's employeed more than two employees. select deptno,count(*) from emp group by deptno having count(*) > 2; Ex:select job,max(sal) from emp where job !=' MANAGER' group by job. Ex:- W.A.Q. to check whether empno is indeed unique. select empno,count(*) from emp having count(*) > 1 group by empno; To list the department number in which maximum employees work select deptno from emp group by deptno having count(*) = (select max(count(*)) from emp group by deptno);

Sub Queries
select statement with in another select statement.

Sub Queries and Correlated Sub Queries Sub Query involves placing a query with in another query. The inner query provides values to the outer query. Correlated Query is the one in which processing the inner query depends on data from the outer query. Here, inner query must be computed for each outer row.
Syn :Select column(s) from <table name> where col = (select stat. );

Processing
First of all inner query is executed and then outer query is executed by taking the result of inner query as the condition for outer query. Ex:W.A.Q. to display the name of employee max salary. Select ename from emp where sal = (select max(sal) from emp); * W.A.Q. to find the name of employee, when get second max salary. Select ename from emp where sal in (select max(sal) from emp where sal not in(select max(sal) from emp));

Sub Queries 1) To find the second max salary of the employees in emp table Select max(sal) from emp where sal <(select max(sal) from emp); 2) To print the name of the employee who draws maximum salary Select ename from emp where sal = (select max(sal) from emp); 3) To print the name of the department in which maximum employees work. select dname from dept where deptno in(select deptno from emp group by deptno having count(*) = (select max(count(*)) from emp group by deptno)); 4) To print the names which have maximum number of characters select ename from emp where length(ename) = (select max(length(ename)) from emp); 5) To list the jobs, which is done by maximum no. of persons select job from emp group by job having count(*) = (select max (count(*)) from emp group by job); 6) To list the name, job, hiredate, deptno of the recently joined employees in each department select ename, job, hiredate, deptno from emp where (hiredate, deptno) in (select max(hiredate), deptno from emp group by deptno;

7) To list names and hiredate of employees who joined on the same day. select ename, hiredate from emp where hiredate in (select hiredate from emp group by hiredate having count (*)>1); 8) To list the year in which more number of employees have joined select to_char(hiredate, yyyy) from emp group by to_char(hiredate, yyyy) having count(*) = (select max(count(*)) from emp group by to_char(hiredate,yyyy)); 9) To list the deptno, deptname and maximum salary of each department select distinct emp.deptno, dept.dname, emp.sal from emp, dept where emp.deptno = dept.deptno and (emp.deptno,sal) in (select deptno,max(sal)from emp group by deptno); 10) To list the employee name, deptno, and salary of the employees, who earn maximum salary in each department select ename, deptno,sal from emp where (deptno, sal) in (select deptno, max(sal) from emp group by deptno); 11) To print the employees who draw first three maximum salaries select ename, sal from emp where sal in (select sal1 from (select distinct sal sal1 from emp), (select distinct sal sal2 from emp) where sal1 <= sal2 group by sal1 having count(*)<=3) order by sal desc; Correlated Sub Queries 12) To print the employees who draw first three maximum salaries select ename, sal from emp e where 3>=(select count(sal) from emp where e.sal<sal) order by sal desc; 13) To print all the employees who have at least one person reporting to them select ename, job from emp e where exists (select mgr from emp where mgr = e.empno);

JOINS

Extraction data from more than one table. It is a horizantal Join (row wise). Joins is 3 Types. 1) EquiJoin 2) Non-EquiJoin 3) OuterJoin 4) Self Join

1) Equi Join
The relation between emp and dept table is equijoin. That is both are tables are having the same column called deptno on which equijoin relationship can be establish using ' = ' operator. Syn:select * [(col1,col2, ..... ) from <table(s)> where join cond(s)]; Ex:select * from emp,dept where emp.deptno=dept.deptno; select empno,ename,job,sal,emp.deptno,dname,loc from emp,dept where emp.deptno=dept.deptno; | Error -----------------------As deptno column is available in both the tables error is encounter, because it is enable to understand from which table the value as be extracted from, when ever there is common field are available in both the tables specify the field name, column by the table name ' . ' the field name. Table Elyasis Referring a table with an alternate name avoiding repeating to typing, which can be upto 30 characters in length, but less than better. select empno,ename,job,sal e.deptno,dname,loc from emp e, dept d where e.deptno=d.deptno; Rules for Joining Condition 1) no. of tables -1 = Join condition NonEqui Join Ex:- display the salary with lowest sal & high sal select ename, job, sal, losal, hisal from emp e, salgrade s where e.sal between s.losal and s.hisal; Outer Join The outer join is to add the one to another table of records with use the ' + ' operator. Ex:select ename, job, sal, e.deptno, dname from emp e, dept d where e.deptno (+) = d.deptno;

Self Join Joining a table using itself table elyasis as it two tables separator. Ex:select e.ename empname, e.sal empsal, m.ename mgrname, m.sal mgrsal from emp e,emp m e.mgr = e.empno;

Set Operators
These are many use to combine the results of two queries into one.

Union
Displayes the result present is first query another second query excluding duplicate rows. select job from emp where deptno = 10 union select job from emp where deptno=30;

Union all
Same as above but including duplicate rows. select job from emp where deptno = 10 union all select job from emp where deptno=30;

Intersect
Returns are rows which are common in both the queries. select job from emp where deptno = 10 intersect select job from emp where deptno=30;

Minus
Returns the rows which are their in first but not present in second. select job from emp where deptno = 10 minus select job from emp where deptno=30;

SQL Plus Commands


Save
save <file name> Save the contains of the sql buffer on to the specified with an extension . sql

Load
load <file name> To load the contains of specified file on to the buffer and execute same and pressing slash ( / ).

Start
start <file name> OR @ <file name> Loads the contains of specified file on to the buffer and or executed automatically.

Ed
To create a new file or open the existing file from modification. Default editor is notepad. ed <file name>

SQL Buffer Commands


L -> To list the contains of the buffer. L() -> To list the specified line number.
L (no)

c -> To change the text Syn:- c / old / new Ex:- c / emp / dept;

SQL Plus Commands


Exit -> To exit from SQL Plus Connect -> To connect a oracle user. Syn :- connect username / password @ connect-string; Show User -> Displays the current user.

Set Commands
These are used to control the working environmental of sql plus. The set command that set or active as non as the system is know. To make the active all the time include these commands in a special file login sql. Which is invoked every time sql plus is run.

login Sql -> This is only system file.

Set AutoCommit On / Off


Default is Off. If it is on the changes that are made or committed automatically without using command commit explicitly. It is Off the changes are made permanent only of the issuing command commit implicitly.

Set LineSize
set linesize <no> Sets the no.of characters access a line. set linesize 120

Set Heading On / Off


Default is On. If it is Off suppress the column headings.

Set Pause On / Off


Default is Off. If it is On it prompt the user, to press any key to continue.

Set Pagesize
set pagesize <no> Sets the no.of line accross a page.

Set FeedBack On / Off


Default is On. If it is Off the message regarding the command that is process is suppressed in the display.

Set Verify On / Off


Default is On. If it is Off the value that is supplied using suppression value is not verify to the expression. Ex:select * from emp where ename = '&name'; select * from emp where ename = 'SCOTT';

Set Serverout On / Off


Default is Off. If on displays the message on the screen while working with PL/SQL using message command.

Set NumFormat
set numformat 'format ' Set the specified no. format which is applicable for all the numeric columns of a table. Ex:set numformat 9,999.99 select empno,deptno,sal,comm from emp;

Variables in SQL/Plus
Whose value keeps going on changing. 1) Substitution Variable There is two types.

2) Bind Variables

Substitution Variable -> Substitution Variable is two types.


a) Single Substitution Variable b) Double Substitution Variable

Bind Variables -> Bind variable are the variables declared in other host environment and can
be reffered in PL/SQL by : var;

Single & Substitution Variable


When it is used it prompts the user to enter the value at run time, and the value that is entered is not stored or saved into the variable, hence it allows the user to enter the new value each time the query is executed to pressing ' / '. Note:character and date values should be enclosed in single qutotion marks and the no's need not. Ex:select * from emp where empno=&eno; select * from emp where ename ='&name';

Entering the Condition At Run Time


select * from emp where & cond; Enter the value of cond : Ename = 'SCOTT'; Job = 'MANAGER'; * W.A.Q. to enter the column names to extracted from a table at run time. select &col1,&col2,&col3 from emp; select &col1,&col2,&col3 from &tablename;

Double && Substitution Variable


It allows the user to enter the value at runtime when the query is executed for first time. The value that is entered is stored in the variable, hence each time the query is executed the pressing ' / ' key the result is displayed with the same previous value. select * from emp where job = '&&desig ';

Define Command
It is used to define a variable or list the variables that are defined. Note:By default the variable that are defined using define command are always type character. * W.A.Q. to calculate the annual salary of employee. Note :To reffer a variable in sql statement specify the variable name pressed by single & . Ex:define annsal = sal * 12 + NVL(comm,0); select ename,job,sal,comm,&annsal from emp;

Undefine
To undefine a variable use the command undefine followed by the variable name. Syn:undefine <var>

Ex:- undefine annsal;

Accept Command
It is used to declare a variable of specified datatype. Syn:accept <variable> <data type> [prompt] [no prompt] [hide] Ex:accept msal number;

Define -> to list the memory variable.


Refferring the memory variables in select statement -> select &msal from dual;

Prompt -> Prompts the user with user defined message.


Ex:accept msal number prompt ' Enter Salary '

Hide -> Hides the value from display, each character that is type is displayed with an astrick (' * ')
Ex:accept prod varchar2 prompt ' Enter Password ' hide

SQL Plus Reports


Reports -> Extracting of data from a database (table) & printing it in a format.

Report LayOut
1) Page Header -> Gets printed at the top of each & every page. 2) Page Footer -> Gets printed at the bottom of each & every page. 3) Detail Bound -> Gets printed for each & every record.

Data Grouping -> Grouping of data


1) On a column, whose values are repeated. 2) Arrange the data in the order of grouping column.

Additional Bonds :1) Group Header -> is printed at the top of each group. 2) Group Footer -> is printed at the end of each group.

Column Command
It is used to specified the format specification on the column display. Syn:column <column name> format <format> heading <heading>

Format -> is accept character or number type. Character is accept - a, number is accept - 9.
Ex:1) column empno format 9999 heading 'Emp No'. 2) column ename format a15 heading 'Emp Name' justify right | 3) column job format a10 heading 'Designation' justify center. 4) column sal format 99,999.99 heading 'Salary' 5) column comm format 9,999.99 heading 'Commission' NULL 'No comm' 6) column deptno format 99 heading 'Dept No' select empno,ename,job,sal,comm,deptno from emp;

TTitle & BTitle Commands


TTitle -> Syn:TTitle ' text '

Is used to display the page no. to wards the right side column and date upper left side corner and text that is specified used TTitle command is displayed in the center of the next line. Ex:TTitle 'Employee Details' BTitle -> Display the specified text at the bottom line of the page centered. Syn:Ex:BTitle ' End of the Records ' select empno,ename,job,sal,deptno from emp; TTitle / BTitle [Off ] :TTitle off -> to remove the top title. BTitle off -> to remove the bottom title. Clear Column -> to clear the columns BTitle 'text'

Break On Reports (Data Grouping )


Break command is used to break the report into smaller groups. Syn:Break on <column> Ex:break on deptno; select deptno,empno,ename, job,sal from emp order by deptno; Summary Calculations Summary calculations can perform using compute command. Syn:compute <clause> of <column(s)> on <column> [on report ] Ex:compute sum avg of sal,comm on deptno;

Data Definition Language Commands (DDL)


3 types of DDL commands 1) Create 2) Alter 3) Drop

Create
It is used to define the structure of a table. Syn:create table <table name> ( col1 datatype(size), col2 datatype(size) ...... coln datatype(size));

Data Types
Determines what type of data a variable. Char -> Fixed character length of width , default is 1, the maximum is 255 characters. version 7.00 - 255 version 8.00 - 2000 Varchar2 -> Variable character length of width, maximum is 2000 in 7.00 & 4000 is 8.00. Date -> To store date and time values. Long -> Same as Varchar2, but can store to a maximum length of 2 GB, only column should exist with type long. Long raw / raw -> same as long, but stores graphic images. Number -> It accept puerly no's of decimals of width, maximum of 38 digits. Number (w,s) -> Store the no. width w, and scale (precesion) of s.

Data Manipulation Language Commands (DML)


1) Insert 2) Delete 3) Update These are used to manipulate the data.

Insert To insert the rows into a table.


Syn:insert into <table name> [(col1,col2,col3, ...... , coln)] values (val1,val2,val3 ........ valn);

->

List of values specified should be equal the no.of columns specified and should match in the order, datatype. insert into std(rno,name) values(1,'sh');

Ex:-

insert into std values(10,'sh',' 20-Jan-04' );

-> Date and Character values should enclosed single codes.


Entering the Date in alternat format other than a default format. insert into stud values(100,'sh',todate( ' Jan-20-04',' Mon-dd-yy' );

Inserting Time ->


Ex:insert into stud values(200,'sh', todate( ' Jan-22-03 10:30 ',' mon-dd-yy hh:min' ); insert into stud values(&rno,'&name','&date' );

Delete -> To delete the records on to selected table, If where condition is used the selected
records are deleted. Syn:delete from <table name> [cond.]; Ex:delete from stud where rno >10; OR delete from stud where rno=10;

Update -> To update the column values of a table.


Syn:update <table name> set col = value / expr [(col2=value / expr, ......)] [where cond]; Ex:update emp set ename='sh' , sal = sal+1000 where hiredate=' 20-Feb-04'; Demobld -> To build the demo tables. Ex:@demobld;

Transaction Processing Commands


Commit -> To save the changes permanently. RollBack -> To Undo OR Cancelled the changes are made. Save Point -> Save point identifies the point transaction to which one can latter rollback with rollback statement. It is helpful in the transaction contains large no. of SQL statements and the user wants to Commit only one's. It required the user can Rollback it a particular transaction. Syn:savepoint <name> Rollback to Save point name -> Undo the canges upto the savepoint. Syn:rollback to <savepoint name>

Ex:1) insert into dept values(40,' ','texas' ); 2) savepoint x; 3) update dept set dname='abc'; 4) rollback to x;

-> Rollback statement will Undo, only the Updation. All the satements before the savepoint 'x',
remain unchanged.

Drop Command
To drop the table; Syn:drop table <table name> [cascade];

-> Cascade option is used to drop the referential integrity constraint.

DLL Commands Integrity Constraints


These are used to enforce to a certain rolls with in a table or between the table.

-> The character, date values can be left blank, by specify null OR a space, and numeric
values is null.

Types of Integrity Constraints -> two types.


1) Column Constraints 2) Table Constraints

1) Column Constraints -> Column constraints of a defined of a column along with a definition of column. 2) Table Constraints -> Table constraints are define outside the definition of a columns.

Table / Column Constraints :- 3 types


1) Domain Integrity Constraints Check, Default 2) Entity Integrity Constraints Primary Key, Unique, Not Null 3) Referential Integrity Constraints Foreign Key

Unique
Insures the uniqueness on that values in a column, that is not two rows in the table should have the same column value.

-> Unique constraint is used duplicate values are not accepted, but null values are accepted.
Syn:[constraint <constraint name>] Unique; Ex:create table stud(rno number(3) constraint conroll Unique, name varchar2(10));

Table Constraints
It is used to set the same Constraint More than One Column also. Syn:Ex:create table stud(rno number(3),name varchar2(10), constraint rnacon Unique(rno,name));

, [constraint <constraint name>] Integrity Constraint (col1,col2, ........);

-> The Table Constraints is used To Check The Constraint Columns Of The Values is Equal
It will Not Accept, Whether, Any One Column Is Not Equal It Will Accept The Records.

Not Null Constraint


Not Null constraint is used Null values are not accepted, but Duplicate values are accepted. Syn:[constraint <constraint name>] Not Null; Ex:create table stud(rno number(3) constraint conroll Not Null, name varchar2(10));

Check Constraint
Checks for the correctness of the value enter with the help of a condition. Syn:[constraint <constraint name>] Check(cond); Ex:create table stud(rno number(3) constraint conroll Check(rno>50), name varchar2(10)); create table stud(rno number(3) constraint conroll Check(rno>50), name varchar2(10) constraint nacon check(name = Upper(name));

-> It will Accept Duplicates & Null values, but it will check the Condition.

Default Provides a default value for a column when value is not supplied for that. Ex:create table department( dept_num number(2) unique, dept_name varchar2(20) default accounts); insert into department (dept_num) values(10); Primary Key
It Enfources the entering of Duplicate and Null Values.

-> We can have only one Primary Key column for a table.
Syn:[constraint <constraint name>] Primary Key Ex:create table stud(rno number(3) constraint conroll Primary Key, name varchar2(10));

Referential Integrity Constraints Foreign Key


It is a combination of columns with values where the Primary Key values from another table. A Foreign Key constraint with is also know as referential integrity constraints with the specifies the values of Foreign Key corresponded to actual values at the Primary Key in Another Table.

-> Foreign Key is used to Establish Parent and Child Relationship Between the Tables.
Syn:[constraint <constraint name>] references <table name> (col);

-> To have the Relation Between of Columns of same Table.


Ex:create table stud(rno number(2) Primary Key, name varchar2(10) constraint rnocon references stud(rno));

Table Constraint
Syn:, [constraint <constraint name>] Foreign Key (col) [cascade] references <table name> (col);

Ex:Parent create table p(rno number(3) Primary Key, name varchar2(10)); Child create table q(rno number(3), name varchar2(10), constraint frno Foregin Key(rno) references p(rno)); Note :1) First Insert the New Rows into Parent Table and then into Child Table 2) First Delete the Rows into Child Table and then Parent Table.

Cascade Option
If Cascade is included the correspond records of Child Table, and it will be Delete OR Update the Child Table of Rows it will be change into the Parent Table. Ex:Child create table q(rno number(3), name varchar2(10), constraint frno Foregin Key(rno) references p(rno) cascade);

Alter
To Change the definition of a Column. Like Column Type and Size, but Column Name not Change. Syn:alter table <table name> add / modify / drop ( col1 datatype(size) [Integrity Constraint] .....) [enable / disable]; Add -> To add the Column on to the existing table. Modify -> To modify the select Column of Datatype & Size. To modify the table of columns, before changing make sure that no rows existing in the table. Ex:alter table stud add( name varchar2(15)); alter table stud add constraint rnocon Primary Key (rno); alter table stud modify name varchar2(20);

Drop Clause

To Drop a Constraint. Syn:alter table <table name> drop (Integrity constraint); Ex:alter table stud drop primary key; alter table stud drop constraint rnocon;

List of Constraints
select * from User constraints;

Enable OR Disable Clause


To make the constraint On / Off without dropping Or recreating. Syn: alter table <table name> Enable / Disable (Integrity Constraint); Ex:alter table stud disable primary key;

-> If Disable the constraint column, the constraint column will accept the duplicate values and null
values. alter table stud enable primary key;

-> If enable the constraint column, the constraint column will not accept the duplicate values and
null values.

Drop Command
To Drop a Table. Syn:drop table <table name> [cascade];

-> Cascade option is used to drop the referential integrity constraint.


Truncate Command Same as Drop Command, but changes made cannot be cancelled. Rename -> Syn:rename <old> as / to <new> To changes the name of a Table.

Data Control Language Commands

1) Grant

2) Revoke

DBA (Database Administrator) is responsible for creating new users, granting of permissions etc.,. It's a Owner of Oracle Database. 1) Creation of new User Syn:create user <user name> identified by <password>; Ex:create user sh identified by sh123; Changing of PassWord Syn:alter user <user name> identified by <pass word>; Ex:alter user sh identified by sh123; Show User Displays the currently logged User. Connect To Connect another Oracle User from the Current User. Syn:Connect username / password @connectstring; Ex:connect sh / sh123@orcl; Show User

Granting of Permissions / DBA


Using Grant Command 2) Grant connect, resource to sh; System Privileges i) Create Session To get connect to the database. ii) Create Table To create a table. iii) Create View

To create a view. Create User To create a user.

Role -> Collection of privileges.


Connect -> Collection of a box privileges.

3) Connecting to New User


connect sh / sh123@orcl;

4) Building of DemoTables
Ex:@demobld;

5) Granting of Permissions Privileges on an Object to a User Privileges


select -> to select the data

delete -> to delete the data update -> to update the data insert index view all Syn:grant previliges (on) table / view to user(s); Ex:grant select on emp to sh; grant select, update on emp to sh; grant update on dept(dname) to sh; grant all on emp to sh; -> to insert the data -> to create an index -> to create an view -> all of the above.

Revoke
To take back the privileges given to another user from user. Syn:revoke privilege(s) on table / view from <user>; Ex:revoke delete on emp from xyz;

Synonyms

To access the table of another user table name should be followed by the user name with the dot(.). Ex:select * from scott.xyz; Instead of referring of a table own by another user by saying user name, table , a synonym can create on a table own by another user. Syn:create synonymn <synonymn name> for <user.table> Ex:create synonymn x for scott.emp; select * from x;

Database Objects

Sequence
It is used to generate the no's in a sequence. Syn:create sequence <sequence name> increment by <no> start with <no> maxvalue / no maxvalue minvalue / no minvalue; Ex:create sequence noseq increment by 1 start with 1 maxvalue 20; Next val It is a suit of col used with the sequence to reffer the next val of sequence. Ex:select noseq.nextval from dual; Curval It is a suit of column used to reffer the current values of sequence. Ex:select noseq.curval from dual; Note :1) Sequence is main used to generate the no's of sequentially which avaids the duplicates values of null values. 2) It is main used to insert command to insert the rows into a table. Ex:insert into x values(noseq.nextval);

Altering the Sequence Using Alter Sequence command. Syn:alter sequence <sequence name> increment by <no> maxvalue / no maxvalue minvalue / no minvalue; Note :1) Start with value can't be alter. 2) One's the sequence is alter it is go to sequence that is to be generated of the altering. Ex:alter sequence noseq increment by 5 maxvalue 100; Droping of Sequence Syn:drop sequence <sequence name> Listing of Sequences user_sequences select * from user_sequences;

Index
the query using where clause on the column on which table is indexed. Types of Indexes unique nonunique (default) concatenated Syn:create [unique] index <index name> on table (col1,col2, ....); Indexes 1) default is non-unique a) create index ind on emp(ename); b) select * from emp where ename='SCOTT';

2) Unique-Index

It is created automatically when a unique constraint is defined on a table. Which entries the Unique values are available. that is no two rows in the table should have same value. Ex:create table x(no number(2) unique); Note :Unique index is created automatically, when a unique constraint is defined on a column avoiding duplicate entries.

Creation of Unique Index


1) create table x(no number(3)); 2) create unique index ind on x(no); 3) insert rows into x tables duplicate values are avoided as unique index is created on no. Concatenated Index Index on more than one column. Ex:created index id on emp(ename,job); Note :It has the effect only when multiple rows have same value. Droping Of Indexes Syn:drop index <index name> Listing of Indexes select * from user_index;

Views
A view is like a window to which data on tables can be view. A view is derived from other table or view, which is referred as the base table of the view. A view is through as select statement only, and it is virtual table, that is a table that not exist physically, but uppers to the user as a exist. A view as no data of it's own but it manipulates the data in the underline based table.

Types
1) Simple View Derived data from only one table and contains no functions or nosub data. 2) Complex View

Derived from any tables and contains functions or groups of data. Create View Syn:create [or replace] [force] view <view name> [(col1,col2, .......)] as select statement; 1) Simple View Ex:create view empview as select * from emp; (OR) create view empview(no,name,desg) as select empno,ename,job from emp; select *from empview; delete from empview where deptno=10; insert into empview(empno,ename,job,deptno) values(100,'abc','manager',20); Complex View create view empdept(deptname,minsal,maxsal,avgsal) as select name,min(sal),max(sal),avg(sal) from dept,emp where dept.deptno=emp.deptno group by dname; Replace It allows the view is created even if the view is exactable in the same name, replacing the old version of the view. create or replace view empview as select * from emp; Force This option allows users create a view even, if the base table does not exist or if there are insufficient table, for the table must be existed by using the view. Ex:create force view empview as select * from emp; Listing of View user_views select * from user_views; Dropping a View drop view <view name>;

PL / SQL

Procedure Language / Structured Query Language. It is an extension to SQL incorporating the feature of other programming languages like Binary Statements, Decimal Making Looping Constructs Functions etc,.

Advantages
1) Variables :- For storing the manipulating the values datatypes includes, datatypes available in SQL Plus datatypes. 2) SQL Support :- Select, Insert, Delete, Update, Commit, Savepoint, RollBack are supported. 3) Composite Datatypes :- Records allowed groups of fields to be defined and manipulated in PL / SQL. i) Record type variables. ii) Column type variables. 4) Flow of Control :- If Statement, Loops, Goto, Labels, provides condition access branching iterative control with programs. 5) Built-In-Functions :- Same as that of SQL, but Group Functions are not supported, but supports two extra functions for error trapping SQL Code SQL Error 6) Cursors :- Is an Identifier for a memory location. 7) Exception Handling :- Warning and error conditions are defined as exceptions which can be handled in each block. Exception Handlers specify what has to be done when the error is encountered.

Structure Of PL / SQL Block


Declare ---Declaration Statement; Begin Executable Statements; ----

Exception Exceptional Handlers; End;

Types Of Blocks :1) Anonymous -> having no name 2) Stored / Named Blocks -> Functions & Procedures

Comments :1) --- ( Single Line ) 2) Set Of Lines ( \* *\ )

Data Representation :Variable & Constraint Variable are used to store data values.

Data Types :1) Number :(SQL 2000)

2) Character :- Max of 255 characters. 3) Varchar2 :- 32,767 Max 4) Date 5) Boolean ::-

Declaration Of Variables
These are declared in the declared section of the block. Syn :identifier datatype[(precession , scale)] := value / Exp;

:= -> assignment operator


Ex:name varchar2(10);

Assignment Of Values (Or) Variable to a Variable :-

1) At time of declaration name varchar2(10) := 'santhosh'; 2) After Declaration name varchar2(10); begin name := 'santhosh' ; Declaration Of Constraint :values of the fixed. Ex:pi constraint number(9,5) := 3.147;

Select Statement In PL / SQL :Select statement is used in PL / SQL with into class, select statement should return only one row. Select statement returning no rows or more than one row encounters an error. To avoid the said problems expressions avoid the raised. Syn:Select col1,col2,...... into var1,var2,.......... from table;

Errors
no :- no data found -> -> if select statement is not returning any row.

Exact fetch returns regretted more rows to be encountered.

The column selected should be equal to be no. of variables into which the values are populated and should match in the order number and type.

Writing PL/SQL Blocks:Anonymous Blocks :1) Writing of PL / SQL block Statement(s) at SQL prompt which are stored in SQL declare ---

--begin ----end; 2) Writing of PL / SQL blocks statements in Script. SQL > Ed <filename> -> getting the contents of the script file onto buffer. SQL > @ <filename>; -> Execution SQL > / SQL > Set Serverout On -> To Display The Result.

To Print Message On The Screen:dbms_output.put_line (' Message Prompt '); dbms_output.put_line ('Result is '); dbms_output.put_line ( c ); dbms_output.put_line ('Result is ' || c); Ex:SQL > ed a 1) declare mname varchar2(10); mjob varchar2(10); msal number; begin select ename, job, sal into mname, mjob, msal from emp where empno = &no; dbms_output.put_line ('Emp Name '||mname); dbms_output.put_line ('Emp job ' || mjob); dbms_output.put_line ('Emp sal ' || msal); end;

2) Save & Exit -> Alt + F4

3) @ a; SQL > /

Declaration of Column Type Variable:Using % type attribute.


The selected column information is to be populated into a variable which is compatible no of to whole of selected column with same size and type. Syn:identifier table.columnname % type; If their is any error occurs. To avoid the above problem % type attribute is used. Ex:declare mname emp.ename%type; mjob emp.job%type; msal emp.sal%type; select ename into mname; select job into mjob; select sal into msal; begin dbms_output.put_line('Emp No ' || erec.empno); dbms_output.put_line ('Emp Name '||erec.ename); dbms_output.put_line ('Emp job ' || erec.job); dbms_output.put_line ('Emp sal ' || erec.sal); end; /

Declaration Of Record Type Variable


% Rowtype attribute.

Recording PL / SQL holds all the column names with their values with same type and size. Syn:recordname table % rowtype; Ex:erec emp%rowtype;

-> To access the column value for the record


recordname.columnname; Ex:erec.sal;

declare erec emp%rowtype; begin select * into erec from emp where empno = &no; dbms_output.put_line('Emp No ' || erec.empno); dbms_output.put_line ('Emp Name '||erec.ename); dbms_output.put_line ('Emp job ' || erec.job); dbms_output.put_line ('Emp sal ' || erec.sal); end; /

COMPOSITE DATA TYPES: RECORD, TABLE RECORD is a composite data type encapsulates other attributes (similar to structures in C) Type statement is used to create RECORD Syntax is: TYPE typename is RECORD ( variable 1 datatype, variable 2 datatype, ); variable typename; A variable of type tablename%rowtype is also a record To access member attributes of a record variable, dot(.) extension is used.

TABLE is similar to array and holds set of values of same type Type statement is used to create TABLE Syntax is : TYPE typename is TABLE OF datatype / record type INDEX BY BINARY_INTEGER; variable typename; Size of the table is not mentioned while defining it. Index is used to pick elements of the table.

Examples: Write a program to demonstrate the use of %rowtype record. Print empno, ename, job, salary of an employee identified by given empno. declare r emp%rowtype; eno emp.empno%type := &eno; begin select * into r from emp where empno=eno; dbms_output.put_line( r.empno || || r.ename|| end;

||r.job|| ||r.sal);

Write a program to demonstrate user-defined record. Print empno, ename, job, salary of an employee identified by given empno. declare type emprec is record (eno emp.empno%type, n emp.ename%type, j emp.job%type, s emp.sal %type); r emprec; eno emp.empno%type :=&eno; begin select empno,ename, job, sal into r from emp where empno=eno. dbms_output.put_line(r.eno|| ||r.n|| ||e.j|| ||r.s) end;

DML Commands In PL / SQL:Insertion Of Record :Declare

begin insert into emp(empno, ename, job, deptno) values (100,'santhosh','stud',30); dbms_output.put_line(' record is inserted '); end;

Update Of Record:Declare begin update emp set ename='santhosh' where empno=&no; dbms_output.put_line('record are updated'); end; /

Deletion Of Record :declare begin delete from emp where empno=&no; dbms_output.put_line('record are deleted'); end; /

Write a program to convert a four-digit number to words i.e. to spell a 4-digit number. declare x number :=&x; s varchar2(50); begin select to_char(to_date(x,yyyy,year) into s from dual; dbms_output.put_line(s); end; Output Enter value for x 77 seventy-seven

Enter value for x 465 four sixty-five Enter value for x 3480 thirty-four eighty Write a program to print the weekday name of a given date in dd-mm-yyyy format. declare s varchar2(50); begin select to_char(to_date(&date,dd-mm-yyyy),day) into s from dual; dbms_output.put_line(s); end; Output Enter value for date 15-8-1947 Friday

Flow Of Controls :Simple If ->


if cond then stat(s); end if;

If - Else ->
if cond then stat(s); else stat(s); end if;

Else If Ladder ->


if cond then

if cond then stat(s); else if cond then stat(s); else stat(s); end if; end if; else stat; end if;

Multiple If ->
if cond then stat; elsif cond then stat; else stat; end if; Ex :-

Simple If
declare age number := &age; begin if age >= 18 then dbms_output.put_line(' eligible '); end if; end; /

If Else
declare age number := &age; begin if age >= 18 then dbms_output.put_line(' eligible '); else dbms_output.put_line(' not eligible '); end if; end;

Else If Ladder
declare name varchar2(10) := 'santhosh' ; m number(2) :=&maths; c number(2) := &che; p number(2) :=&phy; tot number; a number; res varchar2(10); div varchar2(10); begin tot := m+p+c; a := tot / 3; if m>=40 and c>=40 and p>=40 then res :='pass'; else res :='fail'; end if; if res = 'pass' and a >=75 then div :='first'; else if res='pass' and a>=60 then div :='second'; else if res='pass' and a<60 then div :='third'; else div :='**** ' ; end if; end if; end if; dbms_output.put_line('name is ' || name); dbms_output.put_line('maths is ' || m); ------end; /

Complex If Construct
Instead of writing else if different in this we have to write elsif instead of writing else if.

declare name varchar2(10) := 'santhosh' ; m number(2) :=&maths; c number(2) := &che; p number(2) :=&phy; tot number; a number; res varchar2(10); div varchar2(10); begin tot := m+p+c; a := tot / 3; if m>=40 and c>=40 and p>=40 then res :='pass'; else res :='fail'; end if; if res = 'pass' and a >=75 then div :='first'; elsif res='pass' and a>=60 then div :='second'; elsif res='pass' and a<60 then div :='third'; else div :='**** ' ; end if; dbms_output.put_line('name is ' || name); dbms_output.put_line('maths is ' || m); ------end; /

Looping Constructors OR Iterative Statements :Repetition of statements as long as condition is true and exit. When condition is false. Depending upon the Control Structure Looping Constructs are mainly of 2 Types, they are :1) Entry Control Loop 2) Exit Control Loop

1) Entry Control Loop ->


Enters into the loop and executes the body of the loop only when condition is true.

2) Exit Control Loop ->

Enters the Loop and Executes the body of Loop atleast once Unconditionally and then Checks for the Condition.

Points To Remember :1) Initialisation of a value to a variable. 2) Condition checking. 3) Execution of body of the Loop. 4) Step value ( incrementation Or decrementation ).

1) Loop :- (infinite loop)


loop statements; end loop; Ex:- Program to print natural no's. declare i number := 1; begin loop dbms_output.put_line( i ); i := i+1; end loop; end; ( press Ctrl + Break -> To Stop ) /

Exit Statements :It is used to terminate the Loop. Syn :loop stat(s); exit when cond; end loop; Ex:Program to print no's from 1 to 100

declare i number := 1; begin loop

dbms_output.put_line( i ); i := i+1; exit when i = 101; end loop; end; /

While Loop :-> Entry Control Loop. Syn:while cond loop stat(s); end loop; Ex:declare i number := 1; begin while i<=100 loop dbms_output.put_line( i ); i := i+1; end loop; end;

Write a program to print LCM of two numbers declare x number:=&x; y number:=&y; a number:=x; b number:=y; begin while x<>y loop if x<y then x:=x+a; else y:=y+b; end if; end loop; dbms_output.put_line(LCM ||x); end; Output Enter value for x : 12

Enter value for y : 15 LCM = 60 Write a program to print a) number of digits b) sum of the digits c) reverse of the digits, of a number declare x number:=&x; s number:=0; r number:=0; c number:=0; k number; begin while x<>0 loop k := mod(x,10); x := trunc(x/10); c := c+1; s := s+k; r := r*10+k; end loop; dbms_output.put_line(Number of Digits ||c); dbms_output.put_line(Sum of Digits || s); dbms_output.put_line(Reverse of Digits ||r); end; Output Enter value for x : 436 Number of Digits 3 Sum of Digits 13 Reverse of Digits 634

Write a program to print N prime numbers declare c number :=0; pc number :=0; n number :=&n; x number :=1; begin while pc<n loop c :=0; for I in 1..x loop if mod(x,i)=0 then c :=c+1;

end if; end loop; if c=2 then dbms_output.put_line(to_char(x)); pc := pc+1; end if; x := x+1; end loop; end; Output Enter value for n : 4 2 3 5 7
For Loop :Syn :for variable in [reverse] low value ... high value loop stat(s); end loop; Ex:declare i number := 1; begin for i in 1...100 loop dbms_output.put_line( i ); end loop; end; / Ex:- To print the reverse values. declare i number := 1; begin for i in reverse 1...100 loop dbms_output.put_line( i ); end loop; end; /

Write a program to print (*) in triangular shape spread in rows declare n number :=&n; begin for I in 1..n+1 loop dbms_output.put_line(); for j in 1..i loop dbms_output.put_line( * ); end loop; end loop; end; Output Enter value for n 5 * * * * * *

***
Write a program to demonstrate table type (array of integers), to store first five even number and print them declare type numarr is table of number index by binary_integer; a number; k number :=0; begin for I in 1 .. 10 loop if(mod(I,2)=0 then a(k):=I; k:=k+1; end if; end loop; for i in 0 ..4 loop dbms_output.put_line(to_char (a(i))); end loop end; Output 2 4 6

8 10

Branching Statements :Goto ->


It is a Branching or Unconditional Statement to transfer the control from one part of the program to other Unconditionally by Skipping the Statement Between. Syn:goto labelname; Ex:<< a >> Label Defination << label name >> -----

declare x number := 1; begin <<a>> dbms_output.put_line(x); x := x+1; if x < 10 then goto a; end if; end; /

Exceptions :If any type of exception is raised control is passed to the exceptions section of the block in which the exception occured. It the exception is not handled their or if there is no exception section at all that the block terminated without unhandled exception. To trap such events or avoidings the block terminating without handling the exception, exception handlers may be defined in the exception section of the block.

Syn:when exception handler then actions;

Types Of Exceptions :
1) Predefined Exception 2) User Defined Exception

1) Predefined Exception -> These are defined by PL / SQL and are raised implicitly associated with specific error messages. 2) User defined Exception -> These are defined by the user in the declare section of block as normal variables and are raised explicitly.

Predefined :1) No_Data_Found -> It is raised when the select statement is not returning at a row. Raising of exception when (exception handler) then section.

Ex:declare erec emp%rowtype; begin select * into erec from emp where empno=&no; dbms_output.put_line(' EmpNo ' || erec.empno); dbms_output.put_line(' EmpName ' || erec.ename); ----exception when no_data_found then dbms_output.put_line(' Record is not existed ' ); end; / 2) Too_Many_Rows -> It is raised when the select statement is returning more than one row. Syn:when too_many_rows then dbms_output.put_line(' more than one row is returned'); end; Ex:declare erec emp%rowtype; begin

select * into erec from emp where empno=&no; OR deptno=&dno; dbms_output.put_line(' EmpNo ' || erec.empno); dbms_output.put_line(' EmpName ' || erec.ename); ----exception when too_many_rows then dbms_output.put_line(' Too Many Records ' ); end; /

select * into erec from emp where

3) Dup_Val_On_Index -> Is raised when the record is inserted in a table with duplicate value of a column constrained by a Unique Index. Ex:a) create table x ( rno number(2) unique, name varchar2(10)); b) declare begin insert into x values (1,'santhosh'); exception when dup_val_on_index then dbms_output.put_line(' record must be unique ' ); end; /

4) Value_Error -> Is raised when the column size is not sufficient to hold to populated column value. Ex:a) create table x( rno number(2),

name varchar2(10)); b) declare erec x%rowtype begin insert into x values (100,'santhosh'); OR insert into x values(&rno,'&name'); dbms_output.put_line(' Rno ' || erec.rno); dbms_output.put_line(' Name ' || erec.name); exception when value_error then dbms_output.put_line(' size of the column is not sufficient' ); end; /

5) Others

Can catch any type of exception


Is raised when the column is Invalid DataType. Ex:-

Write a program to handle multiple exceptions including OTHERS exception declare j emp.job%type:=&j; n emp.ename%type; begin select ename into n from emp where job=j; exception when too_many_rows then dbms_output.put_line(Too many Records); when no_data_found then dbms_output.put_line(Sorry no Record); when others then dbms_output.put_line(Some Unidentified Error); end; Output Enter value for j : teacher Sorry no Record Enter value for j : Manager

Too many records Enter value for j : 4.5 Some unidentified error
Ex:declare begin insert into emp(empno,ename,deptno) values (101, xyz,10); OR insert into emp(empno,ename,deptno) values (&empno,&ename,&deptno); exception when others then dbms_output.put_line(' Invalid datatype ... No records inserted ' ); end; / 6) Zero_Divide -> It is raised when the divisor = 0 Ex:declare msal emp.sal%type; begin select sal / 0 into msal from emp where empno=&no; exception when zero_divide then dbms_output.put_line(' divisor is equal to zero ' ); end; /

User Defined Exception:Declaration -> Syn:<exception name> Exception; Ex: invalidchoice excepion;

Raising Of An User Defined Exception ->


Syn:If cond then raise <user defined exception>; end if; Ex:* Write a Pl/Sql block to create a user defined exception called invalid choice and raise the same if the choice is other than one and two. If the choice is one print mathematical table or If choice is two print the factorial value or other than to raise the user defined exception.

declare n number; ch number; f number := 1; invalidch exception; begin n := &no; ch := &choice; if ch in (1, 2) then if ch = 1 then for i in 1...10 loop dbms_output.put_line(n || ' * ' || i || ' = ' || n * i ); end loop; elseif ch = 2 then for i in 1...n loop f := f * i; end loop; dbms_output.put_line(' factorial value is ' || f ); end if; else raise invalidch; end if; exception when invalidch then dbms_output.put_line(' wrong choice ' ); end; /

Ex:-

declare eno emp.empno%type :=&eno; c emp.comm%type; comm._is_null exception; /* User defined Exception */ begin select comm. into c from emp where empno=eno; if c is null then raise comm._is_null; else update emp set sal =sal+1000 where empno=eno; dbms_output.put_line(Record Update); end if; exception when comm._is_null then dbms_output.put_line(Commission is Null update failed); end; Output Enter value for eno : 7369 Commission is null update failed

Cursors

It is an identifier given to the memory location.

Cursor is a mechanism that deals with multiple records of a result set fetched by a query It iterates multiple records sequentially one by one. The two-types of cursors are : 1. Explicit cursor 2. Implicit cursor Explicit cursor is declared by the programmer to keep track of a result set. It has to be opened to fetch the records.

Steps to use explicit cursor: CURSOR cursor_name IS query; /*declaring a cursor, must be in DECLARE SECTION */ OPEN cursor_name; FETCH cursor_name INTO variables; /* repeated till fetching closes */ CLOSE cursor_name; We may use FOR loop in work with cursors: FOR record_variable IN cursor_name LOOP End loop; /* here opening, fetching and closing cursor is done automatically */ Implicit cursor is defined by Pl/Sql and keeps track of information of rows affected by INSERT, DELETE, and SELECT INTO Commands.

Types :1) Implicit cursor 1) Implicit Cursor -> These are declared by PL / SQL and can process only one row at a time. 2) Explicit cursor -> These are declared by the user like normal variables in the declaration section of the block using cursor statement which can process more than one row and the rows that are processed by explicit cursors are referred to as active set. 2) Explicit cursor

Explicit Cursor Attributes %found %notfound %rowcount %isopen Default is True, if a cursor can fetch records; False otherwise Default is True, if a cursor cannot fetch records, False otherwise. Holds the record number Default is True, if the cursor is in open state, False otherwise Implicit Cursor Attributes SQL%found SQL%notfound SQL%rowcount SQL%isopen If no records are affected, it returns False If no records are affected, it returns True Holds number of rows affected by the related commands. After executing related commands, it returns False

Implicit Cursor Attributes ->


1) SQL % Row Count -> Counts the no.of rows that are processed by the PL / SQL statements. declare n number; begin delete from emp where n = &empno; n:=sql %rowcount; dbms_output.put_line('no.of rows deleted are ' || n); end; / 2) SQL %Found-> Returns true if the row is processed otherwise false.

declare erec emp%rowtype; begin select * into erec from emp where empno=&no; if sql%found then dbms_output.put_line(' Records are found ' ); dbms_output.put_line('Empno ' || erec,empno); ----else dbms_output.put_line('Record are not found ' ); end if; end; / 3) SQL %NotFound -> Returns true if the row is not processed, otherwise true. declare erec emp%rowtype; begin select * into erec from emp where empno=&no; if sql%notfound then dbms_output.put_line('Record are not found ' ); else dbms_output.put_line(' Records are found ' ); dbms_output.put_line('Empno ' || erec,empno); ----end if; end; /

Explicit Cursor Attributes :There are controlled by the following Four Actions. 1) Declaration of cursor using cursor statement in the declaration section of the block. Syn :cursor <cursor identifier> [(argument list)] is query expr;

cursor identifier -> is name of the cursor. query expr. Ex: declare cursor c is select * from emp; 2) Opening of Cursor Using Open Statement -> When ever the cursor is opened cursor is always pointed to the first rows in the active set. Syn: open <cursor identifier> [(argument list)]; Ex: declare cursor c is select * from emp; begin open c; 3) Fetch statement -> Fetch statement populates the current row data into the corresponding variables or record type variable . Each fetch statement causes the cursor to move it's pointer to the next row in the active set. Syn: fetch <cursor identifier> into var1, var2, ........... ; OR fetch <cursor identifier> into <record> ; Ex: declare cursor c is select * from emp; erec emp%rowtype; begin open c; fetch c into erec; end; / 4) Close -> It is used to close the cursor that is opened. -> is any query statement.

Ex: declare cursor c is select * from emp; erec emp%rowtype; begin open c; loop fetch c into erec; dbms_output.put_line(' EmpNo ' || erec.empno); dbms_output.put_line(' EmpName ' || erec.ename); ----end loop; close c; end; /

Write a program to print the names of all the employees from emp table use cursors declare n emp.ename%type; cursor c1 is select ename from emp; begin open c1; loop fetch c1 into n; exit when c1%notfound; dbms_output.put_line(n); end loop; close c1; end; Write a program to find sum of the salaries of all the employees without using sum function (use cursor) declare s number:=0; pay emp.sal%type; cursor c1 is select sal from emp; begin open c1; loop fetch c1 into pay; exit when c1%notfound;

s := s+pay; end loop; close c1; dbms_output.put_line(sum is ||s); end; Write a program to print empno, ename, job, salary of all employees using cursors. Use a record that holds the values of the four attributes supplied by cursor declare type emprec is record (eno emp.empno%type, n emp.ename%type, j emp.job%type, s emp.sal %type); r emprec; cursor c1 is select empno, ename, job, sal from emp; begin open c1; loop fetch c1 into r; exit when c1%notfound; dbms_output.put_line(r.eno|| ||r.n|| ||r.j|| ||r.s); end loop; close c1; close c1; end; To print empno, ename, job, salary declare type emprec is record(eno emp.emp%type, n emp.ename%type, jo emp.job%type, s emp.sal %type); type empemptab is table of emprec index by binary_integer; r emprec; a emptab; k number:=0; cursor c1 is select empno,ename,job,sal from emp; begin open c1; loop fetch c1 into r; exit when c1%notfound; a(k):=r; k:=k+1; end loop; close c1;

for I in 0..k - 1 loop dbms_output.put_line(a{i}.eno|| ||a(i).n|| ||a(i).j|| ||a(i).s); end loop; end;

To demonstrate %isopen attribute, to print the names and jobs of all employees whose names have 4 characters declare n emp.ename%type; j emp.job%type; cursor c1 is select ename, job from emp where length(ename)=4; begin if not c1%isopen then dbms_output.put_line( Opening the cursor now); open c1; end if; loop fetch c1 into n,j; exit when c1%notfound; dbms_output.put_line(n|| ||j); end loop; close c1; end; To demonstrate implicit cursor attribute sql%notfound, to raise the salary of an employee by 1000 and display whether the record has been updated or not declare eno emp.empno%type :=&eno; begin update emp set sal=sal+1000 where empno=eno; if sql%notfound then dbms_output.put_line(No record! update failed); else dbms_output.put_line(Updated successfully); end if; end; To demonstrate implicit cursor attribute sql%found, sql%rowcount to raise the salary of all managers and display number of records that have been updated or not.

begin update emp set sal=sal+sal*0.1 where job=manager; if sql%found then dbms_output.put_line(sql%rowcount||Records Updated); end if; end; output 3 records updated

Explicit Cursors With Loops :1) The Loop Statement is not given only the first record contains are Fetched from the active set. 2) The Loop Statement is given it Fetch the record to set the active as long as condition is true comes out the Loop, when the no record is found try to fetch the contains of that record giving an error fetch is out of sequence.

Explicit Cursor Attributes :1) Cursor identify % NotFound -> Returns true if the Fetch Statement is not available to fetch the record contains from the active statement, otherwise false. Ex:declare cursor c is select * from emp; erec emp%rowtype; begin open c; loop fetch c into erec; if c%notfound then exit; end if; dbms_output.put_line(' Emp Ename ' || erec.ename); ----end loop; close c; end; / 2) Cursor Identify %Found -> Ex:-

declare cursor c is select * from emp; erec emp%rowtype; begin open c; loop fetch c into erec; if c%found then exit; dbms_output.put_line(' Emp Ename ' || erec.ename); ----end if; end loop; close c; end; / 3) Cursor Identify %rowcount -> Counts the no.of rows that have been fetch so far from active set. Ex:declare cursor c is select * from emp; erec emp%rowtype; n number; begin open c; loop fetch c into erec; n := c%rowcount; if n>5 then exit; dbms_output.put_line(' Emp Name ' || erec.ename); ----end if; end loop; close c; end; / 4) Cursor Identifier %isopen -> Returns true if the cursor is opened, otherwise false. Ex:declare cursor c is select * from emp; erec emp%rowtype; begin if c%isopen then fetch c into erec; else open c;

fetch c into erec; end if; dbms_output.put_line(' Emp Name ' || erec.ename); ----close c; end; /

Cursor With For Loop ->


A cursor For Loop implicitly declare it's loop in the order of record at %rowtype, open the cursor and repetidly fetches the rows of values from the active set into fields in the record. Syn:for indexrecord in cursorname loop stat(s); end loop; Ex:declare erec emp%rowtype; cursor c is select * from emp; begin for erec in c loop dbms_output.put_line(' Emp Name ' || erec.ename); ----end loop; end; /

Cursor With Parameters ->


Parameters allows the values to be pause a cursor when it is open and used executes with in the query. Which means that the express cursor is opened. Syn:cursor identifier (parametername datatype, parametername datatype, ----) is query expr; when the cursor is ladder open values are passed to each of the parameters positionally. Syn:open cursor (argumnts list); Note :The values that are said or noon actual arguments and the values that are received.

Ex:declare cursor c (no number, name varchar2) is select * from emp where empno=no and ename=name; erec emp%rowtype; begin open c(7934,'SCOTT'); OR open c(&no,'&name'); loop fetch c into erec; if c%notfound then exit; end if; dbms_output.put_line(' Emp No ' || erec.empno); dbms_output.put_line(' Emp Name ' || erec.ename); ----end loop; close c; end; /

Entering The Values At RunTime ->


Ex:declare cursor c (no number, name varchar2) is select * from emp where empno=no and ename=name; erec emp%rowtype; a number; b varchar2(10); begin a :=&no; b :='&name'; open c(a,b); loop fetch c into erec; if c%notfound then exit; end if; dbms_output.put_line(' Emp No ' || erec.empno); dbms_output.put_line(' Emp Name ' || erec.ename); ----end loop;

close c; end; /

Sub Programs

Dividing a program into pieces. 2) Called / Sub Program

1) Calling / Main Program Two types of SubPrograms. 1) Procedures -> will not return a value. 2) Functions -> return a value. Advantages -> 1) avoiding the repetation of code. 2) read ability. Procedures ->

Syn:create [ Or replace] procedure <procedure name> [(arguments list)] procedure body; ----end [procedure name]; Excution Of a Procedure -> Syn:Excute <procedurename> [(argument list)]; Procedure WithOut Parameters Ex:- To print the factorial value. 1) Creation of Procedure

SQL> ed f create or replace procedure fact is n number := &no; f number := 1; begin for i in 1...n loop f := f * i; end loop; dbms_output.put_line(' factorial is ' || f); end; / 2) Save & Exit ( Alt + F4 ) 3) @f; Procedure created Excution SQL > Excute fact;

Procedure With Parameters -> Parameters in the values passed the arguments from the command line when the program is executed. Ex:- To print the factorial value. 1) Creation of Procedure SQL> ed f create or replace procedure fact(n number) is f number := 1; begin for i in 1...n loop f := f * i; end loop; dbms_output.put_line(' factorial is ' || f); end; / 2) Save & Exit ( Alt + F4 ) 3) @f; Procedure created Excution SQL > Excute fact(&no); Ex:- Create a procedure to accept a string and prints it's reverse.

create or replace procedure revstr(str varchar2) is l number; p varchar2(10); begin l := length(str); for i in reverse 1...l loop p := p || substr(str,i,1); end loop; dbms_output.put_line(' Reverse string ' || p); end; / Excution -> SQL > Excute revstr( '&string' ); Ex:Whether the string is polindrom or not

create or replace procedure polin(str varchar2) is l number; p varchar2(10); begin l := length(str); for i in reverse 1...l loop p := p || substr(str,i,1); end loop; dbms_output.put_line(' Main string ' || str); dbms_output.put_line(' Reverse string ' || p); if str = p then dbms_output.put_line(' polindrom ' ); else dbms_output.put_line(' Not polin ' ); end if; end; / Excution -> SQL > Excute polin( '&string' );

Procedures Procedure is a database object and can be used in other programs It is block of code that offers reusability Procedure does not return any value It takes three types of parameters: IN, OUT, and IN OUT We can only read values form IN parameter

We can write values into OUT parameter We can read values in the parameters is of type IN OUT Syntax: create [or replace] procedure procedure_name [(list of arguments)] is/as declarations begin statements end;

To find out whether the given number is prime or not create or replace procedure isprime(x number) as c number:=0; begin for I in 1.. x loop if mod(x,i)=0 then c :=c+1; end if; end loop; if c=2 then dbms_output.put_line(Prime number); else dbms_output.put_line(not a prime number); end if; end; Usage in PL/SQL program begin isprime(6); end; Usage at SQL prompt SQL> exec isprimes(5) output : prime number Execute isprime(8); output :not a prime number; To update the salary of an employee whose empno and increment is mentioned create or replace procedure empupdate(eno emp.empno%type,incr number) as begin update emp set sal=sal+incr where empno=eno;

commit; dbms_output.put_line(Updated successfully); end; SQL> exec empupdate(7369,1000); Write a procedure to have salary of an employee in an Out parameter create or replace procedure getsal(eno emp.empno%type, s OUT emp.sal%type) as begin select sal into s from emp where empno=eno; end; Usage in Pl/Sql program declare s emp.sal%type; begin getsal(7369,s); dbms_output.put_line(salary is ||s); end;

Write a procedure to demonstrate IN OUT parameters, to swap two values create or replace procedure swap(x IN OUT number, y IN OUT number) as temp number; begin temp := x; x := y; y := temp; end; declare a number:=30; b number:=40; begin dbms_output.put_line(Before swapping : a = ||a||And b = ||b); swap(a,b); dbms_output.put_line(After swapping : a = ||a|| And b = ||b);

end;

Functions :-

Function is a database object and can be used in other programs It is block of code that offers reusability Function returns a value

Syn :create [or replace] function <functionname> [(argumentslist)] return <datatype> is / as declaration of variables ----begin Excutable statements; ----return (var / expr); end [end function]; Execution Syn:declare local variables; ----begin var = functionname[(arguments list)]; ----end; Function WithOut Arguments Ex: SQL > ed simple create or replace function si return number is p number := &amt; t number := &time; r number := &rate; s number; begin s := (p * t * r) / 100; return (s); end; / SQL > @simple Function created

Excution SQL> ed simple1 declare x number; begin x := si; dbms_output.put_line( ' intrest is ' || x); end; / SQL > @simple1 Function with Arguments -> Ex:SQL > ed simple create or replace function si(p number,t number, r number) return number is s number; begin s := (p * t * r) / 100; return (s); end; / SQL > @simple Function created Excution SQL> ed simple1 declare x number; begin x := si(&pp,&tt,&rr); dbms_output.put_line( ' intrest is ' || x); end; / SQL > @simple1

Write a function to find factorial of a given number create or replace function fact(x number) return number as k number:=1; begin for I in 1..x loop

k : =k*I; end loop; return k end; SQL> exec dbms_output.put_line(fact(4)); OR Pl/Sql declare n number:=&n; begin dbms_output.put_line(factorial is ||fact(n)); end; To find sum of the salaries in a given department create or replace function salsum(dno emp.deptno%type) return number as s number; begin select sum(sal) into s from emp where deptno=dno; return s; end; SQL> exec dbms_output.put_line(salsum(20)); write a function that returns the name of an employee, if empno is given create or replace function getname(eno emp.empno%type) return emp.ename%type as n emp.ename%type; begin select ename into n from emp where empno=eno; return n; end; SQL> exec dbms_output.put_line(getname(7369)); OR begin dbms_output.put_line(getname(7369)); end;

Packages The collection of Procedure and Functions. 1) Package Specification -> declaration of Objects ( Procedure / Function , Procedure and Function ). Syn:create or replace package <package name> is / as declaration of objects; ----end [package name]; 2) Package Body contains description / objects definition. Syn:create or replace package body <package name> is / as definition of objects; ----end; Excution of Procedure from a Package Package Syn:Execute packagename.procedure [(arguments list)]; packagename.function[(arguments.list)] Ex:Creation of a Package containing a Procedure with an Argument. SQL > ed pack1 create or replace package pack is procedure evod(n number); end pack; / SQL > ed body1 create or replace package body pack is procedure evod(n number) as begin if mod(n, 2)=0 then dbms_output.put_line( ' Even ' ); else dbms_output.put_line( ' Odd ' ); end if; end evod; end; Excution of Procedure from a

Local Var =

/ SQL > Execute pack.evod(&no); OR Execute pack.evod(4);

Ex:Creation of a Package containing a Function without an Argument. SQL > ed x create or replace package pack is function revno return number; end pack; SQL > ed xx create or replace package body pack is function revno return number is rem number; n number := &no; rev number := 0; begin while(n != 0) loop rem := mod(n,10); rev := rev * 10 + rem; n := floor (n / 10); end loop; return rev; end revno; end; / Excution SQL > ed xxx declare x number; begin x := pack.revno(); dbms_output.put_line(' Reverse ' || x); end; / Ex:Creation of a Package containing a Function with an Argument. SQL > ed x create or replace package pack is function revno(n number) return number; end pack; SQL > ed xx

create or replace package body pack is function revno(n number) return number is rem number; a number; rev number := 0; begin a := n; while(a != 0) loop rem := mod(a, 10); rev := rev * 10 + rem; a := floor (a / 10); end loop; return rev; end revno; end; / Excution SQL > ed xxx declare x number; begin x := pack.revno(&n); dbms_output.put_line(' Reverse ' || x); end; / Ex:Creation of a Package containing a Procedure & Function with an Argument. SQL > ed x create or replace package procfunc is procedure perfect(n number); function arm(n number) return number; end procfunc; SQL > @ x Package created Creation of Package Body SQL > ed xx create or replace package body procfunc is procedure perfect(n number) is i number := 1; s number := 0; r number; begin while(i < n) loop

r := mod(n, i); if r = 0 then s := s+i; end if; i := i+1; end loop; if n=s then dbms_output.put_line(n || ' is perfect ' ); else dbms_output.put_line(n || ' is not perfect ' ); end if; end perfect; function arm(n number) return number is rem number; aarm number :=0; nn number; begin nn :=n; while(nn !=0) loop rem :=mod(nn, 10) aarm := aarm + rem * rem * rem; nn :=floor(nn / 10); end loop; if n=aarm then return 1; else return 0; end if; end arm; end; / Execution Of Procedure From a Package SQL > Execute procfunc.perfect(&no); Execution Of Function From a Package SQL > ed ex declare p number; begin p :=procfunc.arm(&no); if p = 1 then dbms_output.put_line(' armstrong ' ); else dbms_output.put_line(' not ' ); end if; end; / Database Triggers

is fixed when ever on event occurs. Event -> interaction between user and the object of writing on the board. Object -> anything existing in the word having some properties. Properties -> visual attributes of the object. Types of Database Triggers -> 1) before / after delete Creation of Trigger Syn:create [or replace] trigger <trigger name> before / after delete/ insert/ update on <table> [ for each row] ----end; Ex:Creation of record after delete SQL> ed e create or replace trigger deltrig after delete on emp begin dbms_output.put_line(' record is deleted ' ); end; / SQL > @ e; Trigger created SQL > delete from emp where deptno=10; For Each Row -> If this aoption is used the trigger is fired same no.of times depending upon the no.of the rows present in the table. SQL > ed e Creation of record after delete create or replace trigger deltrig after delete on emp for each row begin dbms_output.put_line(' record is deleted ' ); end; / 2) before / after insert 3) before / after update

Creation of record after Update SQL > ed e create or replace trigger updtrig after update on emp for each row begin dbms_output.put_line(' record is update ' ); end; / SQL > @ e Trigger created SQL > update emp set ename = 'santhosh' where empno=100;

Creation of record after Insert SQL > ed e create or replace trigger instrig after insert on emp begin dbms_output.put_line(' record is inserted ' ); end; / SQL > @ e Trigger created SQL > insert into emp (empno,ename,deptno) values (100,'santhosh',30);

Triggers Trigger is a procedure that gets executed automatically upon an event A trigger files before or after a transactions has occurred It includes the following types: 1. BEFORE/AFTER INSERT for each row 2. for statement 3. Update for each row 4. Update for statement 5. Delete for each row 6. Delete for statement For each row trigger gets executed once for each record that has been affected by an event For each statement trigger gets executed only once but every time the event occurs A trigger may be row level or column level It can be used to enforce complex constraints

It can be used to ensure proper data entry It can be used to keep track of transactions on a table. It can be used to interrupt a transaction when it is inappropriate To interrupt a transaction, we use Raise_Application_Error function, which takes error number and error message as arguments. Error number range must be -20000 to -20999. Syntax: create [or replace] trigger trigger_name before/after insert/[or] delete/[or] update [of column_name] On tablename [for each row] when condition begin statements; end;

Write a trigger that inserts or updates values of ename and job as uppercase strings, even if we give lowercase strings. create or replace trigger uppername before insert or update on emp for each row begin :new.ename:=upper(:new.ename_; :new.job :=upper(:new.job); end; SQL> update emp set job=manager where ename=smith; SQL> insert into emp (empno, ename,job) values (1234,sofech,clerk); Write a column level trigger that does not allow a salary to be updated, if the employees commission is no create or replace trigger empupdate before update of sal on emp for each row begin if :old.comm is null then raise_application_error(-20100,comm is null salary cannot be updated); end if; end; Ans 2: create or replace trigger empupdate before update of sal on emp for each row when (old.comm is null) begin raise_application_error(-20100,comm is null ! salary cannot be updated); end;

SQL> update emp set sal=4000 where ename=smith; Create any table, a table without primary key, write trigger on that table, which simulates primary key for a column First create student table using the following command SQL> create table student(sno number(3), sname varchar2(20)); create or replace trigger primarytrig before insert or update on student for each row declare n number; begin if :new.sno is null then raise_application_error(-20888,No duplicate and Null values for sno); end if; select sno into n from std where sno = :new.sno; raise_application_error(-20888,No duplicate and null values for sno); exception when no_data_found then null; end; SQL> insert into student values(10,sh); SQL> insert into student values(20,santhosh); SQL> insert into student values(10,sk);

Ex:Emp1

To create a Trigger based on two tables.

empno number(4), ename varchar2(10), desig varchar2(10), sal number(10, 2), deptno number(2). Temp1 eno number(4), name varchar2(10), job varchar2(10), salary number(10, 2), dno number(2), per char(4). SQL > ed trigger create or replace trigger iudtrg after insert or update or delete on emp1 for each row declare a number(4); b varchar2(10); c varchar2(10); d number(10, 2);

e number(2); f char(4); begin if INSERTING then a := :new.empno; b := :new.ename; c := :new. desig: d := :new. sal; e := :new. deptno; f := ' I ' ; insert into temp1 values(a,b,c,d,e,f); elsif DELETING then a := :old.empno; b := :old.ename; c := :old. desig: d := :old. sal; e := :old. deptno; f := ' D ' ; insert into temp1 values(a,b,c,d,e,f); elsif UPDATING then a := :new.empno; b := :new.ename; c := :new. desig: d := :new. sal; e := :new. deptno; f := ' U ' ; insert into temp1 values(a,b,c,d,e,f); end if; dbms_output.put_line(' EmpNo ' || a); dbms_output.put_line(' EName ' || b); dbms_output.put_line(' Desig ' || c); dbms_output.put_line(' Salary ' || d); dbms_output.put_line(' DeptNo ' || e); dbms_output.put_line(' Status ' || f); end; / SQL > @ Trigger; Trigger created SQL > insert into emp1 values (100,'abc','mng',3500,20); SQL > insert into emp1 values (200,'xyz','clk',3000,30); SQL > insert into emp1 values (300,'abc','typ',2500,10); SQL > update emp1 set sal = 4000 where sal = 3500; SQL > delete from emp1 where empno=300;

SQL > select * from emp1; EmpNo Ename Desig Sal DetpNo ____________________________________________________________ 100 abc mng 4000 20 200 xyz clk 3000 30

SQL > select * from temp1; ENo Name Job Salary DNo Per _____________________________________________________________________ 100 abc mng 3500 20 I 200 xyz clk 3000 30 I 300 abc clk 3000 30 I 100 abc mng 4000 20 U 300 abc clk 3000 30 D

También podría gustarte