• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
notes
 

notes

on

  • 1,415 views

 

Statistics

Views

Total Views
1,415
Views on SlideShare
1,415
Embed Views
0

Actions

Likes
1
Downloads
150
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    notes notes Document Transcript

    • 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 Example 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 Concept In 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
    • Various RDBMSs are : Informix -- Fastest Oracle -- Most Common Sybase MS SQL Server -- User Friendly Ingres, Progress, Unify-- Character-based(DOS, UNIX platform DB2, CICS, Telon, IDMS -- Mainframe computers MS 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 istands for Internet or Intelligent, as it is an extensive support for Internet-basedapplicationsSome 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) OraTerm1) SQL(Structured Query Language) Supports only 9 commands : Create, Alter, Drop 2
    • Insert, Update, Delete Select Grant, Revoke Initially founded by IBM(International Business Machines), now controlled by ANSI(AMERICAN national Standards Institute)2) SQL * Plus It is an extension of SQL. It removes some limitations of SQL It is an interface with the database to execute SQL and SQL*Plus commands It 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 Reports3) PL/SQL(Procedural Language/SQL) It is the programming language of Oracle. For MS SQL, we have Transact SQL4) Oracle Forms 9i Oracles 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/RDBMS5) Oracle Reports 9i Oracle’s Report Writing Software6) Oracle Menus Oracle’s Menu Building Software7) Oracle Graphics For Charts, Graphs, etc based on Oracle data8) IDS(Integrated Development Suite) Combination of Forms+Reports+Menus+Graphics. Earlier known as D2K(Developer 2000)9) EXP 10) IMP The 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
    • 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 databases11) SQL * Loader To Bring data from another RDBMS to Oracle.12) OEM Oracle Enterprise Manager is a tool used to perform Database Administration tasks.13) Oracle Case CASE tolls for rapid application development using ERDs, DFDs. Designing of these diagrams helps to automatically create tables and their relationships.14) Designer 2000 It includes Oracle Case+IDS15) Oracle Financials The core applications which make up Oracle Financials includes Oracle General Ledger, Oracle Purchasing, Oracle Payables, Oracle Inventory, Oracle Receivables and Oracle Assets.16) Oracle Manufacturing The 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 HRM The 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 4
    • resources-related activities, including recruiting, performance management, learning, compensation, and real time analytics18) Oracle CRM Oracles 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 Application Oracle 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 Oracle A 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 Paradox21) 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. AlsoRelational DatabasesIn relational databases we have only type of Data Stores or Data Structures- called TablesWhy is it called Relational?Suppose you have two tablesEmpMasterEmpno Empname Salary Deptno1 abc 100 12 lkm 2000 23 kkk 876 34 ppp 569 3 5
    • 5 uuu 679 26 yyy 7789 37 ttt 6878 18 rrr 5765 19 eee 6886 210 ppu 687 3DeptMasterDeptno Deptname1 Accounts2 Administration3 MedicalHere, even though the tables are separate and independent, they are related. The filed orcolumn “Deptno” in empmaster table is related to the column “Deptno” in the DeptMastertable. This relationship is the basis of Relational Databases, and this approach is alsocalled the Relational Model approach. The Data is stored only in tables. The tables havecolumns and rows. The tables can be related to each other if each one of them has acolumn 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 StructuredQuery Language or SQL. It is pronounced as SEQUEL.. This language allows the endusers to extract information themselves, without using system level command(which wereused earlier) for retrieving every little piece of information.It is called Structured Language since like any other language it has got a structure or rulesof grammar or syntax.It is called Query Language since it’s fundamental use is to ask questions or query thedatabase 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 iteration no variable declarations no loopsPL/SQL is a procedural extension to SQL. 6
    • It is a superset of SQL which allows you to implement your business rules or logic throughcreation of Stored procedures, packages, Triggers, Functions or any other programminglogic for the execution of SQL Commands.Section of PL SQL Block :Declare Defines and initializes the variables and cursors used in the PL/SQL BlockBegin Uses 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 timeEnd; Marks the end of the PL/SQL Block. Followed by a semicolon called terminator.Theoretical and Physical aspects of OracleOracle 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. Theseprocesses and the SGA are together called ORACLE INSTANCE. Then, the database isopened and maintained.Oracle 8i first came up with the concept of OOPS at the backend or database level thrunested objects, nested tables, etc., thru built in Java support at the database level. I standsfor intelligent or internet, where in the implementation of OOPS at the database levelresulted in faster retrieval of data, especially for Web-based applications. The applicationserver was brought into the picture at the backend level.Oracle 9i came up with the concept of Parallel Processing(or Clustered Servers) whereby aset of low-cost servers(like xeon servers) each having its own set of daemons(system levelprograms handling the single database) could handle or manage a single database, unlikethe 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 orexpensive server on which the Oracle database lies, you can have a set of low-cost serverswith their own set of daemons to handle the database on a single server(or array of 7
    • harddiks storing the database). Thus, it is like having multiple instances of a database,unlike the earlier versions. SGA System Level Database or Background Operations Physical processes for database or handling and data files maintaining the Database User1 Operations also called DAEMONS User2 Operations User3 Operations N users 8i N Users Daemons SGA Physical database or data files N Users Daemons SGA Daemons SGA N Users 9i 8
    • Create a tableRules for Table /Column name : Maximum 30 characters A-Z, a-z, 0-9 Has to begin with alphabet Can contain #, _, $ Case insensitiveDatatypesCharFixed length character data. Maximum 2000 bytes. Default 1 byteNcharMultibyte character set version of char. Since some National character sets may have acharacter taking more than 1 byteVarchar2()Variable length character string having a maximum size of 4000 bytesNvarchar2Variable length character string having a maximum size of 4000 bytes or charactersdepending upon the type of National character set, since in some national character setone character may take 2 or more bytesCLOBCharacter Large Objects upto 4GB in lengthNCLOBSame as CLOB, but for multibyte character setsBLOBBinary Large Objects upto 4 GBBFILETo point to a binary operating system fileCreate table proposal 9
    • (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 Excelspreadsheets 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 proposalCover_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 isactually stored in the database itself), but not BFILE(since such data is not stored in thedatabase, 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 Oraclestores locators(pointers), which point to the locations within the database which are createdby the database to hold LOB objectsNumber(p,d) Example : Number(5,2) can take a maximum of 999.99LongCharacter data of variable size upto 2GB. Only one long column per table. Cannot be usedin subqueries, functions, where clause, indexes. Table cannot be clusteredRawRaw binary data. Upto 255 bytes. Contains Binary data in whatever form the host computerstores 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 BLOBrespectivelyDate 10
    • Dates between January 1, 4712 BC upto December 31, 9999 ADTimestamp(precision)Date plus time where precision is the number of digits in the fractional part of theseconds(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(bydefault 2) is the number of digits in the year part. Example ’12-2’ means 12 years and 2monthsInterval day(day_precision) to second(sec_precision)Difference in two timestamp files in terms of days, hours, minutes and seconds, whereday_precision(by default 2) is the number of digits in the day-part and sec_precision(bydefault 6) is the number of digits in the fractional part of the seconds-part. Example ‘145:56:45.456654’ means 14 days, 5 hours, 56 minutes, 45.456654 secondsRowidA unqiue number assigned to each row in a database. Returned by pseudo-columnROWIDUrowid(size)Hexadecimal string to identify the logical address of a row in a indexed-organised table in adatabase. Maximum size is 4000 bytesCreate 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 valueCreating table from another tablecreate table yostud (r,s,e,m,sc,t,b,te) as select * from studentsorcreate table yostud as select * from students;To rename a table, view, sequence or synonym, we have the rename command :Rename oldname TO newname 11
    • Example: Rename students TO studs;ConstraintsUsually 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 noother 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 existscreate table student(rollno number(3) constraint PK_Stud_rollno primary key,name varchar2(25) NOT NULL,eng number(3,2));orcreate table student 12
    • (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 othercolumn contains a value say “XYZ”, then you cannot have another row with the samecombination 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 thenAlter 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
    • 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 thecolumns 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 thebrackets 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 thetable name. This is also called Implicit method of inserting NULL values for the columns notspecified.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 studentsvalues(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 YYrepresents current century, if while inserting the century is not specified). Because datealso contains time, the default time saved in a date column is 00:00:00. If u want to enterdate in a different format, such as another century than the current century or with aspecific time then : 14
    • insert into students values(299,’Mamta’,’Varma’,to_date(‘NOV 20, 1981 15:45:56’,’MONDD, 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 studentsFor 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 numberAlter 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 billnowill not find values for the existing recordshencealter table orders add(remark varchar2(10),billno varchar2(10))select * from ordersupdate studs set remark=helloalter 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
    • alter table orders set unused column abcalter table tablename set unused(col1, col2)This feature is available 8i onwards so that we do not effect the speed of an onlinedatabase. 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/systemresource use is low. You have no access to the column and is as good as dropped. Noquery allowed on such unused columns. The column name and datatype are not seen withthe describe command.alter table orders drop unused columnsAlter table tablename add/modify column columnname default defaultexpression;Alter table can be used to add a default value for a new/existing columnscan 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 timeif a column is NULL for every row of a tablecan change the columns datatypecan decrease a character columns widthyou can decrease the number of digits in an NUMBERAlter table tablename drop constraint Primary key;To drop the PK constraintAlter table tablename drop constraint unique(column/columns name)To drop the Unique constraint on a column or columnsAlter table tablename drop constraint constraintnameTo drop any constraint by it’s nameAlter 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 theCASCADE CONSTRAINTS option as follows with the alter table :Alter table tablename DROP (columnname) cascade constraints; 16
    • Viewing Constraints :To view the constraint definitions and names :Select constraint_name, constraint_type, search_condition from USER_Constraints wheretable_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_objectsTo 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_catalogYou 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) orspecified table who have got atleast one column with a comment.PRIMARY KEYKey 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
    • 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 arehaving a mobile then even mobile_no can be a PKsPK constraint is at Server level, hence cannot be bypassed by a Front-endSelect * from user_constraints where table_name=’EMP’;EMP in upper case, since Oracle stores table and column names in upper caseIf you don’t specify the constraint name , Oracle gives it’s own constraint names likeConstraint_Name Constraint_TypeSYS146788 Pfor 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
    • eng number(3,2),constraint my_primarykey primary key(stan,div,rollno));If a table is already created thenAlter table studAdd constraint my_con primary key(rollno);FOREIGN KEY and CHECK ConstraintForeign Key :A column or set of columns that take the reference of some other column from some othertable 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, thecorresponding rows in the child table are automatically deleted.ON DELETE SET NULL indicates that when a row in the parent table is deleted, the foreigncolumn in the corresponding child rows will be updated to NULL.Without ON DELETE CASCADE and ON DELETE SET NULL, the parent row cannot bedeleted 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 satisfycreate 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
    • )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 indexesassociated with it. View and Synonyms based on the table still remain , but are invalid. Norollback possible. 20
    • Delete students;Delete all the rows from the students table, but the memory occupied by the rows is still notreleased. 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 stillexists with 0 rows.select * from user_cons_columnsselect * from user_constraintsupdate user_constraints set status=DISABLED where constraint_name=SYS_C0034437For 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;NormalisationFirst Normal Form(FNF) 21
    • A relation or table is said to be in the 1st Normal Form when it has no composite attributesor columns , and every attribute(column or field) is single or individual and describes onlyone property. It is also called Flat fileExample:Order_details Item_code Quantity Price_per_unit1456 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.20FNFOrder_No Order_date Item_code Quantity Price_per_unit1456 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.20Second Normal Form(SNF)A relation is said to be in the 2NF, when it is in the 1NF, and the Non-key attributes arefunctionally dependent on the key attributes(s)or composite Primary Key.Example : Consider the FNF given above. Here, Price_per_unit is functionally dependenton Item_code; and Order_date is functionally dependent on Order_No. Thus, the relation isnot in 2NF. Therefore, it is split into 3 tables as follows to give 2NF :Order_Mast : Order_No Order_date 1456 26/02/1989 1886 04/03/1992 1788 04/04/1992Item_Mast Item_code Price_unit 3687 50.40 4627 60.20 3214 17.50 4629 20.25 22
    • Order_Tran Order_no Item_code Qty 1456 3687 52 1456 4627 38 1456 3214 20 1886 4629 45 1886 4627 30 1788 4627 40Third Normal Form(SNF)A table or relation is said to be in TNF when it is in the 2NF, and No non-key attributes arefunctionally 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 GodavariAssuming 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 attributeHostel_name is dependent on the non-key attribute Year. Therefore, it is split into 2 tablesas 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 4Hostel_MastYear Hostel_name1 Ganga2 Kaveri3 Krishna 23
    • 4 GodavariBCNF(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 100Assumptions :A professor can work in more than one department.Percentage of time spent by professor in each department is givenEach department has only one HODHere the 2 possible composite Keys(Composite Primary keys) could be 1) Professor_code + Department 2) Professor_code + HODThus, 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 P2resigns and rows 3 and 4 have to be deleted, then we loose the information “Rao is theHOD of Chemistry”Therefore, BCNF is needed, and the relation is broken down toProf_MastProfessor_code Department Percent_of_timeP1 Physics 50P1 Mathematics 50P2 Chemistry 25P2 Physics 75P3 Mathematics 100Department_MastDepartment HODPhysics GhoshMathematics KrishnanChemistry Rao4NF 24
    • It is needed when a relation has more than one multivalued dependencies. Thus, a relationis said to be in 4NF when it has one independent multivalued dependency with a functionaldependencyExample : Consider a vendor supplying many items to many projects in an organizationwhere : 1) A vendor may supply many items 2) A project may require many items 3) A vendor supplies to many projects 4) An item may be supplied by many vendors Vendor Item ProjectVendor_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 ablank 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
    • V3 I1 V3 P3Thus, both the tables have only one multivalued dependency(For vendor_item, the MVD isone vendor has supplid many items. For Vendor_project, the MVD is that one vendor hassupplied to many projects)5NFIt is obtained by adding one relation(relation with one MVD) relating attributes of the 2relations in 4NF with one MVD. Thus in addition to the two relations in 4NF, we will havethe following relation with one MVD :Project_itemProject_code Item_codeP1 I1P1 I2P1 I3P2 I1P3 I1P3 I2Types of SQL Commands :DDL(Data Definition Language) : Create, Alter, Drop, Rename, TruncateDML(Data Manipulation Language: Insert, update, delete MergeDQL(Data Query Language) : SelectDCL(Data Control Language) : Grant, RevokeTCL(Transaction Control Language) : Commit, Rollback, SavepointSelect * 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, notselect * from orders where itemno=1 and price>500;select * from orders where itemno=1 or itemno=3 26
    • Special operators: IS NULL, between, like, inselect * 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.65pattern 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 _2select * 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
    • GROUP Functions :Group functions operate on sets of rows to give one value per group(A group could be theentire 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. TheDISTINCT clause, if used with a group function, makes it consider only the non-duplicatevalues. 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 forcharacter or date type of data.Select sum(salary) from employeesGROUP BY Clause :The Group By clause is used to divide the table into groups of rows. By using a whereclause you can exclude certain rows before dividing them into groups. By default rows aresorted in the ascending order of the columns included in the group by clause. You canchange the ordering by using the Order By clause. All the columns in the SELECT list thatare 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, DivSELECT 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 ORDERBY DEPTNOSELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE WHERE DEPTNO>=4 GROUPBY DEPTNO ORDER BY DEPTNOSELECT DEPTNO AS DEPARTMENT, SUM(SALARY) FROM EMPLOYEE WHEREDEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNOSELECT DEPTNO AS DEPARTMENT, SUM(SALARY) AS "SUM OF SALARY" FROMEMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNOThe Count(*) returns the number of rows in a table that satisfy the criteria of the selectstatement, 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 inthe columnThe NVL function can be used to include NULL values as follows :Select AVG(NVL(Maths,0)) from students; 28
    • select deptno, count(*) from employee group by deptnoThe Where Clause cannot be used to restrict the groups or to specify conditions on thegroup 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 havingsum(salary)>1500(Having is used like where on results of groupedfunctions instead ofindividual rows)SELECT DEPTNO, MAX(SALARY) FROM EMPLOYEE GROUP BY DEPTNO ORDER BYMAX(SALARY) DESC`Select * from tablename where condition(s) group by field(s) having condition(s) order byfield(s)SELECT DISTINCT DEPTNO FROM EMPLOYEENesting 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 allrows in the 2nd tableselect empno, empname, deptname from employee,deptmastorselect empno, empname, deptname from employee cross join deptmastLEFT 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 ORDERBY D.DEPTNO, E.EMPNOORselect * from deptmast left outer join employee on deptmast.deptno=employee.deptnoORDER 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 BYD.DEPTNO, E.EMPNOORselect * from deptmast RIGHT outer join employee on deptmast.deptno=employee.deptnoORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO; 29
    • 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.deptnoORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO;ORselect * from deptmast d, employee e where E.DEPTNO(+)=D.DEPTNOunionselect * from deptmast d, employee e where D.DEPTNO(+)=E.DEPTNOAll Records from both the tables, including those who do not have a correspondingdepartment/employee in the other table;Equi JoinAlso called simple join/Inner joinThe relation between an Employee and Department tables involves as Equi-Join. Thevalues in the common field in both the tables must be equal.select * from employee e (alises), deptmast d where e.deptno=d.deptnothis will help uNon-Equi JoinIt involves an operator other than the equality(=) operator. It uses operators like <=, >= orBetween.ExampleEmployee Sal_GradeEmpno 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 wheree.salary BETWEEN j.Min_Sal and j.Max_salInner 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
    • 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 thefields 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 NUMBERDIV VARCHAR2(1)We can use the ‘USING’ clause to decide which of the common columns should beconsidered as follows :Select * from student1 join students using(rollno)UNIONselect deptname from deptmastunionselect dept_desc from dept_mastwill not display duplicate valuesUNION 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 valuesINTERSECTselect deptname from deptmastintersectselect dept_desc from dept_mast 31
    • common values(or intersection) from both the tablesMINUSselect 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 ___mselect * from students where studname like He%Betweenselect * from students where maths between 43 and 70select * from students where maths NOT between 43 and 70Existsselect 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.deptnoExists is same as In, but it is a logical operator 32
    • SubqueriesA subquery is a SELECT statement in the WHERE, HAVING or FROM clause of anotherSELECT statement.Select * from students where maths>(select maths from students wherestudname=Laxman) (assm:only 1 laxmn)The Inner query is also called Nested query or Sub query. The inner or nested or sub querygenerally 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 inthe inner query.There are two type of comparison operators : single row operators and multiple rowoperators, and hence there are two types of sub-queries Single row sub-queries(Query thatreturns only one row from the sub-query) and Multiple Sub-Row queries(Query that returnsmore than one row from the sub-query)Single-Row comparison operators are =,>,>=,<,<=,<>Select rollno, firstname from students where std=(select std from students whererollno=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)>(selectmin(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)=(selectmin(avg(salary)) from employees group by deptno);If the inner query returns more than one row, then it would generate an error. To correctsuch 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.(inlaxmn 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
    • IN(Equal to any number in the list), ANY(Compares value to each value returned by thesubquery), ALL(Compares value to every value returned by the subquery)select * from students where studname IN (select studname from students where rollno=45or rollno=35);To display the employees who are not Programmers and whose salary is less than any ofthe Programmerselect empno, empname, job, salary from employees where salary<ANY(select salary fromemployees where job=’Programer’) and job<>’Programmer’;<ANY means less than the maximum.`>ANY means more than the minimum.=ANY is equivalent to INTo display the employees who are not Programmers and whose salary is less than all theProgrammerselect empno, empname, job, salary from employees where salary<ALL(select salary fromemployees 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 nottake any memory in the database. When a table is dropped, the views on it are notaccessible, 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 dataSimple views:Derives data from a single table. Dose not contain functions or groups of data. Allows youto perform DML operations.Complex views : 34
    • Derives data from many tables. Contains functions or groups of data. Does not allow DMLoperationscreate 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 viewsselect * from stud1;When select is run on a view it will show only those records which satisfy the conditiongiven while creating the view.select * from students;select view_name, text from all_views where view_name=STUD1create 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 clausecreate 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 dwhere e.deptno=d.deptno group by d.deptname;You cannot delete a row from a view if :It contains group by clause 35
    • It contains the DISTINCT keywordIt contains the pseudolumn ROWNUMYou 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 expressionsYou 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 viewWith 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 thatInserts/Updates performed thru the view cannot create rows which the view cannot select,and thus ensures integrity constraints and data validations checks on data beinginserted/updated thru the viewREAD 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 onlyTo drop a viewDrop view viewnameInline ViewsAn inline view is created by placing a subquery in the FROM clause and giving thatsubquery an alias so that it behaves like a separate table. Example to find all theemployees 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, (selectdeptno, max(salary) maxsal from employee group by deptno) b where a.deptno=b.deptnoand a.salary<b.maxsalTop N analysisselect rownum, empno, salary as rank from (select empno, salary from employee where 36
    • salary is not null order by salary desc) where rownum<=3Rownum is pseudo column assigned to each row returned by the inner query. The innerquery contains the order by clause to get the ranking in the desired order. The outer querylimits the number of rows returned by using the where clause which uses a < or <=operatorProducing Readable ReportSubstitution Variables using single ampersandselect * from dept_mast where dept_code=&Department_CodeThe variable is created and discarded after useselect * from dept_mast where dept_name=&Department_namesingle 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-sensitivitySubstitution variables can be used for columns, where clause, table names, order byclause :select &column_name from dept_mast where dept_code=&department_codeselect * from &table_nameselect * from &table_name order by &columnDefining Substitution variables :DEFINE variablename=valueThe value is of type characterExampleDefine abc=hemantDefine xyz=25Both are character type variablesDefine variablenameTo see the value and data type of that variableDefineDisplays all variables, their values and data types for that sessionUndefine variablename 37
    • To remove the variable from memoryA variable remains in memory till you either give it a new value or you undefined it or youend 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 astatement, and don’t want oracle to prompt you for it’s value everytime it is encountered asfollows :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. Oget 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 valuestwice before execution : once the original statement , and once the statement with thesubstituted or entered or new valuesPartitionsTo store large number of records in separate tables to reduce retrieval timecreate 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 DisconnectHow to Rollback1) Rollback command 38
    • 2) Rollback to savepointname Implicit Rollback3) when you switch off;4) hard disk crash5) Power failureinsert 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 immediatelyrollback to b;-third insert statement and savepoint c are undonerollback to a;-second and third insert statement and savepoint b and c are undoneif only rollback is given then all DML statements after last commit are undoneObjects 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
    • /create table employee ( empno number(3), person fullname, address address_type, salary number(6,2) );Table EmployeeEmpnoPerson ---- fullname Fname Mname LnameAddress ---- 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
    • create table employee ( empno number(3), person personal_type, salary number(6,2) );insert into employeevalues(111,personal_type(Hemant,address_type(Mumbai,Maharashtra,400068)),1000.0)Character FunctionsSelect 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 stringsselect lower(studname) from students;lower-displays string in lower caseselect upper(studname) from students;lower-displays string in upper caseupdate 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 capitalselect ascii(studname) from students; 41
    • ascii-ascii value of the first character of the stringselect chr(65) from dual;chr-character corresponding to the given valueselect sysdate from dual;dual is a oracle provided table for such type of temporary operationsselect length(studname) from studentlength-to find length of a stringselect instr(‘man’,studname) from studentsselect 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 notfound 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 onwardsselect 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. Thusmakes it Right Justifiedselect 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 differentnumber of parameters.select ltrim( Hemant ), sysdate from dual;ltrim-removes the spaces from the left of the stringselect rtrim( Hemant ), sysdate from dual;rtrim-removes the spaces from the left of the stringselect ltrim( * * Hemant ,* ), sysdate from dualto remove blank spaces and *, if any from left 42
    • select trim( Hemant ), sysdate from dual;trim-removes the spaces from the left and right of the stringselect 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 stringselect firstname, substr(firstname,-3) from studentsfrom 3rd last character to endselect firstname, substr(firstname,-3,2) from students2 character from 3rd lastselect 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 specificcharacter(s). Case Sensitiveselect replace(firstname,Ja) from studentssince 3rd parameter is missing, replaces ‘Ja’ with nothing, that is removes Jaselect translate(firstname,je, FK) from studentsreplaces j by F and e by K. Hence the two parameters must be of same lengthselect 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 vowelsNumeric functionsselect maths+science, maths-science, maths*science, maths/science from studentsselect sqrt(maths) from students;sqrt-square rootselect sin(90),cos(90),tan(90) from dualSine, Cosine, Tangent of specified numberselect cosh(90), sinh(90), tanh(90) from dual; 43
    • Hyperbolic Sine, Hyperbolic Cosine, Hyperbolic Tangent of specified numberselect vsize(123456789) from dualvsize-size of the value in bytesselect 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 placetrunc-truncates the value to the specified precisionselect sign(-9), sign(0), sign(9) from dual;sign—displays –1,0,1 for negative, zero and positive valuesselect 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 precisionselect 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 2select abs(-10) from dual; gives the absolute or positive value of any numberupdate students set maths=0 where rollno=1select nvl(maths,0) from students;nvl-to replace NULL value numbers with the specified numberselect mod(10.33,3.10),mod(10,3),mod(10.3,3) from dualremainder of the divisionselect log(10,10), log(10,20), log(10,1) from dual 44
    • 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 infinityselect english,floor(english), maths,floor(maths), science, floor(science) from students;floor-largest integer smaller than or equal to the given valueselect english,ceil(english), maths,ceil(maths), science, ceil(science) from studentsceil-smallest inter larger than or equal to the given valueDate 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 itis .5 it means 12 hours. To get rid of the fractionselect trunc(sysdate-to_date(31-Jan-05)) from dualselect 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 dateselect least(to_date(01-Jan-05), to_date(11-Sep-05), to_date(31-Dec-06)) from dualgreatest—earliest date from the given listselect 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 fridayselect last_day(sysdate) from duallast day of the month to which the specified date belongsselect to_char(sysdate) from dual; 45
    • to_char—date to characterselect 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. Roundon any date set it to 12am if time is before noon, and to 12am of the next day of the time isafter noon.select to_date(31-Dec-05) - trunc(sysdate) from dualtrunc-set the date to 12am of the current dayselect current_date from dual;returns date from the current time zoneselect current_timestamp from dual;returns date and time from the current time zoneDifferent 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 separatoralso try the following :DD/MM/YYYDD-MONTH or DD-MONTH-YYYY - Month in upper caseMonth - Month in lower caseMon/mon/MON in the appropriate caseSelect to_char(sysdate,’DAY’) from dual;Try : day, Day, DY, dy, DySelect to_char(sysdate,’YEAR’) from dual; gives Two Thousand SixTry : YearSelect to_char(sysdate,DD) from dual will give 31or 01, etcAlso try : DDTH, DDSP, DDSPTHSelect to_char(sysdate,MM) from dualAlso try MMTH, MMSP, MMSPTHSelect to_char(sysdate,D) from dual; day of the week(1,2 ..7) 46
    • Try DTH, DSP,DSPTH in upper or lower caseSelect to_char(sysdate,DDD) from dual; day of the yearSelect 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 caseSelect 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:SSSelect 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., etcSelect to_char(sysdate,DD/MM/YYYY HH:MI:SS a.M.) "IST" from dual to see IndianStandard TimeSelect to_char(sysdate-5.5/24,DD/MM/YYYY HH:MI:SS a.M.) "GMT" from dual to seeGMT timealter session set nls_date_format =DD/MM/YYYYto 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 NULLAny calculation with NULL returns NULLSelect 5000+NULL from dual;select nvl(salary,0)+300 from employee 47
    • 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 salaryis less than 500 returns 500, else returns the actual salary. Can be sued to set a minimumthreshold value.LeastSelect salary, least(salary,500) from employeeCompares salary of each row with 500 and returns the smallest among the two, i.e., ifsalary is less than 500 returns the salary, else returns 500 Can be sued to set a maximumthreshold 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 dualDecodeselect 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/DecryptionNvl2select 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 5000Nullifselect 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 beof the same datatypeCaseselect empno,salary,case deptno when 1 then 1.10*salarywhen 2 then 1.20*salary 48
    • when 3 then 1.30*salaryelse 500end from employeeIt 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. Theelse part is optional.Environment function :Select user from dual;select userenv(sessionid) from dualselect userenv(terminal) from dual;Numtodsintervalselect numtodsinterval(265, HOUR) from dualconverts 265 hours to 11 days and 1 hours, 0 mins, 0 secsselect numtodsinterval(1, HOUR) from dualconverts 1 hour to 0 days and 1 hour, 0 mins, 0 secsselect numtodsinterval(265, day) from dualconverts 265 days to 265 days and 0 hours, 0 mins, 0 secsselect numtodsinterval(265, Minute) from dualconverts 265 minutes to 0 days, 4 hours, 25 mins, 0 secsselect numtodsinterval(265, second) from dualconverts 265 seconds to 0 days, 0 hours, 4 mins, 25 secsnumtoymintervalselect numtoyminterval(15, month) from dualconverts 15 months to 1 year , 3 monthsselect numtoyminterval(15, year) from dualconverts 15 years to 15 year , 0 monthsselect numtoyminterval(15.3, year) from dualconverts 15.3 years to 15 year , 4 monthsto_charselect to_char(sysdate,dd/mm/yyyy) from dualselect to_char(sysdate,dd-mon-yyyy) from dual 49
    • 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 dualto_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 dualgroup functionsselect deptno, variance(sal), stddev(sal), sum(sal), avg(sal), max(sal), min(sal), count(*)from emp group by deptnoTable dependent database objects : Views, Index, Synonyms, SequenceIndexIt 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 arapid path access methodIndexes are created 1)Automatically : A unique index is created automatically when youdefine a Primary Key or a Unique constraint in a table definition. The name of the index isthe name given to the constraint 2) Manually : Users can create non-unique indexes oncolumns to speed up access to the rowsORA cannot be forced to use indexesSuppose you have the following tableRowid Empno Name Salary1 5 aaa2 2 bbb3 3 ggg4 7 mmm5 9 pon6 1 lon7 4 jhg 50
    • 8 6 jklcreate index empno_idx on emp(empno)then the internal storage is as followsselect * from user_indexesRowid Empno Name Salary6 12 23 37 41 58 64 75 9Now 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 occursat the 4th record, if there is no index the search starts from the first recordCreate 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 ofrows.Some of the table’s columns are frequently used together in a WHERE clause of a joinconditionA column of a table which is frequently used as a search criteria contains either a largenumber 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 followedby 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
    • 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 clausemust be indexedAll index like PK, unique key and others are dropped when you drop the tableORA creates index in a B-tree formatFunction based Indexes :It is an index based on an expression. They are defined with functions like upper /lowerwhich 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, besure that the function does not search NULL values. For example, the following statementis guaranteed to used the index, but without the where clause Oracle would haveperformed 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 columnsseparated 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. Theuser_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 fromuser_indexes ix , user_ind_columns ic where ic.index_name =ix.index_name and 52
    • ic.table_name=’EMPLOYEES’SynonymsTo refer to a table owned by another user, you need to prefix the table name by the username. Creation of a synonym avoids this.It is a pointer to a table/view/sequence/procedure or some other object. It is an alias namefor the table/view/sequence. We can have synonym of synonym(alias of alias) It is usedwhen you have access too another user’s table/view/sequence, therefore instead of usingthat users name as the qualifier for the table/view/sequence, you may create a synonymand 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 wouldhave to give the following :Select * from scott.empselect * from user_synonyms;Simplifies access to objects by creating a synonym. It allows easy reference to a tableowned by another user. Shortens lengthy object namesThe synonym can be created by the object owner(if he has sufficient privileges to create asynonym) or system admin. The synonym name can be used by all users to whom thedatabase owner/system admin has granted some rights on that table for which thesynonym has been created. To allow all users who have got rights on that table, we cancreate a public synonym as follows :Create public synonym synonymname for object;SequencesAutomatically 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
    • sequence can be used for multiple tables.They are used to assign unique numbers to NEW rows being inserted into a table, or oldrows 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 fromuser_sequences;check the last_number, it is equal to 100insert into students(rollno, studname) values(myseq.nextval,abc);select sequence_name, min_value, max_value, increment_by, last_number fromuser_sequences;check the last_number, it is equal to 120insert into students(rollno, studname) values(mysequence.nextval,pqr);select sequence_name, min_value, max_value, increment_by, last_number fromuser_sequences;check the last_number, it is equal to 120This is because Oracle caches 20 values or Oracle pre-allocates 20 values and keepsthem in memory for use.update students set rollno=myseq.nextval where rollno=269update students set rollno=mysequence.nextval where rollno=121select myseq.currval from dual; show the latest number assignedYou 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 maximumvalue is 10^27 for an ascending sequence or –1 for descending.Minvalue specifies minimum value sequence should generate. If it is not given minimumvalue is 1 for an ascending sequence or –(10^26) for descending. 54
    • Cycle/Nocycle : Nocycle is the default. If cycle then the sequence will generate values evenafter the maximum/minimum value is reached. This is useful when you alter the sequencewith a new maxvalue/minvalueCache n specifies the number of values that Oracle should pre-allocate and keep inmemoryNEXTVAL and CURRVAL pseudocolumns :When you use sequencename.nextval, a new sequence number is generated. Thesequencename.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 sequencedept_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 departmenttable 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 anerror message. You can alter the sequence to set a new max valueAlter sequence sequencename Increment by n Maxvalue n Minvalue n Cycle/NocycleCache n/Nocache;You cannot change the start value with alter sequence command. To change the startnumber you need to drop and recreated the sequence.To drop a sequenceDrop Sequence Sequencename;Controlling User AccessPrivileges are the right to execute a particular SQL Statement. The DatabaseAdministrator(DBA) is the highest level user who grants users access to the database andit’s objects. The users require System Privileges to gain access to the database and ObjectPrivileges 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
    • Schema : A schema is a collection of objects such as tables, views, sequences, etc. Theschema 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 : CREATEUSER; 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 specificprivileges 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 ownschema)Roles :A role is a named group of related privileges that can be granted to the users. This makes iteasy 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 rolenameGrant Create session, Create table, Create view to rolenameGrant rolename to user1, user2, etc.I can also grant Connect, Resource roles to a new role as followsCreate role myroleGrant Connect, Resource to myroleCreate user hemant identified by hemant123Grant myrole to hemant 56
    • 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) Resource The RESOURCE role gives the user the right to create, alter, drop his own tables, sequences, indexes, triggers, clusters, datatypes, views, etc.3) DBA This 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 passwordObject PrivilegesAn object privilege is a privilege to perform a particular action on a specific table, view ,sequence or procedurePrivilege 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 thespecific 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
    • GRANT OPTION]Object_privilege—is the object privilege like Alter, Select, Execute, etcALL—specifies that all object privilegesColumns—Specifies the columns from a table/view on which the privileges should begrantedOn 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 theprivileges must be granted.With Grant Option – Allows users to whom the privilege has been granted to further grantthose privileges to other users. When the object owner revokes the privileges granted to auser with the With Grant Option, the ability of that user to grant rights on that object to otherusers 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 objectby means of the References privilege.Database LinkA Database Link is a one-way pointer that defines a communication channel from anOracle Database Server to another Oracle Database Server. The entry of this link pointer ismaintained 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 thedata-dictionary entry about the link. The Link is one-way in the sense that a clientconnected to the local database(say A) in which the link entry is stored to access theremote database(say B) can access the remote Database B, but a user connected toDatabase B cannot access the Database A. The DBA is responsible for creating such linksbetween distributed databases, where each of the database in a distributed database musthave a Unique Global Name. The Data-dictionary view USER_DB_LINKS contains theinformation 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 stringor 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.comTo avoid this long name, you may create a synonym as followsCreate Public Synonym mysyn rmemp for emp@abc.pqr.comAnd now, you may : 58
    • 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 aggregatevalue(summary of summary), else returns 1. It can be us with both Cube and Rollup. The columnpass as parameter to the GROUPING function must be present in the Group By Clausecreate 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
    • 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 SETSIt allows you to specify the Sets of column-groups for which you want to see the aggregates, insteadof seeing all possible combinations.select companyid, deptid, jobid,sum(salary)From employeesGroup ByGrouping Sets ((Companyid, Deptid),(Companyid, jobid)) 60
    • select companyid, deptid, jobid,sum(salary)From employeesGroup ByGrouping Sets ((Companyid, Deptid),(Companyid, jobid),(Deptid, Jobid))select companyid, deptid, jobid,sum(salary)From employeesGroup ByGrouping Sets ((Companyid, Deptid),(Companyid, jobid), (Companyid, deptid,jobid))Composite ColumnsA Composite column is a collection of columns that should be treat as a single unit while calculatingthe aggregatesselect 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 GroupingsIn 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 ByGrouping 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
    • 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 Comparisonselect 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 E2AndAll employees who belong to the same dept as E6 and to the same Manager as E6select 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 E6Sub-Query in the From Clause(Inline View)EMPID EMPNAME MGRID DEPID SALARYE1 Hemant 10 4500E2 Hetal E1 10 500E3 Sheetal E1 10 5500E4 Ram E1 10 5768 62
    • 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 fromemployees group by deptid) b where a.deptid=b.deptid and a.salary>b.salavgSub-Query in the CASE ExpressionSelect empid, empname,(CaseWhen deptid=(Select deptid from employees where empname=’Shyam’) Then ‘Mumbai’Else ‘Outsiders’END) locationFrom employeesSub-Query in the Order By ExpressionDEPTNO DEPTNAME------------ ------------------10 Mical20 AccountsEMPID 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 69Select e.empid, e.empname,e.deptid from employees e order by (Select deptname from dept d wheree.deptid=d.deptno) 63
    • In the alphabetical order by department nameCorrelated SubQueryUnlike 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 evaluatedSelect empid, empname,deptid from employees e where salary>(select avg(salary) from employees dwhere d.deptid=e.deptid)Here for every row of e, the salary of employees is compared with the average salary from dcalculated department wiseSubquery Using ExistsThe 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 wheremgrid=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 employeeswhere 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 DeptnameE1 Hemant 10 4500E2 Hetal E1 10 500E3 Sheetal E1 10 5500E4 Ram E1 10 5768E5 Shyam E2 10 768 64
    • E6 Dick E2 20 7698E7 Harry E2 20 698E8 Ryan E1 20 69Update 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 containsdetails 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 alsopresent 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 whereee.empid=e.empid)WITH ClauseIn case of very complex queries where a query block may be required frequently in a SELECTstatement, the WITH clause can be us to retrieve the results of the query block and store it in theuser’s temporary table space, and use it whenever requiredWithdept_costs as (select d.deptname, sum(e.salary) as dept_total from employees e, dept d wheree.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 Queriescreate 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
    • 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=empidCurrent records empid=previous records mgridTop Down approachselect level, empid, empname,mgrid from emp start with empid=102 connect by prior empid=mgridselect level, empid, empname,mgrid from emp start with empid=103 connect by prior empid=mgridCurrent records mgrid=previous records empidUsing Level and Lpadselect lpad(empname,length(empname)+(level*2)-2,*) as orgchart from emp start with empid=100connect by prior empid=mgridMultiTable InsertsUnconditional Insert AllAll the rows retrieved by the Select statement are inserted into the target tablesInsert all into employees1(empid,empname) values(empid,empname)into employees2(empid,salary) values(empid, salary)select empid, empname, salary from employees where salary>5000If 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
    • into employees2(EMPNO,SAL) values(EMPNO,SAL)select empid EMPNO, empname ENAME, salary SAL from employees where salary>5000If the emplyees1 table contains only 2 fields empid, empname; and employees2 table contains only 2fields empid, salaryInsert all into employees1 values(empid,empname)into employees2 values(empid, salary)select empid, empname, salary from employees where salary>5000Conditional Insert AllRecords retrieved by the select statement are further filtered by using conditionsInsert 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 employeesInsert 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=10Conditional 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 theWhen clause. Rows retrieved, but not satisfying any of the When clauses are inserted into E4Insert 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 employeesPivoting InsertTo convert each row from a table(relational/non-relational table) into n rows into the target relationaltable 67
    • 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) selectempid, month, sales1, sales2, sales3, sales4 from emp_sourcePLSQLcreate 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
    • PL/SQL Block to display the name, total of rollno=1set serveroutput on - for dbms to give outputdeclare vname students.studname%type; vtotal students.total%type;begin select 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 CodePL/SQL Block to display "Very Good Student", if total of Rollno=1 is more than 275, elsedisplay "Average student"declare vname students.studname%type; vtotal students.total%type;begin select studname into vname from students where rollno=1; select total into vtotal from students where rollno=1; if vtotal>=250 then dbms_output.put_line(Vname|| is a very good student); else dbms_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 250declare vname students.studname%type; vtotal students.total%type;begin select studname into vname from students where rollno=1; 69
    • select total into vtotal from students where rollno=1; if vtotal>=275 then dbms_output.put_line(Vname|| is a very good student); elsif vtotal>=250 and vtotal<275 then dbms_output.put_line(Vname|| is an average student); else dbms_output.put_line(Vname|| is a poor student); end if;end;/LOOPS1) For <variable> in [reverse] lowvalue..highvalue loop statement1; statement2; end loopNumbers 1 to 10 in orderdeclare num number(2);begin for num in 1..10 loop 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..10 loop dbms_output.put_line(number || num); end loop;end;/Print odd and even numbers from 1 to 20 and their count 70
    • declare a 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<=100 loop dbms_output.put_line(num); num:=num+10; end loop;end;/loop statement1; statement2; 71
    • exit when <condition>;end loop;print 5.10,15,20,....,50declare num number:=5;begin loop dbms_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_dividedeclare vtotal students.total%type;begin select total into vtotal from students where rollno=16; dbms_output.put_line(the roll number is not correct);exception when 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 theexception 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.declare vtotal students.total%type;begin select total into vtotal from students where total>100;exception 72
    • when too_many_rows then dbms_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;begin select english into venglish from students where rollno=2; if venglish<35 then raise low_mark; end if;exception when 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 isdisplayed.Nested Blocks which means declare....begin...end within the begin of an outerdeclare....begin...enddeclare 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); 73
    • end;/it will display an error related to declaration of variable x, and none of the variables will bedisplayed 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;begin Open 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
    • end loop; close cstudent;end;/Here. exit when cstudent%notfound should be done immediately after fetch, or else the lastrecord will be displayed twice. "notfound" is a cursor attribute which is used to find whetherthe cursor currently contains a record or has reached the end of the file or recordset%rowtypedeclare 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 datatypesdeclare type mytype is record ( x varchar2(30), y number(5,2) ); lmn mytype;begin select studname, total into lmn from students where rollno=2; dbms_output.put_line(Name ||lmn.x); dbms_output.put_line(Total ||lmn.y);end;/declare x number:=5; 75
    • 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 then goto 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 inthe declare part of the enclosing programdeclare x number; function f1 return number is begin dbms_output.put_line(Inside the function); return 10; end;begin dbms_output.put_line(Inside the Main); x:=f1; dbms_output.put_line(value of x is||x); 76
    • end;/Global or stored functionStored in the databaseDefined and saved separately, can be called thru another pl/sql blocktry 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;exception when no_data_found then dbms_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
    • end if;end;/stored function to update the salaries of employees getting less than 3000 with incrementof % percentcreate 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 linemain pl/sql blockdeclare cursor c1 is select empno, sal from emp where sal<3000; incr number :=&incr; incsal number;begin for erec in c1 loop 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
    • 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
    • Local procedurescan accept n number of parametercan return n number of valuesdeclare procedure p1 is begin dbms_output.put_line(P1 is called); end;begin p1; dbms_output.put_line(In the main block);end;/declare procedure p1; procedure p2 is begin dbms_output.put_line(p2 called); p1; end; procedure p1 is begin 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 10create or replace procedure retemp(veno IN number, vename OUT varchar2, vsal OUTnumber) 80
    • isbegin select ename, sal into vename, vsal from emp where empno=veno;end;/main blockdeclare cursor c1 is select empno from emp where deptno=10; ve emp.ename%type; vs emp.ename%type;begin for erec in c1 loop 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 anadditional 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 INnumber) is begin if year>=60 then vsal:=vsal*1.05; end if; end; /main plsql blockdeclare cursor c2 is select empno, sal, hiredate from emp; vsal1 emp.sal%type; vdate1 emp.hiredate%type; years number;begin 81
    • 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 whereempno=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 AfterLevels of Triggers : 1)Statement level used to put restrictions By default triggers are statement level Example: Create or replace trigger t1 before update on emp begin end; 2)Row level Used for auditing purpose Example: Create or replace trigger t1 before update on emp for each row begin 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
    • 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 thecurrent record which is updated, inserted or deletedupdate : :old, :newinsert : :newdelete : :oldWrite a trigger for emp table for the delete operation. Deleted value along with date ofdeletion and user who deleted the record should be storedfor this we create the following tablecreate 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 removedwrite a trigger to restrict a user from doing any DML operation on the table emp before9.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
    • 3 errors:error at line nerror You are timed outerror in execution of triggernamewrite a trigger to restrict a user from doing any DML operation on the table emp onsaturdays and sundays and if the username does not belong with the letter "lib" after5.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 personerror in execution of triggernameTrigger on emp table for deletion and updation of salary. If the employee has some loanpending in a loan table then display appropriate messagescreate table loan (empno number, amount number(4));insert into loan values(7369, 2000);insert into loan values(7499, 2000); 84
    • 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 mixupdelete from emp where empno=7934;Out put : No loan takendelete from emp where empno=7369;3 errors as earlierCreate Trigger which will keep a track of emp table in such a way that if the updated salaryis less than the current salary then a table audit will be maintained to store the empno, dateof updation of salary, current salary, updated salary and the differenceCreate table auditsal(empno number(4),update date,cursal number(7,2),newsal number(7,2),saldif number(7,2)); 85
    • 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 mixupupdate 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 thepackage2) Package Body : body of the procedures and functions in detailNormally, when a procedure or function is called and compiled it gets loaded in the PLSQLarea in the SGAIn case of a package, when a procedure or function from the package is called, all theprocedures 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
    • Begin Insert into dept values(dno, dname, lc);End;Procedure fire_emp(veno number)IsBegin 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 incrementedselect text from user_source where type=PACKAGE and name=EMPPACK ORDER BYLINEselect text from user_source where type=PACKAGE BODY and name=EMPPACKORDER BY LINE 87
    • NESTED TABLESA 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 oraclethat 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 isthe 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 datain the “Breedername” column will be stored in another table(breeder). Pointers aremaintained 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 breederselect * from animals_nt_tab 88
    • error : cannot reference nested table column’s storage table.select birthdate from animal_nterror : procedure, function, type or package is not allowed hereTo select columns like birthdate from nested table, you need to flatten the table to a normaltable 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 wherea.name=’Bruno’;To insert, update, delete in nested table using the TABLE FunctionInsert intoTABLE(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
    • 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.count Loop Dbms_output.put_line(‘Phone ’||y||’ ‘||x.custphon(y).phone); End loop; End loop; 90
    • End;/ 91