Published on

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. 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
  2. 2. 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
  3. 3. 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
  4. 4. 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
  5. 5. 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
  6. 6. 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
  7. 7. 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
  8. 8. 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
  9. 9. 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
  10. 10. (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
  11. 11. 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
  12. 12. 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
  13. 13. (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
  14. 14. 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
  15. 15. 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
  16. 16. 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
  17. 17. 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
  18. 18. 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
  19. 19. 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
  20. 20. )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
  21. 21. 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 * 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
  22. 22. 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
  23. 23. 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
  24. 24. 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
  25. 25. 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
  26. 26. 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
  27. 27. 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
  28. 28. 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
  29. 29. 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
  30. 30. 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 * 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
  31. 31. 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
  32. 32. 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
  33. 33. 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
  34. 34. 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
  35. 35. 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 * 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
  36. 36. 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
  37. 37. 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 * 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
  38. 38. 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
  39. 39. 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
  40. 40. /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
  41. 41. 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
  42. 42. 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 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
  43. 43. 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 * 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
  44. 44. 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
  45. 45. 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 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
  46. 46. 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 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
  47. 47. 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
  48. 48. 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
  49. 49. 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
  50. 50. 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
  51. 51. 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
  52. 52. 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
  53. 53. 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
  54. 54. 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
  55. 55. 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
  56. 56. 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
  57. 57. 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
  58. 58. 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 Using ‘DPR”;Here 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
  59. 59. 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
  60. 60. 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 companyid, deptid, jobid,sum(salary)From employeesGroup ByGrouping Sets ((Companyid, Deptid),(Companyid, jobid)) 60