SlideShare une entreprise Scribd logo
1  sur  91
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 i
stands for Internet or Intelligent, as it is an extensive support for Internet-based
applications

Some of the major Oracle 9i Software Development Tools :
1)  SQL
2)  SQL * Plus
3)  PL/SQL
4)  Oracle Forms 9i
5)  Oracle Reports 9i
6)  Oracle Menus
7)  Oracle Graphics
8)  IDS
9)  EXP
10) IMP
11) SQL * Loader
12) OEM
13) Oracle Case
14) Designer 2000
15) Oracle Financials
16) Oracle Manufacturing
17) Oracle HRMS
18) Oracle Application
19) Oracle CRM
20) Personal Oracle
21) OraTerm

1)   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 Reports

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

4)   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/RDBMS

5)   Oracle Reports 9i
     Oracle’s Report Writing Software

6)   Oracle Menus
     Oracle’s Menu Building Software

7)   Oracle Graphics
     For Charts, Graphs, etc based on Oracle data

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

9)   EXP       10) 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 databases




11)   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+IDS

15)   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 analytics

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

19)   Oracle 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 Paradox

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


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

Why is it called Relational?

Suppose you have two tables

EmpMaster
Empno     Empname              Salary            Deptno
1         abc                  100      1
2         lkm                  2000     2
3         kkk                  876      3
4         ppp                  569      3

                                             5
5          uuu               679         2
6          yyy               7789        3
7          ttt               6878        1
8          rrr               5765        1
9          eee               6886        2
10         ppu               687         3


DeptMaster
Deptno           Deptname
1                Accounts
2                Administration
3                Medical

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



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

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

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

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

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

PL/SQL is a procedural extension to SQL.

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

Section of PL SQL Block :

Declare
            Defines and initializes the variables and cursors used in the PL/SQL Block

Begin
            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 time


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

Theoretical and Physical aspects of Oracle

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

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

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

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

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




Datatypes

Char
Fixed length character data. Maximum 2000 bytes. Default 1 byte

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

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

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

CLOB
Character Large Objects upto 4GB in length

NCLOB
Same as CLOB, but for multibyte character sets

BLOB
Binary Large Objects upto 4 GB

BFILE
To point to a binary operating system file

Create 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 Excel
spreadsheets used for documenting and price-details of the proposal.

Proposal_Text          CLOB(containing the text of the proposal)

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

Cover_letter            BFILE(A binary file stored outside the database that contains your
                        covering letter)
Oracle ensures the data-integrity of CLOB and BLOB and NCLOB(since this type of data is
actually stored in the database itself), but not BFILE(since such data is not stored in the
database, but Oracle just maintains a pointer to such file)

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

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

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

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

Date

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

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

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

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


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

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

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

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


or
create 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;

Constraints

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

Two- types
Column 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 Constraint
NULL values not allowed
Duplicate allowed
Any number of NOT NULL in a table
It is a column level constraint
No composite NOT NULL exists


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

or



create table student

                                              12
(
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 then
Alter table stud modify name varchar2(20) constraint nn_stud_name NOT NULL;


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

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

If table already exists then

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

insert into orders values('ord1','itm1',456,123456.78)
insert into orders values('ord1','itm2',78.90,123456.78)
insert into orders values('ord1','itm3',89.43,123456.789)
insert into orders values('ord1','itm4',89.439,1234567)---error
insert 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 the
columns are defined in the table insert into students values(250,’Hemant’,’Pangam’,’26-
JUL-1976’,’1’,’A’,89.90,67.50,63.75,0,100);

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

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

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

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

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

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

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




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

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

‘ ‘ for character and date, not for number


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

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

select * from orders
update studs set remark='hello'

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

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

alter table orders set unused column remark

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

alter table orders drop unused columns

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

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

if a column is NULL for every row of a table
can change the column's datatype
can decrease a character column's width
you can decrease the number of digits in an NUMBER




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

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

Alter table tablename drop constraint constraintname
To drop any constraint by it’s name

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

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

Alter table tablename DROP (columnname) cascade constraints;


                                            16
Viewing Constraints :

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

To view the columns associated with the constraint names
Select constraint_name, column_name from USER_CONS_COLUMNS where
Table_name=’ORDERS’

Tables owned by the user
Select table_name from user_tables;

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

To see the distinct object types owned by the user
Select distinct object_type from user_objects
To see the tables, views, synonyms and sequences owned by the user
Select * from user_catalog


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

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


PRIMARY KEY

Key that uniquely identifies each row of a table
Duplicate values not allowed
Null values not allowed
Recommended for every table
Any column can be a PK, except LONG and Long RAW

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

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

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

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

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

Constraint_Name                                Constraint_Type
SYS146788                                           P




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

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

for multiple column primary key
create 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 then
Alter table stud
Add constraint my_con primary key(rollno);




FOREIGN KEY and CHECK Constraint

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


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

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

                                              19
)

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

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

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

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

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



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

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


select * from user_cons_columns
select * from user_constraints
update user_constraints set status='DISABLED' where constraint_name='SYS_C0034437'


For inserting & into a field
set 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;

Update
update orders set quantity=500;
rollback;

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

update orders set quantity=null;
rollback;

Drop table tablename;


Normalisation

First Normal Form(FNF)



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

Example:
Order_details          Item_code        Quantity     Price_per_unit
1456 of 26/02/1989          3687            52             50.40
1456 of 26/02/1989          4627            38             60.20
1456 of 26/02/1989          3214            20             17.50
1886 of 04/03/1992          4629            45             20.25
1886 of 04/03/1992          4627            30             60.20
1788 of 04/04/1992          4627            40             60.20

FNF
Order_No Order_date Item_code           Quantity Price_per_unit
1456 26/02/1989 3687          52            50.40
1456      26/02/1989 4627               38        60.20
1456      26/02/1989 3214               20        17.50
1886      04/03/1992 4629               45        20.25
1886      04/03/1992 4627               30        60.20
1788      04/04/1992 4627               40        60.20

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

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

Order_Mast             :    Order_No      Order_date
                       1456          26/02/1989
                       1886          04/03/1992
                       1788          04/04/1992

Item_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                      40



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

Consider the following in 2NF:
Roll_No    Name              Department               Year       Hostel_name
1784       Ram               Physics           1            Ganga
1648       Sham              Chemistry         1            Ganga
1768       Bharat            Maths             2            Kaveri
1848       Arjun             Botany            2            Kaveri
1682       Nakul        Geology        3              Krishna
1485       Sahadeo           Zoology           4            Godavari

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

Stud_mast
Roll_No     Name             Department               Year
1784        Ram         Physics        1
1648        Sham             Chemistry         1
1768        Bharat           Maths                    2
1848        Arjun       Botany         2
1682        Nakul       Geology        3
1485        Sahadeo     Zoology        4

Hostel_Mast
Year      Hostel_name
1         Ganga
2         Kaveri
3         Krishna

                                             23
4          Godavari

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

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

Here the 2 possible composite Keys(Composite Primary keys) could be
      1)    Professor_code + Department
      2)    Professor_code + HOD
Thus, in the 1st case, the attribute Department depends on the attribute HOD of the 2nd CP
And, in the 2nd case, the attribute HOD depends on the attribute Department of the 1st CP.
Also, there is duplication of the combination of “Department + HOD”. Also, if professor P2
resigns and rows 3 and 4 have to be deleted, then we loose the information “Rao is the
HOD of Chemistry”
Therefore, BCNF is needed, and the relation is broken down to

Prof_Mast
Professor_code   Department               Percent_of_time
P1               Physics             50
P1               Mathematics              50
P2               Chemistry           25
P2               Physics             75
P3               Mathematics              100

Department_Mast
Department        HOD
Physics       Ghosh
Mathematics       Krishnan
Chemistry     Rao

4NF

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


Example : Consider a vendor supplying many items to many projects in an organization
where :
     1)   A vendor may supply many 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




                              Project



Vendor_code                   Item_code                Project_code
V1                            I1                       P1
V1                            I2                       P1
V1                            I1                       P3
V1                            I2                       P3
V2                            I2                       P1
V2                            I3                       P1
V3                            I1                       P2
V3                            I1                       P3
Problems :
If vendor V1 has to supply to project P2, but the item is not yet decided, then a row with a
blank item_code will have to be inserted
Information 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_Project
Vendor_code            Item_code          Vendor_code                 Project_code
V1            I1                     V1                 P1
V1            I2                     V1                 P3
V2            I2                     V2                 P1
V2            I3                     V3                 P2

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

5NF
It is obtained by adding one relation(relation with one MVD) relating attributes of the 2
relations in 4NF with one MVD. Thus in addition to the two relations in 4NF, we will have
the following relation with one MVD :
Project_item
Project_code             Item_code
P1                 I1
P1                 I2
P1                 I3
P2                 I1
P3                 I1
P3                 I2

Types of SQL Commands :

DDL(Data Definition Language)     :     Create, Alter, Drop,
                                        Rename, Truncate
DML(Data Manipulation Language:         Insert, update, delete
                                        Merge
DQL(Data Query Language)        :       Select
DCL(Data Control Language)              :     Grant, Revoke
TCL(Transaction Control Language)       :     Commit, Rollback, Savepoint

Select * from tablename;

Select Field name(s) separated by commas;


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


Logical operators :    and, or, not

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


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

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

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

SQL QUERIES
create 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 EMPLOYEE
SELECT * FROM EMPLOYEE ORDER BY SALARY DESC
SELECT * FROM EMPLOYEE WHERE SALARY>400
SELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME, DEPTNO
SELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME DESC,
DEPTNO
SELECT * 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 the
entire table or rows having some common value). Some group functions are AVG(Distinct|
All), COUNT(Distinct|All), MAX(Distinct|All), MIN(Distinct|All), STDDEV(Distinct|All),
SUM(Distinct|All), VARIANCE(Distinct|All). All group functions ignore NULL values. The
DISTINCT clause, if used with a group function, makes it consider only the non-duplicate
values. The ALL clause makes it consider all the values.. The default is ALL.

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



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

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

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

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

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

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

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

Joins
Cartesian Product
When the join condition is invalid or is omitted. All rows in the first table are joined to all
rows in the 2nd table

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

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

RIGHT OUTER JOIN
(display all records frm righttable)
select * from deptmast d, employee e where D.DEPTNO(+)=E.DEPTNO ORDER BY
D.DEPTNO, E.EMPNO
OR
select * from deptmast RIGHT outer join employee on deptmast.deptno=employee.deptno
ORDER 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.deptno
ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO;

OR

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

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

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

this will help u
Non-Equi Join
It involves an operator other than the equality(=) operator. It uses operators like <=, >= or
Between.
Example
Employee                           Sal_Grade
Empno       Empname Salary         Grade       Min_Sal     Max_sal
10          hhh         3300             A     3000        5000
23          ggg         4500             B     5001        7500
35          jjj         7800             C     7501        10000
67          lll         8700             D     10000       15000
89          ppp         9600
67          ooo         10200
Select e.empno, e.empname, e.salary, j.grade from employee e, Sal_Grade j where
e.salary BETWEEN j.Min_Sal and j.Max_sal

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

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

                                             30
Natural Join
SELECT * FROM STUDENT1 NATURAL JOIN STUDENTS;
Here it will display all the records from the 2 tables who have the same values for all the
fields with the same name
ROLLNO                        NUMBER(3)
NAME1                        VARCHAR2(25)
STD                         NUMBER
DIV                        VARCHAR2(1)

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

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

UNION
select deptname from deptmast
union
select dept_desc from dept_mast
will not display duplicate values

UNION ALL
(common records twice&uncomn once)

select deptname from deptmast
union all
select dept_desc from dept_mast
will display all values from both the table including duplicate values

INTERSECT
select deptname from deptmast
intersect
select dept_desc from dept_mast

                                                  31
common values(or intersection) from both the tables

MINUS
select studname from students
minus
select name1 from student1;
present in 1st table but not in second;

select name1 from student1
minus
select studname from students
present in 1st table but not in second;

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

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

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



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

Exists
select deptno,deptname from deptmast d where
exists(select * from employee e where e.deptno=d.deptno
group by e.deptno
having count(e.deptno)=3)
order by d.deptno

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


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

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

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

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

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

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

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

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

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

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

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


Multiple Row Subqueries or Multiple Row Comparison operators

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

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

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

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


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

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

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

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



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

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

create or replace view stud1
as
select * from students where maths>70;

select * from stud1;

update students set english=70 where rollno=1;

select * from stud1;

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

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

select * from students;

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

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

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

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

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




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

                                             35
It contains the DISTINCT keyword
It contains the pseudolumn ROWNUM

You cannot update a row from a view if :
It contains group by clause
It contains the DISTINCT keyword
It contains the pseudolumn ROWNUM
It contains calculated columns or expressions

You cannot insert row thru a view
It contains group by clause
It contains the DISTINCT keyword
It contains the pseudolumn ROWNUM
It contains calculated columns or expressions
NOT NULL columns in the base table are not included in the view

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


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

To drop a view
Drop view viewname

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

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

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

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

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


Producing Readable Report
Substitution Variables using single ampersand
select * from dept_mast where dept_code=&Department_Code
The variable is created and discarded after use

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

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

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

select * from &table_name

select * from &table_name order by &column

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

Example
Define abc=hemant
Define xyz=25

Both are character type variables

Define variablename
To see the value and data type of that variable

Define
Displays all variables, their values and data types for that session

Undefine variablename

                                              37
To remove the variable from memory

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

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

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

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


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

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


commit and rollback
How to commit
1)   commit command;

     Implicit Commit
2)   A DDL Command : Create, Drop, Alter, Audit
3)   When you say :Exit or Quit; Connect or Disconnect

How to Rollback
1)   Rollback command

                                             38
2)    Rollback to savepointname

      Implicit Rollback
3)    when you switch off;
4)    hard disk crash
5)    Power failure

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

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

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

set autocommit on;
now every DML is committed immediately

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

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

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


Objects or User-defined types
create 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 Employee
Empno
Person   ----   fullname
          Fname
          Mname
          Lname
Address ----    city varchar2(15),
          state varchar2(20),
          zip number(7)


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

select * from employee;

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

nested types
create 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 employee
values(111,personal_type('Hemant',address_type('Mumbai','Maharashtra',400068)),1000.0)




Character Functions

Select fname||lname from students;

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

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

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

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

update students set fname=upper(fname)

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

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

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

select ascii(studname) from students;

                                               41
ascii-ascii value of the first character of the string

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

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

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

select instr(‘man’,studname) from students

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

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

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

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

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

select ltrim(' * *         Hemant                     ','* '), sysdate from dual
to 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 string

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

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

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

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

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

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

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

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

Numeric functions
select maths+science, maths-science, maths*science, maths/science from students

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

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

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

                                               43
Hyperbolic Sine, Hyperbolic Cosine, Hyperbolic Tangent of specified number

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

select vsize(maths) from students;

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

trunc-truncates the value to the specified precision

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

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

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

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

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

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

select 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 infinity

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

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


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

select sysdate+1 from dual;

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


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

select localtimestamp from dual;

select months_between(sysdate,to_date('31-Jan-05')) from dual
select 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 dual
next_day—gives the date of the specific day(Monday, Tuesday, etc) after the specified date
select next_day(sysdate-7, 'Friday') from dual
for previous friday

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

select to_char(sysdate) from dual;

                                                  45
to_char—date to character

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

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

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

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

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

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

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

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

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

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

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

                                             46
Try DTH, DSP,DSPTH in upper or lower case

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

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

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

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

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

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

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




LIST Functions
NVL function for NULL
any comparison done with NULL returns NULL
select * from employee where salary=NULL
hence
Select * from employee where salary is NULL

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

select nvl(salary,0)+300 from employee


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

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

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

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

Decode
select decode(deptno, 1,'Sales', 2,'Accounts', 3,'Medical', 'Others') from employee
Similar to your switch case in C/C++
select decode(deptno, 1,salary*2, 2,Salary*3,3,Salary*4, salary*3/2) from employee
Uses :
Number to Word Conversion
Encryption/Decryption

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

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

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

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

                                               48
when 3 then 1.30*salary
else 500
end from employee

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

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

Numtodsinterval

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

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

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

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

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

numtoyminterval
select numtoyminterval(15, 'month') from dual
converts 15 months to 1 year , 3 months

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

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

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

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

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

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


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

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

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

ORA cannot be forced to use indexes


Suppose you have the following table
Rowid          Empno       Name                Salary
1         5          aaa
2         2          bbb
3         3          ggg
4         7          mmm
5         9          pon
6         1          lon
7         4          jhg

                                              50
8          6           jkl

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

select * from user_indexes
Rowid             Empno           Name              Salary
6            1
2            2
3            3
7            4
1            5
8            6
4            7
5            9

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

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

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

When not to create an Index :
The table is quite small
The table is frequently updated by DML operations
The columns of the table are not frequently used as a search condition in a query
Most queries are expected to return more than 4 percent of the rows
The 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 clause
must be indexed
All index like PK, unique key and others are dropped when you drop the table

ORA creates index in a B-tree format




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

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

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

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

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

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

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

                                            52
ic.table_name=’EMPLOYEES’


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

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

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

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

select * from user_synonyms;

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

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

Create public synonym synonymname for object;

Sequences

Automatically generates unique numbers
Is a sharable object
Typically used to create primary key values
Speeds 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 old
rows being updated in the table.



create sequence myseq increment by 1 start with 100;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

To drop a sequence
Drop Sequence Sequencename;

Controlling User Access

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

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

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

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

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

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

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

Create Role rolename

Grant Create session, Create table, Create view to rolename

Grant rolename to user1, user2, etc.

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

Create role myrole

Grant Connect, Resource to myrole

Create user hemant identified by hemant123

Grant myrole to hemant

                                             56
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 password

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

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

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

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

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


                                                 57
GRANT OPTION]

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

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

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

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

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

To avoid this long name, you may create a synonym as follows
Create Public Synonym mysyn rmemp for emp@abc.pqr.com

And now, you may :

                                               58
Select * from mysyn;

You cannot Grant privileges to others on remote objects.


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

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

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

                                                  59
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_GRP
From employees
Group By Rollup(Companyid, Deptid)

select companyid, deptid, sum(salary),
GROUPING(Companyid) Company_GRP,
GROUPING(Deptid) Dept_GRP
From employees
Group By Cube(Companyid, Deptid)

select companyid, deptid, jobid,sum(salary),
GROUPING(Companyid) Company_GRP,
GROUPING(Deptid) Dept_GRP,
GROUPING(Jobid) Job_GRP
From employees
Group By Rollup(Companyid, Deptid,jobid)

select companyid, deptid, jobid,sum(salary),
GROUPING(Companyid) Company_GRP,
GROUPING(Deptid) Dept_GRP,
GROUPING(Jobid) Job_GRP
From employees
Group By Cube(Companyid, Deptid,jobid)

Grouping SETS

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

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


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

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

Composite Columns

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

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

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

Concatenated Groupings

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

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

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

select companyid, deptid, jobid,sum(salary)
From employees
Group 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 Comparison

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

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


Sub-Query in the From Clause(Inline View)

EMPID EMPNAME             MGRID             DEPID        SALARY

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

                                                62
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes
notes

Contenu connexe

Tendances

Overview of oracle database
Overview of oracle databaseOverview of oracle database
Overview of oracle database
Samar Prasad
 
Datastage parallell jobs vs datastage server jobs
Datastage parallell jobs vs datastage server jobsDatastage parallell jobs vs datastage server jobs
Datastage parallell jobs vs datastage server jobs
shanker_uma
 

Tendances (20)

Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangaloreOracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
 
siddharthaBS_DBA
siddharthaBS_DBAsiddharthaBS_DBA
siddharthaBS_DBA
 
Overview of oracle database
Overview of oracle databaseOverview of oracle database
Overview of oracle database
 
Handy annotations-within-oracle-10g
Handy annotations-within-oracle-10gHandy annotations-within-oracle-10g
Handy annotations-within-oracle-10g
 
Whats New Sql Server 2008 R2
Whats New Sql Server 2008 R2Whats New Sql Server 2008 R2
Whats New Sql Server 2008 R2
 
SQL Server 2008 Overview
SQL Server 2008 OverviewSQL Server 2008 Overview
SQL Server 2008 Overview
 
Whats New Sql Server 2008 R2 Cw
Whats New Sql Server 2008 R2 CwWhats New Sql Server 2008 R2 Cw
Whats New Sql Server 2008 R2 Cw
 
Oracle Tablespace - Basic
Oracle Tablespace - BasicOracle Tablespace - Basic
Oracle Tablespace - Basic
 
10g sql e book
10g sql e book10g sql e book
10g sql e book
 
MSBI with SQL Server T-SQL | Microsoft BI With Server T-SQL | Realtime Traini...
MSBI with SQL Server T-SQL | Microsoft BI With Server T-SQL | Realtime Traini...MSBI with SQL Server T-SQL | Microsoft BI With Server T-SQL | Realtime Traini...
MSBI with SQL Server T-SQL | Microsoft BI With Server T-SQL | Realtime Traini...
 
Ramesh_Oracle_DBA
Ramesh_Oracle_DBARamesh_Oracle_DBA
Ramesh_Oracle_DBA
 
Migration from 8.1 to 11.3
Migration from 8.1 to 11.3Migration from 8.1 to 11.3
Migration from 8.1 to 11.3
 
Oracle dba online training
Oracle dba online trainingOracle dba online training
Oracle dba online training
 
Oracle Database Introduction
Oracle Database IntroductionOracle Database Introduction
Oracle Database Introduction
 
Datastage parallell jobs vs datastage server jobs
Datastage parallell jobs vs datastage server jobsDatastage parallell jobs vs datastage server jobs
Datastage parallell jobs vs datastage server jobs
 
Summer training oracle
Summer training   oracle Summer training   oracle
Summer training oracle
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Windowing Functions - Little Rock Tech Fest 2019
Windowing Functions - Little Rock Tech Fest 2019Windowing Functions - Little Rock Tech Fest 2019
Windowing Functions - Little Rock Tech Fest 2019
 
Oracle DBA
Oracle DBAOracle DBA
Oracle DBA
 
Homework help on oracle
Homework help on oracleHomework help on oracle
Homework help on oracle
 

En vedette (6)

D17111 gc30 sg2
D17111 gc30 sg2D17111 gc30 sg2
D17111 gc30 sg2
 
D17108 gc30 sg3
D17108 gc30 sg3D17108 gc30 sg3
D17108 gc30 sg3
 
D17108 gc30 sg1
D17108 gc30 sg1D17108 gc30 sg1
D17108 gc30 sg1
 
D17111 gc30 sg1
D17111 gc30 sg1D17111 gc30 sg1
D17111 gc30 sg1
 
D17108 gc30 sg2
D17108 gc30 sg2D17108 gc30 sg2
D17108 gc30 sg2
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 

Similaire à notes

Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
arihantplastictanksh
 
1.sap basis material_keylabs1
1.sap basis material_keylabs11.sap basis material_keylabs1
1.sap basis material_keylabs1
chipanda
 
Perfsystems- Consulting Services
Perfsystems- Consulting ServicesPerfsystems- Consulting Services
Perfsystems- Consulting Services
Perfsys Tems
 
Discussion post· The proper implementation of a database is es.docx
Discussion post· The proper implementation of a database is es.docxDiscussion post· The proper implementation of a database is es.docx
Discussion post· The proper implementation of a database is es.docx
madlynplamondon
 

Similaire à notes (20)

Database Management System
Database Management SystemDatabase Management System
Database Management System
 
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdfCompare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
Compare the capabilities of the Microsoft Access, Microsoft SQL Serv.pdf
 
Mohamed Mahgoub_CV
Mohamed Mahgoub_CVMohamed Mahgoub_CV
Mohamed Mahgoub_CV
 
Introduction to Oracle Database
Introduction to Oracle DatabaseIntroduction to Oracle Database
Introduction to Oracle Database
 
Informatica Interview Questions & Answers
Informatica Interview Questions & AnswersInformatica Interview Questions & Answers
Informatica Interview Questions & Answers
 
SAP BASIS ONLINE TRAINING MATERIAL by Keylabs
SAP BASIS ONLINE TRAINING MATERIAL by KeylabsSAP BASIS ONLINE TRAINING MATERIAL by Keylabs
SAP BASIS ONLINE TRAINING MATERIAL by Keylabs
 
1.sap basis material_keylabs1
1.sap basis material_keylabs11.sap basis material_keylabs1
1.sap basis material_keylabs1
 
Project seminar
Project seminarProject seminar
Project seminar
 
LESSON 1 - DATABASE MANAGEMENT SYSTEM.pptx
LESSON 1 - DATABASE MANAGEMENT SYSTEM.pptxLESSON 1 - DATABASE MANAGEMENT SYSTEM.pptx
LESSON 1 - DATABASE MANAGEMENT SYSTEM.pptx
 
MySQL 8.0 Featured for Developers
MySQL 8.0 Featured for DevelopersMySQL 8.0 Featured for Developers
MySQL 8.0 Featured for Developers
 
Best Practices for Building and Deploying Data Pipelines in Apache Spark
Best Practices for Building and Deploying Data Pipelines in Apache SparkBest Practices for Building and Deploying Data Pipelines in Apache Spark
Best Practices for Building and Deploying Data Pipelines in Apache Spark
 
Perfsystems- Consulting Services
Perfsystems- Consulting ServicesPerfsystems- Consulting Services
Perfsystems- Consulting Services
 
Vineet Kurrewar
Vineet KurrewarVineet Kurrewar
Vineet Kurrewar
 
Technology
TechnologyTechnology
Technology
 
Oracle Intro.ppt
Oracle Intro.pptOracle Intro.ppt
Oracle Intro.ppt
 
Oracle's history
Oracle's historyOracle's history
Oracle's history
 
The oracle database architecture
The oracle database architectureThe oracle database architecture
The oracle database architecture
 
Discussion post· The proper implementation of a database is es.docx
Discussion post· The proper implementation of a database is es.docxDiscussion post· The proper implementation of a database is es.docx
Discussion post· The proper implementation of a database is es.docx
 
Technical Skillwise
Technical SkillwiseTechnical Skillwise
Technical Skillwise
 
Oracle
OracleOracle
Oracle
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

notes

  • 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. 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 i stands for Internet or Intelligent, as it is an extensive support for Internet-based applications Some of the major Oracle 9i Software Development Tools : 1) SQL 2) SQL * Plus 3) PL/SQL 4) Oracle Forms 9i 5) Oracle Reports 9i 6) Oracle Menus 7) Oracle Graphics 8) IDS 9) EXP 10) IMP 11) SQL * Loader 12) OEM 13) Oracle Case 14) Designer 2000 15) Oracle Financials 16) Oracle Manufacturing 17) Oracle HRMS 18) Oracle Application 19) Oracle CRM 20) Personal Oracle 21) OraTerm 1) SQL(Structured Query Language) Supports only 9 commands : Create, Alter, Drop 2
  • 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 Reports 3) PL/SQL(Procedural Language/SQL) It is the programming language of Oracle. For MS SQL, we have Transact SQL 4) 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/RDBMS 5) Oracle Reports 9i Oracle’s Report Writing Software 6) Oracle Menus Oracle’s Menu Building Software 7) Oracle Graphics For Charts, Graphs, etc based on Oracle data 8) IDS(Integrated Development Suite) Combination of Forms+Reports+Menus+Graphics. Earlier known as D2K(Developer 2000) 9) EXP 10) 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. databases. One cannot export data and expect to import it into a non-Oracle database. They are used to perform the following : • Backup and recovery (small databases only) • Reorganization of data/ Eliminate database fragmentation • Detect database corruption. Ensure that all the data can be read. • Transporting tablespaces between databases 11) SQL * 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+IDS 15) 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. resources-related activities, including recruiting, performance management, learning, compensation, and real time analytics 18) Oracle CRM Oracle's integrated Customer Relationship Management (CRM) solution is a set of applications that give you information-driven sales, service, and marketing. Oracle CRM is built on an open, standards-based architecture that streamlines business processes, improves data quality, and allows all your key divisions to draw from the same source of data. 19) Oracle 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 Paradox 21) OraTerm(Used for Keyboard Mapping) On the terminal side, when a key is pressed on the keyboard, the keyboard controller produces a code, or a sequence of codes, which are then sent on to the host system. These codes are different for each type of keyboard (PC, Macintosh, Sun), and thus we must have a unique resource file for each keyboard type. For example, an Enter key pressed would mean to press OK in a Dialog Box. The Enter key could be configured to do something else, if needed. Also Relational Databases In relational databases we have only type of Data Stores or Data Structures- called Tables Why is it called Relational? Suppose you have two tables EmpMaster Empno Empname Salary Deptno 1 abc 100 1 2 lkm 2000 2 3 kkk 876 3 4 ppp 569 3 5
  • 6. 5 uuu 679 2 6 yyy 7789 3 7 ttt 6878 1 8 rrr 5765 1 9 eee 6886 2 10 ppu 687 3 DeptMaster Deptno Deptname 1 Accounts 2 Administration 3 Medical Here, even though the tables are separate and independent, they are related. The filed or column “Deptno” in empmaster table is related to the column “Deptno” in the DeptMaster table. This relationship is the basis of Relational Databases, and this approach is also called the Relational Model approach. The Data is stored only in tables. The tables have columns and rows. The tables can be related to each other if each one of them has a column with a common type of information. What is SQL(Structured Query Language) Oracle was the first company to release a product that used a English-based Structured Query Language or SQL. It is pronounced as SEQUEL.. This language allows the end users to extract information themselves, without using system level command(which were used earlier) for retrieving every little piece of information. It is called Structured Language since like any other language it has got a structure or rules of grammar or syntax. It is called Query Language since it’s fundamental use is to ask questions or query the database and get the relevant answers to those questions or queries. What is PL/SQL(Procedural Language/Structured Query Language) SQL is a Non-procedural 4th Generation Language, which means it has got no iteration no variable declarations no loops PL/SQL is a procedural extension to SQL. 6
  • 7. It is a superset of SQL which allows you to implement your business rules or logic through creation of Stored procedures, packages, Triggers, Functions or any other programming logic for the execution of SQL Commands. Section of PL SQL Block : Declare Defines and initializes the variables and cursors used in the PL/SQL Block Begin 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 time End; Marks the end of the PL/SQL Block. Followed by a semicolon called terminator. Theoretical and Physical aspects of Oracle Oracle creates a SGA(System/Shared Global Area) when you start the Oracle Database. Also a few background processes are started to maintain the Oracle Database. These processes and the SGA are together called ORACLE INSTANCE. Then, the database is opened and maintained. Oracle 8i first came up with the concept of OOPS at the backend or database level thru nested objects, nested tables, etc., thru built in Java support at the database level. I stands for intelligent or internet, where in the implementation of OOPS at the database level resulted in faster retrieval of data, especially for Web-based applications. The application server was brought into the picture at the backend level. Oracle 9i came up with the concept of Parallel Processing(or Clustered Servers) whereby a set of low-cost servers(like xeon servers) each having its own set of daemons(system level programs handling the single database) could handle or manage a single database, unlike the earlier versions, where only one set of daemons could handle the database(dbf files). Thus there is tremendous reduction in costs(instead of using a single mainframe or expensive server on which the Oracle database lies, you can have a set of low-cost servers with their own set of daemons to handle the database on a single server(or array of 7
  • 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. Create a table Rules for Table /Column name : Maximum 30 characters A-Z, a-z, 0-9 Has to begin with alphabet Can contain #, _, $ Case insensitive Datatypes Char Fixed length character data. Maximum 2000 bytes. Default 1 byte Nchar Multibyte character set version of char. Since some National character sets may have a character taking more than 1 byte Varchar2() Variable length character string having a maximum size of 4000 bytes Nvarchar2 Variable length character string having a maximum size of 4000 bytes or characters depending upon the type of National character set, since in some national character set one character may take 2 or more bytes CLOB Character Large Objects upto 4GB in length NCLOB Same as CLOB, but for multibyte character sets BLOB Binary Large Objects upto 4 GB BFILE To point to a binary operating system file Create table proposal 9
  • 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 Excel spreadsheets used for documenting and price-details of the proposal. Proposal_Text CLOB(containing the text of the proposal) Budget BLOB(containing spreadsheet showing calculations of cost and profit from proposal Cover_letter BFILE(A binary file stored outside the database that contains your covering letter) Oracle ensures the data-integrity of CLOB and BLOB and NCLOB(since this type of data is actually stored in the database itself), but not BFILE(since such data is not stored in the database, but Oracle just maintains a pointer to such file) For all LOB columns the data is not stored within the table. Actually within the table Oracle stores locators(pointers), which point to the locations within the database which are created by the database to hold LOB objects Number(p,d) Example : Number(5,2) can take a maximum of 999.99 Long Character data of variable size upto 2GB. Only one long column per table. Cannot be used in subqueries, functions, where clause, indexes. Table cannot be clustered Raw Raw binary data. Upto 255 bytes. Contains Binary data in whatever form the host computer stores it. Used for storing binary(non-character data) small sized(less bytes) photos, images Long Raw Raw binary data, otherwise the same as Long. Large sized photos and images. In place of LONG and LONG RAW, Oracle recommends that you use CLOB and BLOB respectively Date 10
  • 11. Dates between January 1, 4712 BC upto December 31, 9999 AD Timestamp(precision) Date plus time where precision is the number of digits in the fractional part of the seconds(by default 6). Example ’23-JAN-06 8:45:34.000000’ Interval Year(precision) to month Difference in two timestamp fields/values in terms of years to months, where precision(by default 2) is the number of digits in the year part. Example ’12-2’ means 12 years and 2 months Interval day(day_precision) to second(sec_precision) Difference in two timestamp files in terms of days, hours, minutes and seconds, where day_precision(by default 2) is the number of digits in the day-part and sec_precision(by default 6) is the number of digits in the fractional part of the seconds-part. Example ‘14 5:56:45.456654’ means 14 days, 5 hours, 56 minutes, 45.456654 seconds Rowid A unqiue number assigned to each row in a database. Returned by pseudo-column ROWID Urowid(size) Hexadecimal string to identify the logical address of a row in a indexed-organised table in a database. Maximum size is 4000 bytes Create table mystuds ( rollno number(5), Name varchar2(25), Total number(5,2) default 0); The default value is put for every new row instead of a NULL value Creating table from another table create table yostud (r,s,e,m,sc,t,b,te) as select * from students or create 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. Example: Rename students TO studs; Constraints Usually created at the same time as the table creation. Can also be added to a table after the table creation Can also be temporarily disabled and enabled. Can be permanently dropped The system may give it’s own unique constraint names like SYS_PK779 If the constraint names are given by the user, then care should be taken to ensure that no other constraint for any other table has the same name. You can add, drop, enable or disable constraints, but not modify it. Two- types Column 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 Constraint NULL values not allowed Duplicate allowed Any number of NOT NULL in a table It is a column level constraint No composite NOT NULL exists create table student ( rollno number(3) constraint PK_Stud_rollno primary key, name varchar2(25) NOT NULL, eng number(3,2)); or create table student 12
  • 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 then Alter table stud modify name varchar2(20) constraint nn_stud_name NOT NULL; UNIQUE KEY Duplicates not allowed NULL values allowed, unless otherwise specified as NOT NULL Long and LONG RAW cannot be unique Composite Unique key allowed No upper limit on individual Unique keys/Composite Unique Keys In case of Individual Uk, any number of rows can have NULL values for that column In case of Composite UK, both columns can have NULL values for any number of rows But in case of Composite UK, if one column contains NULL value for a row , and the other column contains a value say “XYZ”, then you cannot have another row with the same combination of values(that is NULL value for first column and ‘XYZ’ for second column) create table orders ( orderno varchar2(15), itemno varchar2(15), quantity number(5), price number(8,2), constraint myconstraint unique(orderno,itemno) ) If table already exists then Alter table orders add constraint my_un_con unique(ordeno, itemno) insert into orders values('ord1','itm1',456,123456.78) insert into orders values('ord1','itm2',78.90,123456.78) insert into orders values('ord1','itm3',89.43,123456.789) insert into orders values('ord1','itm4',89.439,1234567)---error insert into orders(quantity,price) values(90.99,999999.99) Other options of Inserting Rows : 13
  • 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 the columns are defined in the table insert into students values(250,’Hemant’,’Pangam’,’26- JUL-1976’,’1’,’A’,89.90,67.50,63.75,0,100); For changing the order in which the values are entered you have to specify the same in the brackets after the tablename : Insert into students(Firstname, Lastname, rollno, Div, Std, Birthdate, Tcode, Total, Maths, Science, English) values(‘Manoj’,’Pangam’,202,’C’,’10’,’02-DEC-1977’,200,0, 75.75,50.25,90.50); For inserting values only into specific columns, specify the columns in the brackets after the table name. This is also called Implicit method of inserting NULL values for the columns not specified. Insert into students(Firstname, Lastname, rollno) values(‘Hetal’,’Pangam’,212); For explicitly inserting NULL values : insert into students values(265,’Jairaj’,’Saraf’,’06- MAR-2001’,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Inserting special values like current date, current user : insert into students values(269,user,’Saraf’,sysdate,NULL,NULL,NULL,NULL,NULL,NULL,NULL); Inserting specific date values : By default date is always inserted into the table in the DD-MON-YY format(where YY represents current century, if while inserting the century is not specified). Because date also contains time, the default time saved in a date column is 00:00:00. If u want to enter date in a different format, such as another century than the current century or with a specific time then : 14
  • 15. insert into students values(299,’Mamta’,’Varma’,to_date(‘NOV 20, 1981 15:45:56’,’MON DD, YYYY hh24:mi:ss’),NULL, NULL, NULL, NULL, NULL, NULL, NULL); to see the actual values stored : select firstname, to_char(birthdate,'DD-MM-YYYY hh24:mi:ss') from students For inserting with a suitable prompt insert into students values('&ordernumber', '&itemnumber', &quan, &pric") insert into students values(&RollNumber, '&Firstname', '&Lastname', '&Birth', '&Standard', '&Division', &ENGmarks, &mathematics, &Sciencescore, &FinalTotal,&teacher ) ‘ ‘ for character and date, not for number Alter Table alter table orders add( remark varchar2(10), billno varchar2(10) not null) error-since table must be empty(delete all records), as there are records and hence billno will not find values for the existing records hence alter table orders add( remark varchar2(10), billno varchar2(10)) select * from orders update studs set remark='hello' alter table orders modify ( remark varchar2(10) not null ) alter table orders drop column remark alter table orders drop(remark, abc) alter table orders set unused column remark 15
  • 16. alter table orders set unused column abc alter table tablename set unused(col1, col2) This feature is available 8i onwards so that we do not effect the speed of an online database. Since dropping a column at peak hours may slow down the speed tremendously. So we mark a column as unsued and later on drop it when the system demand/system resource use is low. You have no access to the column and is as good as dropped. No query allowed on such unused columns. The column name and datatype are not seen with the describe command. alter table orders drop unused columns Alter table tablename add/modify column columnname default defaultexpression; Alter table can be used to add a default value for a new/existing columns can increase character columns width at any time can increase the number of digits in a number column at any time can increase or decrease the number of decimal places in a number column at any time if a column is NULL for every row of a table can change the column's datatype can decrease a character column's width you can decrease the number of digits in an NUMBER Alter table tablename drop constraint Primary key; To drop the PK constraint Alter table tablename drop constraint unique(column/columns name) To drop the Unique constraint on a column or columns Alter table tablename drop constraint constraintname To drop any constraint by it’s name Alter table tablename disable constraint constraintname; Alter table tablename enable constraint constraintname; A column cannot be dropped, if it is involved in some constraints. Hence we used the CASCADE CONSTRAINTS option as follows with the alter table : Alter table tablename DROP (columnname) cascade constraints; 16
  • 17. Viewing Constraints : To view the constraint definitions and names : Select constraint_name, constraint_type, search_condition from USER_Constraints where table_name =’ORDERS’ To view the columns associated with the constraint names Select constraint_name, column_name from USER_CONS_COLUMNS where Table_name=’ORDERS’ Tables owned by the user Select table_name from user_tables; To see the different objects owned by the user Select distinct object_type, object_name from user_objects To see the distinct object types owned by the user Select distinct object_type from user_objects To see the tables, views, synonyms and sequences owned by the user Select * from user_catalog You can add comment to a table/column as follows : comment on table students is 'Information abount my students'; select * from user_tab_comments where table_name='STUDENTS'; select * from all_tab_comments where table_name='STUDENTS'; Will show all the user tables(if where absent)/all tables(if where absent)/specified table with/ without a comment. comment on column students.studname is 'Names of my students'; select * from user_col_comments where table_name='STUDENTS'; select * from all_col_comments where table_name='STUDENTS'; both the above will show all the columns of all the tables(if where clause not given) or specified table who have got atleast one column with a comment. PRIMARY KEY Key that uniquely identifies each row of a table Duplicate values not allowed Null values not allowed Recommended for every table Any column can be a PK, except LONG and Long RAW 17
  • 18. Purpose : Record Uniqueness Can have a Composite PK Null values not allowed for any column of the Composite PK. Only one PK/Composite PK per table PK can be defined at column level. CPK is always defined at table-level. A candidate key is that key that can also serve as a PK. Example if all employees are having a mobile then even mobile_no can be a PKs PK constraint is at Server level, hence cannot be bypassed by a Front-end Select * from user_constraints where table_name=’EMP’; EMP in upper case, since Oracle stores table and column names in upper case If you don’t specify the constraint name , Oracle gives it’s own constraint names like Constraint_Name Constraint_Type SYS146788 P for single column primary key create table student ( rollno number(3) primary key, name varchar2(25) NOT NULL, eng number(3,2)); OR create table student ( rollno number(3) constraint PK_Stud_rollno primary key, name varchar2(25) NOT NULL, eng number(3,2)); for multiple column primary key create table student1 ( stan varchar2(2) NOT NULL, div varchar2(1) NOT NULL, rollno number(3), name1 varchar2(25) NOT NULL, 18
  • 19. eng number(3,2), constraint my_primarykey primary key(stan,div,rollno) ); If a table is already created then Alter table stud Add constraint my_con primary key(rollno); FOREIGN KEY and CHECK Constraint Foreign Key : A column or set of columns that take the reference of some other column from some other table or the same table Must be a Primary or Unique Key in the parent table Child table may have NULL or duplicate values Master records cannot be deleted, if a child record exists ON DELETE CASCADE indicates that when a row in the parent table is deleted, the corresponding rows in the child table are automatically deleted. ON DELETE SET NULL indicates that when a row in the parent table is deleted, the foreign column in the corresponding child rows will be updated to NULL. Without ON DELETE CASCADE and ON DELETE SET NULL, the parent row cannot be deleted if a child row exists. Both these options can be set at column or table level. Check constraint : It defines a condition that each row must satisfy create table itemmast ( itemno varchar2(15) primary key, itemname varchar2(25) NOT NULL, company varchar2(15) NOT NULL, remark varchar2(25) NOT NULL, unitprice number(8,2) constraint upcons CHECK(unitprice>100) 19
  • 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) ) or column level : create table orders ( orderno varchar2(15), itemno varchar2(15) constraint fk references itemmast(itemno), quantity number(5), price number(8,2) check (price>100.50), constraint myconstraint1 unique(orderno,itemno) ) create table orders1 ( orderno varchar2(15), itemno varchar2(15), quantity number(5), price number(8,2) check (price>100.50), constraint myconstraint6 unique(orderno,itemno), constraint fk11 foreign key(itemno) references itemmast(itemno) on delete cascade ) insert into orders values('o3','4',67,89) insert into orders values('o3','4',67,989) drop table orders; when a table is dropped, the database looses all the data in the table and all the indexes associated with it. View and Synonyms based on the table still remain , but are invalid. No rollback possible. 20
  • 21. Delete students; Delete all the rows from the students table, but the memory occupied by the rows is still not released. Rollback can be used to get back the rows. truncate table orders; It is a DDL statement, which is used to remove all the rows permanently from the table , i.e, no rollback possible.. The storage spaced occupied by the rows is released. Table still exists with 0 rows. select * from user_cons_columns select * from user_constraints update user_constraints set status='DISABLED' where constraint_name='SYS_C0034437' For inserting & into a field set 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; Update update orders set quantity=500; rollback; update orders set quantity=550, price=900 where quantity=500 or price=190.9; commit; update orders set quantity=null; rollback; Drop table tablename; Normalisation First Normal Form(FNF) 21
  • 22. A relation or table is said to be in the 1st Normal Form when it has no composite attributes or columns , and every attribute(column or field) is single or individual and describes only one property. It is also called Flat file Example: Order_details Item_code Quantity Price_per_unit 1456 of 26/02/1989 3687 52 50.40 1456 of 26/02/1989 4627 38 60.20 1456 of 26/02/1989 3214 20 17.50 1886 of 04/03/1992 4629 45 20.25 1886 of 04/03/1992 4627 30 60.20 1788 of 04/04/1992 4627 40 60.20 FNF Order_No Order_date Item_code Quantity Price_per_unit 1456 26/02/1989 3687 52 50.40 1456 26/02/1989 4627 38 60.20 1456 26/02/1989 3214 20 17.50 1886 04/03/1992 4629 45 20.25 1886 04/03/1992 4627 30 60.20 1788 04/04/1992 4627 40 60.20 Second Normal Form(SNF) A relation is said to be in the 2NF, when it is in the 1NF, and the Non-key attributes are functionally dependent on the key attributes(s)or composite Primary Key. Example : Consider the FNF given above. Here, Price_per_unit is functionally dependent on Item_code; and Order_date is functionally dependent on Order_No. Thus, the relation is not in 2NF. Therefore, it is split into 3 tables as follows to give 2NF : Order_Mast : Order_No Order_date 1456 26/02/1989 1886 04/03/1992 1788 04/04/1992 Item_Mast Item_code Price_unit 3687 50.40 4627 60.20 3214 17.50 4629 20.25 22
  • 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 40 Third Normal Form(SNF) A table or relation is said to be in TNF when it is in the 2NF, and No non-key attributes are functionally dependent on any other non-key attribute Example : Consider the following in 2NF: Roll_No Name Department Year Hostel_name 1784 Ram Physics 1 Ganga 1648 Sham Chemistry 1 Ganga 1768 Bharat Maths 2 Kaveri 1848 Arjun Botany 2 Kaveri 1682 Nakul Geology 3 Krishna 1485 Sahadeo Zoology 4 Godavari Assuming that the 1st Year, 2nd Year, 3rd Year and 4th Year students stay in Hostels Ganga, Kaveri, Krishna and Godavari respectively, then in such a case, the non-key attribute Hostel_name is dependent on the non-key attribute Year. Therefore, it is split into 2 tables as follows to give 3NF : Stud_mast Roll_No Name Department Year 1784 Ram Physics 1 1648 Sham Chemistry 1 1768 Bharat Maths 2 1848 Arjun Botany 2 1682 Nakul Geology 3 1485 Sahadeo Zoology 4 Hostel_Mast Year Hostel_name 1 Ganga 2 Kaveri 3 Krishna 23
  • 24. 4 Godavari BCNF(Boyce-Codd Normal Form) If an attribute of a composite key is dependent on an attribute of another composite key, then the BCNF is needed. Example: Professor_code Department HOD Percent_of_time P1 Physics Ghosh 50 P1 Mathematics Krishnan 50 P2 Chemistry Rao 25 P2 Physics Ghosh 75 P3 Mathematics Krishnan 100 Assumptions : A professor can work in more than one department. Percentage of time spent by professor in each department is given Each department has only one HOD Here the 2 possible composite Keys(Composite Primary keys) could be 1) Professor_code + Department 2) Professor_code + HOD Thus, in the 1st case, the attribute Department depends on the attribute HOD of the 2nd CP And, in the 2nd case, the attribute HOD depends on the attribute Department of the 1st CP. Also, there is duplication of the combination of “Department + HOD”. Also, if professor P2 resigns and rows 3 and 4 have to be deleted, then we loose the information “Rao is the HOD of Chemistry” Therefore, BCNF is needed, and the relation is broken down to Prof_Mast Professor_code Department Percent_of_time P1 Physics 50 P1 Mathematics 50 P2 Chemistry 25 P2 Physics 75 P3 Mathematics 100 Department_Mast Department HOD Physics Ghosh Mathematics Krishnan Chemistry Rao 4NF 24
  • 25. It is needed when a relation has more than one multivalued dependencies. Thus, a relation is said to be in 4NF when it has one independent multivalued dependency with a functional dependency Example : Consider a vendor supplying many items to many projects in an organization where : 1) A vendor may supply many 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 Project Vendor_code Item_code Project_code V1 I1 P1 V1 I2 P1 V1 I1 P3 V1 I2 P3 V2 I2 P1 V2 I3 P1 V3 I1 P2 V3 I1 P3 Problems : If vendor V1 has to supply to project P2, but the item is not yet decided, then a row with a blank item_code will have to be inserted Information 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_Project Vendor_code Item_code Vendor_code Project_code V1 I1 V1 P1 V1 I2 V1 P3 V2 I2 V2 P1 V2 I3 V3 P2 25
  • 26. V3 I1 V3 P3 Thus, both the tables have only one multivalued dependency(For vendor_item, the MVD is one vendor has supplid many items. For Vendor_project, the MVD is that one vendor has supplied to many projects) 5NF It is obtained by adding one relation(relation with one MVD) relating attributes of the 2 relations in 4NF with one MVD. Thus in addition to the two relations in 4NF, we will have the following relation with one MVD : Project_item Project_code Item_code P1 I1 P1 I2 P1 I3 P2 I1 P3 I1 P3 I2 Types of SQL Commands : DDL(Data Definition Language) : Create, Alter, Drop, Rename, Truncate DML(Data Manipulation Language: Insert, update, delete Merge DQL(Data Query Language) : Select DCL(Data Control Language) : Grant, Revoke TCL(Transaction Control Language) : Commit, Rollback, Savepoint Select * from tablename; Select Field name(s) separated by commas; Conditional/relational operators: <, >, <=, >=, !, <> select * from orders where quantity<>4; select * from orders where quantity!=4; Logical operators : and, or, not select * from orders where itemno='1' and price>500; select * from orders where itemno='1' or itemno=3 26
  • 27. Special operators: IS NULL, between, like, in select * from orders where quantity is null select * from orders where price is NOT null select * from orders where price between 190 and 876.65(both inclusive) select * from orders where price NOT between 190 and 876.65 pattern matching with like operator : % and _ select * from orders where orderno like 'o9%' select * from orders where orderno like 'o_' select * from orders where orderno like '_2' select * from orders where orderno like '___'(3 _s) desc user_tables; desc all_tables; select table_name from user_tables; select table_name from all_tables; SQL QUERIES create 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 EMPLOYEE SELECT * FROM EMPLOYEE ORDER BY SALARY DESC SELECT * FROM EMPLOYEE WHERE SALARY>400 SELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME, DEPTNO SELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME DESC, DEPTNO SELECT * FROM EMPLOYEE WHERE SALARY>400 ORDER BY EMPNAME DESC, DEPTNO DESC 27
  • 28. GROUP Functions : Group functions operate on sets of rows to give one value per group(A group could be the entire table or rows having some common value). Some group functions are AVG(Distinct| All), COUNT(Distinct|All), MAX(Distinct|All), MIN(Distinct|All), STDDEV(Distinct|All), SUM(Distinct|All), VARIANCE(Distinct|All). All group functions ignore NULL values. The DISTINCT clause, if used with a group function, makes it consider only the non-duplicate values. The ALL clause makes it consider all the values.. The default is ALL. The AVG and SUM are used for numeric data. MAX and MIN may be used even for character or date type of data. Select sum(salary) from employees GROUP BY Clause : The Group By clause is used to divide the table into groups of rows. By using a where clause you can exclude certain rows before dividing them into groups. By default rows are sorted in the ascending order of the columns included in the group by clause. You can change the ordering by using the Order By clause. All the columns in the SELECT list that are not group functions must be included in the GROUP BY Clause. Select deptno, sum(salary) from employees Group By Deptno Select std, div, max(maths), min(science) from students group by Std, Div SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPTNO SELECT DEPTNO, MAX(SALARY) FROM EMPLOYEE GROUP BY DEPTNO; SELECT DEPTNO, MIN(SALARY) FROM EMPLOYEE GROUP BY DEPTNO; SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPTNO ORDER BY DEPTNO SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNO SELECT DEPTNO AS DEPARTMENT, SUM(SALARY) FROM EMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNO SELECT DEPTNO AS DEPARTMENT, SUM(SALARY) AS "SUM OF SALARY" FROM EMPLOYEE WHERE DEPTNO>=4 GROUP BY DEPTNO ORDER BY DEPTNO The Count(*) returns the number of rows in a table that satisfy the criteria of the select statement, including duplicate rows and rows containing NULL values. The Count(column) returns the number of rows having Non-Null values in the column The Count(distinct column) returns the number of rows having Unique Non-Null values in the column The NVL function can be used to include NULL values as follows : Select AVG(NVL(Maths,0)) from students; 28
  • 29. select deptno, count(*) from employee group by deptno The Where Clause cannot be used to restrict the groups or to specify conditions on the group function-results. To do this we use the HAVING Clause select deptno, count(*) from employee group by deptno having count(*)>=4 SELECT DEPTNO, SUM(SALARY) FROM EMPLOYEE GROUP BY DEPTNO having sum(salary)>1500(Having is used like where on results of groupedfunctions instead of individual rows) SELECT DEPTNO, MAX(SALARY) FROM EMPLOYEE GROUP BY DEPTNO ORDER BY MAX(SALARY) DESC` Select * from tablename where condition(s) group by field(s) having condition(s) order by field(s) SELECT DISTINCT DEPTNO FROM EMPLOYEE Nesting Group Functions Select Max(Avg(Maths)) from students group by std; Joins Cartesian Product When the join condition is invalid or is omitted. All rows in the first table are joined to all rows in the 2nd table select empno, empname, deptname from employee,deptmast or select empno, empname, deptname from employee cross join deptmast LEFT OUTER JOIN (non mathing records r shown .display all records frm lefttable) select * from deptmast d, employee e where E.DEPTNO(all emp+)=D.DEPTNO ORDER BY D.DEPTNO, E.EMPNO OR select * from deptmast left outer join employee on deptmast.deptno=employee.deptno ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO; All Records from department including those who do not have a corresponding employee; RIGHT OUTER JOIN (display all records frm righttable) select * from deptmast d, employee e where D.DEPTNO(+)=E.DEPTNO ORDER BY D.DEPTNO, E.EMPNO OR select * from deptmast RIGHT outer join employee on deptmast.deptno=employee.deptno ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO; 29
  • 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.deptno ORDER BY DEPTMAST.DEPTNO,EMPLOYEE.EMPNO; OR select * from deptmast d, employee e where E.DEPTNO(+)=D.DEPTNO union select * from deptmast d, employee e where D.DEPTNO(+)=E.DEPTNO All Records from both the tables, including those who do not have a corresponding department/employee in the other table; Equi Join Also called simple join/Inner join The relation between an Employee and Department tables involves as Equi-Join. The values in the common field in both the tables must be equal. select * from employee e (alises), deptmast d where e.deptno=d.deptno this will help u Non-Equi Join It involves an operator other than the equality(=) operator. It uses operators like <=, >= or Between. Example Employee Sal_Grade Empno Empname Salary Grade Min_Sal Max_sal 10 hhh 3300 A 3000 5000 23 ggg 4500 B 5001 7500 35 jjj 7800 C 7501 10000 67 lll 8700 D 10000 15000 89 ppp 9600 67 ooo 10200 Select e.empno, e.empname, e.salary, j.grade from employee e, Sal_Grade j where e.salary BETWEEN j.Min_Sal and j.Max_sal Inner Join (nt givng non matching records) select * from employee e inner join deptmast d using(deptno) same as equi join, but the column dept is not repeated as in euqi join 30
  • 31. Natural Join SELECT * FROM STUDENT1 NATURAL JOIN STUDENTS; Here it will display all the records from the 2 tables who have the same values for all the fields with the same name ROLLNO NUMBER(3) NAME1 VARCHAR2(25) STD NUMBER DIV VARCHAR2(1) Name Null? Type -------------------------- ------------- ROLLNO NOT NULL NUMBER(3) STUDNAME VARCHAR2(20) ENGLISH NUMBER(5,2) MATHS NUMBER(5,2) SCIENCE NUMBER(5,2) TOTAL NUMBER(5,2) STD NUMBER DIV VARCHAR2(1) We can use the ‘USING’ clause to decide which of the common columns should be considered as follows : Select * from student1 join students using(rollno) UNION select deptname from deptmast union select dept_desc from dept_mast will not display duplicate values UNION ALL (common records twice&uncomn once) select deptname from deptmast union all select dept_desc from dept_mast will display all values from both the table including duplicate values INTERSECT select deptname from deptmast intersect select dept_desc from dept_mast 31
  • 32. common values(or intersection) from both the tables MINUS select studname from students minus select name1 from student1; present in 1st table but not in second; select name1 from student1 minus select studname from students present in 1st table but not in second; self join (primary&) consider the table emp in scott/tiger select x.ename worker, y.ename manager from emp x, emp y where x.mgr=y.empno; IN Operator select * from students where studname NOT IN ('Hemant','Laxman') select * from students where studname IN ('Hemant','Laxman') Like Operator select * from students where studname like '___m'(last char m&3rd m) select * from students where studname NOT like '___m' select * from students where studname like 'He% Between select * from students where maths between 43 and 70 select * from students where maths NOT between 43 and 70 Exists select deptno,deptname from deptmast d where exists(select * from employee e where e.deptno=d.deptno group by e.deptno having count(e.deptno)=3) order by d.deptno Exists is same as In, but it is a logical operator 32
  • 33. Subqueries A subquery is a SELECT statement in the WHERE, HAVING or FROM clause of another SELECT statement. Select * from students where maths>(select maths from students where studname='Laxman') (assm:only 1 laxmn) The Inner query is also called Nested query or Sub query. The inner or nested or sub query generally executes first and it’s output is used as the input for the outer or main query. Enclose subqueries inside parenthesis. Oracle 8i onwards “Order by” clause can be used in the inner query. There are two type of comparison operators : single row operators and multiple row operators, and hence there are two types of sub-queries Single row sub-queries(Query that returns only one row from the sub-query) and Multiple Sub-Row queries(Query that returns more than one row from the sub-query) Single-Row comparison operators are =,>,>=,<,<=,<> Select rollno, firstname from students where std=(select std from students where rollno=101) and div=( select div from students where rollno=101) The outer and inner queries can get data from different tables. Group functions can be used in a sub-query Select rollno, firstname from students where maths=(select max(maths) from students); HAVING clause with subqueries Select deptno, min(salary) from employees group by deptno having min(salary)>(select min(salary) from employees where deptno=50); To find the Department with the lowest average salary Select deptno, avg(salary) from employees group by deptno having avg(salary)=(select min(avg(salary)) from employees group by deptno); If the inner query returns more than one row, then it would generate an error. To correct such errors we use the IN, ANY or ALL operators. If the inner query returns no rows or NULL value, then the outer query returns no rows.(in laxmn eg. Laxmn nt there then it ret==no rows&if laxmn maths null then it ret==null ) Multiple Row Subqueries or Multiple Row Comparison operators 33
  • 34. IN(Equal to any number in the list), ANY(Compares value to each value returned by the subquery), ALL(Compares value to every value returned by the subquery) select * from students where studname IN (select studname from students where rollno=45 or rollno=35); To display the employees who are not Programmers and whose salary is less than any of the Programmer select empno, empname, job, salary from employees where salary<ANY(select salary from employees where job=’Programer’) and job<>’Programmer’; <ANY means less than the maximum.` >ANY means more than the minimum. =ANY is equivalent to IN To display the employees who are not Programmers and whose salary is less than all the Programmer select empno, empname, job, salary from employees where salary<ALL(select salary from employees where job=’Programer’) and job<>’Programmer’; <ALL means less than the minimum. >ALL means more than the maximum. ROLLUP select STD, DIV, SUM(MATHS) from STUDENTS group by rollup(STD, DIV, MATHS) CUBE select STD, DIV, SUM(MATHS) from STUDENTS group by CUBE(STD, DIV, MATHS) VIEWS Views are virtual tables. It is a query. It is a pointer to the underlying base table. It does not take any memory in the database. When a table is dropped, the views on it are not accessible, but become active again, when the table is recreated. To restrict access of data because the view can display selective columns from table/tables To make complicated queries simpler by storing them as a view. To present different views of the same data Simple views: Derives data from a single table. Dose not contain functions or groups of data. Allows you to perform DML operations. Complex views : 34
  • 35. Derives data from many tables. Contains functions or groups of data. Does not allow DML operations create or replace view stud1 as select * from students where maths>70; select * from stud1; update students set english=70 where rollno=1; select * from stud1; insert into stud1(rollno, studname) values(29,'Pappu'); values can be inserted into the base table through views select * from stud1; When select is run on a view it will show only those records which satisfy the condition given while creating the view. select * from students; select view_name, text from all_views where view_name='STUD1' create or replace view stud2 as select * from students order by rollno; insert into stud2(rollno, studname) values(31,'Sunil'); cannot insert values in this view because of the order by clause create or replace view v1(employee_no, employee_name, sal) as select empno, empname, salary from employee where salary<=500 -to add an alias to each column. Complex view : create view v2(name, minsal, maxsal, avgsal) as select d.deptname, min(e.salary), max(e.salary), avg(e.salary) from employee e, deptmast d where e.deptno=d.deptno group by d.deptname; You cannot delete a row from a view if : It contains group by clause 35
  • 36. It contains the DISTINCT keyword It contains the pseudolumn ROWNUM You cannot update a row from a view if : It contains group by clause It contains the DISTINCT keyword It contains the pseudolumn ROWNUM It contains calculated columns or expressions You cannot insert row thru a view It contains group by clause It contains the DISTINCT keyword It contains the pseudolumn ROWNUM It contains calculated columns or expressions NOT NULL columns in the base table are not included in the view With Check Option create view v4 as select * from employee where deptno=1 with check option constraint mycon; The constraint constraintname is optional. The with check option ensures that Inserts/Updates performed thru the view cannot create rows which the view cannot select, and thus ensures integrity constraints and data validations checks on data being inserted/updated thru the view READ only views They do not allow to insert/update/delete values into the base table thru the view Create or replace view v5 as select * from employee where deptno=1 with read only To drop a view Drop view viewname Inline Views An inline view is created by placing a subquery in the FROM clause and giving that subquery an alias so that it behaves like a separate table. Example to find all the employees who earn a salary less than the maximum salary in that department. create view v6 as select a.empname, a.salary, a.deptno, b.maxsal from employee a, (select deptno, max(salary) maxsal from employee group by deptno) b where a.deptno=b.deptno and a.salary<b.maxsal Top N analysis select rownum, empno, salary as rank from (select empno, salary from employee where 36
  • 37. salary is not null order by salary desc) where rownum<=3 Rownum is pseudo column assigned to each row returned by the inner query. The inner query contains the order by clause to get the ranking in the desired order. The outer query limits the number of rows returned by using the where clause which uses a < or <=operator Producing Readable Report Substitution Variables using single ampersand select * from dept_mast where dept_code=&Department_Code The variable is created and discarded after use select * from dept_mast where dept_name='&Department_name' single quotes are used for date and character and date type of values. select * from dept_mast where upper(dept_name)=upper('&Department_name') To remove case-sensitivity Substitution variables can be used for columns, where clause, table names, order by clause : select &column_name from dept_mast where dept_code=&department_code select * from &table_name select * from &table_name order by &column Defining Substitution variables : DEFINE variablename=value The value is of type character Example Define abc=hemant Define xyz=25 Both are character type variables Define variablename To see the value and data type of that variable Define Displays all variables, their values and data types for that session Undefine variablename 37
  • 38. To remove the variable from memory A variable remains in memory till you either give it a new value or you undefined it or you end the SQL Session Define command with &substitution variable Define dep=10 select * from dept_mast where dept_code=&dep &&substitution variable You should use && before the variable name, if you are going to use it more than once in a statement, and don’t want oracle to prompt you for it’s value everytime it is encountered as follows : Select &&department, dept_name from dept_mast order by &department; The single & should be used as the last occurrence Now whenever you use the variable department, it will use the value it has already got. O get rid off the old value use :undefine department(variable name) Set verify on/off By default it is on, hence it displays you the statement containing the substitution values twice before execution : once the original statement , and once the statement with the substituted or entered or new values Partitions To store large number of records in separate tables to reduce retrieval time create table empsal(empno number(3), salary number(8,2)) partition by range(salary) (partition part1 values less than(1000) tablespace TRAINING, partition part2 values less THAN (MAXVALUE) TABLESPACE TEMP) commit and rollback How to commit 1) commit command; Implicit Commit 2) A DDL Command : Create, Drop, Alter, Audit 3) When you say :Exit or Quit; Connect or Disconnect How to Rollback 1) Rollback command 38
  • 39. 2) Rollback to savepointname Implicit Rollback 3) when you switch off; 4) hard disk crash 5) Power failure insert into students(rollno, studname) values(7,'rajesh'); savepoint a; insert into students(rollno, studname) values(8,'mudliar'); savepoint b; insert into students(rollno, studname) values(9,'bande'); savepoint c; set autocommit on; now every DML is committed immediately rollback to b; -third insert statement and savepoint c are undone rollback to a; -second and third insert statement and savepoint b and c are undone if only rollback is given then all DML statements after last commit are undone Objects or User-defined types create 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. / create table employee ( empno number(3), person fullname, address address_type, salary number(6,2) ); Table Employee Empno Person ---- fullname Fname Mname Lname Address ---- city varchar2(15), state varchar2(20), zip number(7) insert into employee values(1, fullname('Hemant','Jayawant', 'Pangam'),address_type('Mumbai','Maharashtra',400068), 789.90); select * from employee; cannot drop or replace a type when a table is using it hence “drop table employee” and then “drop type address_type;” and “drop type fullname” nested types create 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. create table employee ( empno number(3), person personal_type, salary number(6,2) ); insert into employee values(111,personal_type('Hemant',address_type('Mumbai','Maharashtra',400068)),1000.0) Character Functions Select fname||lname from students; Select fname||’ ‘||lname from students; Select concat(fname,lname) from students; Select concat(concat(fname,’ ‘),lname) from students; select concat('hemant', 'boy') from dual select concat('hemant', 'is a boy') from dual select concat(to_char(rollno),studname) from students concat-used to merge two strings select lower(studname) from students; lower-displays string in lower case select upper(studname) from students; lower-displays string in upper case update students set fname=upper(fname) select upper(concat(fname,lname)) from students; To make a query insensitive to the case used Select * from students where upper(fname)=’ARUN’; select initcap(studname) from students; initcap-First character of every string is displayed as capital select ascii(studname) from students; 41
  • 42. ascii-ascii value of the first character of the string select chr(65) from dual; chr-character corresponding to the given value select sysdate from dual; dual is a oracle provided table for such type of temporary operations select length(studname) from student length-to find length of a string select instr(‘man’,studname) from students select instr(studname, 'man') from students; select firstname, instr(firstname,'He') from students instr-shows the start position of ‘man’ or ‘He’ in the given string. Case Sensitive. If not found then 0 select firstname, instr(firstname,'e',3) from students start searching from 3 character onwards select lastname, instr(lastname,'a',1,2) from students; start searching for second occurrence of ‘a’ from 1st character onwards select lpad(studname,25) from students select lpad(studname,25,'*') from students lpad-makes the string of specified length by adding the specific character to it’s left. Thus makes it Right Justified select rpad(studname,25) from students select rpad(studname,25,'*') from students rpad-makes the string of specified length by adding the specific character to it’s right. Makes string left justified This is sort of function overloading where same function works differently with different number of parameters. select ltrim(' Hemant '), sysdate from dual; ltrim-removes the spaces from the left of the string select rtrim(' Hemant '), sysdate from dual; rtrim-removes the spaces from the left of the string select ltrim(' * * Hemant ','* '), sysdate from dual to remove blank spaces and *, if any from left 42
  • 43. select trim(' Hemant '), sysdate from dual; trim-removes the spaces from the left and right of the string select substr(fname,3) from students; Starting from 3rd position upto end select substr(studname, 2,3) from students; substr-extracts 3 characters from the 2nd position of the specified string select firstname, substr(firstname,-3) from students from 3rd last character to end select firstname, substr(firstname,-3,2) from students 2 character from 3rd last select replace(studname,'H','M') from students; select replace(studname,'H','Man') from students select replace(firstname,'Ja','HH') from students replace-to replace a specified character(s) from a specified string with a specific character(s). Case Sensitive select replace(firstname,'Ja') from students since 3rd parameter is missing, replaces ‘Ja’ with nothing, that is removes Ja select translate(firstname,'je', 'FK') from students replaces j by F and e by K. Hence the two parameters must be of same length select translate(firstname,'je', 'F') from students replaces j by F and e by nothing, that is removes e. select * from students where soundex(firstname)=soundex('Himant'); select * from students where soundex(lastname)=soundex(‘Paaangam’) to compare same sounding words. It checks the strings after removing the vowels Numeric functions select maths+science, maths-science, maths*science, maths/science from students select sqrt(maths) from students; sqrt-square root select sin(90),cos(90),tan(90) from dual Sine, Cosine, Tangent of specified number select cosh(90), sinh(90), tanh(90) from dual; 43
  • 44. Hyperbolic Sine, Hyperbolic Cosine, Hyperbolic Tangent of specified number select vsize(123456789) from dual vsize-size of the value in bytes select vsize(maths) from students; select science, trunc(science,0) from students select salary, trunc(salary) from employee -- just cuts off all the decimal places select salary, trunc(salary,1) from employee -- cuts of to only one decimal place select science, trunc(science,1) from students select salary, trunc(salary,-1) from employee truncates to a lesser 10 place select salary, trunc(salary,-1) from employee truncates to a lesser 100 place select salary, trunc(salary,-1) from employee truncates to a lesser 1000 place trunc-truncates the value to the specified precision select sign(-9), sign(0), sign(9) from dual; sign—displays –1,0,1 for negative, zero and positive values select science, round(science,1) from students select science, round(science,0) from students select salary, round(salary) from employee—rounds to 0 decimal places select salary, round(salary,-1) from employee rounds to nearest 10 select salary, round(salary,-3) from employee rounds to nearest 100 select salary, round(salary,-3) from employee rounds to nearest 1000 round-rounds the value to the specified precision select power(10,2) from dual select power(10,1/2) from dual gives square root select power(1000,1/3) from dual gives cube root power—10 raised to power of 2 select abs(-10) from dual; gives the absolute or positive value of any number update students set maths=0 where rollno=1 select nvl(maths,0) from students; nvl-to replace NULL value numbers with the specified number select mod(10.33,3.10),mod(10,3),mod(10.3,3) from dual remainder of the division select log(10,10), log(10,20), log(10,1) from dual 44
  • 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 infinity select english,floor(english), maths,floor(maths), science, floor(science) from students; floor-largest integer smaller than or equal to the given value select english,ceil(english), maths,ceil(maths), science, ceil(science) from students ceil-smallest inter larger than or equal to the given value Date functions select sysdate-to_date('31-Jan-05') from dual difference between two dates in terms of days. The fraction part is the number of hours. If it is .5 it means 12 hours. To get rid of the fraction select trunc(sysdate-to_date('31-Jan-05')) from dual select sysdate+1 from dual; select add_months(sysdate,8) from dual; select add_months(sysdate,-3) from dual; add_months—to add specific months to the given date select least(to_date('01-Jan-05'), to_date('11-Sep-05'), to_date('31-Dec-06')) from dual greatest—earliest date from the given list select localtimestamp from dual; select months_between(sysdate,to_date('31-Jan-05')) from dual select 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 dual next_day—gives the date of the specific day(Monday, Tuesday, etc) after the specified date select next_day(sysdate-7, 'Friday') from dual for previous friday select last_day(sysdate) from dual last day of the month to which the specified date belongs select to_char(sysdate) from dual; 45
  • 46. to_char—date to character select to_date('31-Dec-05') - sysdate from dual select to_date('31-Dec-05') – round(sysdate) from dual round—used to find out the rounded number of days between the two given days. Round on any date set it to 12am if time is before noon, and to 12am of the next day of the time is after noon. select to_date('31-Dec-05') - trunc(sysdate) from dual trunc-set the date to 12am of the current day select current_date from dual; returns date from the current time zone select current_timestamp from dual; returns date and time from the current time zone Different Date formats: select to_char(sysdate,'DD/MM/YYYY') from dual; British separator select to_char(sysdate,'DD-MM-YYYY') from dual; American separator select to_char(sysdate,'DD:MM:YYYY') from dual; French separator select to_char(sysdate,'DD.MM.YYYY') from dual; German separator select to_char(sysdate,'DD*MM*YYYY') from dual;Italian separator also try the following : DD/MM/YYY DD-MONTH or DD-MONTH-YYYY - Month in upper case Month - Month in lower case Mon/mon/MON in the appropriate case Select to_char(sysdate,’DAY’) from dual; Try : day, Day, DY, dy, Dy Select to_char(sysdate,’YEAR’) from dual; gives Two Thousand Six Try : Year Select to_char(sysdate,'DD') from dual will give 31or 01, etc Also try : DDTH, DDSP, DDSPTH Select to_char(sysdate,'MM') from dual Also try MMTH, MMSP, MMSPTH Select to_char(sysdate,'D') from dual; day of the week(1,2 ..7) 46
  • 47. Try DTH, DSP,DSPTH in upper or lower case Select to_char(sysdate,'DDD') from dual; day of the year Select to_char(sysdate,'W') from dual; week of month(1,2..5) Select to_char(sysdate,'WW') from dual; week of the year Also try WWSP, WWSPTH in upper lower case Select to_char(sysdate,'DD/MM/YYYY HH:MI') from dual; Select to_char(sysdate,'DD/MM/YYYY HH:MI:SS') from dual; By default 12 hour format For 24 hour format HH24:MI:SS Select to_char(sysdate,'DD/MM/YYYY HH:MI:SS am') from dual; Give am or pm for am/pm format Also try : AM,a.m., PM, P.M., p.m., etc Select to_char(sysdate,'DD/MM/YYYY HH:MI:SS a.M.') "IST" from dual to see Indian Standard Time Select to_char(sysdate-5.5/24,'DD/MM/YYYY HH:MI:SS a.M.') "GMT" from dual to see GMT time alter session set nls_date_format ='DD/MM/YYYY' to change date format for a session. LIST Functions NVL function for NULL any comparison done with NULL returns NULL select * from employee where salary=NULL hence Select * from employee where salary is NULL Any calculation with NULL returns NULL Select 5000+NULL from dual; select nvl(salary,0)+300 from employee 47
  • 48. nvl is independent of the datatype Select nvl(city,’Mumbai) from employees; if city is NULL, it displays ‘Mumbai’. Greatest Select salary, greatest(salary,500) from employee Compares salary of each row with 500 and returns the largest among the two, i.e., if salary is less than 500 returns 500, else returns the actual salary. Can be sued to set a minimum threshold value. Least Select salary, least(salary,500) from employee Compares salary of each row with 500 and returns the smallest among the two, i.e., if salary is less than 500 returns the salary, else returns 500 Can be sued to set a maximum threshold value. Greatest and Least can have any number of parameters : select greatest(40,2300,80,5000,30000) from dual select least(40,2300,10,5000,30000) from dual Decode select decode(deptno, 1,'Sales', 2,'Accounts', 3,'Medical', 'Others') from employee Similar to your switch case in C/C++ select decode(deptno, 1,salary*2, 2,Salary*3,3,Salary*4, salary*3/2) from employee Uses : Number to Word Conversion Encryption/Decryption Nvl2 select nvl2(salary,10000,5000) from employee; If salary is not null, then a bonus of 10000, else if salary is null, then a bonus of 5000 Nullif select nullif(salary,567) from employee; Returns NULL if the two values are the same, else returns the first value. Coalesce Select coalesce(basic, da, ta) from empsalary; Returns the first NON-NULL value from the list of parameters. All the parameters must be of the same datatype Case select empno,salary,case deptno when 1 then 1.10*salary when 2 then 1.20*salary 48
  • 49. when 3 then 1.30*salary else 500 end from employee It works like IF-THEN-ELSE without the need to use procedures. The 2 blue parts and the column in consideration must be all of the same datatype. The else part is optional. Environment function : Select user from dual; select userenv('sessionid') from dual select userenv('terminal') from dual; Numtodsinterval select numtodsinterval(265, 'HOUR') from dual converts 265 hours to 11 days and 1 hours, 0 mins, 0 secs select numtodsinterval(1, 'HOUR') from dual converts 1 hour to 0 days and 1 hour, 0 mins, 0 secs select numtodsinterval(265, 'day') from dual converts 265 days to 265 days and 0 hours, 0 mins, 0 secs select numtodsinterval(265, 'Minute') from dual converts 265 minutes to 0 days, 4 hours, 25 mins, 0 secs select numtodsinterval(265, 'second') from dual converts 265 seconds to 0 days, 0 hours, 4 mins, 25 secs numtoyminterval select numtoyminterval(15, 'month') from dual converts 15 months to 1 year , 3 months select numtoyminterval(15, 'year') from dual converts 15 years to 15 year , 0 months select numtoyminterval(15.3, 'year') from dual converts 15.3 years to 15 year , 4 months to_char select to_char(sysdate,'dd/mm/yyyy') from dual select to_char(sysdate,'dd-mon-yyyy') from dual 49
  • 50. select to_char(sysdate,'dd-Mon-yyyy') from dual select to_char(sysdate,'dd-MON-yyyy') from dual select to_char(sysdate,'Day-MON-yyyy') from dual select to_char(sysdate,'Day,dd-MON-yyyy') from dual select to_char(sysdate,'Day,ddth-MONTH-yyyy') from dual select to_char(sysdate,'Day,ddth-MONTH-yyyy hh:mi:ss') from dual select to_char(sysdate,'Day,ddth-RM-yyyy hh24:mi:ss') from dual select to_char(sysdate,'Day,DDth-RM-yyyy hh24:mi:ss') from dual to_date select to_date('01-Jan-2005') from dual select to_date('01-Jan-2005',’dd/mm/yy’) from dual select to_date('01-Jan-2005','dd/MON/yy') from dual group functions select deptno, variance(sal), stddev(sal), sum(sal), avg(sal), max(sal), min(sal), count(*) from emp group by deptno Table dependent database objects : Views, Index, Synonyms, Sequence Index It is a schema object for faster data access or speed up retrieval of rows by using a pointer. Indexes are maintained automatically by the Oracle Server. It reduces disk I/O by using a rapid path access method Indexes are created 1)Automatically : A unique index is created automatically when you define a Primary Key or a Unique constraint in a table definition. The name of the index is the name given to the constraint 2) Manually : Users can create non-unique indexes on columns to speed up access to the rows ORA cannot be forced to use indexes Suppose you have the following table Rowid Empno Name Salary 1 5 aaa 2 2 bbb 3 3 ggg 4 7 mmm 5 9 pon 6 1 lon 7 4 jhg 50
  • 51. 8 6 jkl create index empno_idx on emp(empno) then the internal storage is as follows select * from user_indexes Rowid Empno Name Salary 6 1 2 2 3 3 7 4 1 5 8 6 4 7 5 9 Now if u use a select command like Select * from emp where empno=4 The search will start from the 4th record onwards and not the 1st record, as empno 4 occurs at the 4th record, if there is no index the search starts from the first record Create Index emp_last_name_idx on employee(last_name); Create Index emp_last_first_name_idx on employee(last_name, first_name); When to create an Index : A Table is very large and most queries are expected to retrieve less than 2 to 4 percent of rows. Some of the table’s columns are frequently used together in a WHERE clause of a join condition A column of a table which is frequently used as a search criteria contains either a large number of NULL values or a wide range of values. The table is not subject to a lot of DML operations, since every DML operation is followed by updation(of reorgansation of all the indexes on the table) When not to create an Index : The table is quite small The table is frequently updated by DML operations The columns of the table are not frequently used as a search condition in a query Most queries are expected to return more than 4 percent of the rows The already indexed columns are referenced as part of an expression. Indexes should not be created on dynamic tables, it degrades performance 51
  • 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 clause must be indexed All index like PK, unique key and others are dropped when you drop the table ORA creates index in a B-tree format Function based Indexes : It is an index based on an expression. They are defined with functions like upper /lower which allow case-insensitive search. The index expression is built from table columns, constants, SQL function or user-defined function as follows : Create Index upper_emp_name_idx on employee(upper(emp_name)); This will help in quick search like : Select * from employee where upper(emp_name) =’Tom’; To ensure that the Oracle server uses the index and dose not carry out full table scan, be sure that the function does not search NULL values. For example, the following statement is guaranteed to used the index, but without the where clause Oracle would have performed a full table scan : Select * from employee where upper(emp_name)=’TOM’ and upper(ename) is not null; Some other way of creating a unique indexes : Create unique index indexname on tablename(column or columns separated by commas) Alter table tablename add constraint constraintname primary key(column or columns separated by commas) To drop an index : Drop index indexname. You cannot modify indexes. You need to drop and recreate it. User_indexes view contains the name of the index and it’s uniqueness. The user_ind_columns view contains the index name, table name, and the column name. Select ic.index_name, ic.column_name, ic.column_position, ix.uniqueness from user_indexes ix , user_ind_columns ic where ic.index_name =ix.index_name and 52
  • 53. ic.table_name=’EMPLOYEES’ Synonyms To refer to a table owned by another user, you need to prefix the table name by the user name. Creation of a synonym avoids this. It is a pointer to a table/view/sequence/procedure or some other object. It is an alias name for the table/view/sequence. We can have synonym of synonym(alias of alias) It is used when you have access too another user’s table/view/sequence, therefore instead of using that users name as the qualifier for the table/view/sequence, you may create a synonym and use it when required to query the data. Example login as system/manager create synonym mysyn for scott.emp; select * from mysyn; Without the synonym mysyn, to access the table students from the user scott, you would have to give the following : Select * from scott.emp select * from user_synonyms; Simplifies access to objects by creating a synonym. It allows easy reference to a table owned by another user. Shortens lengthy object names The synonym can be created by the object owner(if he has sufficient privileges to create a synonym) or system admin. The synonym name can be used by all users to whom the database owner/system admin has granted some rights on that table for which the synonym has been created. To allow all users who have got rights on that table, we can create a public synonym as follows : Create public synonym synonymname for object; Sequences Automatically generates unique numbers Is a sharable object Typically used to create primary key values Speeds 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. sequence can be used for multiple tables. They are used to assign unique numbers to NEW rows being inserted into a table, or old rows being updated in the table. create sequence myseq increment by 1 start with 100; select sequence_name, min_value, max_value, increment_by, last_number from user_sequences; check the last_number, it is equal to 100 insert into students(rollno, studname) values(myseq.nextval,'abc'); select sequence_name, min_value, max_value, increment_by, last_number from user_sequences; check the last_number, it is equal to 120 insert into students(rollno, studname) values(mysequence.nextval,'pqr'); select sequence_name, min_value, max_value, increment_by, last_number from user_sequences; check the last_number, it is equal to 120 This is because Oracle caches 20 values or Oracle pre-allocates 20 values and keeps them in memory for use. update students set rollno=myseq.nextval where rollno=269 update students set rollno=mysequence.nextval where rollno=121 select myseq.currval from dual; show the latest number assigned You can use the mysequence.currval to update records in some other transaction table; Create sequence sequencename Increment by n Start with n Maxvalue n Minvalue n Cycle/ Nocycle Cache n/Nocache; If increment is not given , it increment by 1; If start with is not given, it starts with 1; Maxvalue n specifies maximum value sequence should generate. If it is not given maximum value is 10^27 for an ascending sequence or –1 for descending. Minvalue specifies minimum value sequence should generate. If it is not given minimum value is 1 for an ascending sequence or –(10^26) for descending. 54
  • 55. Cycle/Nocycle : Nocycle is the default. If cycle then the sequence will generate values even after the maximum/minimum value is reached. This is useful when you alter the sequence with a new maxvalue/minvalue Cache n specifies the number of values that Oracle should pre-allocate and keep in memory NEXTVAL and CURRVAL pseudocolumns : When you use sequencename.nextval, a new sequence number is generated. The sequencename.currval is referenced to see the last value returned to the user. Example : Insert into department(departmentno, departmentname) values (dept_seq.nextval,’Accounts’); This will generate a new sequence number and put the current value of the sequence dept_seq into the table department and will also put the current value into the currval So to insert employees for this new department which is just inserted into the department table we use the following : Insert into employees(empid, empname, departmentno) values (employees_seq.nextval, ‘Manoj’, dept_seq.currval); If you reach the maximum value limit, no new values are generated and you will receive an error message. You can alter the sequence to set a new max value Alter sequence sequencename Increment by n Maxvalue n Minvalue n Cycle/Nocycle Cache n/Nocache; You cannot change the start value with alter sequence command. To change the start number you need to drop and recreated the sequence. To drop a sequence Drop Sequence Sequencename; Controlling User Access Privileges are the right to execute a particular SQL Statement. The Database Administrator(DBA) is the highest level user who grants users access to the database and it’s objects. The users require System Privileges to gain access to the database and Object Privileges to manipulate the contents of the objects in the database. Hence, Database Security is of 2 categories : 1) System Security which covers access and use of the database at the system level, such as username and password, disk space allocated to users, and system operations that a user can perform. 2) Database security covers access and use of the database objects and the actions that those users can have on the objects. 55
  • 56. Schema : A schema is a collection of objects such as tables, views, sequences, etc. The schema is owned by the database user and has the same name as that user. System Privileges : The DBA has more than 100 high-level system privileges for tasks such as : CREATE USER; DROP USER; CREATE, BACKUP, SELECT and DROP a Table in any schema. To create a new user, the DBA does the following : Create User Username Identified By Password; This will just create a new user, who has no privileges as of now. To grant specific privileges to the new user, the DBA uses the GRANT Command as follows : Grant privilge1, privilege2, etc to Username; Typical User System privileges are : Create Session(To connect to the database) Create Table(To create table in the user’s own schema) Create Sequence(To create a Sequence in the user’s own schema) Create View(To create a view in the user’s own schema) Create Procedure(To create stored procedure, function, or package in the user’s own schema) Roles : A role is a named group of related privileges that can be granted to the users. This makes it easy to manage users and privileges. The DBA create a role, then grants rights to that role, and then grants that role to other users as follows : Create Role rolename Grant Create session, Create table, Create view to rolename Grant rolename to user1, user2, etc. I can also grant Connect, Resource roles to a new role as follows Create role myrole Grant Connect, Resource to myrole Create user hemant identified by hemant123 Grant myrole to hemant 56
  • 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 password Object Privileges An object privilege is a privilege to perform a particular action on a specific table, view , sequence or procedure Privilege Table View Sequence Procedure Alter -- -- Delete -- -- Execute -- Index -- Insert -- -- References -- -- Select -- -- -- Update -- -- -- indicates whether or not a right or object privilege of that type can be granted on the specific objects in the first row. Object privileges vary from object to object. The owner has all the privileges on that object. The owner can give specific privileges on that object to other users. GRANT Object_privilege(s)[column(s)]/ALL on OBJECT To USER(s)/Role(s)/Pubic [WITH 57
  • 58. GRANT OPTION] Object_privilege—is the object privilege like Alter, Select, Execute, etc ALL—specifies that all object privileges Columns—Specifies the columns from a table/view on which the privileges should be granted On Object -—specifies the object on which the privileges are to be granted To User/Role/Public—specifies the user or role or public(meaning all users) to whom the privileges must be granted. With Grant Option – Allows users to whom the privilege has been granted to further grant those privileges to other users. When the object owner revokes the privileges granted to a user with the With Grant Option, the ability of that user to grant rights on that object to other users is also automatically revoked. To revoke a privilege : Revoke Privilege(s)/ALL On Object From User(s)/Role(s)/Public Cascade Constraints Cascade Constraints -- to remove any referential integrity constraints made to the object by means of the References privilege. Database Link A Database Link is a one-way pointer that defines a communication channel from an Oracle Database Server to another Oracle Database Server. The entry of this link pointer is maintained in the Data-Dictionary table of the Server on which the Link was created. Therefore, to use the link you must be connected to the local database that contains the data-dictionary entry about the link. The Link is one-way in the sense that a client connected to the local database(say A) in which the link entry is stored to access the remote database(say B) can access the remote Database B, but a user connected to Database B cannot access the Database A. The DBA is responsible for creating such links between distributed databases, where each of the database in a distributed database must have a Unique Global Name. The Data-dictionary view USER_DB_LINKS contains the information about such links. Create Public Database Link abc.pqr.com Using ‘DPR”; Here abc.pqr.com is the name for the link The Using clause specifies the Connection string or service name of the remote Oracle Database Now, you can select data from the emp table on the remote database as follows : Select * from emp @abc.pqr.com To avoid this long name, you may create a synonym as follows Create Public Synonym mysyn rmemp for emp@abc.pqr.com And now, you may : 58
  • 59. Select * from mysyn; You cannot Grant privileges to others on remote objects. Grouping Function Grouping Function returns 0, if the column pass to it as parameter is us to calculate the aggregate value(summary of summary), else returns 1. It can be us with both Cube and Rollup. The column pass as parameter to the GROUPING function must be present in the Group By Clause create table employees (companyid varchar2(5), deptid varchar2(5), jobid varchar2(5), empid varchar2(5), empname varchar2(20), salary number(5)); insert into employees values('C1','D1','J1','E1','Hemant',8798); insert into employees values('C1','D1','J1','E2','Hema',879) insert into employees values('C1','D1','J1','E3','Seema',8879) insert into employees values('C1','D1','J2','E4','Rahul',878); insert into employees values('C1','D1','J2','E5','Rahul',78) insert into employees values('C1','D2','J1','E6','Rohan',798) insert into employees values('C1','D2','J1','E7','Sam',98) insert into employees values('C1','D2','J1','E8','Sameer',598) insert into employees values('C1','D2','J2','E9','Sachin',98) insert into employees values('C2','D1','J3','E10','Soham',988) insert into employees values('C2','D1','J3','E11','Rajesh',9988) insert into employees values('C2','D1','J3','E12','Mahesh',998) insert into employees values('C2','D1','J1','E13','Mahesh',98) insert into employees values('C2','D1','J1','E14','Somesh',948) insert into employees values('C2','D2','J1','E14','Yuvraj',48) insert into employees values('C2','D2','J1','E15','Kaif',648) insert into employees values('C2','D3','J1','E15','Saif',9648) insert into employees values('C3','D1','J1','E16','Haif',948) insert into employees values('C3','D1','J1','E17','Ram',978) insert into employees values('C3','D1','J1','E18','Tom',78) insert into employees values('C3','D1','J5','E19','Dick',788) insert into employees values('C3','D1','J5','E20','Harry',88) insert into employees values('C3','D2','J1','E21','Laxman',898) insert into employees values('C3','D2','J1','E22','Bharat',98) insert into employees values('C3','D1','J1','E23','Ryan',698) 59
  • 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_GRP From employees Group By Rollup(Companyid, Deptid) select companyid, deptid, sum(salary), GROUPING(Companyid) Company_GRP, GROUPING(Deptid) Dept_GRP From employees Group By Cube(Companyid, Deptid) select companyid, deptid, jobid,sum(salary), GROUPING(Companyid) Company_GRP, GROUPING(Deptid) Dept_GRP, GROUPING(Jobid) Job_GRP From employees Group By Rollup(Companyid, Deptid,jobid) select companyid, deptid, jobid,sum(salary), GROUPING(Companyid) Company_GRP, GROUPING(Deptid) Dept_GRP, GROUPING(Jobid) Job_GRP From employees Group By Cube(Companyid, Deptid,jobid) Grouping SETS It allows you to specify the Sets of column-groups for which you want to see the aggregates, instead of seeing all possible combinations. select companyid, deptid, jobid,sum(salary) From employees Group By Grouping Sets ((Companyid, Deptid),(Companyid, jobid)) 60
  • 61. select companyid, deptid, jobid,sum(salary) From employees Group By Grouping Sets ((Companyid, Deptid),(Companyid, jobid),(Deptid, Jobid)) select companyid, deptid, jobid,sum(salary) From employees Group By Grouping Sets ((Companyid, Deptid),(Companyid, jobid), (Companyid, deptid,jobid)) Composite Columns A Composite column is a collection of columns that should be treat as a single unit while calculating the aggregates select companyid, deptid, jobid,sum(salary) From employees Group By Rollup (Companyid, (Deptid,jobid)) select companyid, deptid, jobid,sum(salary) From employees Group By Cube(Companyid, (Deptid,jobid)) Concatenated Groupings In general Group By Grouping Sets(a,b), Grouping Sets(c,d) would generate : (a,c),(a,d), (b,c), (b,d) select companyid, deptid, jobid,sum(salary) From employees Group By Grouping Sets (Companyid, Deptid),Grouping Sets(Companyid, jobid) Generates aggregates for (Companyid, Deptid),(Companyid, jobid) and (Deptid, Jobid) select companyid, deptid, jobid,sum(salary) From employees Group By Companyid, Rollup(Deptid), Cube(jobid) Generates aggregates for (Companyid,deptid, jobid), (Companyid, jobid), (Companyid, deptid), (Companyid) 61
  • 62. SubQueries : Create table employees (empid varchar2(3), empname varchar2(20), mgrid varchar2(3), deptid varchar2(3)); insert into employees values('E1','Hemant',NULL,'10'); insert into employees values('E2','Hetal','E1','10') insert into employees values('E3','Sheetal','E1','10') insert into employees values('E4','Ram','E1','10') insert into employees values('E5','Shyam','E2','10'); insert into employees values('E6','Tom','E2','10') insert into employees values('E7','Harry','E2','20') insert into employees values('E8','Ryan','E1','20') insert into employees values('E9','Sheryl','E1','20') Pairwise Comparison select empid, empname, mgrid,deptid from employees where (mgrid,deptid) IN (Select mgrid,deptid from employees where empid in ('E2','E6')) All employees who belong to the same dept as E2 and to the same Manager as E2 And All employees who belong to the same dept as E6 and to the same Manager as E6 select empid, empname, mgrid,deptid from employees where (mgrid,deptid) IN (Select mgrid,deptid from employees where empid in ('E2','E6')) All employees who belong to the same dept as E2 or E6 and to the same Manager as E2 Or E6 Sub-Query in the From Clause(Inline View) EMPID EMPNAME MGRID DEPID SALARY E1 Hemant 10 4500 E2 Hetal E1 10 500 E3 Sheetal E1 10 5500 E4 Ram E1 10 5768 62