1. INTRODUCTION Every business enterprise maintains large volumes of data for its operations .With more and more people accessing this data for their work, the need to maintain its integrity and relevance increases. Normally with the traditional methods of storing data and information in the files, the chan ces those data losses its integrity and validity are very high. ORACLE is an object relation al database management system. It of fers capa biliti es o f both relat ional and o bjec t oriente d dat abas e sys tems . Orac le products are based on a concept known as client/server technology. This concept involves segregating the process ing of an application between two systems. One performs all activities related to the database (server) and the other performs activities that help the user to interact with the application (client). The tools provided by oracle are user friendly. The main tools are: 1. SQL*PLUS 2. PL/SQL SQL*PLUS It is structu red quer y languag e suppor ted by Oracle. Usi ng this we can store, retrieve, edit, enter and run SQL commands and PL/SQL blocks. We can also perform calculations on listed definitions for any table and can also format results in the form of a report. PL/SQL It is an extension of SQL. It combines the data manipulating process of SQL with data processing process of procedural language. 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Every business enterprise maintains large volumes of data for its operations .With
more and more people accessing this data for their work, the need to maintain itsintegrity and relevance increases. Normally with the traditional methods of storingdata and information in the files, the chances those data losses its integrity andvalidity are very high.
ORACLE is an object relational database management system. It offerscapabilities of both relational and object oriented database systems. Oracleproducts are based on a concept known as client/server technology. Thisconcept involves segregating the processing of an application between twosystems. One performs all activities related to the database (server) and the otherperforms activities that help the user to interact with the application (client).
The tools provided by oracle are user friendly. The main tools are:
1. SQL*PLUS
2. PL/SQL
SQL*PLUS
It is structured query language supported by Oracle. Using this we can store,retrieve, edit, enter and run SQL commands and PL/SQL blocks. We can also
perform calculations on listed definitions for any table and can also format resultsin the form of a report.
PL/SQL
It is an extension of SQL. It combines the data manipulating process of SQL withdata processing process of procedural language.
SQL was invented and developed by IBM in early 1970’s.Oracle’s databaselanguage is SQL, which is used for storing and retrieving information in oracle.
A table is primary database object of SQL that is used to store data. A table holdsdata in the form of rows and columns.
SQL supports the following categories of commands:
Data Definition Language -create, alter, and drop commands.Data Manipulation Language-insert, delete and update commands.Data Retrieval Language-select.
Data Control Language- grants and revokes commands.Transaction Control Language-commit, save point and rollback.
The following are the Benefits on SQL:
1. Non-procedural language because more than one record can be
accesses rather than one record at a time.2. It is the common language for all relation.
3. Very simple commands for querying, inserting, deleting and modifying
data and objects.
Oracle internal data types
In order to create a table we need to specify a data type for individual columns inthe create table command. Oracle supports the following data types to achieve theabove requirements.
1. Character data types 7. Raw
2. Char data types 8. Long raw
3. Varchar2 data types 9. Large object
4. Long data types 10. CLOB
5. Number data types 11. BLOB
6. Data data types 12. BFILE
Thus in order to create a table we need to specify a data type for individualcolumns in the create table command.
Thus Oracle supports the data types to achieve the above requirements.
SQL>insert into student3 (rno, name, class) values (05109094,’Nani’,’mca’);
1 row created.
4. INSERT VARYING VALUES
SQL>insert into student3 (rno, name, class) values (&rno,’&name’,’&class’);Enter value for rno: 05109008Enter value for name:ReddyEnter value for class:msc
old 1:insert into student3(rno,name,class)values(&rno,’&name’,’&class’)new 1;insert into student3(rno,name,class)values(05109008,’reddy’,’msc’)
Enter value for rno: 05109054Enter value for name:RajEnter value for class:mbaold 1:insert into student3(rno,name,class)values(&rno,’&name’,’&class’)new 1;insert into student3(rno,name,class)values(05109054,’raj’,’mba’)
1 row created.
SQL>/
Enter value for rno: 05109083Enter value for name:BobbyEnter value for class:mcomold 1:insert into student3(rno,name,class)values(&rno,’&name’,’&class’)new 1;insert into student3(rno,name,class)values(05109083,’bobby’,’mcom’)
1 row created.
5. INSERT A ROW WITH ROLL NO, CLASS, AND MARKS IN 3 SUBJECTS
10. CREATE QUERIES USING ORDER BY AND GROUP BY CLAUSE.
ORDER BY CLAUSE:
This clause is used to arrange the retrived data in some sorted manner. By defaultthe sorting is done in ascending order .The clause should be spwcified just beforethe statement terminates.
1. List the department numbers and department names sorted on
department name.
SQL>select deptno, dname from dept order by dname;
DEPTNO DNAME10 ACCOUNTING
40 OPERATIONS20 RESEARCH30 SALES
2. Display the employees information in ascending order of salary.
3. Display the employees information in descending order of salary.
SQL>select empno, ename, sal from emp order by sal desc;
EMPNO ENAME SAL7839 LUCKY 50007788 SCOTT 30007902 FORD 30007566 JONES 29757698 BLAKE 28507782 CLARK 24507499 ALLEN 16007844 TURNER 15007934 MILLER 13007521 WARD 12507654 MARTIN 1250
7876 ADAMS 11007900 JAMES 9507369 SMITH 800
14 rows selected.
GROUP BY CLAUSE:
This clause places condition on group of records. Group by clause is used whenaggregate operators to be applied to each of row in a relation where the number
of groups depends on the relation instance.
SYNTAX:
Select [DIATINCT] select-listFrom from-listWhere<condition>Group By grouping-list
1.list the count of different jobs held by employees in Deptno 30.
SQL>select count (job) from emp where deptno=30 group by job;
This clause is used to specify condition/ qualifications over group. Theexpressions appearing in the group qualification of having clause must a singlevalue of group i.e, having clause determines whether row is to be generated for agiven group
SYNTAX:
Select [DIATINCT] select-list
From from-listWhere<condition>Group By grouping-listHaving group-qualification.
1. .find the average salary in each department.where dept has atleast 2employees
ALLEN SALESBLAKE SALESMARTIN SALESJAMES SALESTURNER SALESWARD SALES
14 rows selected.
B. SELF JOIN:
A join between a table and itself is called a self join.
1. Display employee number and name along with their manager’s
number and name.
SQL>select e.empno, e.ename, e.mgr, m.ename from emp e, emp m wheree.mgr=m.empno;
EMPNO ENAME MGR ENAME7369 SMITH 7902 FORD7499 ALLEN 7698 BLAKE7521 WARD 7698 BLAKE7566 JONES 7839 LUCKY7654 MARTIN 7698 BLAKE
7698 BLAKE 7839 LUCKY7782 CLARK 7839 LUCKY7788 SCOTT 7566 JONES7844 TURNER 7698 BLAKE7876 ADAMS 7788 SCOTT7900 JAMES 7698 BLAKE7902 FORD 7566 JONES7934 MILLER 7782 CLARK
The output of this join takes one row from the 1st table and combines with all therows of 2nd table. Likewise all rows of 1st table get combined with all the rows of 2nd table.
EXAMPLE:
A= {1, 2, 3}B= {4, 5}
The Cartesian product of {A,B} is={(1,4),(1,5),(2,4),(2,5),(3,4),(3,5)}
SQL> select empno, ename, dname , loc from emp, dept;
EMPNO ENAME DNAME LOC7369 SMITH ACCOUNTING NEWYORK
7499 ALLEN ACCOUNTING NEWYORK7521 WARD ACCOUNTING NEWYORK7566 JONES ACCOUNTING NEWYORK------- ---------- -------------------- ---------------------- ---------- -------------------- ---------------56 rows selected.
PROGRAM
12. Use commands on locks.
LOCKS:
A lock is a small book-keeping object associated with a database
There are 2 types of locks1. Row level Lock2. Table level Lock.
IMPLEMENTATION OF LOCKS
1. Row level Lock:
SQL> select * from sailors where Sid=95 for update of age;
SQL>select ename from emp e, dept d where e.deptno=d.deptno andloc=’Chicago’;
ENAMEALLENWARDMARTINBLAKETURNERJAMES
6 rows selected.
14. CREATE QUERIES USING ROW FUNCTIONS.
FUNCTION:
A function takes one or more arguments and returns a value. Functions supportedby SQL are classified into:a. Single row functions.b. Group functions.
SINGLE ROW FUNCTIONS:
A single row function or a scalar function returns only one value for a row queriedin the table. Single row functions can appear in a select command and also
Can be included in a where clause.
NOTE:
“Dual” is a system table which is automatically created by ORACLE. It has onecolumn defined to be of varchar2 type and contains only one row with value ‘x’.
There are 5 types of single row functions.
a. Numeric Functions.b. Character Functions.c. Conversion Functions.
A synonym is an alternative name(or alias) for a database object such as aTable or view. They are useful for references purposes, providing securityEtc.
Creating Synonym:
SQL> create synonym dept-syn for dept;Synonym created.
20 RESEARCH DALLAS30 SALES CHICAGO40 OPERATIONS BOSTON4 rows selected.
3. SEQUENCE:
Oracle generates a series of numbers for a particular table in the database. Fore.g: Generating unique numbers such as invoice numbers or customer IDnumbers. While defining a sequence specify the starting value.
Creating Sequencing:
SQL>create sequence emp_seq start with 5000 increment by 1;Sequence created.
SQL>select emp_seq.nextval from dual;
NEXTVAL5000
SQL>select emp_seq.nextval from dual;
NEXTVAL5001
SQL>select emp_seq.nextval from dual;
NEXTVAL5002
4.INDEXES:
Indexes are special objects that oracle creates to provide rapid access (lookups)to Tables in database.
Creating Indexes:
SQL>create index emp_ind on emp (ename);Index created.
PL/SQL stands for Procedural Language /SQL. PL/SQL by adding controlstructures found in other procedural language.PL/SQL is unique as it combinesthe flexibility of SQL with the power and configurability of a third generationlanguage.
PL/SQL BLOCK
Declare: Declaration of memory variables, constants, cursors etc in PL/SQL.
Exception: PL/SQL code to handle errors that may arise during the execution of acode Block between begin and exception.
End: End of the code.
THE CHARACTER SET
The basic character set includes the following:
• Upper case alphabets: {A-Z}.
• Lower case alphabets: {a, b}.
• Numerals: {0, 9}.
• Symbols: (),+,-,/,<,>,=,!,;,:,.,@.%,#,$,^.
LITERALS
A literal is a numeric values or a character string used to represent itself. Thereare 4 types of literals. They are:> Numeric literal> String literal> Character literal> Logical (Boolean literal)
DATA TYPES
The default data types are integers, chars, date, Boolean and they can haveNULL values
The % type attribute is used to declare the variables based on definitions of columns in a table
Is a package that includes a no. of procedures and functions that accumulateInformation in a buffer so that it can be retrived later. These functions can also beused to display a message to the user.
PUT-LINE
Put-line puts a piece of information in the buffer followed by an end of linemarker. It can also be used to display a message (i.e. it is the message string) tothe user. Put-line accepts only parameter of character data type.
To display message to the user server output should be set to ON.
SYNTAX: SQL> SET SERVEROUTPUT (ON/OFF);
CONDITION CONTROL IN PL/SQL
Sequence of statements can be executed based on certain condition using the ‘ if statement’. There are 3 forms of statements namely
• If then
• If then else
• If then else if
ITERATIVE CONTROL
A sequence of statements can be executed any number of times using loopconstructs. Loop can be classified into:
• Simple loop
• For loop
• While loop
SEQUENTIAL CONTROL
The “goto” statement allows us to branch to a label unconditionally.
Procedure is a set of logical instructions. Which perform a task, because aprocedure is stored?In the database it must be named. This distinguishes it from other storedprocedures and makeIt possible for application to call it.
Each procedure in a scheme must have a unique name & the name must be alegal PL/SQL.
SYNTAX:
CREATE [OR REPLACE] PROCEDURE<PROCEDURE NAME>
(<ARG 1 [MODE] DATA TYPE, -------------------------------------- )
IS/AS [LOCAL DECLARATION]
BEGIN [EXCEPTION HANDLING]
END [POCEDURE NAME].
DROPING A PROCEDURE
SYNTAX SQL>DROP PROCEDURE <PROCEDURE NAME>;
PARAMETER MODES
There are 3 types of parameter modes
• IN [DEFAULT]-pass values to procedure.
• OUT -return values to called procedures
• INOUT -pass initial values to stored procedures
& returns updated values from stored procedures.
18. Give an employee no display job n salary should be > 20000.
SQL> create table std(rno number (3),name varchar2 (10),
c1 number (3),c2 number (3),c3 number (3),total number (3),percentage number (5,2));result varchar2(10),grade varchar2(10));
Table created.
SQL>insert into student2 (rno, name, c1, c2, c3)
Values (&rno, ’&name’, &c1, &c2, &c3);Enter value for rno:1Enter value for name: NaniEnter value for m1: 60Enter value for m2: 70Enter value for m3: 80old 2: values (&rno, ‘&name’,&c1, &c2, &c3)new 2: values (1,’Nani’,60,70,80)
1 row created.
SQL>/
Enter value for rno:2Enter value for name: AnuEnter value for m1: 71Enter value for m2: 81Enter value for m3: 91old 2: values (&rno, ‘&name’,&c1, &c2, &c3)new 2: values (2,’Anu’,71,81,91)
1 row created.
SQL>/Enter value for rno:3Enter value for name: LuckyEnter value for m1: 67
Enter value for m2: 77Enter value for m3: 78old 2: values (&rno, ‘&name’,&c1, &c2, &c3)new 2: values (3,’Lucky’,67,77,78)
1 row created.
SQL>/
Enter value for rno:4Enter value for name: RahulEnter value for m1: 69Enter value for m2: 79Enter value for m3: 87old 2: values (&rno, ‘&name’,&c1, &c2, &c3)new 2: values (4,’Rahul’,60,70,80)
1 row created.
SQL>select * from std;
RNO NAME C1 C2 C3 TOTAL PERCENTAGE RESULT GRADE1 Nani 60 70 802 Anu 71 81 913 Lucky 67 77 78
EMPNO ENAME SAL DEPTNO DNAME7369 BOBBY 800 20 RESEARCH7499 RAJ 1600 30 SALES7521 SING 1250 30 SALES7566 LUCKY 2975 20 RESEARCH7654 SANDEEP 1250 30 SALES
22. TRIGGERS:
The new SQL-99 standard includes support for triggers, which are actionsexecuted by the DBMS, whenever changes to the database meet conditions
specified in the triggers.
A trigger is a procedure that is automatically invoked by DBMS in response tospecified changes to the database and it’s typically specified by the DBA. Thedatabase that has a set of associated triggers is called an active database.
A trigger description contains 3 parts
>EVENT: A change to database that activates the trigger.>CONDITION: A query or test that is run when the trigger is activated.>ACTION: The procedure that is executed when the trigger is activated
andits condition is true.
A trigger can be thought of as DAEMON that monitors a database and executedwhen the database is modified in a way that matches the event specification. Acondition in a trigger can be true (or) false statement (or) query.
A trigger action can examine the answer to the query in the condition part of thetrigger, refer to old and new values of tuples modified by the statement activatingthe trigger, executes new queries & makes changes to the database.
PROGRAM:
23.PL/SQL Program to display the employee details of given dept usingcursors.
1 declare2 dno number:=&dno;3 cursor c1 is select * from dept where deptno=dno;4 x emp% rowtype;5 ch boclean:=false;6 begin
7 open c1;8 loop
9 fetch c1 into x;10 exit when c1%not found;11 dbms_output.put_line(x.ename||’—‘||x.sal||’—‘||x.hiredate||’—‘||x.job);12 ch:=true;13 end loop;14 close c1;
15 if ch=false then
16 dbms_output.put_line(‘ no employees found in dept’||dno);17 end if;18 end;
6 select * into x from emp where empno=eno;7 if x.job=’manager’ then raise invalidjob;8 end if;9 dbms_output.put_line(x.ename);10 dbms_output.put_line(x.job);11 dbms_output.put_line(x.sal);12 dbms_output.put_line(x.hiredate);13 exception when no_data found then
14 raise_application_error(-20399,’data not found for given number’);15 when invalidjob then