3dbms lab record

39
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

Upload: abhiknl1

Post on 09-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 1/39

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 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.

1

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 2/39

2. STRUCTURED QUERY 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.

2

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 3/39

3. DATA DEFINITION LANGUAGE

The DDL is used to create an object (eg. Table), alter the structure of an objectand also to drop the object created.

Table Definition:

A table is a unit of storage that holds data in the form of rows and columns. TheDDL is used for table definition and can classify into:

1. Create table command.

2. Alter table command.

3. Truncate table command.

4.Drop table command.

1. CREATE:

SYNTAX:

Create table<table name>(column definition1<data type (length)>column definition1<data type (length)>….);

2. ALTER  

SYNTAX:ALTER table<table name>modify (column definition1);

3. TRUNCATE

SYNTAX:TRUNCATE table<table name>;

4. DROP

SYNTAX:DROP table<table name>;

3

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 4/39

4. Use DML statements for database tables.

SQL>create table student2 (rno number (3), name varchar2 (10),m1 number (3),m2 number (3),m3 number (3),total number (3),percentage number (5,2));

Table created.

Implementation of insert command.

SQL>insert into student2 (rno, name, m1, m2, m3)Values (&rno,’&name’, &m1, &m2, &m3);Enter value for rno:1Enter value for name: Naresh

Enter value for m1: 75Enter value for m2: 65Enter value for m3: 85old 2: values (&rno, ‘&name’,&m1, &m2, &m3)new 2: values (1,’Naresh’,75,65,85)

1 row created.SQL>/

Enter value for rno:2Enter value for name: AnithaEnter value for m1: 65

Enter value for m2: 88Enter value for m3: 56old 2: values (&rno, ‘&name’,&m1, &m2, &m3)new 2: values (2,’Anitha’,65,88,56)

1 row created.

SQL>/Enter value for rno:3Enter value for name: PadmaEnter value for m1: 45Enter value for m2: 78Enter value for m3: 96

old 2: values (&rno, ‘&name’, &m1, &m2, &m3)new 2: values (3,’Padma’, 45,78,96)

1 row created.

4

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 5/39

SQL>select * from student2;

RNO NAME M1 M2 M3 TOTAL PERCENTAGE------ --------- ----- ----- ----- -------- ----------------1 Naresh 75 65 852 Anitha 65 88 563 Padma 45 78 96

Implementation of update command

SQL>update student2 set total=m1+m2+m3;3 rows updated.

SQL>select *from student2;

RNO NAME M1 M2 M3 TOTAL PERCENTAGE------ --------- ----- ----- ----- --------- --------------------

1 Naresh 75 65 85 2252 Anitha 65 88 56 2093 Padma 45 78 96 219

SQL>update student2 set percentage=total/3;3 rows updated.

SQL>select *from student2;

RNO NAME M1 M2 M3 TOTAL PERCENTAGE------ --------- ----- ------ ----- ----------- --------------------

1 Naresh 75 65 85 225 752 Anitha 65 88 56 209 69.673 Padma 45 78 96 219 73

Implementation of delete command

SQL>delete from student3 where rno=3;

1 row deleted.

SQL>select *from student2;

RNO AME M1 M2 M3 TOTAL PERCENTAGE------ --------- ----- ----- ----- ----------- --------------------1 Naresh 75 65 85 225 752 Anitha 65 88 56 209 69.67

5

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 6/39

5. DDL COMMANDS

STUDENT TABLE

1. CREATE A STUDENT TABLE HAVING ROLL NO, NAME, CLASS ANDMARKS IN 3 SUBJECTS

SQL>create table student3 (rno varchar2 (7), name char (10), class varchar2(10),

m1 number (3),m2 number (3),m3 number (3));

Table created.

2. DESCRIPTION OF THE TABLE

SQL>desc student3;

Name Null? Type--------- --------- --------RNO VARCHAR2 (7)NAME CHAR (10)CLASS VARCHAR2 (10)M1 NUMBER(3)M2 NUMBER(3)M3 NUMBER(3)

3. INSERT CONSTANT VALUES

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’)

1 row created.

6

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 7/39

SQL>/

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

SQL>insert into

student3(rno,class,m1,m2,m3)values(05109113,’mca’,61,82,77);

1 row created.

6. LIST THE CONTENTS OF THE TABLE

SQL>select*from student3;

RNO NAME CLASS M1 M2 M3------- ---------- ----------- ----- ----- ------5109094 NANI mca5109008 REDDY msc5109054 RAJ mba5109083 BOBBY mcom5109113 mca 61 82 77

7. ADD NEW COLUMN TO THE TABLE AS TOTAL

SQL>alter table student3 add (total number (3));

Table altered.

7

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 8/39

SQL>desc student3;

Name Null? Type--------- --------- --------RNO VARCHAR2 (7)NAME CHAR (10)CLASS VARCHAR2 (10)M1 NUMBER(3)M2 NUMBER(3)M3 NUMBER(3)TOTAL NUMBER(3)

8. UPDATE THE TOTAL COLUMN IN THE TOTAL

SQL>update student3 set total=m1+m2+m3;

5 rows updated.

SQL> select*from student3;

RNO NAME CLASS M1 M2 M3 TOTAL------- ---------- ----------- ----- ----- ------ ------------5109094 NANI mca5109008 REDDY msc5109054 RAJ mba5109083 BOBBY mcom5109113 mca 61 82 77 220

9. ALTER THE NAME COLUMN WIDTH TO 25 CHARECTERS

SQL>alter table student3 modify (name char (25));

Table altered.

SQL>desc student3;

Name Null? Type--------- --------- --------

RNO VARCHAR2 (7)NAME CHAR (25)CLASS VARCHAR2 (10)M1 NUMBER (3)M2 NUMBER (3)M3 NUMBER (3)TOTAL NUMBER (3)

8

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 9/39

10. MAKE DUPLICATE COPY OF THE TABLE

SQL>create table dup_std1 as select * from student3;Table created.

11. COPY THE CONTENTS ROLL NO<NAME AND CLASS INTO THE NEW

TABLE

SQL>create table new_std1 as select rno,name,class from student3;

Table created.

SQL>desc new_std1;

Name Null? Type

--------- --------- --------RNO VARCHAR2 (7)NAME CHAR (25)CLASS VARCHAR2 (10)

12. DELETE THE CONTENTS OF THE NEW TABLE

SQL>delete from new_std1;

5 rows deleted.

13. DROP THE STUDENT TABLE

SQL>drop table student3;

Table dropped.

9

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 10/39

6. NUMERIC FUNCTIONS

Accepts numeric input and returns values as output.

1. abs (n):SQL>select abs (-53) from dual;ABS (-53)53

2. ceil(n):SQL>select ceil (53.35) from dual;CEIL(53.35)54

3. exp(n):

SQL>select exp (3) from dual;

EXP (3)20..85537

4. floor (n):SQL>select floor (53.35) from dual;FLOOR (53.35)53

5. power (m,n):SQL> select power (5,3) from dual;POWER(5,3)

125

6. mod (m,n):SQL>select mod (5,3) from dual;MOD (5,3)2

7. round (m,n):

SQL>select round (53.2568,2) from dual;ROUND (53.2568,2)53.25

8. trunk (m,n):SQL>select trunk(53.2568,2) from dual;TRUNC (53.2568,2)53.25

10

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 11/39

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 12/39

8. soundex: This function words that are spelled differently but sound alike.

SQL>select sname from sailors where soundex(sname)=soundex(‘nani’);SNAMENANI

8. CONVERSION FUNCTIONS

1. to char(): It converts date to character.

SYNTAX: to_char (d,[fmt])

SQL>select to_char(sysdate,’ddth ”of” fmmonth yyyy’) from dual;

TO_CHAR20th of October 2007

2. to date(): it converts character to date.

SYNTAX:to_date (char,[fmt])

SQL>select to_date (‘aug 15 47’,’mon-dd-yy’) from dual;

TO_DATE15-AUG-47

GENERAL FUNCTIONS:

1. SQL>select greatest (53, 35, 99) from dual;

GREATEST:99

2. SQL>select least (53, 35, 99) from dual;

LEAST:35

12

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 13/39

9. DATE FUNCTIONS

1. add months:

Syntax: add_months (d,n) where d is date & n is no. of months.

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

If sysdate is 21-OCT-08 result isADD_MONTH20-OCT-08

2. last day:

Syntax: last_day (d) displays last day of the month.

SQL>select last_day (sysdate) from dual;

LAST_DAY 31-OCT-07

3. months between:

Syntax: months_between (d1, d2), returns no of months between two dates.

SQL>select months_between (’11-09-06’,’dd-mm-yy’),

(to_date (’20-10-07’,’dd-mm-yy’)))from dual;

MONTHS_BETWEEN-13.29032

4. next day:

Syntax: next_day (d, day), where d represents date & day represents weekday.

SQL>select next_day (sysdate,’sunday’) from dual;

NEXT_DAY21-OCT-07

13

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 14/39

5. round:

Syntax: round (d, [fmt])

SQL>select round (to_date (’20-Oct-07’,’dd-mm-yy’),’year’) from dual;

ROUND01-JAN-08

6. truncate:

Syntax: trunc(d,[fmt])

SQL>select trunk (to_date (’20-OCT-07’,’dd-mm-yy’),’month’) from dual;

TRUNC :01-OCT-07

7. greatest:

Syntax: gratest(d1,d2),returns latest date present in the arg.

SQL>select greatest (to_date(’20-oct-07’,’dd-mm-yy’),

(to_date(’30-oct-07’,’dd-mm-yy’)))from dual;

GREATEST31-OCT-07

14

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 15/39

PROGRAM:

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.

SQL>select * from emp order by sal;

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7369 SMITH CLERK 7902 17-DEC-80 800 20

7900 JAMES CLERK 7698 03-DEC-81 950 307876 ADAMS CLERK 7788 23-MAY-87 1100 20

7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

7654 MARTIN SALESMAN 7698 28-sep-81 1250 1400 30

7934 MILLER CLERK 7782 23-JAN-82 1300 10

7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30

7499 ALLEN SALESMAN 7698 20-FEB-81 2450 10

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

7566 JONES MANAGER 7839 02-APR-81 975 20

7788 SCOTT ANALYST 7566 19-APR-87 3000 20

7902 FORD ANALYST 7566 03-DEC-81 3000 20

7839 LUCKY PRESIDENT 16-NOV-81 5000 10

14 rows selected.

15

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 16/39

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;

COUNT(JOB)114

2.list the average salary in each department.

16

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 17/39

SQL> select deptno, avg(sal) from emp group by deptno;

DEPTNO AVG(sal)10 2916.666720 217530 1566.6667

3. count the employees and calculate the avg salary in each job group ineach Department

SQL> select deptno, job, count (*), avg (sal) from emp group by job, deptno;

DEPTNO JOB COUNT (*) AVG (SAL)20 ANALYST 2 3000

10 CLERK 1 130020 CLERK 2 95030 CLERK 1 95010 MANAGER 1 245020 MANAGER 1 297530 MANAGER 1 285010 PRESIDENT 1 500030 SALESMAN 4 1400

9 rows selected.

HAVING CLAUSE:

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

17

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 18/39

SQL> select deptno, avg(sal) from emp group by deptno having count(*)>1;

DEPTNO AVG(sal)10 2916.666720 217530 1566.6667

PROGRAM:

11. CREATE QUERIES USING EQUI JOINS, OUTER JOINS, SELF JOIN andCARTESIAN JOIN.

JOINS:

Join is a select command that combines rows from two or more tables i.e. Itextracts information from more than one table

Types of joins:1. Equijoin2. Non-equijoin.

A. EQUIJOIN:

Equijoins exits when there is a common attribute in both the table.

Types of joins:a. self joinb. outer join.

1. List employee name, department name of all employees displaying in

a sorted order of dept Name.

SQL>select ename, dname from emp, dept where emp.deptno=dept.deptnoorder by dname;

ENAME DNAME

CLARK ACCOUNTINGLUCKY ACCOUNTINGMILLER ACCOUNTINGSMITH RESEARCHADAMS RESEARCHFORD RESEARCHSCOTT RESEARCHJONES RESEARCH

18

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 19/39

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

13 rows selected.

C.OUTER JOIN:

19

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 20/39

Outer join displays all information from both the tables.

1. List all department numbers, names along with their employee names.

SQL>select ename, dname from emp, dept where emp.deptno=dept.deptno & dept.deptno in(30,40);ENAME DNAMEALLEN SALESWARD SALESMARTIN SALESBLAKE SALESTURNER SALESJAMES SALES

6 rows selected.

D.NON-EQUI JOIN

Exits when there are no common attributes in the tables.

1. Display employee numbers, names and grade of all employees.

SQL>select empno, ename, job, grade from emp, salgrade where sal betweenlosal & hisal;

EMPNO ENAME JOB GRADE7369 SMITH CLERK 17876 ADAMS CLERK 17900 JAMES CLERK 17521 WARD SALESMAN 27654 MARTIN SALESMAN 27934 MILLER CLERK 27499 ALLEN SALESMAN 37844 TURNER SALESMAN 37566 JONES MANAGER 47698 BLAKE MANAGER 4

7782 CLARK MANAGER 47788 SCOTT ANALYST 47902 FORD ANALYST 47839 LUCKY PRESIDENT 5

14 rows selected

20

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 21/39

E.CARTESIAN JOIN:

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;

SID SNAME RATING AGE95 Lucky 3 64

2. Table level Lock:

21

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 22/39

SQL>lock table sailors in share mode;

Table(s) Locked.

SQL>lock table sailors in share update mode;

Table(s) Locked.

SQL>lock table sailors in exclusive mode;

Table(s) Locked.

PROGRAM:

13.Create queries on multiple tables.

1. List employee name, department name of all employees displaying in asorted order of dept name.

SQL>select e.ename, d.deptno, d.dname from emp e, dept d wheree.deptno=d.deptno;

ENAME DEPTNO DNAMESMITH 20 RESEARCHALLEN 30 SALESWARD 30 SALESJONES 20 RESEARCHMARTIN 30 SALESBLAKE 30 SALESCLARK 10 ACCOUNTINGSCOTT 20 RESEARCHLUCKY 10 ACCOUNTINGTURNER 30 SALES

ADAMS 20 RESEARCHJAMES 30 SALESFORD 20 RESEARCHMILLER 10 ACCOUNTING

14 rows selected.

2. List all employees who are working in CHICAGO.

22

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 23/39

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.

d. General Functions.e. Date Functions.

PROGRAM;

23

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 24/39

15.Create views, synonyms, sequences, indexes.

1.VIEWS:

A view is a virtual table. It does not actually exist in the database, but is accessedJust like a normal table.

Creating Views:

SQL>create view emp_view as select empno,ename from emp;View created.

SQL>select * from emp_view;

EMPNO ENAME7369 SMITH7499 ALLEN

7521 WARD7566 JONES7654 MARTIN7698 BLAKE7782 CLARK7788 SCOTT7839 LUCKY7844 TURNER7876 ADAMS7900 JAMES7901 FORD

7934 MILLER

14 rows selected.

2. SYNONYM:

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.

SQL> select * from dept_syn;

DEPTNO DNAME LOC10 ACCOUNTING NEWYORK

24

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 25/39

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

25

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 26/39

16. INTRODUCTION TO PL/SQL

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.

Begin: SQL executable statements PL/SQL executable statements.

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

Variable in PL/SQL blocks are ’named’ variables.

26

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 27/39

DBMS-OUTPUT

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.

27

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 28/39

17. PROCEDURE

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.

28

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 29/39

Declare

No emp.empno%type:=&no;

Name emp.ename%type;

Salary emp.sal%type;

Begin

Select ename, sal into name, salary from emp where empno=no;

If salary > 20000 then dbms_output.put_line (‘ename:”||name||”sal:”||salary);

Else dbms_output.put_line (‘since sal<20000, hence it is not displayed’);

End if;

End;

OUTPUT

SQL>/

Enter value for no: 9999

Since sal<20000, hence it is not displayed

PL/SQL procedure successfully completed.

PROGRAM:

19.Write a pl/sql program to display the grade and rank of a student.

29

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 30/39

Fields of std table are(rno, name, c1, c2, c3, total, percentage, result, grade).

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

30

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 31/39

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

4 Rahul 69 79 8

PL/SQL PROGRAM

SQL> set server output on;

31

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 32/39

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 33/39

Rollnumber : 1Student name: NaniMarks1: 60Marks2: 70Marks3: 80Total: 210Percentage: 70Result: passGrade: first

PL/SQL procedure successfully completed.

OUTPUT:

SQL>select * from std;

RNO NAME C1 C2 C3 TOTAL PERCENTAGE RESULT GRADE1 Nani 60 70 80 210 70 pass first2 Anu 71 81 913 Lucky 67 77 784 Rahul 69 79 87

PROGRAM

20.Write a PL/SQL program to accept to student number and display theirname and marks.

33

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 34/39

Prompt for student details.

SQL> select * from stud;

RNO NAME C1 C2 C31 Nani 60 70 802 Anu 71 81 91

2 rows selected.

Pl/ SQL PROGRAM

SQL>declaresno stud.rno%type:=&sno;x stud%rowtype;begin

select * into x from stud where rno=sno;

dbms_output.put_line(‘Sname:’||x.sname);dbms_output.put_line(‘ M1:’||x.m1);dbms_output.put_line(‘ M2:’||x.m2);dbms_output.put_line(‘ M3:’||x.m3);end;

 /SQL>/

Enter value for sno:1old 2: sno stud.rno%type:=&sno;new 2:sno stud.rno%type:=1;

OUTPUT:

sname:NaniM1: 75M2: 65M3: 85

PL/SQL procedure succeccfully completed.

PROGRAM:

34

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 35/39

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 36/39

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.

36

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 37/39

PL/SQL PROGARM:

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;

19 /

OUTPUT:

enter value for dno:20old 2: dno number:=&dno;

new 2: dno number:=20;

ANU—800—17—DEC—80—CLERKNANI—2975—02—APR—81—MANAGERSATYA—3000—19—APR—87—ANALYST

PL/SQL procedure successfully completed.

PROGRAM:

24.PL/SQL Program using stored procedure and stored functions.

PL/SQL PROGARM

37

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 38/39

1 create procedure print2(n char) is2 begin3 dbms_output.put_line (n);4 end;5 /6 begin7 print2 (‘HELLO NANI’);8 end;9 /

OUTPUT:

Procedure created.HELLO NANIPL/SQL Procedure successfully completed.

PROGARM:

25.PL/SQL Program for Error Handling.

PL/SQL PROGARM

1 declare

2 eno number:=&eno;3 x emp%rowtype;

4 invalic job exception;5 begin

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

16 raise_application_error(-20399,’insufficient privileges..cannot retry’);17 end;18 /

OUTPUT:enter value for eno:7099old 2: eno number:=&eno;

38

8/8/2019 3dbms Lab Record

http://slidepdf.com/reader/full/3dbms-lab-record 39/39

new 2: eno number:=7099;declare*

ERROR at line1:ORA-20399: data not found for given numberORA-06512: at line 14

PL/SQL successfully not completed.