Top Banner
Data--------------------Computer------------------ Information(Meaningful/processed Data) A Database is a collection of large amount of data. According to the ANSI standards a Database is a software that allows you to Insert, Update, Delete and Process your Data. Example : MS Excel, Dbase, Foxbase, FoxPro, Clipper, Lotus 123, DB Vista, etc. Oracle 9i is a RDBMS. It is an OODBMS. Hence called a ORDBMS(Object RDBMS). Differences between DBMS and RDBMS 1) In a DBMS, we have the concept of Fields, Records and Files In a RDBMS, we have the concept of Column(attribute), Row(Tuple or Entity) and Table(Relation or Entity Class/Set or Applet) 2) In a DBMS, relation between two files is created and maintained programmatically. Hence the relation is temporary. In a RDBMS, relation between the two tables can be created at the time of table creation or later on, and hence it is permanent 3) IN a DBMS, Network traffic is high, since most of the processing is done at the client or requestors side. In a RDBMS, network traffic is low, since most of the processing is done at the Server side 4) DBMS does not support the Client-Server architecture. It is a point-to-point communication between two machines Most of the RDBMSs support the Client-Server Architecture 1
117
Welcome message from author
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.
Transcript
Page 1: notes

Data--------------------Computer------------------Information(Meaningful/processed Data)

A Database is a collection of large amount of data.

According to the ANSI standards a Database is a software that allows you to Insert, Update, Delete and Process your Data.Example : MS Excel, Dbase, Foxbase, FoxPro, Clipper, Lotus 123, DB Vista, etc.

Oracle 9i is a RDBMS. It is an OODBMS. Hence called a ORDBMS(Object RDBMS).

Differences between DBMS and RDBMS1) In a DBMS, we have the concept of Fields, Records and Files

In a RDBMS, we have the concept of Column(attribute), Row(Tuple or Entity) and Table(Relation or Entity Class/Set or Applet)

2) In a DBMS, relation between two files is created and maintained programmatically. Hence the relation is temporary.

In a RDBMS, relation between the two tables can be created at the time of table creation or later on, and hence it is permanent

3) IN a DBMS, Network traffic is high, since most of the processing is done at the client or requestors side.In a RDBMS, network traffic is low, since most of the processing is done at the Server side

4) DBMS does not support the Client-Server architecture. It is a point-to-point communication between two machines

Most of the RDBMSs support the Client-Server ArchitectureExample MS Access is a RDBMS, which does not support the Client-Server Architecture.

5) In a DBMS, we have file –level locking.In a RDBMS, we have table, as well as Row-level locking

6) In a DBMS, there is no support for Distributed-Database ConceptIn a RDBMS, there is support for a Distributed-Database Concept

7) In a DBMS. There is no Security of Data.In a RDBMS, we have multiple levels of Data-Security like i)Logging in Security ii) Command Level Security iii)Object Level Security

1

Page 2: notes

Various RDBMSs are :Informix -- FastestOracle -- Most CommonSybaseMS SQL Server -- User FriendlyIngres, Progress, Unify-- Character-based(DOS, UNIX platformDB2, CICS, Telon, IDMS -- Mainframe computersMS Access, Paradox, Vatcom SQL -- PC based(not for Network)

According to some statistics, Oracle 9i is used by 53% of the worlds RDBMS Market. The i stands for Internet or Intelligent, as it is an extensive support for Internet-based applications

Some of the major Oracle 9i Software Development Tools :1) SQL2) SQL * Plus3) PL/SQL4) Oracle Forms 9i5) Oracle Reports 9i6) Oracle Menus7) Oracle Graphics8) IDS9) EXP10) IMP11) SQL * Loader12) OEM13) Oracle Case14) Designer 200015) Oracle Financials16) Oracle Manufacturing17) Oracle HRMS18) Oracle Application19) Oracle CRM20) Personal Oracle21) OraTerm

1) SQL(Structured Query Language)Supports only 9 commands : Create, Alter, Drop

2

Page 3: notes

Insert, Update, DeleteSelectGrant, Revoke

Initially founded by IBM(International Business Machines), now controlled by ANSI(AMERICAN national Standards Institute)

2) SQL * PlusIt is an extension of SQL.It removes some limitations of SQLIt is an interface with the database to execute SQL and SQL*Plus commandsIt also works as a Reporting tool(Character-based reports). Example telephone bills, mobile bills are character based, and printed on pre-printed stationery)

The best Reporting tool available in the Market is ACTUATE. Others are Seagate’s Crystal Reports

3) PL/SQL(Procedural Language/SQL)It is the programming language of Oracle. For MS SQL, we have Transact SQL

4) Oracle Forms 9iOracles Front-End. Other front ends can be sued with Oracle like Visual Basic and Java. But Forms 9i is best suited for Oracle and cannot be used as a front-end for any other DBMS/RDBMS

5) Oracle Reports 9iOracle’s Report Writing Software

6) Oracle MenusOracle’s Menu Building Software

7) Oracle GraphicsFor Charts, Graphs, etc based on Oracle data

8) IDS(Integrated Development Suite)Combination of Forms+Reports+Menus+Graphics. Earlier known as D2K(Developer 2000)

9) EXP 10) IMPThe Oracle export (EXP) and import (IMP) utilities are used to perform logical database backup and recovery. They are also used to move Oracle data from one machine, database or schema to another. Can only be used between Oracle

3

Page 4: notes

databases. One cannot export data and expect to import it into a non-Oracle database. They are used to perform the following :

Backup and recovery (small databases only) Reorganization of data/ Eliminate database fragmentation Detect database corruption. Ensure that all the data can be read. Transporting tablespaces between databases

11) SQL * LoaderTo Bring data from another RDBMS to Oracle.

12) OEMOracle Enterprise Manager is a tool used to perform Database Administration tasks.

13) Oracle CaseCASE tolls for rapid application development using ERDs, DFDs. Designing of these diagrams helps to automatically create tables and their relationships.

14) Designer 2000It includes Oracle Case+IDS

15) Oracle FinancialsThe core applications which make up Oracle Financials includes Oracle General Ledger, Oracle Purchasing, Oracle Payables, Oracle Inventory, Oracle Receivables and Oracle Assets.

16) Oracle ManufacturingThe Oracle E-Business Suite Manufacturing family of applications enables you to optimize production capacity, from raw materials through final product — regardless of manufacturing methodology. A unified data model provides a single, accurate view of your manufacturing process, so you can configure customer orders, optimize subcontracting, and manage for cost, quality, and compliance. And when Oracle Manufacturing runs on Oracle technology, you speed implementation, optimize performance, streamline support, and maximize return on your investment.

17) Oracle HRMThe Oracle E-Business Suite Human Resources Management family of applications automates the entire recruit-to-retire process, so you can align your workforce with strategic objectives. A unified data model provides a single, accurate view of human resources-related activities, including recruiting, performance management, learning, compensation, and real time analytics

4

Page 5: notes

18) Oracle CRMOracle's integrated Customer Relationship Management (CRM) solution is a set of applications that give you information-driven sales, service, and marketing. Oracle CRM is built on an open, standards-based architecture that streamlines business processes, improves data quality, and allows all your key divisions to draw from the same source of data.

19) Oracle ApplicationOracle applications enable information-driven business processes that connect, automate, and energize your business. It includes HRM, DRM, Financial, Performance Management, Project Management, etc.

20) Personal OracleA version of the Oracle database software scaled-down small enough to reside on a PC, but still containing enough power to handle large-scale database tasks better than Access or Paradox

21) OraTerm(Used for Keyboard Mapping)On the terminal side, when a key is pressed on the keyboard, the keyboard controller produces a code, or a sequence of codes, which are then sent on to the host system. These codes are different for each type of keyboard (PC, Macintosh, Sun), and thus we must have a unique resource file for each keyboard type. For example, an Enter key pressed would mean to press OK in a Dialog Box. The Enter key could be configured to do something else, if needed. Also

Relational DatabasesIn relational databases we have only type of Data Stores or Data Structures- called Tables

Why is it called Relational?

Suppose you have two tables

EmpMasterEmpno Empname Salary Deptno1 abc 100 12 lkm 2000 23 kkk 876 34 ppp 569 35 uuu 679 26 yyy 7789 3

5

Page 6: notes

7 ttt 6878 18 rrr 5765 19 eee 6886 210 ppu 687 3

DeptMasterDeptno Deptname1 Accounts2 Administration3 Medical

Here, even though the tables are separate and independent, they are related. The filed or column “Deptno” in empmaster table is related to the column “Deptno” in the DeptMaster table. This relationship is the basis of Relational Databases, and this approach is also called the Relational Model approach. The Data is stored only in tables. The tables have columns and rows. The tables can be related to each other if each one of them has a column with a common type of information.

What is SQL(Structured Query Language)Oracle was the first company to release a product that used a English-based Structured Query Language or SQL. It is pronounced as SEQUEL.. This language allows the end users to extract information themselves, without using system level command(which were used earlier) for retrieving every little piece of information.

It is called Structured Language since like any other language it has got a structure or rules of grammar or syntax.

It is called Query Language since it’s fundamental use is to ask questions or query the database and get the relevant answers to those questions or queries.

What is PL/SQL(Procedural Language/Structured Query Language)

SQL is a Non-procedural 4th Generation Language, which means it has got no iterationno variable declarationsno loops

PL/SQL is a procedural extension to SQL.

6

Page 7: notes

It is a superset of SQL which allows you to implement your business rules or logic through creation of Stored procedures, packages, Triggers, Functions or any other programming logic for the execution of SQL Commands.

Section of PL SQL Block :

DeclareDefines and initializes the variables and cursors used in the PL/SQL Block

BeginUses flow control commands such as (if… else… end if;) and loops to assign/manipulate the values of variables. All the business logic is actually implemented here.

Exception(Optional)

Customised handling of errors or such other exceptional situation which may occur at run time

End; Marks the end of the PL/SQL Block. Followed by a semicolon called terminator.

Theoretical and Physical aspects of Oracle

Oracle creates a SGA(System/Shared Global Area) when you start the Oracle Database. Also a few background processes are started to maintain the Oracle Database. These processes and the SGA are together called ORACLE INSTANCE. Then, the database is opened and maintained.

Oracle 8i first came up with the concept of OOPS at the backend or database level thru nested objects, nested tables, etc., thru built in Java support at the database level. I stands for intelligent or internet, where in the implementation of OOPS at the database level resulted in faster retrieval of data, especially for Web-based applications. The application server was brought into the picture at the backend level.

Oracle 9i came up with the concept of Parallel Processing(or Clustered Servers) whereby a set of low-cost servers(like xeon servers) each having its own set of daemons(system level programs handling the single database) could handle or manage a single database, unlike the earlier versions, where only one set of daemons could handle the database(dbf files). Thus there is tremendous reduction in costs(instead of using a single mainframe or expensive server on which the Oracle database lies, you can have a set of low-cost servers with their own set of daemons to handle the database on a single server(or array of

7

Page 8: notes

harddiks storing the database). Thus, it is like having multiple instances of a database, unlike the earlier versions.

8i

9i

8

Physical database or data files

SGA

Database Operations

User1 Operations

User2 Operations

User3 Operations

System Level or Background processes for handling and maintaining the Database also called DAEMONS

N users

Physical database or data files

Daemons SGA

Daemons SGA

Daemons SGAN Users

N Users

N Users

Page 9: notes

Create a table

Rules for Table /Column name :Maximum 30 charactersA-Z, a-z, 0-9Has to begin with alphabetCan contain #, _, $Case insensitive

Datatypes

CharFixed length character data. Maximum 2000 bytes. Default 1 byte

NcharMultibyte character set version of char. Since some National character sets may have a character taking more than 1 byte

Varchar2()Variable length character string having a maximum size of 4000 bytes

Nvarchar2Variable length character string having a maximum size of 4000 bytes or characters depending upon the type of National character set, since in some national character set one character may take 2 or more bytes

CLOBCharacter Large Objects upto 4GB in length

NCLOBSame as CLOB, but for multibyte character sets

BLOBBinary Large Objects upto 4 GB

BFILETo point to a binary operating system file

Create table proposal

9

Page 10: notes

(Proposalid number(10),Recipient_name varchar2(20),Proposal_name varchar2(20),Short_description varchar2(1000),Proposal_text CLOB,Budget BLOB,Cover_letter BFILE);

Assuming that each proposal will be containing a few word-processing files and Excel spreadsheets used for documenting and price-details of the proposal.

Proposal_Text CLOB(containing the text of the proposal)

Budget BLOB(containing spreadsheet showing calculations of cost and profit from proposal

Cover_letter BFILE(A binary file stored outside the database that contains your covering letter)

Oracle ensures the data-integrity of CLOB and BLOB and NCLOB(since this type of data is actually stored in the database itself), but not BFILE(since such data is not stored in the database, but Oracle just maintains a pointer to such file)

For all LOB columns the data is not stored within the table. Actually within the table Oracle stores locators(pointers), which point to the locations within the database which are created by the database to hold LOB objects

Number(p,d) Example : Number(5,2) can take a maximum of 999.99

Long Character data of variable size upto 2GB. Only one long column per table. Cannot be used in subqueries, functions, where clause, indexes. Table cannot be clusteredRawRaw binary data. Upto 255 bytes. Contains Binary data in whatever form the host computer stores it. Used for storing binary(non-character data) small sized(less bytes) photos, imagesLong RawRaw binary data, otherwise the same as Long. Large sized photos and images.

In place of LONG and LONG RAW, Oracle recommends that you use CLOB and BLOB respectively

Date

10

Page 11: notes

Dates between January 1, 4712 BC upto December 31, 9999 AD

Timestamp(precision)Date plus time where precision is the number of digits in the fractional part of the seconds(by default 6).Example ’23-JAN-06 8:45:34.000000’

Interval Year(precision) to monthDifference in two timestamp fields/values in terms of years to months, where precision(by default 2) is the number of digits in the year part. Example ’12-2’ means 12 years and 2 months

Interval day(day_precision) to second(sec_precision)Difference in two timestamp files in terms of days, hours, minutes and seconds, where day_precision(by default 2) is the number of digits in the day-part and sec_precision(by default 6) is the number of digits in the fractional part of the seconds-part. Example ‘14 5:56:45.456654’ means 14 days, 5 hours, 56 minutes, 45.456654 seconds

RowidA unqiue number assigned to each row in a database. Returned by pseudo-column ROWID

Urowid(size)Hexadecimal string to identify the logical address of a row in a indexed-organised table in a database. Maximum size is 4000 bytes

Create table mystuds(rollno number(5),Name varchar2(25),Total number(5,2) default 0);The default value is put for every new row instead of a NULL value

Creating table from another tablecreate table yostud (r,s,e,m,sc,t,b,te) as select * from students

orcreate table yostud as select * from students;

To rename a table, view, sequence or synonym, we have the rename command :Rename oldname TO newname

11

Page 12: notes

Example: Rename students TO studs;

Constraints

Usually created at the same time as the table creation.Can also be added to a table after the table creationCan also be temporarily disabled and enabled.Can be permanently droppedThe system may give it’s own unique constraint names like SYS_PK779If the constraint names are given by the user, then care should be taken to ensure that no other constraint for any other table has the same name.You can add, drop, enable or disable constraints, but not modify it.

Two- typesColumn Level :Refers to a single column and is defined with the definition of the column itself.All 5 types of constraints can be column level.

Table Level :Refers to one or more columns and is defined separately from the definition of the column, that is, after all the column-definitions.Except NOT NULL, all other constraints can be table-level.

NOT NULL ConstraintNULL values not allowedDuplicate allowedAny number of NOT NULL in a tableIt is a column level constraintNo composite NOT NULL exists

create table student(rollno number(3) constraint PK_Stud_rollno primary key,name varchar2(25) NOT NULL,eng number(3,2));

or

create table student

12

Page 13: notes

(rollno number(3) constraint PK_Stud_rollno primary key,name varchar2(25) constraint nn_stud_name NOT NULL,eng number(3,2));

If already created thenAlter table stud modify name varchar2(20) constraint nn_stud_name NOT NULL;

UNIQUE KEYDuplicates not allowedNULL values allowed, unless otherwise specified as NOT NULLLong and LONG RAW cannot be uniqueComposite Unique key allowedNo upper limit on individual Unique keys/Composite Unique KeysIn case of Individual Uk, any number of rows can have NULL values for that columnIn case of Composite UK, both columns can have NULL values for any number of rowsBut in case of Composite UK, if one column contains NULL value for a row , and the other column contains a value say “XYZ”, then you cannot have another row with the same combination of values(that is NULL value for first column and ‘XYZ’ for second column)

create table orders(orderno varchar2(15),itemno varchar2(15),quantity number(5),price number(8,2),constraint myconstraint unique(orderno,itemno))

If table already exists then

Alter table orders add constraint my_un_con unique(ordeno, itemno)

insert into orders values('ord1','itm1',456,123456.78)insert into orders values('ord1','itm2',78.90,123456.78)insert into orders values('ord1','itm3',89.43,123456.789)insert into orders values('ord1','itm4',89.439,1234567)---errorinsert into orders(quantity,price) values(90.99,999999.99)

Other options of Inserting Rows :

13

Page 14: notes

Create table students(Rollno number(5),Firstname varchar2(10),Lastname varchar2(10),Birthdate date,Std char(2),Div char(1),English number(5,2),Maths number(5,2), Science number(5,2),Total number(5,2),Tcode number(3));

For inserting values for all the columns in the table, insert values in the order in which the columns are defined in the table insert into students values(250,’Hemant’,’Pangam’,’26-JUL-1976’,’1’,’A’,89.90,67.50,63.75,0,100);

For changing the order in which the values are entered you have to specify the same in the brackets after the tablename :Insert into students(Firstname, Lastname, rollno, Div, Std, Birthdate, Tcode, Total, Maths, Science, English) values(‘Manoj’,’Pangam’,202,’C’,’10’,’02-DEC-1977’,200,0, 75.75,50.25,90.50);

For inserting values only into specific columns, specify the columns in the brackets after the table name. This is also called Implicit method of inserting NULL values for the columns not specified.Insert into students(Firstname, Lastname, rollno) values(‘Hetal’,’Pangam’,212);

For explicitly inserting NULL values :insert into students values(265,’Jairaj’,’Saraf’,’06-MAR-2001’,NULL,NULL,NULL,NULL,NULL,NULL,NULL);

Inserting special values like current date, current user :insert into students values(269,user,’Saraf’,sysdate,NULL,NULL,NULL,NULL,NULL,NULL,NULL);

Inserting specific date values :By default date is always inserted into the table in the DD-MON-YY format(where YY represents current century, if while inserting the century is not specified). Because date also contains time, the default time saved in a date column is 00:00:00. If u want to enter date in a different format, such as another century than the current century or with a specific time then :

14

Page 15: notes

insert into students values(299,’Mamta’,’Varma’,to_date(‘NOV 20, 1981 15:45:56’,’MON DD, YYYY hh24:mi:ss’),NULL, NULL, NULL, NULL, NULL, NULL, NULL);

to see the actual values stored :select firstname, to_char(birthdate,'DD-MM-YYYY hh24:mi:ss') from students

For inserting with a suitable promptinsert into students values('&ordernumber', '&itemnumber', &quan, &pric")

insert into students values(&RollNumber, '&Firstname', '&Lastname', '&Birth', '&Standard', '&Division', &ENGmarks, &mathematics, &Sciencescore, &FinalTotal,&teacher )

‘ ‘ for character and date, not for number

Alter Tablealter table orders add(remark varchar2(10),billno varchar2(10) not null)error-since table must be empty(delete all records), as there are records and hence billno will not find values for the existing records

hence alter table orders add(remark varchar2(10),billno varchar2(10))

select * from ordersupdate studs set remark='hello'

alter table orders modify(remark varchar2(10) not null)

alter table orders drop column remarkalter table orders drop(remark, abc)

alter table orders set unused column remark

15

Page 16: notes

alter table orders set unused column abc alter table tablename set unused(col1, col2)This feature is available 8i onwards so that we do not effect the speed of an online database. Since dropping a column at peak hours may slow down the speed tremendously. So we mark a column as unsued and later on drop it when the system demand/system resource use is low. You have no access to the column and is as good as dropped. No query allowed on such unused columns. The column name and datatype are not seen with the describe command.

alter table orders drop unused columns

Alter table tablename add/modify column columnname default defaultexpression;Alter table can be used to add a default value for a new/existing columns

can increase character columns width at any timecan increase the number of digits in a number column at any timecan increase or decrease the number of decimal places in a number column at any time

if a column is NULL for every row of a tablecan change the column's datatypecan decrease a character column's widthyou can decrease the number of digits in an NUMBER

Alter table tablename drop constraint Primary key;To drop the PK constraint

Alter table tablename drop constraint unique(column/columns name)To drop the Unique constraint on a column or columns

Alter table tablename drop constraint constraintnameTo drop any constraint by it’s name

Alter table tablename disable constraint constraintname;Alter table tablename enable constraint constraintname;

A column cannot be dropped, if it is involved in some constraints. Hence we used the CASCADE CONSTRAINTS option as follows with the alter table :

Alter table tablename DROP (columnname) cascade constraints;

16

Page 17: notes

Viewing Constraints :

To view the constraint definitions and names :Select constraint_name, constraint_type, search_condition from USER_Constraints where table_name =’ORDERS’

To view the columns associated with the constraint namesSelect constraint_name, column_name from USER_CONS_COLUMNS whereTable_name=’ORDERS’

Tables owned by the userSelect table_name from user_tables;

To see the different objects owned by the userSelect distinct object_type, object_name from user_objects

To see the distinct object types owned by the userSelect distinct object_type from user_objectsTo see the tables, views, synonyms and sequences owned by the userSelect * from user_catalog

You can add comment to a table/column as follows :comment on table students is 'Information abount my students';select * from user_tab_comments where table_name='STUDENTS';select * from all_tab_comments where table_name='STUDENTS';Will show all the user tables(if where absent)/all tables(if where absent)/specified table with/without a comment.

comment on column students.studname is 'Names of my students';select * from user_col_comments where table_name='STUDENTS';select * from all_col_comments where table_name='STUDENTS';both the above will show all the columns of all the tables(if where clause not given) or specified table who have got atleast one column with a comment.

PRIMARY KEY

Key that uniquely identifies each row of a tableDuplicate values not allowedNull values not allowedRecommended for every tableAny column can be a PK, except LONG and Long RAW

17

Page 18: notes

Purpose : Record UniquenessCan have a Composite PKNull values not allowed for any column of the Composite PK.Only one PK/Composite PK per tablePK can be defined at column level. CPK is always defined at table-level.

A candidate key is that key that can also serve as a PK. Example if all employees are having a mobile then even mobile_no can be a PKs

PK constraint is at Server level, hence cannot be bypassed by a Front-end

Select * from user_constraints where table_name=’EMP’;EMP in upper case, since Oracle stores table and column names in upper case

If you don’t specify the constraint name , Oracle gives it’s own constraint names like

Constraint_Name Constraint_Type SYS146788 P

for single column primary keycreate table student(rollno number(3) primary key,name varchar2(25) NOT NULL,eng number(3,2));

ORcreate table student(rollno number(3) constraint PK_Stud_rollno primary key,name varchar2(25) NOT NULL,eng number(3,2));

for multiple column primary keycreate table student1(stan varchar2(2) NOT NULL,div varchar2(1) NOT NULL,rollno number(3),name1 varchar2(25) NOT NULL,

18

Page 19: notes

eng number(3,2),constraint my_primarykey primary key(stan,div,rollno));

If a table is already created thenAlter table stud Add constraint my_con primary key(rollno);

FOREIGN KEY and CHECK Constraint

Foreign Key :A column or set of columns that take the reference of some other column from some other table or the same tableMust be a Primary or Unique Key in the parent tableChild table may have NULL or duplicate valuesMaster records cannot be deleted, if a child record existsON DELETE CASCADE indicates that when a row in the parent table is deleted, the corresponding rows in the child table are automatically deleted.ON DELETE SET NULL indicates that when a row in the parent table is deleted, the foreign column in the corresponding child rows will be updated to NULL.Without ON DELETE CASCADE and ON DELETE SET NULL, the parent row cannot be deleted if a child row exists.Both these options can be set at column or table level.

Check constraint :It defines a condition that each row must satisfy

create table itemmast(itemno varchar2(15) primary key,itemname varchar2(25) NOT NULL,company varchar2(15) NOT NULL,remark varchar2(25) NOT NULL,unitprice number(8,2) constraint upcons CHECK(unitprice>100)

19

Page 20: notes

)

table-level :create table orders(orderno varchar2(15),itemno varchar2(15),quantity number(5),price number(8,2) check (price>100.50),constraint myconstraint1 unique(orderno,itemno),constraint fk foreign key(itemno) references itemmast(itemno))

orcolumn level :create table orders(orderno varchar2(15),itemno varchar2(15) constraint fk references itemmast(itemno),quantity number(5),price number(8,2) check (price>100.50),constraint myconstraint1 unique(orderno,itemno))

create table orders1(orderno varchar2(15),itemno varchar2(15),quantity number(5),price number(8,2) check (price>100.50),constraint myconstraint6 unique(orderno,itemno),constraint fk11 foreign key(itemno) references itemmast(itemno) on delete cascade)

insert into orders values('o3','4',67,89)insert into orders values('o3','4',67,989)

drop table orders;when a table is dropped, the database looses all the data in the table and all the indexes associated with it. View and Synonyms based on the table still remain , but are invalid. No rollback possible.

20

Page 21: notes

Delete students;Delete all the rows from the students table, but the memory occupied by the rows is still not released. Rollback can be used to get back the rows.

truncate table orders;It is a DDL statement, which is used to remove all the rows permanently from the table , i.e, no rollback possible.. The storage spaced occupied by the rows is released. Table still exists with 0 rows.

select * from user_cons_columnsselect * from user_constraintsupdate user_constraints set status='DISABLED' where constraint_name='SYS_C0034437'

For inserting & into a fieldset escape #;insert into orders values('o#&','1',150,190.90);insert into orders values('o#&7','1',900,900.89);

delete from orders;rollback;delete from orders where orderno='o&';commit;

Updateupdate orders set quantity=500;rollback;

update orders set quantity=550, price=900 where quantity=500 or price=190.9;commit;

update orders set quantity=null;rollback;

Drop table tablename;

Normalisation

First Normal Form(FNF)

21

Page 22: notes

A relation or table is said to be in the 1st Normal Form when it has no composite attributes or columns , and every attribute(column or field) is single or individual and describes only one property. It is also called Flat file

Example:Order_details Item_code Quantity Price_per_unit 1456 of 26/02/1989 3687 52 50.401456 of 26/02/1989 4627 38 60.201456 of 26/02/1989 3214 20 17.501886 of 04/03/1992 4629 45 20.251886 of 04/03/1992 4627 30 60.201788 of 04/04/1992 4627 40 60.20

FNFOrder_No Order_date Item_code Quantity Price_per_unit 1456 26/02/1989 3687 52 50.401456 26/02/1989 4627 38 60.201456 26/02/1989 3214 20 17.501886 04/03/1992 4629 45 20.251886 04/03/1992 4627 30 60.201788 04/04/1992 4627 40 60.20

Second Normal Form(SNF)A relation is said to be in the 2NF, when it is in the 1NF, and the Non-key attributes are functionally dependent on the key attributes(s)or composite Primary Key.

Example : Consider the FNF given above. Here, Price_per_unit is functionally dependent on Item_code; and Order_date is functionally dependent on Order_No. Thus, the relation is not in 2NF. Therefore, it is split into 3 tables as follows to give 2NF :

Order_Mast : Order_No Order_date1456 26/02/19891886 04/03/19921788 04/04/1992

Item_Mast Item_code Price_unit3687 50.404627 60.203214 17.504629 20.25

22

Page 23: notes

Order_Tran Order_no Item_code Qty1456 3687 521456 4627 381456 3214 201886 4629 451886 4627 301788 4627 40

Third Normal Form(SNF)A table or relation is said to be in TNF when it is in the 2NF, and No non-key attributes are functionally dependent on any other non-key attributeExample :

Consider the following in 2NF:Roll_No Name Department Year Hostel_name1784 Ram Physics 1 Ganga1648 Sham Chemistry 1 Ganga1768 Bharat Maths 2 Kaveri1848 Arjun Botany 2 Kaveri1682 Nakul Geology 3 Krishna1485 Sahadeo Zoology 4 Godavari

Assuming that the 1st Year, 2nd Year, 3rd Year and 4th Year students stay in Hostels Ganga, Kaveri, Krishna and Godavari respectively, then in such a case, the non-key attribute Hostel_name is dependent on the non-key attribute Year. Therefore, it is split into 2 tables as follows to give 3NF :

Stud_mastRoll_No Name Department Year1784 Ram Physics 11648 Sham Chemistry 11768 Bharat Maths 21848 Arjun Botany 21682 Nakul Geology 31485 Sahadeo Zoology 4

Hostel_MastYear Hostel_name1 Ganga2 Kaveri3 Krishna

23

Page 24: notes

4 Godavari

BCNF(Boyce-Codd Normal Form)If an attribute of a composite key is dependent on an attribute of another composite key, then the BCNF is needed.Example: Professor_code Department HOD Percent_of_timeP1 Physics Ghosh 50P1 Mathematics Krishnan 50P2 Chemistry Rao 25P2 Physics Ghosh 75P3 Mathematics Krishnan 100

Assumptions :A professor can work in more than one department.Percentage of time spent by professor in each department is givenEach department has only one HOD

Here the 2 possible composite Keys(Composite Primary keys) could be 1) Professor_code + Department2) Professor_code + HOD

Thus, in the 1st case, the attribute Department depends on the attribute HOD of the 2nd CPAnd, in the 2nd case, the attribute HOD depends on the attribute Department of the 1st CP. Also, there is duplication of the combination of “Department + HOD”. Also, if professor P2 resigns and rows 3 and 4 have to be deleted, then we loose the information “Rao is the HOD of Chemistry”Therefore, BCNF is needed, and the relation is broken down to

Prof_MastProfessor_code Department Percent_of_timeP1 Physics 50P1 Mathematics 50P2 Chemistry 25P2 Physics 75P3 Mathematics 100

Department_MastDepartment HODPhysics GhoshMathematics KrishnanChemistry Rao

4NF

24

Page 25: notes

It is needed when a relation has more than one multivalued dependencies. Thus, a relation is said to be in 4NF when it has one independent multivalued dependency with a functional dependency

Example : Consider a vendor supplying many items to many projects in an organization where :

1) A vendor may supply many items2) A project may require many items3) A vendor supplies to many projects4) An item may be supplied by many vendors

Vendor_code Item_code Project_codeV1 I1 P1V1 I2 P1V1 I1 P3V1 I2 P3V2 I2 P1V2 I3 P1V3 I1 P2V3 I1 P3Problems :If vendor V1 has to supply to project P2, but the item is not yet decided, then a row with a blank item_code will have to be insertedInformation about Item I1 is stored twice for vendor V1(in rows 1 and 3).Therefore 4NF is achieved, by dividing it into 2 relations as follows :

Vendor_Item Vendor_ProjectVendor_code Item_code Vendor_code Project_codeV1 I1 V1 P1V1 I2 V1 P3V2 I2 V2 P1V2 I3 V3 P2

25

Vendor

Project

Item

Page 26: notes

V3 I1 V3 P3Thus, both the tables have only one multivalued dependency(For vendor_item, the MVD is one vendor has supplid many items. For Vendor_project, the MVD is that one vendor has supplied to many projects)

5NFIt is obtained by adding one relation(relation with one MVD) relating attributes of the 2 relations in 4NF with one MVD. Thus in addition to the two relations in 4NF, we will have the following relation with one MVD :Project_itemProject_code Item_codeP1 I1P1 I2P1 I3P2 I1P3 I1P3 I2

Types of SQL Commands :

DDL(Data Definition Language) : Create, Alter, Drop, Rename, Truncate

DML(Data Manipulation Language: Insert, update, deleteMerge

DQL(Data Query Language) : SelectDCL(Data Control Language) : Grant, RevokeTCL(Transaction Control Language) : Commit, Rollback, Savepoint

Select * from tablename;

Select Field name(s) separated by commas;

Conditional/relational operators: <, >, <=, >=, !, <>select * from orders where quantity<>4;select * from orders where quantity!=4;

Logical operators : and, or, not

select * from orders where itemno='1' and price>500;select * from orders where itemno='1' or itemno=3

26

Page 27: notes

Special operators: IS NULL, between, like, in select * from orders where quantity is nullselect * from orders where price is NOT nullselect * from orders where price between 190 and 876.65(both inclusive)select * from orders where price NOT between 190 and 876.65

pattern matching with like operator : % and _ select * from orders where orderno like 'o9%'select * from orders where orderno like 'o_'select * from orders where orderno like '_2'select * from orders where orderno like '___'(3 _s)

desc user_tables;desc all_tables;select table_name from user_tables;select table_name from all_tables;

SQL QUERIEScreate table deptmast(deptno number(2) primary key,deptname varchar2(20));

create table employee(empno number(3) primary key,empname varchar2(15),salary number(5,2),deptno number(2),constraint my_constraint Foreign key(deptno) references deptmast(deptno));

SELECT * FROM EMPLOYEE;SELECT EMPNO,SALARY FROM EMPLOYEESELECT * FROM EMPLOYEE ORDER BY SALARY DESCSELECT * FROM EMPLOYEE WHERE SALARY>400SELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME, DEPTNOSELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME DESC, DEPTNOSELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME DESC, DEPTNO DESC

27

Page 28: notes

GROUP Functions :Group functions operate on sets of rows to give one value per group(A group could be the entire table or rows having some common value). Some group functions are AVG(Distinct|All), COUNT(Distinct|All), MAX(Distinct|All), MIN(Distinct|All), STDDEV(Distinct|All), SUM(Distinct|All), VARIANCE(Distinct|All). All group functions ignore NULL values. The DISTINCT clause, if used with a group function, makes it consider only the non-duplicate values. The ALL clause makes it consider all the values.. The default is ALL.

The AVG and SUM are used for numeric data. MAX and MIN may be used even for character or date type of data.Select sum(salary) from employees

GROUP BY Clause :The Group By clause is used to divide the table into groups of rows. By using a where clause you can exclude certain rows before dividing them into groups. By default rows are sorted in the ascending order of the columns included in the group by clause. You can change the ordering by using the Order By clause. All the columns in the SELECT list that are not group functions must be included in the GROUP BY Clause.Select deptno, sum(salary) from employees Group By DeptnoSelect std, div, max(maths), min(science) from students group by Std, Div

SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPTNOSELECT DEPTNO, MAX(SALARY) FROM EMPLOYEE GROUP BY DEPTNO;SELECT DEPTNO, MIN(SALARY) FROM EMPLOYEE GROUP BY DEPTNO;SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPTNO ORDER BY DEPTNOSELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNOSELECT DEPTNO AS DEPARTMENT, SUM(SALARY) FROM EMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNOSELECT DEPTNO AS DEPARTMENT, SUM(SALARY) AS "SUM OF SALARY" FROM EMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNO

The Count(*) returns the number of rows in a table that satisfy the criteria of the select statement, including duplicate rows and rows containing NULL values. The Count(column) returns the number of rows having Non-Null values in the columnThe Count(distinct column) returns the number of rows having Unique Non-Null values in the column

The NVL function can be used to include NULL values as follows :Select AVG(NVL(Maths,0)) from students;

28

Page 29: notes

select deptno, count(*) from employee group by deptno

The Where Clause cannot be used to restrict the groups or to specify conditions on the group function-results. To do this we use the HAVING Clauseselect deptno, count(*) from employee group by deptno having count(*)>=4SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPTNO having sum(salary)>1500(Having is used like where on results of groupedfunctions instead of individual rows)SELECT DEPTNO, MAX(SALARY) FROM EMPLOYEE GROUP BY DEPTNO ORDER BY MAX(SALARY) DESC`Select * from tablename where condition(s) group by field(s) having condition(s) order by field(s)SELECT DISTINCT DEPTNO FROM EMPLOYEE

Nesting Group FunctionsSelect Max(Avg(Maths)) from students group by std;

JoinsCartesian ProductWhen the join condition is invalid or is omitted. All rows in the first table are joined to all rows in the 2nd table

select empno, empname, deptname from employee,deptmastorselect empno, empname, deptname from employee cross join deptmast

LEFT OUTER JOIN (non mathing records r shown .display all records frm lefttable)select * from deptmast d, employee e where E.DEPTNO(all emp+)=D.DEPTNO ORDER BY D.DEPTNO, E.EMPNOORselect * from deptmast left outer join employee on deptmast.deptno=employee.deptno ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO;All Records from department including those who do not have a corresponding employee;

RIGHT OUTER JOIN (display all records frm righttable)select * from deptmast d, employee e where D.DEPTNO(+)=E.DEPTNO ORDER BY D.DEPTNO, E.EMPNOORselect * from deptmast RIGHT outer join employee on deptmast.deptno=employee.deptno ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO;

29

Page 30: notes

All Records from employee including those who do not have a corresponding department;

FULL OUTER JOIN(display all nonmatching records frm both table)select * from deptmast FULL outer join employee on deptmast.deptno=employee.deptno ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO;

OR

select * from deptmast d, employee e where E.DEPTNO(+)=D.DEPTNO unionselect * from deptmast d, employee e where D.DEPTNO(+)=E.DEPTNO

All Records from both the tables, including those who do not have a corresponding department/employee in the other table;

Equi JoinAlso called simple join/Inner joinThe relation between an Employee and Department tables involves as Equi-Join. The values in the common field in both the tables must be equal.select * from employee e (alises), deptmast d where e.deptno=d.deptno

this will help uNon-Equi JoinIt involves an operator other than the equality(=) operator. It uses operators like <=, >= or Between.ExampleEmployee Sal_Grade Empno Empname Salary Grade Min_Sal Max_sal10 hhh 3300 A 3000 500023 ggg 4500 B 5001 750035 jjj 7800 C 7501 1000067 lll 8700 D 10000 1500089 ppp 960067 ooo 10200Select e.empno, e.empname, e.salary, j.grade from employee e, Sal_Grade j where e.salary BETWEEN j.Min_Sal and j.Max_sal

Inner Join (nt givng non matching records)select * from employee e inner join deptmast d using(deptno)

same as equi join, but the column dept is not repeated as in euqi join

30

Page 31: notes

Natural JoinSELECT * FROM STUDENT1 NATURAL JOIN STUDENTS;Here it will display all the records from the 2 tables who have the same values for all the fields with the same nameROLLNO NUMBER(3)NAME1 VARCHAR2(25)STD NUMBERDIV VARCHAR2(1)

Name Null? Type -------------------------- ------------- ROLLNO NOT NULL NUMBER(3) STUDNAME VARCHAR2(20) ENGLISH NUMBER(5,2) MATHS NUMBER(5,2) SCIENCE NUMBER(5,2) TOTAL NUMBER(5,2) STD NUMBER DIV VARCHAR2(1)

We can use the ‘USING’ clause to decide which of the common columns should be considered as follows :Select * from student1 join students using(rollno)

UNIONselect deptname from deptmastunion select dept_desc from dept_mastwill not display duplicate values

UNION ALL(common records twice&uncomn once)

select deptname from deptmastunion allselect dept_desc from dept_mastwill display all values from both the table including duplicate values

INTERSECTselect deptname from deptmastintersectselect dept_desc from dept_mast

31

Page 32: notes

common values(or intersection) from both the tables

MINUSselect studname from studentsminusselect name1 from student1;present in 1st table but not in second;

select name1 from student1minusselect studname from studentspresent in 1st table but not in second;

self join(primary&)consider the table emp in scott/tigerselect x.ename worker, y.ename manager from emp x, emp y where x.mgr=y.empno;

IN Operatorselect * from students where studname NOT IN ('Hemant','Laxman')select * from students where studname IN ('Hemant','Laxman')

Like Operatorselect * from students where studname like '___m'(last char m&3rd m)select * from students where studname NOT like '___m'select * from students where studname like 'He%

Betweenselect * from students where maths between 43 and 70select * from students where maths NOT between 43 and 70

Existsselect deptno,deptname from deptmast d whereexists(select * from employee e where e.deptno=d.deptnogroup by e.deptnohaving count(e.deptno)=3)order by d.deptno

Exists is same as In, but it is a logical operator

32

Page 33: notes

SubqueriesA subquery is a SELECT statement in the WHERE, HAVING or FROM clause of another SELECT statement.

Select * from students where maths>(select maths from students where studname='Laxman') (assm:only 1 laxmn)

The Inner query is also called Nested query or Sub query. The inner or nested or sub query generally executes first and it’s output is used as the input for the outer or main query.

Enclose subqueries inside parenthesis. Oracle 8i onwards “Order by” clause can be used in the inner query.

There are two type of comparison operators : single row operators and multiple row operators, and hence there are two types of sub-queries Single row sub-queries(Query that returns only one row from the sub-query) and Multiple Sub-Row queries(Query that returns more than one row from the sub-query)

Single-Row comparison operators are =,>,>=,<,<=,<>Select rollno, firstname from students where std=(select std from students where rollno=101) and div=( select div from students where rollno=101)The outer and inner queries can get data from different tables.

Group functions can be used in a sub-querySelect rollno, firstname from students where maths=(select max(maths) from students);

HAVING clause with subqueriesSelect deptno, min(salary) from employees group by deptno having min(salary)>(select min(salary) from employees where deptno=50);

To find the Department with the lowest average salarySelect deptno, avg(salary) from employees group by deptno having avg(salary)=(select min(avg(salary)) from employees group by deptno);

If the inner query returns more than one row, then it would generate an error. To correct such errors we use the IN, ANY or ALL operators.

If the inner query returns no rows or NULL value, then the outer query returns no rows.(in laxmn eg. Laxmn nt there then it ret==no rows&if laxmn maths null then it ret==null )

Multiple Row Subqueries or Multiple Row Comparison operators

33

Page 34: notes

IN(Equal to any number in the list), ANY(Compares value to each value returned by the subquery), ALL(Compares value to every value returned by the subquery)

select * from students where studname IN (select studname from students where rollno=45 or rollno=35);

To display the employees who are not Programmers and whose salary is less than any of the Programmerselect empno, empname, job, salary from employees where salary<ANY(select salary from employees where job=’Programer’) and job<>’Programmer’;<ANY means less than the maximum.`>ANY means more than the minimum.=ANY is equivalent to IN

To display the employees who are not Programmers and whose salary is less than all the Programmerselect empno, empname, job, salary from employees where salary<ALL(select salary from employees where job=’Programer’) and job<>’Programmer’;<ALL means less than the minimum.>ALL means more than the maximum.

ROLLUPselect STD, DIV, SUM(MATHS) from STUDENTS group by rollup(STD, DIV, MATHS)

CUBEselect STD, DIV, SUM(MATHS) from STUDENTS group by CUBE(STD, DIV, MATHS)

VIEWSViews are virtual tables. It is a query. It is a pointer to the underlying base table. It does not take any memory in the database. When a table is dropped, the views on it are not accessible, but become active again, when the table is recreated.

To restrict access of data because the view can display selective columns from table/tablesTo make complicated queries simpler by storing them as a view.To present different views of the same data

Simple views:Derives data from a single table. Dose not contain functions or groups of data. Allows you to perform DML operations.Complex views :

34

Page 35: notes

Derives data from many tables. Contains functions or groups of data. Does not allow DML operations

create or replace view stud1asselect * from students where maths>70;

select * from stud1;

update students set english=70 where rollno=1;

select * from stud1;

insert into stud1(rollno, studname) values(29,'Pappu');values can be inserted into the base table through views

select * from stud1;When select is run on a view it will show only those records which satisfy the condition given while creating the view.

select * from students;

select view_name, text from all_views where view_name='STUD1'

create or replace view stud2 as select * from students order by rollno;insert into stud2(rollno, studname) values(31,'Sunil');

cannot insert values in this view because of the order by clause

create or replace view v1(employee_no, employee_name, sal) as select empno, empname, salary from employee where salary<=500-to add an alias to each column.

Complex view :create view v2(name, minsal, maxsal, avgsal) as select d.deptname, min(e.salary), max(e.salary), avg(e.salary) from employee e, deptmast d where e.deptno=d.deptno group by d.deptname;

You cannot delete a row from a view if :It contains group by clause

35

Page 36: notes

It contains the DISTINCT keywordIt contains the pseudolumn ROWNUM

You cannot update a row from a view if :It contains group by clauseIt contains the DISTINCT keywordIt contains the pseudolumn ROWNUMIt contains calculated columns or expressions

You cannot insert row thru a viewIt contains group by clauseIt contains the DISTINCT keywordIt contains the pseudolumn ROWNUMIt contains calculated columns or expressionsNOT NULL columns in the base table are not included in the view

With Check Optioncreate view v4 as select * from employee where deptno=1with check option constraint mycon;The constraint constraintname is optional. The with check option ensures that Inserts/Updates performed thru the view cannot create rows which the view cannot select, and thus ensures integrity constraints and data validations checks on data being inserted/updated thru the view

READ only viewsThey do not allow to insert/update/delete values into the base table thru the viewCreate or replace view v5 as select * from employee where deptno=1 with read only

To drop a viewDrop view viewname

Inline ViewsAn inline view is created by placing a subquery in the FROM clause and giving that subquery an alias so that it behaves like a separate table. Example to find all the employees who earn a salary less than the maximum salary in that department.

create view v6 as select a.empname, a.salary, a.deptno, b.maxsal from employee a, (select deptno, max(salary) maxsal from employee group by deptno) b where a.deptno=b.deptno and a.salary<b.maxsal

Top N analysisselect rownum, empno, salary as rank from (select empno, salary from employee where

36

Page 37: notes

salary is not null order by salary desc) where rownum<=3

Rownum is pseudo column assigned to each row returned by the inner query. The inner query contains the order by clause to get the ranking in the desired order. The outer query limits the number of rows returned by using the where clause which uses a < or <=operator

Producing Readable ReportSubstitution Variables using single ampersandselect * from dept_mast where dept_code=&Department_CodeThe variable is created and discarded after use

select * from dept_mast where dept_name='&Department_name'single quotes are used for date and character and date type of values.

select * from dept_mast where upper(dept_name)=upper('&Department_name')To remove case-sensitivity

Substitution variables can be used for columns, where clause, table names, order by clause :select &column_name from dept_mast where dept_code=&department_code

select * from &table_name

select * from &table_name order by &column

Defining Substitution variables :DEFINE variablename=valueThe value is of type character

ExampleDefine abc=hemantDefine xyz=25

Both are character type variables

Define variablenameTo see the value and data type of that variable

DefineDisplays all variables, their values and data types for that session

Undefine variablename

37

Page 38: notes

To remove the variable from memory

A variable remains in memory till you either give it a new value or you undefined it or you end the SQL SessionDefine command with &substitution variableDefine dep=10select * from dept_mast where dept_code=&dep

&&substitution variableYou should use && before the variable name, if you are going to use it more than once in a statement, and don’t want oracle to prompt you for it’s value everytime it is encountered as follows :

Select &&department, dept_name from dept_mast order by &department;The single & should be used as the last occurrenceNow whenever you use the variable department, it will use the value it has already got. O get rid off the old value use :undefine department(variable name)

Set verify on/offBy default it is on, hence it displays you the statement containing the substitution values twice before execution : once the original statement , and once the statement with the substituted or entered or new values

PartitionsTo store large number of records in separate tables to reduce retrieval time

create table empsal(empno number(3), salary number(8,2))partition by range(salary)(partition part1 values less than(1000) tablespace TRAINING,partition part2 values less THAN (MAXVALUE) TABLESPACE TEMP)

commit and rollbackHow to commit1) commit command;

Implicit Commit2) A DDL Command : Create, Drop, Alter, Audit3) When you say :Exit or Quit; Connect or Disconnect

How to Rollback1) Rollback command

38

Page 39: notes

2) Rollback to savepointname

Implicit Rollback3) when you switch off;4) hard disk crash5) Power failure

insert into students(rollno, studname) values(7,'rajesh');savepoint a;

insert into students(rollno, studname) values(8,'mudliar');savepoint b;

insert into students(rollno, studname) values(9,'bande');savepoint c;

set autocommit on;now every DML is committed immediately

rollback to b;-third insert statement and savepoint c are undone

rollback to a;-second and third insert statement and savepoint b and c are undone

if only rollback is given then all DML statements after last commit are undone

Objects or User-defined typescreate or replace type address_type as object ( city varchar2(15), state varchar2(20), zip number(7) ); /

create or replace type fullname as object ( fname varchar2(10), mname varchar2(10), lname varchar2(10) );

39

Page 40: notes

/

create table employee ( empno number(3), person fullname, address address_type, salary number(6,2) );

Table EmployeeEmpnoPerson ---- fullname

FnameMnameLname

Address ---- city varchar2(15), state varchar2(20), zip number(7)

insert into employee values(1, fullname('Hemant','Jayawant', 'Pangam'),address_type('Mumbai','Maharashtra',400068), 789.90);

select * from employee;

cannot drop or replace a type when a table is using it hence “drop table employee” and then “drop type address_type;” and “drop type fullname”

nested typescreate or replace type address_type as object ( city varchar2(15), state varchar2(20), zip number(7) ); /

create or replace type personal_type as object(empname varchar2(20),empaddress address_type);/

40

Page 41: notes

create table employee ( empno number(3), person personal_type, salary number(6,2) );

insert into employee values(111,personal_type('Hemant',address_type('Mumbai','Maharashtra',400068)),1000.0)

Character Functions

Select fname||lname from students;

Select fname||’ ‘||lname from students;

Select concat(fname,lname) from students;Select concat(concat(fname,’ ‘),lname) from students;select concat('hemant', 'boy') from dualselect concat('hemant', 'is a boy') from dualselect concat(to_char(rollno),studname) from studentsconcat-used to merge two strings

select lower(studname) from students;lower-displays string in lower case

select upper(studname) from students;lower-displays string in upper case

update students set fname=upper(fname)

select upper(concat(fname,lname)) from students;

To make a query insensitive to the case usedSelect * from students where upper(fname)=’ARUN’;

select initcap(studname) from students;initcap-First character of every string is displayed as capital

select ascii(studname) from students;

41

Page 42: notes

ascii-ascii value of the first character of the string

select chr(65) from dual;chr-character corresponding to the given value

select sysdate from dual;dual is a oracle provided table for such type of temporary operations

select length(studname) from studentlength-to find length of a string

select instr(‘man’,studname) from students

select instr(studname, 'man') from students;select firstname, instr(firstname,'He') from studentsinstr-shows the start position of ‘man’ or ‘He’ in the given string. Case Sensitive. If not found then 0select firstname, instr(firstname,'e',3) from studentsstart searching from 3 character onwardsselect lastname, instr(lastname,'a',1,2) from students;start searching for second occurrence of ‘a’ from 1st character onwards

select lpad(studname,25) from studentsselect lpad(studname,25,'*') from studentslpad-makes the string of specified length by adding the specific character to it’s left. Thus makes it Right Justified

select rpad(studname,25) from studentsselect rpad(studname,25,'*') from studentsrpad-makes the string of specified length by adding the specific character to it’s right. Makes string left justifiedThis is sort of function overloading where same function works differently with different number of parameters.

select ltrim(' Hemant '), sysdate from dual;ltrim-removes the spaces from the left of the string

select rtrim(' Hemant '), sysdate from dual;rtrim-removes the spaces from the left of the string

select ltrim(' * * Hemant ','* '), sysdate from dualto remove blank spaces and *, if any from left

42

Page 43: notes

select trim(' Hemant '), sysdate from dual;trim-removes the spaces from the left and right of the string

select substr(fname,3) from students;Starting from 3rd position upto endselect substr(studname, 2,3) from students;substr-extracts 3 characters from the 2nd position of the specified string

select firstname, substr(firstname,-3) from studentsfrom 3rd last character to end

select firstname, substr(firstname,-3,2) from students2 character from 3rd last

select replace(studname,'H','M') from students;select replace(studname,'H','Man') from studentsselect replace(firstname,'Ja','HH') from studentsreplace-to replace a specified character(s) from a specified string with a specific character(s). Case Sensitive

select replace(firstname,'Ja') from studentssince 3rd parameter is missing, replaces ‘Ja’ with nothing, that is removes Ja

select translate(firstname,'je', 'FK') from studentsreplaces j by F and e by K. Hence the two parameters must be of same length

select translate(firstname,'je', 'F') from studentsreplaces j by F and e by nothing, that is removes e.

select * from students where soundex(firstname)=soundex('Himant');select * from students where soundex(lastname)=soundex(‘Paaangam’) to compare same sounding words. It checks the strings after removing the vowels

Numeric functionsselect maths+science, maths-science, maths*science, maths/science from students

select sqrt(maths) from students;sqrt-square root

select sin(90),cos(90),tan(90) from dualSine, Cosine, Tangent of specified number

select cosh(90), sinh(90), tanh(90) from dual;

43

Page 44: notes

Hyperbolic Sine, Hyperbolic Cosine, Hyperbolic Tangent of specified number

select vsize(123456789) from dualvsize-size of the value in bytes

select vsize(maths) from students;

select science, trunc(science,0) from studentsselect salary, trunc(salary) from employee -- just cuts off all the decimal placesselect salary, trunc(salary,1) from employee -- cuts of to only one decimal placeselect science, trunc(science,1) from studentsselect salary, trunc(salary,-1) from employee truncates to a lesser 10 placeselect salary, trunc(salary,-1) from employee truncates to a lesser 100 placeselect salary, trunc(salary,-1) from employee truncates to a lesser 1000 place

trunc-truncates the value to the specified precision

select sign(-9), sign(0), sign(9) from dual;sign—displays –1,0,1 for negative, zero and positive values

select science, round(science,1) from studentsselect science, round(science,0) from studentsselect salary, round(salary) from employee—rounds to 0 decimal placesselect salary, round(salary,-1) from employee rounds to nearest 10select salary, round(salary,-3) from employee rounds to nearest 100select salary, round(salary,-3) from employee rounds to nearest 1000round-rounds the value to the specified precision

select power(10,2) from dualselect power(10,1/2) from dual gives square rootselect power(1000,1/3) from dual gives cube rootpower—10 raised to power of 2

select abs(-10) from dual; gives the absolute or positive value of any number

update students set maths=0 where rollno=1select nvl(maths,0) from students;nvl-to replace NULL value numbers with the specified number

select mod(10.33,3.10),mod(10,3),mod(10.3,3) from dualremainder of the division

select log(10,10), log(10,20), log(10,1) from dual

44

Page 45: notes

log-log of 10,20 and 1 to the base 10;

select log(10,0) from dual;error since log of 0 to the base 10 is infinity

select english,floor(english), maths,floor(maths), science, floor(science) from students;floor-largest integer smaller than or equal to the given value

select english,ceil(english), maths,ceil(maths), science, ceil(science) from studentsceil-smallest inter larger than or equal to the given value

Date functionsselect sysdate-to_date('31-Jan-05') from dualdifference between two dates in terms of days. The fraction part is the number of hours. If it is .5 it means 12 hours. To get rid of the fractionselect trunc(sysdate-to_date('31-Jan-05')) from dual

select sysdate+1 from dual;

select add_months(sysdate,8) from dual;select add_months(sysdate,-3) from dual;add_months—to add specific months to the given date

select least(to_date('01-Jan-05'), to_date('11-Sep-05'), to_date('31-Dec-06')) from dualgreatest—earliest date from the given list

select localtimestamp from dual;

select months_between(sysdate,to_date('31-Jan-05')) from dualselect months_between(to_date('31-Jan-05'), sysdate) from dual;difference between 2 dates in terms of months. The fraction is the number of days.

select next_day(sysdate, 'Friday') from dualnext_day—gives the date of the specific day(Monday, Tuesday, etc) after the specified dateselect next_day(sysdate-7, 'Friday') from dualfor previous friday

select last_day(sysdate) from duallast day of the month to which the specified date belongs

select to_char(sysdate) from dual;

45

Page 46: notes

to_char—date to character

select to_date('31-Dec-05') - sysdate from dualselect to_date('31-Dec-05') – round(sysdate) from dualround—used to find out the rounded number of days between the two given days. Round on any date set it to 12am if time is before noon, and to 12am of the next day of the time is after noon.

select to_date('31-Dec-05') - trunc(sysdate) from dualtrunc-set the date to 12am of the current day

select current_date from dual;returns date from the current time zone

select current_timestamp from dual;returns date and time from the current time zone

Different Date formats:select to_char(sysdate,'DD/MM/YYYY') from dual; British separatorselect to_char(sysdate,'DD-MM-YYYY') from dual; American separatorselect to_char(sysdate,'DD:MM:YYYY') from dual; French separatorselect to_char(sysdate,'DD.MM.YYYY') from dual; German separatorselect to_char(sysdate,'DD*MM*YYYY') from dual;Italian separator

also try the following :DD/MM/YYYDD-MONTH or DD-MONTH-YYYY - Month in upper caseMonth - Month in lower caseMon/mon/MON in the appropriate case

Select to_char(sysdate,’DAY’) from dual;Try : day, Day, DY, dy, Dy

Select to_char(sysdate,’YEAR’) from dual; gives Two Thousand SixTry : Year

Select to_char(sysdate,'DD') from dual will give 31or 01, etcAlso try : DDTH, DDSP, DDSPTH

Select to_char(sysdate,'MM') from dualAlso try MMTH, MMSP, MMSPTH

Select to_char(sysdate,'D') from dual; day of the week(1,2 ..7)

46

Page 47: notes

Try DTH, DSP,DSPTH in upper or lower case

Select to_char(sysdate,'DDD') from dual; day of the year

Select to_char(sysdate,'W') from dual; week of month(1,2..5)Select to_char(sysdate,'WW') from dual; week of the yearAlso try WWSP, WWSPTH in upper lower case

Select to_char(sysdate,'DD/MM/YYYY HH:MI') from dual;Select to_char(sysdate,'DD/MM/YYYY HH:MI:SS') from dual;By default 12 hour formatFor 24 hour format HH24:MI:SS

Select to_char(sysdate,'DD/MM/YYYY HH:MI:SS am') from dual;Give am or pm for am/pm formatAlso try : AM,a.m., PM, P.M., p.m., etc

Select to_char(sysdate,'DD/MM/YYYY HH:MI:SS a.M.') "IST" from dual to see Indian Standard Time

Select to_char(sysdate-5.5/24,'DD/MM/YYYY HH:MI:SS a.M.') "GMT" from dual to see GMT time

alter session set nls_date_format ='DD/MM/YYYY'to change date format for a session.

LIST FunctionsNVL function for NULLany comparison done with NULL returns NULLselect * from employee where salary=NULLhenceSelect * from employee where salary is NULL

Any calculation with NULL returns NULLSelect 5000+NULL from dual;

select nvl(salary,0)+300 from employee

47

Page 48: notes

nvl is independent of the datatypeSelect nvl(city,’Mumbai) from employees; if city is NULL, it displays ‘Mumbai’.

GreatestSelect salary, greatest(salary,500) from employeeCompares salary of each row with 500 and returns the largest among the two, i.e., if salary is less than 500 returns 500, else returns the actual salary. Can be sued to set a minimum threshold value.

LeastSelect salary, least(salary,500) from employeeCompares salary of each row with 500 and returns the smallest among the two, i.e., if salary is less than 500 returns the salary, else returns 500 Can be sued to set a maximum threshold value.

Greatest and Least can have any number of parameters :select greatest(40,2300,80,5000,30000) from dualselect least(40,2300,10,5000,30000) from dual

Decodeselect decode(deptno, 1,'Sales', 2,'Accounts', 3,'Medical', 'Others') from employeeSimilar to your switch case in C/C++select decode(deptno, 1,salary*2, 2,Salary*3,3,Salary*4, salary*3/2) from employeeUses :Number to Word ConversionEncryption/Decryption

Nvl2select nvl2(salary,10000,5000) from employee;If salary is not null, then a bonus of 10000, else if salary is null, then a bonus of 5000

Nullifselect nullif(salary,567) from employee;Returns NULL if the two values are the same, else returns the first value.

CoalesceSelect coalesce(basic, da, ta) from empsalary;Returns the first NON-NULL value from the list of parameters. All the parameters must be of the same datatype

Caseselect empno,salary,case deptno when 1 then 1.10*salary when 2 then 1.20*salary

48

Page 49: notes

when 3 then 1.30*salaryelse 500end from employee

It works like IF-THEN-ELSE without the need to use procedures.The 2 blue parts and the column in consideration must be all of the same datatype. The else part is optional.

Environment function :Select user from dual;select userenv('sessionid') from dualselect userenv('terminal') from dual;

Numtodsinterval

select numtodsinterval(265, 'HOUR') from dualconverts 265 hours to 11 days and 1 hours, 0 mins, 0 secs

select numtodsinterval(1, 'HOUR') from dualconverts 1 hour to 0 days and 1 hour, 0 mins, 0 secs

select numtodsinterval(265, 'day') from dualconverts 265 days to 265 days and 0 hours, 0 mins, 0 secs

select numtodsinterval(265, 'Minute') from dualconverts 265 minutes to 0 days, 4 hours, 25 mins, 0 secs

select numtodsinterval(265, 'second') from dualconverts 265 seconds to 0 days, 0 hours, 4 mins, 25 secs

numtoymintervalselect numtoyminterval(15, 'month') from dualconverts 15 months to 1 year , 3 months

select numtoyminterval(15, 'year') from dualconverts 15 years to 15 year , 0 months

select numtoyminterval(15.3, 'year') from dualconverts 15.3 years to 15 year , 4 months

to_charselect to_char(sysdate,'dd/mm/yyyy') from dualselect to_char(sysdate,'dd-mon-yyyy') from dual

49

Page 50: notes

select to_char(sysdate,'dd-Mon-yyyy') from dualselect to_char(sysdate,'dd-MON-yyyy') from dualselect to_char(sysdate,'Day-MON-yyyy') from dualselect to_char(sysdate,'Day,dd-MON-yyyy') from dualselect to_char(sysdate,'Day,ddth-MONTH-yyyy') from dualselect to_char(sysdate,'Day,ddth-MONTH-yyyy hh:mi:ss') from dualselect to_char(sysdate,'Day,ddth-RM-yyyy hh24:mi:ss') from dualselect to_char(sysdate,'Day,DDth-RM-yyyy hh24:mi:ss') from dual

to_dateselect to_date('01-Jan-2005') from dualselect to_date('01-Jan-2005',’dd/mm/yy’) from dualselect to_date('01-Jan-2005','dd/MON/yy') from dual

group functionsselect deptno, variance(sal), stddev(sal), sum(sal), avg(sal), max(sal), min(sal), count(*) from emp group by deptno

Table dependent database objects : Views, Index, Synonyms, Sequence

IndexIt is a schema object for faster data access or speed up retrieval of rows by using a pointer. Indexes are maintained automatically by the Oracle Server. It reduces disk I/O by using a rapid path access method

Indexes are created 1)Automatically : A unique index is created automatically when you define a Primary Key or a Unique constraint in a table definition. The name of the index is the name given to the constraint 2) Manually : Users can create non-unique indexes on columns to speed up access to the rows

ORA cannot be forced to use indexes

Suppose you have the following tableRowid Empno Name Salary1 5 aaa2 2 bbb3 3 ggg4 7 mmm5 9 pon6 1 lon7 4 jhg

50

Page 51: notes

8 6 jkl

create index empno_idx on emp(empno)then the internal storage is as follows

select * from user_indexesRowid Empno Name Salary6 12 23 37 41 58 64 75 9

Now if u use a select command likeSelect * from emp where empno=4The search will start from the 4th record onwards and not the 1st record, as empno 4 occurs at the 4th record, if there is no index the search starts from the first record

Create Index emp_last_name_idx on employee(last_name);Create Index emp_last_first_name_idx on employee(last_name, first_name);

When to create an Index : A Table is very large and most queries are expected to retrieve less than 2 to 4 percent of rows.Some of the table’s columns are frequently used together in a WHERE clause of a join conditionA column of a table which is frequently used as a search criteria contains either a large number of NULL values or a wide range of values.The table is not subject to a lot of DML operations, since every DML operation is followed by updation(of reorgansation of all the indexes on the table)

When not to create an Index :The table is quite smallThe table is frequently updated by DML operationsThe columns of the table are not frequently used as a search condition in a queryMost queries are expected to return more than 4 percent of the rowsThe already indexed columns are referenced as part of an expression.Indexes should not be created on dynamic tables, it degrades performance

51

Page 52: notes

Oracle uses index for searching when you use relational operators like =,<,>Index is a database object, hence the most frequently used columns in a where clause must be indexedAll index like PK, unique key and others are dropped when you drop the table

ORA creates index in a B-tree format

Function based Indexes :It is an index based on an expression. They are defined with functions like upper /lower which allow case-insensitive search. The index expression is built from table columns, constants, SQL function or user-defined function as follows :Create Index upper_emp_name_idx on employee(upper(emp_name));This will help in quick search like :Select * from employee where upper(emp_name) =’Tom’;

To ensure that the Oracle server uses the index and dose not carry out full table scan, be sure that the function does not search NULL values. For example, the following statement is guaranteed to used the index, but without the where clause Oracle would have performed a full table scan :Select * from employee where upper(emp_name)=’TOM’ and upper(ename) is not null;

Some other way of creating a unique indexes :Create unique index indexname on tablename(column or columns separated by commas)

Alter table tablename add constraint constraintname primary key(column or columns separated by commas)

To drop an index :Drop index indexname.You cannot modify indexes. You need to drop and recreate it.

User_indexes view contains the name of the index and it’s uniqueness. The user_ind_columns view contains the index name, table name, and the column name.

Select ic.index_name, ic.column_name, ic.column_position, ix.uniqueness from user_indexes ix , user_ind_columns ic where ic.index_name =ix.index_name and

52

Page 53: notes

ic.table_name=’EMPLOYEES’

SynonymsTo refer to a table owned by another user, you need to prefix the table name by the user name. Creation of a synonym avoids this.

It is a pointer to a table/view/sequence/procedure or some other object. It is an alias name for the table/view/sequence. We can have synonym of synonym(alias of alias) It is used when you have access too another user’s table/view/sequence, therefore instead of using that users name as the qualifier for the table/view/sequence, you may create a synonym and use it when required to query the data.

Example login as system/managercreate synonym mysyn for scott.emp;select * from mysyn;

Without the synonym mysyn, to access the table students from the user scott, you would have to give the following :Select * from scott.emp

select * from user_synonyms;

Simplifies access to objects by creating a synonym. It allows easy reference to a table owned by another user. Shortens lengthy object names

The synonym can be created by the object owner(if he has sufficient privileges to create a synonym) or system admin. The synonym name can be used by all users to whom the database owner/system admin has granted some rights on that table for which the synonym has been created. To allow all users who have got rights on that table, we can create a public synonym as follows :

Create public synonym synonymname for object;

Sequences

Automatically generates unique numbersIs a sharable objectTypically used to create primary key valuesSpeeds up the efficiency of accessing sequence-values when they are cached in memory.Can be used by multiple users to generate unique numbers.The sequence is generated and incremented/decremented by an internal Oracle routine..Sequence numbers are stored and generated independently of tables. Hence same

53

Page 54: notes

sequence can be used for multiple tables.

They are used to assign unique numbers to NEW rows being inserted into a table, or old rows being updated in the table.

create sequence myseq increment by 1 start with 100;

select sequence_name, min_value, max_value, increment_by, last_number from user_sequences;check the last_number, it is equal to 100

insert into students(rollno, studname) values(myseq.nextval,'abc');

select sequence_name, min_value, max_value, increment_by, last_number from user_sequences;check the last_number, it is equal to 120

insert into students(rollno, studname) values(mysequence.nextval,'pqr');

select sequence_name, min_value, max_value, increment_by, last_number from user_sequences;check the last_number, it is equal to 120This is because Oracle caches 20 values or Oracle pre-allocates 20 values and keeps them in memory for use.

update students set rollno=myseq.nextval where rollno=269update students set rollno=mysequence.nextval where rollno=121

select myseq.currval from dual; show the latest number assigned

You can use the mysequence.currval to update records in some other transaction table;

Create sequence sequencename Increment by n Start with n Maxvalue n Minvalue n Cycle/Nocycle Cache n/Nocache;

If increment is not given , it increment by 1;If start with is not given, it starts with 1;Maxvalue n specifies maximum value sequence should generate. If it is not given maximum value is 10^27 for an ascending sequence or –1 for descending.Minvalue specifies minimum value sequence should generate. If it is not given minimum value is 1 for an ascending sequence or –(10^26) for descending.

54

Page 55: notes

Cycle/Nocycle : Nocycle is the default. If cycle then the sequence will generate values even after the maximum/minimum value is reached. This is useful when you alter the sequence with a new maxvalue/minvalue Cache n specifies the number of values that Oracle should pre-allocate and keep in memory

NEXTVAL and CURRVAL pseudocolumns :When you use sequencename.nextval, a new sequence number is generated. The sequencename.currval is referenced to see the last value returned to the user. Example :Insert into department(departmentno, departmentname) values (dept_seq.nextval,’Accounts’);This will generate a new sequence number and put the current value of the sequence dept_seq into the table department and will also put the current value into the currvalSo to insert employees for this new department which is just inserted into the department table we use the following :Insert into employees(empid, empname, departmentno) values (employees_seq.nextval, ‘Manoj’, dept_seq.currval);

If you reach the maximum value limit, no new values are generated and you will receive an error message. You can alter the sequence to set a new max value

Alter sequence sequencename Increment by n Maxvalue n Minvalue n Cycle/Nocycle Cache n/Nocache;You cannot change the start value with alter sequence command. To change the start number you need to drop and recreated the sequence.

To drop a sequenceDrop Sequence Sequencename;

Controlling User Access

Privileges are the right to execute a particular SQL Statement. The Database Administrator(DBA) is the highest level user who grants users access to the database and it’s objects. The users require System Privileges to gain access to the database and Object Privileges to manipulate the contents of the objects in the database.Hence, Database Security is of 2 categories :1) System Security which covers access and use of the database at the system level,

such as username and password, disk space allocated to users, and system operations that a user can perform.

2) Database security covers access and use of the database objects and the actions that those users can have on the objects.

55

Page 56: notes

Schema : A schema is a collection of objects such as tables, views, sequences, etc. The schema is owned by the database user and has the same name as that user.

System Privileges :The DBA has more than 100 high-level system privileges for tasks such as : CREATE USER; DROP USER; CREATE, BACKUP, SELECT and DROP a Table in any schema.

To create a new user, the DBA does the following :Create User Username Identified By Password;

This will just create a new user, who has no privileges as of now. To grant specific privileges to the new user, the DBA uses the GRANT Command as follows :

Grant privilge1, privilege2, etc to Username;Typical User System privileges are :Create Session(To connect to the database)Create Table(To create table in the user’s own schema)Create Sequence(To create a Sequence in the user’s own schema)Create View(To create a view in the user’s own schema)Create Procedure(To create stored procedure, function, or package in the user’s own schema)Roles :A role is a named group of related privileges that can be granted to the users. This makes it easy to manage users and privileges. The DBA create a role, then grants rights to that role, and then grants that role to other users as follows :

Create Role rolename

Grant Create session, Create table, Create view to rolename

Grant rolename to user1, user2, etc.

I can also grant Connect, Resource roles to a new role as follows

Create role myrole

Grant Connect, Resource to myrole

Create user hemant identified by hemant123

Grant myrole to hemant

56

Page 57: notes

Three Standard Roles :1) Connect

This role gives the users the ability to log in and perform basic operations. Along with this role, the user should be granted access to specific tables of other users, and the privileges to SELECT, INSERT, UPDATE and DELETE from those table. Without all such rights, only the connect role granted to a user makes no sense, and will just allow the user to login.

2) ResourceThe RESOURCE role gives the user the right to create, alter, drop his own tables, sequences, indexes, triggers, clusters, datatypes, views, etc.

3) DBAThis role has all the system privileges-including unlimited space, and the ability to grant all privileges to other users.

The DBA can also change user passwords as follows :Alter user username identified by password

Object PrivilegesAn object privilege is a privilege to perform a particular action on a specific table, view , sequence or procedure

Privilege Table View Sequence ProcedureAlter -- --Delete -- --Execute --Index --Insert -- --References -- --Select -- -- --Update -- --

-- indicates whether or not a right or object privilege of that type can be granted on the specific objects in the first row.

Object privileges vary from object to object. The owner has all the privileges on that object. The owner can give specific privileges on that object to other users.

GRANT Object_privilege(s)[column(s)]/ALL on OBJECT To USER(s)/Role(s)/Pubic [WITH

57

Page 58: notes

GRANT OPTION]

Object_privilege—is the object privilege like Alter, Select, Execute, etcALL—specifies that all object privileges Columns—Specifies the columns from a table/view on which the privileges should be grantedOn Object -—specifies the object on which the privileges are to be grantedTo User/Role/Public—specifies the user or role or public(meaning all users) to whom the privileges must be granted.With Grant Option – Allows users to whom the privilege has been granted to further grant those privileges to other users. When the object owner revokes the privileges granted to a user with the With Grant Option, the ability of that user to grant rights on that object to other users is also automatically revoked.

To revoke a privilege :Revoke Privilege(s)/ALL On Object From User(s)/Role(s)/Public Cascade ConstraintsCascade Constraints -- to remove any referential integrity constraints made to the object by means of the References privilege.

Database LinkA Database Link is a one-way pointer that defines a communication channel from an Oracle Database Server to another Oracle Database Server. The entry of this link pointer is maintained in the Data-Dictionary table of the Server on which the Link was created. Therefore, to use the link you must be connected to the local database that contains the data-dictionary entry about the link. The Link is one-way in the sense that a client connected to the local database(say A) in which the link entry is stored to access the remote database(say B) can access the remote Database B, but a user connected to Database B cannot access the Database A. The DBA is responsible for creating such links between distributed databases, where each of the database in a distributed database must have a Unique Global Name. The Data-dictionary view USER_DB_LINKS contains the information about such links.

Create Public Database Link abc.pqr.com Using ‘DPR”;

Here abc.pqr.com is the name for the link The Using clause specifies the Connection string or service name of the remote Oracle DatabaseNow, you can select data from the emp table on the remote database as follows :Select * from emp @abc.pqr.com

To avoid this long name, you may create a synonym as followsCreate Public Synonym mysyn rmemp for [email protected]

And now, you may :

58

Page 59: notes

Select * from mysyn;

You cannot Grant privileges to others on remote objects.

Grouping FunctionGrouping Function returns 0, if the column pass to it as parameter is us to calculate the aggregate value(summary of summary), else returns 1. It can be us with both Cube and Rollup. The column pass as parameter to the GROUPING function must be present in the Group By Clause

create table employees(companyid varchar2(5),deptid varchar2(5),jobid varchar2(5),empid varchar2(5),empname varchar2(20),salary number(5));

insert into employees values('C1','D1','J1','E1','Hemant',8798);insert into employees values('C1','D1','J1','E2','Hema',879)insert into employees values('C1','D1','J1','E3','Seema',8879)insert into employees values('C1','D1','J2','E4','Rahul',878);insert into employees values('C1','D1','J2','E5','Rahul',78)insert into employees values('C1','D2','J1','E6','Rohan',798)insert into employees values('C1','D2','J1','E7','Sam',98)insert into employees values('C1','D2','J1','E8','Sameer',598)insert into employees values('C1','D2','J2','E9','Sachin',98)insert into employees values('C2','D1','J3','E10','Soham',988)insert into employees values('C2','D1','J3','E11','Rajesh',9988)insert into employees values('C2','D1','J3','E12','Mahesh',998)insert into employees values('C2','D1','J1','E13','Mahesh',98)insert into employees values('C2','D1','J1','E14','Somesh',948)insert into employees values('C2','D2','J1','E14','Yuvraj',48)insert into employees values('C2','D2','J1','E15','Kaif',648)insert into employees values('C2','D3','J1','E15','Saif',9648)insert into employees values('C3','D1','J1','E16','Haif',948)insert into employees values('C3','D1','J1','E17','Ram',978)insert into employees values('C3','D1','J1','E18','Tom',78)insert into employees values('C3','D1','J5','E19','Dick',788)insert into employees values('C3','D1','J5','E20','Harry',88)insert into employees values('C3','D2','J1','E21','Laxman',898)insert into employees values('C3','D2','J1','E22','Bharat',98)insert into employees values('C3','D1','J1','E23','Ryan',698)

59

Page 60: notes

insert into employees values('C3','D1','J1','E23','Rehan',6898)insert into employees values('C3','D1','J2','E24','Ketan',778)insert into employees values('C3','D1','J2','E24','Hetal',78)

select companyid, deptid, sum(salary),GROUPING(Companyid) Company_GRP,GROUPING(Deptid) Dept_GRPFrom employeesGroup By Rollup(Companyid, Deptid)

select companyid, deptid, sum(salary),GROUPING(Companyid) Company_GRP,GROUPING(Deptid) Dept_GRPFrom employeesGroup By Cube(Companyid, Deptid)

select companyid, deptid, jobid,sum(salary),GROUPING(Companyid) Company_GRP,GROUPING(Deptid) Dept_GRP,GROUPING(Jobid) Job_GRPFrom employeesGroup By Rollup(Companyid, Deptid,jobid)

select companyid, deptid, jobid,sum(salary),GROUPING(Companyid) Company_GRP,GROUPING(Deptid) Dept_GRP,GROUPING(Jobid) Job_GRPFrom employeesGroup By Cube(Companyid, Deptid,jobid)

Grouping SETS

It allows you to specify the Sets of column-groups for which you want to see the aggregates, instead of seeing all possible combinations.

select companyid, deptid, jobid,sum(salary)From employeesGroup By Grouping Sets ((Companyid, Deptid),(Companyid, jobid))

60

Page 61: notes

select companyid, deptid, jobid,sum(salary)From employeesGroup By Grouping Sets ((Companyid, Deptid),(Companyid, jobid),(Deptid, Jobid))

select companyid, deptid, jobid,sum(salary)From employeesGroup By Grouping Sets ((Companyid, Deptid),(Companyid, jobid), (Companyid, deptid,jobid))

Composite Columns

A Composite column is a collection of columns that should be treat as a single unit while calculating the aggregates

select companyid, deptid, jobid,sum(salary)From employeesGroup By Rollup (Companyid, (Deptid,jobid))

select companyid, deptid, jobid,sum(salary)From employeesGroup By Cube(Companyid, (Deptid,jobid))

Concatenated Groupings

In general Group By Grouping Sets(a,b), Grouping Sets(c,d) would generate :(a,c),(a,d), (b,c), (b,d)

select companyid, deptid, jobid,sum(salary)From employeesGroup By Grouping Sets (Companyid, Deptid),Grouping Sets(Companyid, jobid)

Generates aggregates for (Companyid, Deptid),(Companyid, jobid) and (Deptid, Jobid)

select companyid, deptid, jobid,sum(salary)From employeesGroup By Companyid, Rollup(Deptid), Cube(jobid)

Generates aggregates for (Companyid,deptid, jobid), (Companyid, jobid), (Companyid, deptid), (Companyid)

61

Page 62: notes

SubQueries :

Create table employees(empid varchar2(3),empname varchar2(20),mgrid varchar2(3),deptid varchar2(3));

insert into employees values('E1','Hemant',NULL,'10');insert into employees values('E2','Hetal','E1','10')insert into employees values('E3','Sheetal','E1','10')insert into employees values('E4','Ram','E1','10')insert into employees values('E5','Shyam','E2','10');insert into employees values('E6','Tom','E2','10')insert into employees values('E7','Harry','E2','20')insert into employees values('E8','Ryan','E1','20')insert into employees values('E9','Sheryl','E1','20')

Pairwise Comparison

select empid, empname, mgrid,deptid from employeeswhere (mgrid,deptid) IN (Select mgrid,deptid from employeeswhere empid in ('E2','E6'))All employees who belong to the same dept as E2 and to the same Manager as E2And All employees who belong to the same dept as E6 and to the same Manager as E6

select empid, empname, mgrid,deptid from employeeswhere (mgrid,deptid) IN (Select mgrid,deptid from employeeswhere empid in ('E2','E6'))All employees who belong to the same dept as E2 or E6 and to the same Manager as E2Or E6

Sub-Query in the From Clause(Inline View)

EMPID EMPNAME MGRID DEPID SALARY

E1 Hemant 10 4500E2 Hetal E1 10 500E3 Sheetal E1 10 5500E4 Ram E1 10 5768

62

Page 63: notes

E5 Shyam E2 10 768E6 Dick E2 20 7698E7 Harry E2 20 698E8 Ryan E1 20 69E9 Sheryl E1 20 6679select a.empname, a.salary,b.salavg from employees a,(select deptid, avg(salary) salavg from employees group by deptid) b where a.deptid=b.deptid and a.salary>b.salavg

Sub-Query in the CASE Expression

Select empid, empname,(CaseWhen deptid=(Select deptid from employees where empname=’Shyam’) Then ‘Mumbai’Else ‘Outsiders’END) locationFrom employees

Sub-Query in the Order By Expression

DEPTNO DEPTNAME------------ ------------------10 Mical20 Accounts

EMPID EMPNAME MGRID DEPID SALARY--- -------------------- --- --- ----------E1 Hemant 10 4500E2 Hetal E1 10 500E3 Sheetal E1 10 5500E4 Ram E1 10 5768E5 Shyam E2 10 768E6 Dick E2 20 7698E7 Harry E2 20 698E8 Ryan E1 20 69

Select e.empid, e.empname,e.deptid from employees e order by (Select deptname from dept d where e.deptid=d.deptno)

63

Page 64: notes

In the alphabetical order by department name

Correlated SubQuery

Unlike a normal nest query, in a correlated sub query, the inner query is driven by the outer query. Each time a row from the outer query is process, the inner query is evaluated

Select empid, empname,deptid from employees e where salary>(select avg(salary) from employees d where d.deptid=e.deptid)

Here for every row of e, the salary of employees is compared with the average salary from d calculated department wise

Subquery Using Exists

The Exists Operator returns TRUE, if the subquery returns at least one row.

To find out all employees who have at least one employee reporting to themSelect empid, empname, deptid from employees e where EXISTS( Select 'X' from employees where mgrid=e.empid)

To find out all employees who have no employee reporting to themSelect empid, empname, deptid from employees e where NOT EXISTS( Select 'X' from employees where mgrid=e.empid)

Correlated UPDATETo update outer table bas on rows of the inner table.

alter table employees add deptname varchar2(10)

EMPID EMPNAME MGRID DEPID SALARY Deptname

E1 Hemant 10 4500E2 Hetal E1 10 500E3 Sheetal E1 10 5500E4 Ram E1 10 5768E5 Shyam E2 10 768

64

Page 65: notes

E6 Dick E2 20 7698E7 Harry E2 20 698E8 Ryan E1 20 69

Update employees e set deptname=(select deptname from dept d where e.deptid=d.deptno)

Correlated UPDATETo delete rows from outer table bas on rows of the inner table.

Suppose there are two tables : Employees and Employees_History. The Employees table contains details of all current employees and Employees_History table contains rows of retired employees. Let us assume a situation where due to some reasons some retired employees’s records are also present in the current employees table and you have to delete all such records.

Delete from employees e where empid=(select empid from employees_history ee where ee.empid=e.empid)

WITH Clause

In case of very complex queries where a query block may be required frequently in a SELECT statement, the WITH clause can be us to retrieve the results of the query block and store it in the user’s temporary table space, and use it whenever required

Withdept_costs as (select d.deptname, sum(e.salary) as dept_total from employees e, dept d where e.deptid=d.deptno group by d.deptname),avg_cost as (select sum(dept_total)/count(*) as dept_avg from dept_costs)select * from dept_costs where dept_total>(select dept_avg from avg_cost)

Hierarchical Queries

create table emp(empid number(3), empname varchar2(20), mgrid number(3));

insert into emp values(100,'Hemant',NULL);insert into emp values(101,'Hema',100)insert into emp values(102,'Hetal',100)insert into emp values(103,'Manoj',100)insert into emp values(104,'Heena',100)insert into emp values(105,'Seema',101)

65

Page 66: notes

insert into emp values(106,'Reema',101)insert into emp values(107,'Reema',102)insert into emp values(108,'Rahul',103)insert into emp values(109,'Rohan',103)insert into emp values(110,'Rina',103)insert into emp values(111,'Tina',103)insert into emp values(112,'Fardeen',104)insert into emp values(113,'Salim',104)insert into emp values(114,'Rahim',104)insert into emp values(115,'Rohini',106)insert into emp values(116,'Prashant',107)select empid, empname,mgrid from emp start with empid=110 connect by prior mgrid=empid;

Bottom approachselect empid, empname,mgrid from emp start with empid=110 connect by prior mgrid=empid;

select level, empid, empname,mgrid from emp start with empid=110 connect by prior mgrid=empid

Current records empid=previous records mgrid

Top Down approachselect level, empid, empname,mgrid from emp start with empid=102 connect by prior empid=mgrid

select level, empid, empname,mgrid from emp start with empid=103 connect by prior empid=mgrid

Current records mgrid=previous records empid

Using Level and Lpadselect lpad(empname,length(empname)+(level*2)-2,'*') as orgchart from emp start with empid=100 connect by prior empid=mgrid

MultiTable InsertsUnconditional Insert AllAll the rows retrieved by the Select statement are inserted into the target tables

Insert all into employees1(empid,empname) values(empid,empname)into employees2(empid,salary) values(empid, salary)select empid, empname, salary from employees where salary>5000

If the column names in the source and target tables are different then make use of alias namesInsert all into employees1(EMPNO,ENAME) values(EMPNO,ENAME)

66

Page 67: notes

into employees2(EMPNO,SAL) values(EMPNO,SAL)select empid EMPNO, empname ENAME, salary SAL from employees where salary>5000

If the emplyees1 table contains only 2 fields empid, empname; and employees2 table contains only 2 fields empid, salaryInsert all into employees1 values(empid,empname)into employees2 values(empid, salary)select empid, empname, salary from employees where salary>5000

Conditional Insert AllRecords retrieved by the select statement are further filtered by using conditions

Insert all when salary>600 then into employees1(empid,empname) values(empid,empname)When salary>4000 then into employees2(empid,salary) values(empid, salary)select empid, empname, salary from employees

Insert all when salary>10 and salary<700 then into employees1(empid,empname) values(empid,empname)When salary>700 then into employees2(empid,salary) values(empid, salary)select empid, empname, salary from employees where deptid=10

Conditional First InsertFor all the rows that are inserted into the first table, the subsequent when clauses are not evaluated. All the remaining rows are inserted into the tables E2 and E3 as per the conditions given with the When clause. Rows retrieved, but not satisfying any of the When clauses are inserted into E4

Insert First when salary>10 and salary<700 then into employees1(empid,empname) values(empid,empname)When salary<100 then into employees2(empid,salary) values(empid, salary)When salary>1000 and salary<5000 then into employees3(empid,salary) values(empid, salary)elseinto employees4(empid,salary) values(empid, salary)select empid, empname, salary from employees

Pivoting InsertTo convert each row from a table(relational/non-relational table) into n rows into the target relational table

67

Page 68: notes

create table emp_source(empid varchar(2), month varchar2(15), sales1 number(5), sales2 number(5), sales3 number(5), sales4 number(5));

insert into emp_source values('1','Jan',87,6876,765,76);insert into emp_source values('1','Feb',387,876,65,476)

create table emp_target(empid varchar2(2), month varchar2(15),sales number(5));

insert all into emp_target values(empid,month, sales1) into emp_target values(empid, month, sales2) into emp_target values(empid, month, sales3) into emp_target values(empid, month, sales4) select empid, month, sales1, sales2, sales3, sales4 from emp_source

PLSQLcreate table students(rollno number(3) primary key,studname varchar2(20),english number(3,2),maths number(3,2),science number(3,2),total number(3,2),constraint chk_eng check(english<=100),constraint chk_maths check(maths<=100),constraint chk_science check(science<=100))

insert into students values(1,'Hetal',97.90,99.00, 56.48,0)

alter table students modify(english number(5,2),maths number(5,2),science number(5,2),total number(5,2));

insert into students values(1,'Hetal',97.90,99.00, 56.48,0);insert into students values(2,'Hemant',67.60,45.00, 44.44,0);

update students set total=english+maths+science;

68

Page 69: notes

PL/SQL Block to display the name, total of rollno=1set serveroutput on - for dbms to give output

declarevname students.studname%type;vtotal students.total%type;

beginselect studname into vname from students where rollno=1;select total into vtotal from students where rollno=1;dbms_output.put_line('Name of Student is :'||vname);dbms_output.put_line('Total of Student is :'||vtotal);

end;/

/ - to execute the PL/SQL Code

PL/SQL Block to display "Very Good Student", if total of Rollno=1 is more than 275, else display "Average student"

declarevname students.studname%type;vtotal students.total%type;

beginselect studname into vname from students where rollno=1;select total into vtotal from students where rollno=1;

if vtotal>=250 thendbms_output.put_line(Vname||' is a very good student');

elsedbms_output.put_line(Vname||' is an average student');

end if;end;/

PL/SQL Block to display "Very Good Student", if total of Rollno=1 is more than 275, "Average student" if total between 250 and <275, and "poor student" if total less than 250

declarevname students.studname%type;vtotal students.total%type;

beginselect studname into vname from students where rollno=1;

69

Page 70: notes

select total into vtotal from students where rollno=1;

if vtotal>=275 thendbms_output.put_line(Vname||' is a very good student');

elsif vtotal>=250 and vtotal<275 thendbms_output.put_line(Vname||' is an average student');

elsedbms_output.put_line(Vname||' is a poor student');

end if;end;/

LOOPS 1) For <variable> in [reverse] lowvalue..highvalue

loopstatement1;statement2;

end loop

Numbers 1 to 10 in orderdeclare

num number(2);begin

for num in 1..10loop

dbms_output.put_line('number '|| num);end loop;

end;/

Numbers 1 to 10 in reverse orderdeclare

num number(2);begin

for num in reverse 1..10loop

dbms_output.put_line('number '|| num);end loop;

end;/

Print odd and even numbers from 1 to 20 and their count

70

Page 71: notes

declarea number:=0;

b number:=0;begin For x in 1..20 loop if mod(x,2)=0 then dbms_output.put_line('Number '||x||' is Even'); a:=a+1; else dbms_output.put_line('Number '||x||' is Odd'); b:=b+1; end if; end loop; dbms_output.put_line('There are '||a||' even numbers'); dbms_output.put_line('There are '||b||' odd numbers');end;/

While <condition>loop

statement1;statement2;

end loop;

print 10,20,30,...100declare

num number:=10;begin

while num<=100loop

dbms_output.put_line(num);num:=num+10;

end loop;end;/

loopstatement1;statement2;

71

Page 72: notes

exit when <condition>;end loop;

print 5.10,15,20,....,50declare

num number:=5;begin

loopdbms_output.put_line(num);num:=num+5;

exit when num>50;end loop;

end;/

Exception Handling1)no_data_found2)too_many_rows3)value_error4)zero_divide

declarevtotal students.total%type;

beginselect total into vtotal from students where rollno=16;dbms_output.put_line('the roll number is not correct');

exceptionwhen no_data_found then

dbms_output.put_line('Check the roll number');end;/

Here, since the data is not found, an error has occurred and the control is transferred to the exception handler, and the line which is after the line that caused the error is not executed, since when the error is encountered, the control is not passed to the immediate next line, but to the exception handler.

declarevtotal students.total%type;

beginselect total into vtotal from students where total>100;

exception

72

Page 73: notes

when too_many_rows thendbms_output.put_line('More than 1 row selected');

end;/

User Defined Exception1)declare 2)raise 3)handle the exceptiondeclare

low_mark exception;venglish students.english%type;

beginselect english into venglish from students where rollno=2;if venglish<35 then

raise low_mark;end if;

exceptionwhen low_mark then

dbms_output.put_line('Failed in English');end;/if marks in english are less than 35 then the exception is raised and the message is displayed.

Nested Blocks which means declare....begin...end within the begin of an outer declare....begin...enddeclare

y number:=10;m number:=15;

begindeclare

x number:=20;m number:=5;

begindbms_output.put_line('x,y, m for inner block');dbms_output.put_line('x is :'||x);dbms_output.put_line('y is :'||y);dbms_output.put_line('m is :'||m);

end;dbms_output.put_line('x,y, m for outer block');dbms_output.put_line('x is :'||x);dbms_output.put_line('y is :'||y);dbms_output.put_line('m is :'||m);

73

Page 74: notes

end;/

it will display an error related to declaration of variable x, and none of the variables will be displayed since the entire block is ignored because of the errorSo, comment the line which displays x in the outer block as follows :

declare y number:=10; m number:=15; begin declare x number:=20; m number:=5; begin dbms_output.put_line('x,y, m for inner block'); dbms_output.put_line('x is :'||x); dbms_output.put_line('y is :'||y); dbms_output.put_line('m is :'||m); end; dbms_output.put_line('x,y, m for outer block'); -- dbms_output.put_line('x is :'||x); dbms_output.put_line('y is :'||y); dbms_output.put_line('m is :'||m); end; /

multi row processing or CURSORS1)declare 2)Open 3)Fetch and process 4)closeto print the name, total of all the studentsdeclare

cursor cstudent is Select Rollno,studname,total from students;vrollno students.rollno%type;vname students.studname%type;vtotal students.total%type;

beginOpen cstudent;loop

fetch cstudent into vrollno, vname, vtotal;exit when cstudent%notfound;dbms_output.put_line('Roll number :'||vrollno);dbms_output.put_line('Name :'||vname);dbms_output.put_line('Total :'||vtotal);

74

Page 75: notes

end loop;close cstudent;

end;/

Here. exit when cstudent%notfound should be done immediately after fetch, or else the last record will be displayed twice. "notfound" is a cursor attribute which is used to find whether the cursor currently contains a record or has reached the end of the file or recordset

%rowtype

declare x students%rowtype;begin select * into x from students where rollno=1; dbms_output.put_line('Name :'||x.studname); dbms_output.put_line('Rollno :'||x.rollno); dbms_output.put_line('English :'||x.english); dbms_output.put_line('Maths :'||x.maths); dbms_output.put_line('Science :'||x.science); dbms_output.put_line('Total :'||x.total);end;/

user defined datatypes

declaretype mytype is record(

x varchar2(30),y number(5,2)

);lmn mytype;

beginselect studname, total into lmn from students where rollno=2;dbms_output.put_line('Name '||lmn.x);dbms_output.put_line('Total '||lmn.y);

end;/

declarex number:=5;

75

Page 76: notes

y number:=1;begin

while x<=20 loop

x:=x+y;dbms_output.put_line('x is '||x);if x=10 then

goto abc;end if;

if x=16 thengoto pqr;

end if;end loop;

<<abc>>dbms_output.put_line('Hello Man');y:=2;

<<pqr>>dbms_output.put_line('Hello Brother');

end;/

Local Functions : Not stored in databasedefined and called within the same programfunctions do not have declare. if it is necessary to declare a variable it should be done in the declare part of the enclosing programdeclare

x number;function f1 return number isbegin

dbms_output.put_line('Inside the function');return 10;

end;

begindbms_output.put_line('Inside the Main');x:=f1;dbms_output.put_line('value of x is'||x);

76

Page 77: notes

end;/

Global or stored functionStored in the databaseDefined and saved separately, can be called thru another pl/sql block

try the following on emp in scotted f1;

create or replace function chkemp(veno number)return boolean isvsal emp.sal%type;

beginselect sal into vsal from emp where empno=veno;dbms_output.put_line('salary is '|| vsal);return true;

exceptionwhen no_data_found thendbms_output.put_line('salary is not found');

return false;

end;/at the sql prompt :>show_error;

to show the errors in the function coding;

to execute>@f1;

main blockdeclare y number :=&eno; flag boolean;begin flag:=chkemp(y); if flag=True then dbms_output.put_line('Employee Existing'); else dbms_output.put_line('Employee Not Existing');

77

Page 78: notes

end if;end;/

stored function to update the salaries of employees getting less than 3000 with increment of % percent

create or replace function upsal(veno number, inc number)return number is

vsal number;begin

update emp set sal=sal+(sal*inc/100) where empno=veno;commit;select sal into vsal from emp where empno=veno;return vsal;

end;/

select text from user_source where type ='FUNCTION' and name='UPSAL' order by line

main pl/sql blockdeclare

cursor c1 is select empno, sal from emp where sal<3000;incr number :=&incr;incsal number;

beginfor erec in c1loop

incsal:=upsal(erec.empno, incr);dbms_output.put_line('Increased salary is '||incsal||' for employee '||

erec.empno);end loop;

end;/

With input parametercreate or replace function getavg(xyz in number) return number as

lmn number; begin select avg(total) into lmn from students;

78

Page 79: notes

if lmn is NULL then lmn:=-1; end if; return lmn; exception when others then return -2; end getavg;/declare

avgtot number;begin

avgtot:=getavg(1);dbms_output.put_line(avgtot);

end;/

Without input parametercreate or replace function getavg return number as lmn number; begin select avg(total) into lmn from students; if lmn is NULL then lmn:=-1; end if; return lmn; exception when others then return -2; end getavg; /

declare avgtot number; begin avgtot:=getavg(); dbms_output.put_line(avgtot); end; /

79

Page 80: notes

Local procedurescan accept n number of parametercan return n number of values

declareprocedure p1 isbegin

dbms_output.put_line('P1 is called');end;

beginp1;dbms_output.put_line('In the main block');

end;/

declareprocedure p1;procedure p2 isbegin

dbms_output.put_line('p2 called');p1;

end;

procedure p1 isbegin

dbms_output.put_line('p1 called');p2;

end;begin

p1;dbms_output.put_line('In the main block');p2;

end;/

it will show error : p1 must be declared(if procedure p1; is not types as line 1)The result is an infinite loop, and dbms.... is never executed.

Global or stored proceduresStored Procedure to display employee numbers and their salaries for department 10

create or replace procedure retemp(veno IN number, vename OUT varchar2, vsal OUT number)

80

Page 81: notes

isbegin

select ename, sal into vename, vsal from emp where empno=veno;end;/

main block

declarecursor c1 is select empno from emp where deptno=10;ve emp.ename%type;vs emp.ename%type;

beginfor erec in c1loop

retemp(erec.empno, ve, vs);dbms_output.put_line('Employee number is '||erec.empno);dbms_output.put_line('Employee name is '||ve);dbms_output.put_line('Employee salary is '||vs);

end loop;end;/

stored procedure to show increase in salary by 10 percent for all employees and an additional 5 percent for those who have completed more than 5 years of service

create or replace procedure retemp(veno IN number, vsal IN OUT number, year IN number) is begin if year>=60 then vsal:=vsal*1.05; end if; end; /

main plsql block declare cursor c2 is select empno, sal, hiredate from emp; vsal1 emp.sal%type; vdate1 emp.hiredate%type; years number; begin

81

Page 82: notes

for rec in c2 loop dbms_output.put_line('Employee number '||rec.empno); dbms_output.put_line('Employee salary '||rec.sal); vsal1:=rec.sal*1.1; dbms_output.put_line('Employee salary '||vsal1); select months_between(sysdate,hiredate) INTO YEARS from emp where empno=rec.empno; retemp(rec.empno,vsal1, years); dbms_output.put_line('Employee salary '||vsal1); end loop; end;/

TriggersThey are fired on events : Insert, Update, DeleteThey are fired on time : Befor or After

Levels of Triggers : 1)Statement levelused to put restrictionsBy default triggers are statement levelExample:Create or replace trigger t1before update on empbegin

end;

2)Row levelUsed for auditing purposeExample:Create or replace trigger t1before update on empfor each rowbegin

end;

Have to be specified as row levelTriggers cannot have Transaction Control statementsTriggers can have declaration partEven a function or procedure called by a trigger cannot have transaction Control

82

Page 83: notes

Statements.

Auditing: PL/SQL provides two system variables :old and :new which belong to a %rowtype. They can be used only for row level triggers, since they hold the values of the current record which is updated, inserted or deleted

update : :old, :newinsert : :newdelete : :old

Write a trigger for emp table for the delete operation. Deleted value along with date of deletion and user who deleted the record should be stored

for this we create the following table

create table auditemp(eno number(4), deldate date, username varchar2(20));

create or replace trigger chkemp after delete on empfor each rowbegininsert into auditemp values(:old.empno, sysdate, user);end;/

select user from dual;select * from auditemp;--you will see the recordrollback; -- the record from auditemp is removed

write a trigger to restrict a user from doing any DML operation on the table emp before 9.00am and after 5.00pm

create or replace trigger timechk before insert or update or delete on emp begin if to_number(to_char(sysdate,'hh24')) NOT BETWEEN 09 and 17 then raise_application_error(-20001, 'you are timed out'); end if; end;/

83

Page 84: notes

3 errors:error at line nerror 'You are timed out'error in execution of triggername

write a trigger to restrict a user from doing any DML operation on the table emp on saturdays and sundays and if the username does not belong with the letter "lib" after 5.00pm

create or replace trigger mycheck before insert or update or delete on emp declare weekend_error EXCEPTION; Not_valid_user EXCEPTION; begin if to_char(sysdate, 'DY')='SAT' or to_char(sysdate, 'DY')='SUN' then RAISE weekend_error; end if; if substr(user, 1,3)<>'LIB' then RAISE Not_valid_user; end if; EXCEPTION when weekend_error then raise_application_error(-20222,'Not allowed on weekends'); when Not_valid_user then raise_application_error(-20226,'Not a valid person'); end; /

3 errors:error at line nerror 'Not allowed on weekends' or 'Not a valid person'error in execution of triggername

Trigger on emp table for deletion and updation of salary. If the employee has some loan pending in a loan table then display appropriate messages

create table loan (empno number, amount number(4));

insert into loan values(7369, 2000);insert into loan values(7499, 2000);

84

Page 85: notes

insert into loan values(7521, 2000);insert into loan values(7566, 2000);insert into loan values(7654, 2000);

create or replace trigger loanchk before delete or update of sal on emp for each row declare lamt number; begin select amount into lamt from loan where empno=:old.empno; if lamt>0 then raise_application_error(-20121, 'Loan Exists'); end if; exception when no_data_found then dbms_output.put_line('No loan taken'); end; /

drop any other triggers on emp to avoid mixup

delete from emp where empno=7934;Out put : No loan taken

delete from emp where empno=7369;3 errors as earlier

Create Trigger which will keep a track of emp table in such a way that if the updated salary is less than the current salary then a table audit will be maintained to store the empno, date of updation of salary, current salary, updated salary and the difference

Create table auditsal(empno number(4),update date,cursal number(7,2),newsal number(7,2),saldif number(7,2));

85

Page 86: notes

create or replace trigger chksal after update of sal on emp for each row when(new.sal<old.sal) begin insert into auditsal values(:old.empno, sysdate, :old.sal, :new.sal, :old.sal-:new.sal); end; /

drop any other triggers on emp to avoid mixup

update emp set sal=800 where empno=7369update emp set sal=1000 where empno=7369;

PackagesIt is a collection of Procedures and functionIt is a modular approach to programming which enhances performance.Global variables declaration in the package specification.Package has got 2 parts :1) Package Specification: contains prototypes of procedures and functions in the package2) Package Body : body of the procedures and functions in detailNormally, when a procedure or function is called and compiled it gets loaded in the PLSQL area in the SGAIn case of a package, when a procedure or function from the package is called, all the procedures and functions from that package h=get loaded into the PLSQL area in the SGA.

Package specificationCreate or replace package emppack asProcedure new_dept(dno number, dname varchar2, lc varchar2);Procedure fire_emp(veno number);Function ret_sal(veno number) return number;Gvar number:=0;End;/

Package BodyCreate or replace package body emppack asProcedure new_dept(dno number, dname varchar2, lc varchar2)Is

86

Page 87: notes

BeginInsert into dept values(dno, dname, lc);

End;

Procedure fire_emp(veno number)Is Begin

Delete from emp where empno=veno;End;

Function ret_sal(veno number)Return numberIsVsal number;Begin

Select sal into vsal from emp where empno=veno;Return vsal;

End;End;/

PLSQL BlockDeclare

Ret number;Begin

Emppack.new_dept(61,’Medical’,’Wadala’);Emppack.fire_emp(7788);Ret:=emppack.ret_sal(7698);Dbms_output.put_line(‘Salary is’||ret);

Dbms_output.put_line(‘Global variable is’||emppack.gvar);Emppack.gvar:=emppack.gvar+10;Dbms_output.put_line(‘Global variable is’||emppack.gvar);

End;/every time you execute this package body the value of gvar keeps on getting incremented

select text from user_source where type='PACKAGE' and name='EMPPACK' ORDER BY LINE

select text from user_source where type='PACKAGE BODY' and name='EMPPACK' ORDER BY LINE

87

Page 88: notes

NESTED TABLES

A nested table is a collection of rows, represented as a column within the main table.For each record within the main table, the nested table may contain multiple rows.It is a one-to-many relationship within the same table.

First you create a type(or datatype) as follows:create or replace type animal_ty as object ( breed varchar2(25), name varchar2(25), birthdate date);

Then you create a another type(or datatype) with the “as table of” clause, which tells oracle that you will be using this type as the basis for a nested table.Create type animal_nt as table of animal_ty;

Now create the nested table as follows :Create table breeder(breedername varchar2(25),animals animal_nt)nested table animals store as animals_nt_tab;

The 1st column is the Breedername column. The 2nd column is animals, whose definition is the nested table animal_ntThe data of the nested table is not stored inline with the rest of the data of the main table. The data in the “animals” column will be stored in one table(animals_nt_tab), and the data in the “Breedername” column will be stored in another table(breeder). Pointers are maintained by oracle between the two tables.

Inserting records in the Breeder tableInsert into breeder values(‘Hemant’, animal_nt( animal_ty(‘Dog’, ‘Tommy’, ’31-Dec-2005’),

animal_ty(‘Dog’, ‘Bruno’, ’31-Dec-2005’),animal_ty(‘Cat’, ‘Pussy’, ’31-Dec-2005’))

);

select * from breeder

select * from animals_nt_tab

88

Page 89: notes

error : cannot reference nested table column’s storage table.

select birthdate from animal_nterror : procedure, function, type or package is not allowed here

To select columns like birthdate from nested table, you need to flatten the table to a normal table by using the table function as follows:

Select breedername, a.name, a.birthdate from breeder, table(breeder.animals) a;

Select breedername, a.name, a.birthdate from breeder, table(breeder.animals) a where a.name=’Bruno’;

To insert, update, delete in nested table using the TABLE FunctionInsert into TABLE(select animals from breeder where breedername=’Hemant’)values(animal_ty(‘Sheep’,’Mary’,’26-Jul-2001’));

Update TABLE(select animals from breeder where breedername=’Hemant’) Aset A.birthdate=’01-Jan-1990’ where A.name=’Bruno’;

Delete TABLE(select animals from breeder where breedername=’Hemant’) Awhere A.name=’Bruno’;

Varying (VARRAYS) ARRAYSIt is a set of objects, each with the same datatype, seen as a column within a table.The size of the array is limited when it is created.The Varray is treated as a column in the main table.

create or replace type address_type as object ( city varchar2(15), state varchar2(20), zip number(7) ); /

create or replace type fullname as object (

89

Page 90: notes

fname varchar2(10), mname varchar2(10), lname varchar2(10) ); /

create or replace type phone_ty as object(phone number(8));

create or replace type phone_va as VARRAY(5) OF PHONE_TY;

CREATE TABLE CUSTOMERS ( custno number(3) primary key, custname fullname, custaddr address_type, custphon phone_va);

insert into customers values(100, fullname('Hemant','Jayawant','Pangam'),address_type('Mumbai', 'Maharashtra',400068),phone_va(phone_ty(28968531),phone_ty(56252739), phone_ty(1234567)))

select custno, a.custname.fname, a.custaddr.city from customers a;

Block to see all the values in a varraydeclare

cursor vc is select * from customers;begin

For x in vc Loop

Dbms_output.put_line(‘Customer Number :‘||x.custno||’ Customer Name :’ ||x.custname.fname||’ ‘||x.custname.mname||’ ‘||x.custname.lname);

For y in 1..x.custphon.countLoop

Dbms_output.put_line(‘Phone ’||y||’ ‘||x.custphon(y).phone);End loop;

End loop;

90

Page 91: notes

End;/

91