SQL Notes by Topic
SQL Notes by Topic
Data :-
Information :-
Database :-
DBMS :-
DBMS is a software system that allows users to create and access data in a database.
The primary purpose of the DBMS is to manage and serve user request. The actual
database users are always unaware of the following.
Where the data is physically located on the storage media. In a multi user
system, who else is accessing such data.
A DBMS
Reduces Redundency
Improves Data consistency
Provides Security at different levels
Ensures Data integrity
Provides transaction support
Provides Concurrency control
Provides Data Recovery methods
Metadata :-
the DBMS provides a Data Dictionary function. The Data Dictionary can be regarded as
a system database rather than user database.
Data Dictionary contains “Data about the Data” called Metadata , that is definitions of
other objects instead of just raw data.
RDBMS :-
1 AJAY 5000
2 RAJU 6000
3 SATISH 4000
ER MODEL :-
ENTITIES
ENTITY SETS
ATTRIBUTES
RELATIONSHIPS
ENTITY :-
Entity is an object
Example :- employee ,customer, bank a/c etc.
ENTITY SET :-
Collection of entities that share common characterstics.
Example :- EMP
ATTRIBUTES :-
Property of an entity is called attribute.
Example :- empno, ename,job,sal
RELATIONSHIP :-
Relationship is an association between entities of entity sets.
Types of relationships :-
1:1
1:M
M:N
VERSION FEATURES
Oracle 8 LOB
User defined datatypes
Table partitioning
MERGE command
ANSI joins
SQL
Sublanguages of SQL :-
DDL :-
CREATE
ALTER
DROP
TRUNCATE
RENAME
DML :-
INSERT
UPDATE
DELETE
INSERT ALL
MERGE
DRL :-
SELECT
TCL :-
COMMIT
ROLLBACK
SAVEPOINT
DCL :-
GRANT
REVOKE
SQL*PLUS :-
SQL*PLUS is tool or environment from ORACLE CORP, used to execute all the
commands of SQL and SQL*PLUS commands.
SQL SQL*PLUS
Language environment
PASSWORD :- password
Datatypes in Oracle :-
String Datatypes :-
Char Datatype :-
Varchar2 Datatype :-
Nchar/Nvarchar2 :-
Long Datatype :-
Number Datatype :-
Number(P,[S])
Allows Numbers.
P is the precision i.e. total no of digits allowed
S is the scale i.e. no of digits allowed after decimal.
Precision can be between 1 to 38.
Scale can be between -84 to 127.
ORACLE stores
DAY
MONTH
YEAR
HOUR
MINUTE
SECOND
TIMESTAMP DATATYPE:-
TIMESTAMP[(fractional-second)]
It is used to store and manipulate the intervals of years and months. The syntax is as
follows:
Here precision specifies the number of digits in the years field. The valid values of
precision are between 0 to 4, and the default value is 2.
It is used to store and manipulate intervals of days, hours, minutes, and seconds. The
syntax is:
SECOND [(fractional_seconds_precision)]
The valid values of precision are in the range 0 to 9. The defaults are 2 and 6,
respectively.
RAW :-
LONG RAW :-
LOB DATATYPES :-
BFILE/BLOB Datatype :-
Both BFILE and BLOB datatypes allows binary data upto 4GB.
If datatype is BFILE then object stored externally ORACLE stores locator.
If datatype is BLOB then object stored internally in ORACLE database.
CLOB Datatype :-
Allows Character data or character objects upto 4GB.
BINARY_FLOAT :-
This Datatype introduced in Oracle 10g.
BINARY_FLOAT is a 32-bit single precision floating point number datatype.
BINARY_FLOAT requires 5 bytes including a length byte.
BINARY_DOUBLE :-
This Datatype also introduced in Oracle 10g.
BINARY_DOUBLE is a 64-bit double precision floating point number datatype.
OPERATORS IN ORACLE :-
Operators in ORACLE categorized into following categories
ARTHMETIC OPERATORS :-
+
-
*
/
Operator precedence:-
RELATIONAL OPERATORS :-
>
<
>=
<=
=
<>
LOGICAL OPERATORS :-
AND
OR
NOT
SPECIAL OPERATORS :-
||
BETWEEN
IN
LIKE
IS
ANY
ALL
EXISTS
PIVOT
SET OPERATORS :-
UNION
UNION ALL
INTERSECT
MINUS
Creating table :-
Syntax:-
Syntax:-
Example :-
VALUES(1000,’BLAKE’,’MANAGER’,’10-JAN-10’,5000,500,10) ;
The order of the values should be equal to the order of the columns declared in the
table.
VALUES(‘ADAMS’,’CLERK’,3000,200,’11-JAN-10’,1001,10);
Example :-
Example :-
One INSERT command can be executed with different values by using substitution
variables.
Values assigned to these variables exists upto the execution of INSERT command ,
once command execution is completed the values are erased.
Example :-
VALUES(&EMPNO,’&ENAME’,’&JOB’,
’&HIREDATE’,&SAL,&COMM,&DEPTNO);
Example :-
SELECT Statement used to retrieve data from one or more tables, views.
Syntax:-
DECLARING ALIAS :-
Column Alias
Table Alias
Column Alias :-
Syntax :-
Example :-
Display ename,sal,hra,da,tax,totsal ?
Concatenation Operator:-
Example :-
LITERALS IN ORACLE:-
A Literal is a Constant
Typesof Literals :-
String
Number
Date
CLAUSES IN ORACLE :-
WHERE
ORDER BY
DISTINCT
GROUP BY
HAVING
ON
USING
START WITH
CONNECT BY
WITH
RETURNING
FOLLOWS
MODEL
WHERE clause is used to get particular records from table based on a condition.
Records that satisfies the WHERE cond are selected and remaining records are
discarded.
Syntax:-
CONDITION :-
BETWEEN operator :-
Syntax :-
Example :-
Display employee records who are earning between 2000 and 5000 ?
IN OPERATOR :-
Syntax :-
IN (V1,V2,V3,------)
NOT IN (V1,V2,V3,-----)
LIKE Operator:-
Syntax:-
LIKE ‘pattern’
NOT LIKE ‘pattern’
Pattern consists of alphabets,digits and metacharacters.
IS operator:-
IS operator is used to compare column value with NULL OR NOT NULL value
Syntax :-
IS NULL
IS NOT NULL
Example:-
display employee records whose comm. Is null ?
Dates Earliest-Latest
String A-Z;
NULL last
Syntax:-
[WHERE condition]
[NULLS LAST/FIRST]
By default records are sorted in ascending order to sort records in descending order
use DESC option.
By default NULL values arranged last in ascending order to control NULL value records
use NULLS LAST OR NULLS FIRST option.
Display employee records working for 10th dept and arrange the result in ascending
order of their sal ?
Arrange employee records in ascending of their deptno and with in dept arrange
records in descending order of their sal ?
Arrange employee records in descending order of their comm. If comm. Is null then
arrange those records last ?
DISTINCT clause :-
Syntax :-
DISTINCT colname
DISTINCT col1,col2
DISTINCT *
DML commands :-
INSERT
UPDATE
DELETE
INSERT ALL
MERGE
Syntax:-
Example :-
UPDATE command :-
Syntax:-
UPDATE table
SET column = value[, column = value,……]
[WHERE condition];
Example :-
Returning Clause:-
Bind variables are declared at SQL prompt , and accessed using : operator.
Sql>Update Emp
Set Sal=Sal*1.2
Where Deptno=10
DELETE command :-
Syntax:-
Using INSERT ALL command we can extract data from one or more tables and insert
data into multiple tables.
Syntax:-
INSERT ALL
INTO <TAB1> VALUES (VALUE LIST)
INTO <TAB2> VALUES(VALUE LIST)
SELECT STATEMENT ;
Example :-
Emp1(empno,ename,sal)
Emp2(empno,ename,sal)
INSERT ALL
INTO EMP1 VALUES(EMPNO,ENAME,SAL)
INTO EMP2 VALUES(EMPNO,ENAME,SAL)
SELECT EMPNO,ENAME,SAL FROM EMP ;
Syntax :-
INSERT ALL
WHEN COND1 THEN
INTO <TAB1> VALUES (VALUE LIST)
WHEN COND2 THEN
INTO <TAB2> VALUES (VALUE LIST)
SELECT STATEMENT ;
Example :-
INSERT ALL
WHEN JOB=’CLERK’ THEN
INTO EMP1 VALUES(EMPNO,ENAME,SAL)
MERGE Statement:-
Syntax :-
Example :-
EMPS EMPT
Example :-
DDL commands :-
CREATE
ALTER
DROP
TRUNCATE
RENAME
Syntax :-
Example :-
CREATE TABLE EMPA
AS
SELECT * FROM EMP ;
COPYING ONLY STRUCTURE :-
ALTER command :-
ADD A COLUMN
DROP A COLUMN
MODIFY A COLUMN
INCR/DECR FIELD SIZE
CHANGING DATATYPE
ADDING A COLUMN:-
Syntax :-
Example:-
DROPING A COLUMN :-
Syntax :-
Example :-
MODIFYING A COLUMN :-
Example :-
CHANGING DATATYPE :-
NOTE :-
To change datatype of a column the column should be empty.
DROP command :-
Syntax :-
Example :-
TRUNCATE command :-
Syntax :-
Example :-
DELETE TRUNCATE
RENAME command :-
Syntax :-
Integrity Constraints :-
Integrity constraints are the rules in real life, which are to be imposed on the data. If
the computer data is not satisfying the constraints then it is considered as inconsistent.
These rules are to be enforced on data because of the presence of these rules in real
life. These rules are called integrity constraints. The data, which is not obeying
integrity constraints, is called inconsistent data. Every software must enforce integrity
constraints, otherwise inconsistent data is generated.
Domain constraints:-
Entity Integrity :-
Unique Constraint
Primary Constraint
Refrential Integrity :-
A refrential integrity constraint states that the values of the foreign key value should
match with values of primary key/unique Column of another or same table.
If a foreign key in one table refers primary key/unique column of the same table then
it is called self refrential
Integrity.
INSERTION
Parent – No restriction.
Child - restriction
UPDATION
Parent –Restriction
Child - Restriction
DELETION
Parent – Restriction
Child – No Restriction
NOT NULL
UNIQUE
PRIMARY KEY
CHECK
FOREIGN KEY
1 Column level
2 Table level
Column level :-
Table level :-
Example :-
UNIQUE constraint :-
Syntax :-
Example :-
PRIMARY KEY is the candidate key which uniquely identifies a record in a table
Limitations :-
Syntax :-
Example :-
Syntax :-
CHECK CONSTRAINT :-
Limitations :-
Syntax :-
COLNAME DATATYPE(SIZE)
[CONSTRAINT <NAME>] CHECK(CONDITION)
Example :-
Syntax :-
Example :-
DEFAULT Option :-
Example :-
Ename Varchar2(20) ,
Hiredate Date Default Sysdate);
After executing the above command oracle inserts sysdate into Hiredate column.
Syntax :-
Example :-
NOVALIDATE :-
If constraint is added with NOVALIDATE option then oracle doesn’t validate existing
data and validates only future
DML operations.
Droping Constraint :-
Syntax :-
Example :-
Note :-
PRIMARY KEY cannot dropped if that PRIMARY KEY is referenced by any FOREIGN KEY.
Enabling/Disabling a Constraint:-
If the constraints are present, then for each DML operation constraints are checked by
executing certain codes internally. It may slow down the DML operation marginally. For
massive DML operations, such as transferring data from one table to another because
of the presence of constraint, the speed will be considered slower. To improve the
speed in such cases, the
Disabling constraint
Performing the DML operation DML operation
Enabling constraint
Disabling Constraint:-
Syntax :-
Example :-
Enabling Constraint :-
Syntax :-
Example :-
Suppose the constraint uses the deferrable clause the enforcement of constraint is
deferred, untill commit is issued by the user. Let us understand it using:
Create Table T2
A B C
2 3 4
2 2 5
2 6 0
Committing a transaction
commit;
the clause deffer able causes postponing of the enforcement of constraint checking.
Therefore, no error is issued even though second and third row violates the constraint.
If you issue commit, the whole transaction is rolled back and you will not get all the
rows that are inserted prior to it. If initially deferred is specified then that constraint is
checked at the end of the transaction.
If the rows that are manipulated by the transaction do not satisfy the constraint, then
the whole transaction is rolled back. When initially immediate is specified, which is also
the default setting then the constraints are enforced at the end of every DML
statement.
When the clause deferrable is used, the behavior of constraint can be changed in the
transaction by using the set constraint command.
Now the user can issue the following command for deferring it:
If the constraint is not deferrable, then it cannot be manipulated using the set
constraint command. These facilities are provided to tackle various situations in the
practical application where data is made according to the constraint at the end of the
transaction.
Delete Rules :-
Delete Rules specifies how a child record is affected if parent record is deleted.
Oracle supports following Delete Rules
ON DELETE NO ACTION (DEFAULT)
ON DELETE CASCADE
ON DELETE SET NULL
ON DELETE NO ACTION :-
If Delete Rule is ON DELETE NO ACTION then parent record cannot be deleted if any
child record present.
ON DELETE CASCADE :-
If foreign key declared with ON DELETE CASCADE then records in child table deleted
automatically when user deletes record
From parent table.
BUILT-IN FUNCTIONS
CHARACTER FUNCTIONS :-
FUNCTION DESCRIPTION
Ex :- CONCAT(‘oracle’,’ server’)
=oracle server
numeric
Position 5, if m= 1 is provided.
Ex:-length (‘abc’) = 3
case.
‘cityNagpur’
AXIS BANK
of word in char.
Ex:-soundex(‘son’)=soundex(‘sun’)
‘BOMBAY’
DATE FUNCTIONS :-
FUNCTION DESCRIPTION
17-JUL-99
containing d.
Ex:-MONTHS_BETWEEEN (’17-MAY-99’,
‘19-JUL-99’) =2
22-DEC-99
=2003
Displaying date:-
NUMBER FUNCTIONS:-
to n.
1 if n>0;
0 if n=0
SGN (5) = 1
SGN (0) =0
CONVERSION FUNCTIONS :-
TO_CHAR ():-
Year.
year.
details .
EIGHT
characters.
month in uppercase.
case.
month is IV
case.
uppercase.
Second).
CS Centisecond(hunderedths of a sec 10
separator characters that allow you to separate the For the date Dec 13,
-/,.;: aspects of a date and time. You can supply 1969, DD-MM-YYYY
12-13-1969, and
DD/MM/YYYY would
Produce 12/13/1969.
Suffix AM AM or PM as appropriate. AM
or PM
or
P.M.
AD or AD or BC as appropriate. AD
BC
B.C.
28TH.
Produce TWENTY-
Would produce
Twenty-eight.
Produce TWENTY-
Would produce
Twenty-eight.
Zones.”
TO_CHAR():-
negative.
Zeros .
Zeros.
Position.
Position.
period character).
notation.
the number.
database parameter.
parameter.
minus sign.
bracket(<>).
notation.
rounded.
an integer.
SPECIAL FUNCTIONS :-
DECODE FUNCTION :-
Decode functions works like if-then-else
Syntax :-
DECODE(EXPR,VALUE1,RETURN EXPR1,
VALUE2, RETURN EXPR2,
-------------------,
DEFAULT EXPR)
If EXPR is equal to VALUE1 then DECODE returns EXPR1
If EXPR is equal to VALUE2 then DECODE returns EXPR2
If EXPR is equal not equal to VALUE1 or VALUE2 then DECODE
Returns DEFAULT EXPR.
Example :-
SELECT ENAME,SAL,
DECODE(JOB,’CLERK’,’WORKER’,
‘MANAGER’,’BOSS’,
‘PRESIDENT’,’BIG BOSS’,
‘EMPLOYEE’) AS JOB
FROM EMP;
SAL*1.05)
NVL:-
NVL function converts NULL values
Syntax :-
NVL(expr1,expr2)
If expr1 is NULL then NVL function returns expr2
Example :-
SELECT ENAME,SAL,SAL+NVL(COMM,0) AS TOTSAL
FROM EMP;
NVL2 :-
NVL2 function converts NULL values and NOT NULL values.
NVL2(expr1,expr2,expr3)
If expr1 is NOT NULL returns expr2 otherwise returns expr3
Example :-
UPDATE EMP SET
COMM = NVL2(COMM,COMM+200,500)
GREATEST :-
Returns GREATEST number among given numbers
Syntax :-
GREATEST(expr1,expr2,expr4,----)
Example :-
SELECT GREATEST(10,20,30) FROM DUAL ;
LEAST :-
Returns LEAST number among given numbers
Syntax:-
LEAST(expr1,expr2,expr3)
Example:-
SELECT LEAST(10,20,30) FROM DUAL;
NULLIF :-
Syntax:-
NULLIF(expr1,expr2)
Returns NULL if given expressions are equal otherwise returns expr1.
SELECT NULLIF(100,200) FROM DUAL;
MAX :-
Returns maximum value of a given expression
Syntax:-
MAX(expr)
Example :-
SELECT MAX(SAL) FROM EMP;
MIN:-
Returns minimum value of a given expression.
Syntax :-
MIN(expr)
Example:-
SELECT MIN(SAL) FROM EMP;
SUM :-
Returns sum of a given expression.
This function cannot be applied on strings and dates.
Syntax:-
SUM(expr)
Example:-
SELECT SUM(SAL) FROM EMP;
AVG :-
Returns avg value of a given expression.
Syntax:-
AVG(expr)
Example:-
SELECT AVG(SAL) FROM EMP;
COUNT :-
Returns no of values present in a column.
Syntax :-
COUNT(expr)
Example:-
COUNT(*):-
Returns no of records
Example :-
SELECT COUNT(*) FROM EMP;
CASE Statement :-
The CASE expression performs if-then –else logic .
supported in Oracle Database 9i and above.
The CASE expression works in a similar manner to DECODE. use CASE because
it is ANSI-compliant .
the CASE expression is easier to read.
END
Search_expression is the expression to be evaluated.
expression1, expression2, …………,expression are the expressions to be evaluated
against search_expression.
result1, result2,………….., result are the returned results(one for each possible
expression). If expression1 evaluates to search_expression, results is returned, and
similarly for the other expressions.
default_result is returned when no matching expression is found.
Example :-
SELECT ENAME,SAL, CASE JOB
WHEN ‘CLERK’ THEN ‘WORKER’
WHEN ‘MANAGER’ THEN ‘BOSS’
WHEN ‘PRESIDENT’ THEN ‘BIG BOSS’
ELSE
‘EMPLOYEE’
END AS JOB
FROM EMP ;
Example :-
SELECT ENAME,SAL,CASE
WHEN SAL>3000 THEN ‘HISAL’
WHEN SAL<3000 THEN ‘LOSAL’
ELSE
‘MODERATE SAL’
END AS SALRANGE
FROM EMP ;
Group By Clause :-
Group by Clause is used to group rows based on one or more columns to get some
information on those groups of rows.
For Example , you might want to get the total salaries paid to each department to do
this the rows must be grouped based on department.
Using Group by Clause we can get summarized data from detailed data.
Syntax:-
SELECT <COLLIST> FROM <TABNAME>
[WHERE <COND>]
GROUP BY <COL1> [, <COL2>-----]
[HAVING <COND>]
[ORDER BY <COL1> [DESC] [,<COL2>-----]
CAUTION:-
Only GROUP BY column and aggregate function should appear in SELECT list.
Example :-
SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY DEPTNO;
SELECT JOB,MIN(SAL),MAX(SAL),SUM(SAL),COUNT(*)
FROM EMP
GROUP BY JOB
.
SELECT
EXTRACT(YEAR FROM HIREDATE) AS YEAR,COUNT(*) AS EMPS
FROM EMP
GROUP BY EXTRACT(YEAR FROM HIREDATE)
CAUTION :-
You cannot use an aggregation function to limit rows in WHERE clause .
SELECT DEPTNO,SUM(SAL)
FROM EMP
WHERE SUM(SAL)>10000
GROUP BY DEPTNO ;
Error at Line 3 :
ORA-00934 : group function is not allowed here.
Example :-
SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY DEPTNO
HAVING SUM(SAL)>10000 ;
NOTE :-
GROUP BY can be used without HAVING , but HAVING must be used in conjunction
with GROUP BY.
WHERE VS HAVING :-
You can use WHERE,GROUP BY, and HAVING clauses together in the same query.
When you do this the WHERE clause first filters the rows, the GROUP BY clause then
groups the remaining rows and finally HAVING clause filters the groups.
Example :-
SELECT DEPTNO,SUM(SAL)
FROM EMP
WHERE DEPTNO IN (10,20)
GROUP BY DEPTNO
HAVING SUM(SAL) > 10000
Example :-
SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY DEPTNO,JOB
Above example , groups records based on department wise and within the department
records are grouped based on job wise.
CROSS TABULATION :-
SELECT * FROM
(SELECT DEPTNO,SAL,JOB FROM EMP)
PIVOT
(
SUM(SAL) FOR JOB IN (‘CLERK’,’MANAGER’,’SALESMAN’)
)
ORDER BY DEPTNO;
ROLLUP
CUBE
ROLLUP :-
ROLLUP returns a row containing a subtotal for each group ,plus a row containing a
grand total for all the groups.
Example : -
SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY ROLLUP(DEPTNO) ;
SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY ROLLUP(DEPTNO,JOB)
ORDER BY DEPTNO,JOB;
CUBE :-
Cube returns rows containing a subtotal for all combinations of columns, plus a row
containing the grand total.
Example : -
Passing single column to CUBE :-
SELECT DEPTNO,SUM(SAL)
FROM EMP
GROUP BY CUBE(DEPTNO) ;
SELECT DEPTNO,JOB,SUM(SAL)
FROM EMP
GROUP BY CUBE(DEPTNO,JOB)
ORDER BY DEPTNO,JOB;
JOINS
There are times, when data has to be retrieved from more than one table. In such
situations JOINS are used.
Tables involved in JOIN operation must share a meaningful relationship.
Oracle performs JOIN operation when more than one table appears in FROM clause.
Types of JOINS :-
Equi Join or Inner Join
Non-Equi Join
Self Join
Outer Join
Cross Join
EQUI JOIN :-
In EQUI JOIN Join operation is performed based on common columns.
To perform EQUI JOIN there should be a common column in joining tables.
To perform EQUI JOIN parent/child relationship between the table is not mandatory.
Syntax :-
SELECT <COLLIST> FROM <TAB1> , <TAB2>
Guidelines:-
When writing a SELECT statement that joins tables, precede the column name with the
table name or table alias for clarity and to improve performance.
If the same column name appears in more than one table, the column name must be
prefixed with the table name.
Example:-
Select E.Empno, E. Ename , E.Deptno ,
D. Deptno , D. Dname , D. Loc
From Emp E,Dept D
where E.Deptno = D.deptno;
NON-EQUI JOIN :-
Use NON-EQUI JOIN when there is no common column in joining tables.
Syntax:-
Select col1,col2,…….
From<table 1>,<table 2>
Where <JOIN COND>
[AND <JOIN COND> AND--------]
In NON-EQUI JOIN JOIN COND is not based on = operator. Its based on other
than = operator usually BETWEEN operator.
Example:-
Select E.empno,E.Ename,E.Sal,S.Grade,S.Losal,S.Hisal
From Emp E, Salgrade S
Where E.Sal between S.Losal and S.Hisal;
SELF JOIN :-
Joining a table to itself is called SELF JOIN
SELF JOIN is performed when tables having self refrential integrity.
To perform SELF JOIN same table must be listed twice with different alias.
SELF JOIN is performing EQUI JOIN with in the table.
Syntax :-
Sql>Select Columns
From Table1 T1, Table1 T2
Where T1.Column1=T2.Column2;
Example:-
Sql>Select E.Ename “Employee Name”,
M.Enmae “Manager Name”
From Emp E,Emp M
Where E.Mgr=M.Empno;
OUTER JOIN :-
Example :-
Select e.ename,d.dname
from emp e,dept d
where e.deptno = d.deptno(+) ;
RIGHT OUTER JOIN returns all rows from RIGHT SIDE table and matching records from
LEFT SIDE table.
Syntax :-
Select Table1.Column,Table2.Column
From Table1,Table2
Where Table1.Column(+)=Table2.Column
Example :-
Select e.ename,d.dname
from emp e,dept d
where e.deptno(+) = d.deptno ;
Select e.ename,d.dname
from emp e,dept d
where e.deptno(+) = d.deptno ;
UNION ALL
Select e.ename,d.dname
from emp e,dept d
where e.deptno = d.deptno (+);
HINT :-
(+) should not be on both sides.
CROSS JOIN :-
CROSS JOIN returns cross product of two tables.
Each record of one table is combined with each and every record of another table.
If table1 contains 10 records and table2 contains 5 records then CROSS JOIN between
table1 and table2 returns 50 records.
ORACLE performs CROSS JOIN when we submit query without JOIN COND.
Syntax :-
SELECT COL1,COL2
FROM TAB1,TAB2
Example:-
ORDERS DISCOUNT
ORDAMT DIS
100000 5
7
12
15
EQUI JOIN :-
in ANSI style to perform EQUI JOIN use keyword JOIN or INNER JOIN.
JOIN COND is specified by using ON clause or USING clause.
Use USING clause if common column name is same.
Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO)
Joining more than two tables in ANSI style
SELECT E.ENAME,D.DNAME,M.MNAME MGRNAME
FROM EMP E JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO)
JOIN MGR M
ON (M.DEPTNO=D.DEPTNO)
Using USING clause :-
SELECT E.ENAME,D.DNAME
FROM EMP E JOIN DEPT D
USING (DEPTNO)
HINT :-
In USING clause common column name should not be prefixed with table alias.
NON-EQUI JOIN :
in NON-EQUI JOIN to specify the JOIN COND use ON clause
Example :-
SELECT E.ENAME,G.GRADE
FROM EMP E JOIN SALGRDE G
ON (E.SAL BETWEEN G.LOSAL AND G.HISAL)
SELF JOIN :-
OUTER JOIN :-
Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E LEFT OUTER JOIN DEPT D
ON (E.DEPTNO = D.DEPTNO)
SELEC E.ENAME,D.DNAME
FROM EMP E RIGHT OUTER JOIN DEPT D
USING(DEPTNO)
Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E FULL OUTER JOIN DEPT D
USING(DEPTNO)
NATURAL JOIN :-
Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E NATURAL JOIN DEPT D
SELECT E.ENAME,D.DNAME
FROM EMP E NATURAL JOIN DEPT D
USING(DEPTNO)
CROSS JOIN :-
to perform CROSS JOIN use keyword CROSS JOIN
Example :-
SELECT E.ENAME,D.DNAME
FROM EMP E CROSS JOIN DEPT D
SET OPERATORS :-
UNION
UNION ALL
INTERSECT
MINUS
UNION :-
UNION operator
combines data returned by two SELECT statement.
eliminates duplicates.
Sorts result
Syntax:-
SELECT <Column1>,……<ColumnN> FROM <DerivedTable>
UNION
SELECT<Column1>,……<ColumnN> FROM <DerivedTable>
To perform UNION the structure of the first query must be equal to structure of the
second query (no of columns & datatype)
ORDER BY clause should be used only for last query but not for each query
Example :-
SELECT JOB FROM EMP WHERE DEPTNO=10
UNION
SELECT JOB FROM EMP WHERE DEPTNO=20
UNION ALL :-
UNION ALL is similar to UNION but it includes duplicates
Example :-
SELECT JOB FROM EMP WHERE DEPTNO=10
UNION ALL
SELECT JOB FROM EMP WHERE DEPTNO=20
UNION vs JOIN :-
UNION combines data but JOIN relates data.
Only Similar structures can be combined with UNION.
Dissimilar structures can also be JOINED.
INTERSECT :-
INTERSECT operator returns common values from the result of two SELECT
statements.
Syntax:-
SELECT <Column1>,…….<ColumnN> FROM <DerivedTable>
INTERSECT
SELECT<Column1>,………<ColumnN> FROM <DerivedTable>
Example:-
SELECT JOB FROM EMP WHERE DEPTNO=10
INTERSECT
SELECT JOB FROM EMP WHERE DEPTNO=20
MINUS:-
MINUS operator returns values present in the result of first SELECT statement and not
present in the result of second SELECT statement.
Syntax:-
SELECT <Column1>,……..<ColumnN> FROM <DerivedTable>
MINUS
SELECT <Column1>,………<ColumnN> FROM <DerivedTable>
Example:-
SELECT JOB FROM EMP WHERE DEPTNO=10
MINUS
SELECT JOB FROM EMP WHERE DEPTNO=20
SUBQUERIES
SUBQUERY :-
a query embedded in another query is called subquery.
One query is called inner/child/subquery.
Another query is called outer/parent/main query.
The result of inner query acts as input to outer query.
Outer query can be
INSERT
UPDATE
DELETE
SELECT
Inner query must be always
SELECT
Subqueries appears in WHERE CLAUSE
HAVING CLAUSE
FROM CLAUSE
SELECT CLAUSE
Syntax :-
SELECT <COLLIST> FROM <TABNAME>
WHERE COLNAME OP (SELECT STATEMENT)
OP can be < > <= >= = <>
Example :-
SUBQUERIES IN WHERE CLAUSE :-
Display employee records whose job equals to job of SMITH?
SELECT * FROM EMP
WHERE JOB = (SELECT JOB FROM EMP WHERE
ENAME=’SMITH’) ;
Display employee names earning between minimum salary of 10 dept and maximum
salary of 30 dept ?
Syntax :-
OP must be IN
NOT IN
ANY
ALL
Example :-
Display 4th,7th,11th record in EMP table ?
SELECT * FROM EMP
WHERE ROWID IN (SELECT DECODE(ROW,NUM,4,ROWID,
7,ROWID,
11,ROWID)
FROM EMP)
NESTED QUERIES :-
A subquery embedded in another subquery is called NESTED QUERY.
Queries can be nested upto 255 level.
Example :-
Display employee name earning second maximum salary ?
SELECT ENAME FROM EMP
WHERE SAL = (SELECT MAX(SAL) FROM EMP
WHERE SAL < (SELECT MAX(SAL) FROM EMP))
If inner query returns more than one column value then it is called MULTI COLUMN
subquery.
Example :-
Display employee names earning maximum salaries in their dept ?
SELECT ENAME FROM EMP
WHERE (DEPTNO,SAL) IN (SELECT DEPTNO,MAX(SAL)
FROM EMP
GROUP BY DEPTNO)
CO-RELATED SUBQUERIES :-
A subquery references one or more columns of parent query
is called CO-RELATED subquery because it is related to outer query.
This subquery executes once for each and every row of main query.
Example :-
ORACLE recommends EXISTS and NOT EXISTS operator instead of IN and NOT IN.
INLINE VIEWS :-
Syntax :-
SELECT <COLLIST> FROM (SELECT STATEMENT ) ;
The result of inner query acts as TABLE for outer query.
Example :-
Display top 3 maximum salaries in EMP table ?
SELECT DISTINCT SAL FROM
(SELECT ENAME,SAL,
DENSE_RANK() OVER (ORDER BY SAL DESC) AS RNK
FROM EMP)
WHERE RNK<=3 ;
Database Transactions
A database transaction is a group of SQL statements that perform a logical unit of
work. You can think of transaction as an inseparable set of SQL statements whose
results should be made permanent in the database as a whole or undone as a whole .
An example of a database transaction is a transfer of money from one bank account to
another. One UPDATE statement would subtract from the total amount of money from
one account, and another UPDATE would add money to the other account. Both the
subtraction and the addition must be permanently recorded in the database; otherwise,
money will be lost. If there is a problem with the money transfer, then the subtraction
and addition must both be undone. The simple example outlined in this paragraph uses
only two UPDATE statements, but a transaction may consist of many INSERT, UPDATE,
and DELETE statements.
A transaction is a logical unit of work that enables you to spit up your SQL statements.
A transaction has a beginning and an end.
Transaction begins when one of the following events occurs:
You connect to the database and perform a DML statement (an INSERT,UPDATE, OR
DELETE).
A previous transaction ends and you enter another DML statement.
ROLLBACK TO save1;
Rollback complete.
This has undone the price change for product #5, but left the price change for product
#4 intact. The following query shows this:
If users are running transactions that affect the same table, the effects of those
transactions are separated from each other until a COMMIT is performed. The following
sequence of events, based on two transactions named T1 and T2 that access the
customers table, illustrates the separation of transactions:
1. T1 and T2 perform a SELECT that retrieves all the rows from the customer table.
2. T1 performs an INSERT to add a row in the customers table, but T1 doesn’t perform
a COMMIT.
3.T2 performs another SELECT and retrieves the same rows as those in step1. T2
doesn’t “see” the new row added by T1 in step2.
4. T1 finally performs a COMMIT to permanently record the new row added in step2.
5. T2 performs another SELECT and finally “sees” the new row added by T1.
To summarize: T2 doesn’t see the changes made by T1 until T1 commits its changes.
Transactions Locking:
To support concurrent transactions, the Oracle database software must ensure that the
data in the tables remain valid. It does this through the use of locks. Consider the
following example in which two transactions named T1 and T2 attempt to modify
customer #1 in the customer table:
1. T1 performs an UPDATE to modify customer #1, but T1 doesn’t perform a COMMIT.
T1 is said to have “locked” the row.
2. T2 also attempts to perform an UPDATE to modify customer #1, but since this row is
already locked by T1,T2 is prevented from getting a lock on the row. T2’s UPDATE
statement has to wait until T1 ends and frees the lock on the row.
3. T1 ends by performing a COMMIT, thus freeing the lock on the row.
4. T2 gets the lock on the row and the UPDATE is performed.T2 holds the lock on the
row until T2 ends.
To summarize: A transaction cannot get a lock on a row while another transaction
already holds the lock on that row.
Transaction 1 T1 Transaction 2 T2
(1) SELECT * (2) SELECT *
FROM customers; FROM customers;
(3) INSERT INTO customers
(customers_id, first_name,last_name)
VALUES(7, ‘Jason’, ‘Price’);
(4) UPDATE customers
SET last_name = ‘Orange’
WHERE customer_id = 2;
(5) SELECT * (6)SELECT *
In the following list, you’ll see examples of two concurrent transactions named T1 and
T2 that are accessing the same rows; listed are the three types of potential transaction
processing problems.
Phantom reads:-
T1 reads a set of rows returned by a specified WHERE clause. T2 then inserts a new
row, which also happens to satisfy the WHERE clause of the query previously used by
T1. T1 then reads the rows again using the same query, but now sees the additional
row just inserted by T2. This new row is known as a “phantom” because to T1 this row
seems to have magically appeared.
Nonrepeatable reads:-
T1 reads a row, and T2 updates the same row just read by T1. T1 then reads the
same row again and discovers that the row is read earlier is now different. This is
known as a “non repeatable” read, because the row originally read by T1 has been
changed.
Dirty reads:-
T1 updates a row, but doesn’t commit the update
T2 then reads the updated row.T1 then performs a rollback,
Undoing the previous update. Now the row just read by T2 is
no longer valid (it’s “dirty”) because the update made by T1
wasn’t committed when the row was read by T2.
To deal with these potential problems, database implement
various levels of transaction isolation to prevent concurrent
transactions from interfering with each other. The SQL
standard defines the following transaction isolation levels,
FLASHBACK QUERIES:-
Flashbacking Data :-
The above query displays data that exists before one day.
EXECUTE DBMS_FLASHBACK.ENABLE_AT_TIME(SYSDATE-2) ;
Example :-
EXECUTE DBMS_FLASHBACK.DISABLE() ;
Flashback Table :-
Example :-
PURGE command :-
PURGE RECYCLEBIN ;
Creating a user
To create a user in the database, you use the CREATE USER statement. The simplified
syntax for the CREATE USER statement is as follows:
Deleting a User:-
You delete a user using the DROP USER statement.
CONNECT system/manager
DROP USER Naresh ;
System Privileges:-
A system privilege allows a user to perform certain actions within the database, such
as executing DDL statements. For example, CREATE TABLE allows a user to create a
table in their schema. Some of the commonly used system privileges are shown in the
table:
Granting System Privileges to a user:-
You use GRANT to grant system privilege to a user. The following example grants some
system privilege to steve (assuming you’re still connected to the database as system):
GRANT CREATE SESSION, CREATE USER,
You can also use WITH ADMIN OPTION to allow a user to grant a privilege to another
user. The following example grants the EXECUTE ANY PROCEDURE privilege with the
ADMIN option to Naresh.
GRANT EXECUTE ANY PROCEDURE TO Naresh WITH ADMIN OPTION;
EXECUTE ANY PROCEDURE can then be granted to another user by Naresh. The
following example connects as Naresh and grants EXECUTE ANY PROCEDURE to vijay
CONNECT Naresh/oracle11g
GRANT EXECUTE ANY PROCEDURE TO vijay ;
You can grant a privilege to all users by granting to PUBLIC.
EXECUTE ANY PROCEDURE to PUBLIC:
CONNECT system/manager
GRANT EXECUTE ANY PROCEDURE TO PUBLIC;
Every user in the database now has the EXECUTE ANY PROCEDURE privilege.
CONNECT store/store_password
GRANT SELECT, INSERT, UPDATE ON store.products TO steve;
GRANT SELECT ON store.employees TO steve;
The next example grants the UPDATE privilege on the last_name and salary columns to
steve:
GRANT UPDATE (last_name, salary) ON store.employees TO steve;
You can also use the GRANT option to enable a user to grant a privilege to another
user. The following example grants the SELECT privilege on the customers table with
the GRANT option to steve:
CONNECT steve/button
GRANT SELECT ON store.customers TO gail;
The next example revokes the SELECT privilege on the customers table from steve:
Roles
A role is a group of privileges that you can assign to a user or to another role. The
following points summarize the benefits and features of roles:
Rather than assigning privileges one at a time directly to a user, you can create a role,
assign privileges to that role, and then grant that role to multiple users and roles.
When you add or delete a privilege from a role, all users and roles assigned that role
automatically receive or lose that privilege.
You can assign multiple roles to a user or role.
You can assign a password to a role.
As you can see from these points, roles can help you manage multiple privileges
assigned to multiple users.
Creating Roles:-
To create a role, you must have the CREATE ROLE system privilege.
CONNECT system/manager
GRANT CREATE ROLE TO store;
GRANT CREATE USER TO store WITH ADMIN OPTION;
You create a role using the CREATE ROLE statement. The following statements
connects as store and create the three roles shown in table:
CONNECT store/store_password
CREATE ROLE product_manager;
CREATE ROLE hr_manager;
CREATE ROLE overall_manager IDENTIFIED by manager_password;
You can check which system privileges have been granted to a role by querying
role_sys_privs.
The following example retrieves the rows from role_sys_privs (assuming you’re still
connected as store):
SELECT *
FROM role_sys_privs
ORDER BY privilege;
Revoking a Role:-
You revoke a role using REVOKE. The following example connects as store and revokes
the overall_manager role from steve:
CONNECT store/store_password
REVOKE overall_manager FROM steve;
Dropping a Role:-
You drop a role using DROP ROLE. The following example drops the overall_manager,
product_manager, and hr_manager roles.
DROP ROLE overall_manager;
DROP ROLE product_manager;
Hierarchical Queries :-
A hierarchical query presents data in a inverted tree structure.
The tree comprises of interconnected nodes.
Each node may be connected to none,one or more childnodes.
Each node is connected to one parent node. The top most
node is the Root Node that has no parent.
Nodes that do not have child nodes are called Leaf Nodes.
Syntax :-
SELECT [LEVEL] , <COLUMNNAME> -------
FROM <TABNAME>
[WHERE <COND>]
[START WITH <COND>]
[CONNECT BY PRIOR <COND>]
KING
JONES
SCOTT
ADAMS
FORD
SMITH
BLAKE
ALLEN
WARD
MARTIN
TURNER
JAMES
CLARK
MILLER
Example :-
Example :-
SYS_CONNECT_BY_PATH :-
Example :-
SELECT ENAME,SYS_CONNECT_BY_PATH(ENAME,'\')
FROM EMP
CONNECT_BY_ISLEAF :-
Example :-
SELECT ENAME,CONNECT_BY_ISLEAF
FROM EMP
START WITH ENAME='KING'
CONNECT BY PRIOR EMPNO=MGR
ORDER SIBLINGS BY ENAME
TABLES
SEQUENCES
VIEWS
MATERIALIZED VIEWS
SYNONYMS
INDEXES
CLUSTERS
PROCEDURES
FUNCTIONS
PACKAGE
DB TRIGGER
SEQUENCE
A SEQUENCE is a schema object that can generate unique sequential values.
The SEQUENCE Values are often user for PRIMARY KEY’S and UNIQUE KEY’S.
CREATING SEQUENCES:-
Syntax:-
CREATE SEQUENCE sequenceName
[INCREMENT BY n]
[START WITH n]
[MAXVALUE n|NOMAXVALUE]
[MINVALUE n|NOMINVALUE]
[CYCLE |NOCYCLE]
[CACHE n|NOCACHE]
ORDER/NORDER;
INCREMENT BY:-
Specifies the interval between the Sequence Numbers.
Value can be Positive or Negative, but can not be 0.
NOMINVALUE:-
Specifies a minimum value of 1 for an ascending sequence and –(10)^26) for a
descending sequence.
MAXVALUE:-
Specifies the maximum value that sequence can generate.
NOMAXVALUE:-
Specifies a maximum value of 10^27 for an ascending sequence and -1 for a
descending sequence.
START WITH:-
Specifies the first sequence number to be generated.
For ascending sequence the default value is SEQUENCES’S MINIMUM value.
CYCLE:-
Specifies whether the sequence contains to generate values after reaching its
maximum or minimum value.
NOCYCLE:-
Specifies the SEQUENCE cannot general more values after the targeted limit.
CACHE:-
Specifies how many values the Oracle Server Preallocates and keep in memory.
NOCACHE:-
Specifies the values of a SEQUENCE are not preallocated.
If the above parameters are not specified by default 20 values are cached.
ORDER:-
Gurantee the sequence numbers to be generated in the order of request.
NOORDER:-
Does not generate the sequence Number with Order.
NOTE:-
If the above parameters are not specified by default
START WITH Will be 1.
INCREMENT BY Will be positive 1.
SEQUENCE is NOCYCLE.
The CACHE Value Will be 20
SEQUENCE is ORDER.
Test Table:-
CREATE TABLE TDEPT
( DEPTNO NUMBER(4) Constraint Tdeptno_PK PrimaryKey,
DNAME VARCHAR2(14),
LOC VARCHAR2(13)
);
Example :-
Modifying a Sequence:-
The ALTER command can be used to change the present status of a SEQUENCE.
The ALTER SEQUENCE command can be used to change………
Increment Value
Maximum Value
Minimum Value
Cycle Option
Cache Option
Syntax:-
ALTER SEQUENCE sequence
[INCREMENT BY n]
[{MAXVALUE n| NOMAXVALUE}]
[{MINVALUE n| NOMINVALUE}]
[{CYCLE | NOCYCLE}]
[{CACHE n |NOCACHE}];
EXAMPLE:-
Alter SEQUENCE TDept_DeptNo_Seq
INCREMENT BY10
MAXVALUE 500
NOCACHE
NOCYCLE;
Removing a Sequence:-
Remove a sequence from the data dictionary by using the DROP SEQUENCE statement.
Once removed, the sequence can no longer be referenced.
Remember:-
The owner of the sequence or have the DROP ANY SEQUENCE privilege to remove it.
Once removed, the sequence can no longer be referenced.
The Data Dictionary in which the information of SEQUENCES are stored is
USER_OBJECTS.
Select Sequence_Name,Min_Value,Max_Value,Increment_By,
Last_Number From User_Sequences
Where Sequence_Name= ‘SEQ1’;
VIEWS
Data abstraction is usually required after a table is created and populated with data.
Data held by some tables might require restricted access to prevent all users from
accessing all columns of a table, for data security reasons.
Such a security issue can be solved by creating several tables with appropriate columns
and assigning specific users to each such table, as required. This answers data security
requirements very well but gives rise to a great deal of redundant data being resident
in tables, in the database.To reduce redundant data to the minimum possible, Oracle
provides using Virtual tables which are Views.
VIEW DEFINITION:-
A View is a virtual table based on the result returned by a SELECT query. The content
of which is taken from table with the help of a query.
The most basic purpose of a view is restricting access to specific column/rows from a
table thus allowing different users to see only certain rows or columns of a table.
Composition Of View:-
A view is composed of rows and columns, very similar to table. The fields in a view are
fields from one or more database tables in the database.
SQL functions, WHERE clauses and JOIN statements can be applied to a view in the
same manner as they are applied to a table.
View storage:-
A view is not a part of the physical schema like other ordinary tables, it is a dynamic,
virtual table computed or collated from the data available in the database. Changing
the data in a base table alters the data shown by the view.
Oracle does not store the view data. It recreates the data, using the view’s SELECT
statement, every time a user queries a view.
A view is stored only as a definition in Oracle’s system catalog.
When a reference is made to a view, its definition is scanned, the base table is opened
and the view is created on top of the base table.This, therefore, means that a view
never holds data, until a specific call to the view is made. This reduces redundant data
on the HDD to a very large extent.
Advantages Of View:-
Security:- Each user can be given permission to access only a set of views that
contain specific data.
Query simplicity:- A view can draw from several different tables and present it as a
single table turning multiple table queries into single table queries against the view.
Data Integrity:- If data is accessed and entered through a view, the DBMS can
automatically check the data to ensure that it meets specified integrity constraints.
Disadvantage of View:-
Performance:- Views only create the appearance of the table but the RDBMS must
still translate queries against the views into the queries against the underlined source
tables. If the view is defined on a complex multiple table query then even a simple
query against the view becomes a complicated join and takes a long time to execute.
Types of Views :-
Simple Views
Complex Views
Simple Views :-
Syntax:-
CREATE VIEW V1
AS
SELECT EMPNO,ENAME,SAL,COMM FROM EMP ;
Views can also be used for manipulating the data that is available in the base
tables[i.e. the user can perform the Insert, Update and Delete operations].
Views on which data manipulation can be done are called Updateable Views.
If an Insert, Update or Delete SQL statement is fired on a view, modifications to data in
the view are passed to the underlying base table.
If the user wants to INSERT records with the help of a view, then the PRIMARY KEY
column(s) and all the NOT NULL columns must be included in the view.
If VIEW created with WITH CHECK OPTION then any DML operation through that view
violates where condition then that DML operation returns error.
CREATE VIEW V2
As
SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP
WHERE DEPTNO=10
WITH CHECK OPTION ;
The above INSERT returns error because view based 10 th dept but employee joined in
20th dept.
COMPLEX VIEWS :-
Sub-queries
Constants,Strings or Values Expressions
UNION,INTERSECT,MINUS operators.
Example :-
CREATE VIEW V3
AS
SELECT E.EMPNO,E.ENAME,E.SAL,D.DEPTNO,D.DNAME,D.LOC
FROM EMP E JOIN DEPT D
USING(DEPTNO) ;
CREATE VIEW V2
AS
SELECT DEPTNO,SUM(SAL) SUMSAL FROM EMP
GROUP BY DEPTNO;
Destroying a View:-
The DROP VIEW command is used to destroy a view from the database.
Syntax:-
DROP VIEW<viewName>
Example :-
SYNONYMS
Syntax:-
CREATE SYNONYM <NAME> FOR <TABLENAME>;
Example :-
CREATE SYNONYM EMP FOR EMPLOYEE_INFORMATION;
Public Synonyms:-
You can also create a public synonym for a table. When you do this , all users see the
synonym.
CONNECT system/manager
GRANT CREATE PUBLIC SYNONYM TO store;
CONNECT store/store_password
CREATE PUBLIC SYNONYM products FOR store.products;
If you connect as steve, who has the SELECT privilege on store.products, you can now
retrieve rows from store.products through the products public synonym:
CONNECT steve/button
SELECT *
FROM products;
Indexes
When looking for a particular topic in a book, you either scan the whole book, or you
can use the index to find the location. An index for a database table is similar in
concept to a book index, except that database indexes are used to find specific rows in
a table.
Oracle server uses following methods to locate the desired information
1 Table Scan2 Index Scan
In table scan oracle scans the entire table to locate the desired information.
In index scan oracle uses index to locate the place that holds the required data and
then jumps to that place to get required data. This is much faster than table scan.
How Does Indexing Work :-
When an index is created on a table, oracle internally forms a two dimensional matrix
that contains
1 Data extracted from the column on which index is created
2 Physical Address of the record (rowid)
When an SQL query that has a WHERE clause based on the column on which index is
fired , oracle finds the value in index and locates the record in the table using ROWID .
TYPES OF INDEXES :-
B-tree Indexes
Bitmap Indexes
B-TREE INDEXES :-
UNIQUE INDEX :-
UNIQUE index doesn’t allow duplicate values into the column on which INDEX is
created.
Example :-
CREATE UNIQUE INDEX I3 ON DEPT(DNAME)
NOTE:-
PRIMARY KEY columns and UNIQUE columns are automatically indexed by ORACLE.
ORACLE automatically creates UNIQUE index on PRIMARY KEY and UNIQUE columns.
BITMAP INDEXES :-
Bitmap indexes are typically used in Data Warehouse.
Bitmap indexes are created on low cardinality columns.
Bitmap indexes are useful when data is not modified by concurrent transactions.
Bitmap is used for each key value, the bitmap enables the database to locate a row.
A mapping function converts bitmaps to rowids
Ex ample :-
Modifying an Index:-
ALTER command is used to Modify an INDEX.
Example :-
ALTER INDEX I1 RENAME TO I10
Dropping an Index:-
SYNTAX :-
DROP INDEX <NAME>
EXAMPLE :-
DROP INDEX I1
Retrieving index information :-
USER_INDEXES :-
Maintains information about indexes .
USER_IND_COLUMNS :-
Maintains information about on which columns indexes are created.
MATERIALIZED VIEWS
A materialized view is a database object that contains the results of a query unlike
normal views that only contains the query definition and not the results.
Materialized views are usually a choice when creating summary tables on aggregate of
a table’s data.
A materialized view can query tables, view’s and other materialized views.
Since Materialized view does not contain up-to-the –minute information. When an
ordinary view is queried, the data retrieved includes changes made up to the last
committed transaction.However, when an materialized view is queried the data
retrieved would be at a state when the view was created or last refreshed.
REFRESH:-
Since the materialized view is built on underlying data that is periodically changed,
specify how and when to refresh the data in the view. The following keywords in the
REFRESH clause can also be used to create a schedule for recurring refresh operations:
FAST: - Updates only the values in the materialized view, assuming that some
preconditions are met.
FORCE: - Does a FAST refresh if possible and a COMPLETE refresh if the preconditions
for a FAST refresh are not available.
ON COMMIT:- Causes a refresh to occur whenever the underlying data is changed and
the change is committed.
START WITH DATE:- Indicates the date and interval at which the materialized view is
to be refreshed
NEXT DATE:- Indicates the time and interval at which the materialized view is to be
refreshed next
WITH PRIMARY KEY: - Indicates whether the materialized view is based on Primary
Key
Primary key materialized views allow materialized view master tables to be reorganized
without affecting the eligibility of the materialized view for fast refresh.
Such materialized view is based on the primary key of the master table instead of
RowID.
Example :-
RowID materialized views should have a single master table and cannot contain any of
the following:
Distinct or aggregate functions
GROUP BY
Subqueries
Joins and Set operations
The following statement creates the RowID materialized view on table Empoyees:
Example:-
CREATE MATERIALIZED VIEW mv_rowid_Employees
REFRESH ON COMMIT
WITH RowID
AS SELECT *FROM Employees;
TABLE PARTITIONING :-
As the number of rows in your table grows, the meanagement and performance
impacts will increase. Backups will take longer, recoveries will take longer and queries
on that will take longer.
Administrative and performance issues can be simplified by seperating rows of a single
table into multiple parts.
Dividing a table’s data in this manner is called partitioning the table, and table is called
partitioned table and parts are called partitions.
Advantages :-
1. RANGE PARTITION
2. LIST PARTITION
3. HASH PARTITION
RANGE PARTITION:-
which record assinged to which partition depends on range of the partition key.
Example :-
ENAME VARCHAR2(20) ,
SAL NUMBER(7,2)
)
PARTITION BY RANGE(SAL)
(
PARTITION P1 VALUES LESS THAN(2000) ,
PARTITION P2 VALUES LESS THAN(4000),
PARTITION P3 VALUES LESS THAN(MAXVALUE)
);
Employee whose salaries less than 2000 all those records are assinged to partition P1.
Employee whose salaries less than 2000 all those records are assinged to partition P2 .
MAXVALUE is a keyword , any data that could not be stored in earlier partitions are
assigned to partition P3.
LIST PARTITION :-
Which record is assinged to which partition depends on value of partition key value.
HASH PARTITION :-
A Hash paritition determines the physical placement of data by applying hash function
on partition key .
CREATING SUBPARTITIONS :-
We can create subpartitions that is, paritions of partitions. You can use subpartitions to
combine all types of partitions like range partitions, hash partitions,list partitions.
Example :-
MANAGING PARTITIONS :-
Partitions can be dropped , new partitions can be added , and two partitions can be
merged.
DROPING PARTITION :-
Syntax :-
Example :-
VARRAYS :-
Example :-
CPHONE PHONE_ARRAY
);
NESTED TABLE :-
Example :-
USER_TYPES :-
Analytic Functions
Analytic Functions are commonly used to compute cumulative, moving, centered and
reporting aggregates.
Oracle provides several analytic functions that help compute an aggregate value based
on a group of rows.
Analytic Functions provided by Oracle open up a whole new way of looking at the data.
It helps remove a lot of procedural code and complex code spec that would have taken
a long time to develop, to achieve the same result.
Whatever an analytic function does, can be done by using SQL, with the help of joins
and subqueries. However, an analytic function always does it faster, when compared to
native SQL.
Example:-
The OrderDetails table holds the order details of all the products that were sold. It is
desired to display the total Order Value against each OrderNo. Every Order in this table
is broken down into Products for that order.
SELECT OrderNo, SUM(Cost) “Order Value” FROM
OrderDetails
GROUP BY OrderNo ORDER BY OrderNo;
Example:-
It is desired to display the total Order Value against each OrderNo along with product
details.
SELECT OrderNo, ProductName, Cost, SUM(Cost)
OVER (PARTITION BY OrderNo) “Order Value”
FROM OrderDetails ORDER BY OrderNo,Cost;
Example:-
It is desired to display the total Order Value against each OrderNo along with product
details for all the products except Products named TV and AC.
The PARTITION BY clause logically breaks a single result set into N groups, according
to the criteria set by the partition expressions.
The words partition and group are used synonymously here.
The analytic functions are applied to each group independently.
Order By Clause:
The ORDER BY clause specifies how the data is sorted within each group [partition].
This will definitely affects the outcome of any analytic function.
Windowing Clause:
The windowing clause allows defining a sliding or anchored window of data, on which
the analytic function will operate, within a group.
This report displays a row by row cumulative order-wise total [Order Wise Running
Total], with each such row including a summation of the previous row’s price [Product
Wise Running Total].
Row_Number:-
Example:-
A customer can buy multiple products. An order can therefore be made up of a set of
products.
The organization wants to know the top two expensive products that a customer
bought on order basis.
SELECT * FROM (SELECT OrderNo, ProductName, Cost,
ROW_NUMBER()
OVER(PARTITION BY OrderNo ORDER BY Cost DESC)
Top TwoProducts
FROM OrderDetails)
WHERE Top TwoProducts<=2;
Dense_Rank:-
The organization wants to rank the top four expensive products that a customer bought
on order basis.
SELECT * FROM (SELECT OrderNo, ProductName, Cost,
DENSE_RANK()
OVER(PARTITION BY OrderNo ORDER BY Cost DESC)
Top TwoProducts
FROM OrderDetails)
WHERE Top TwoProducts <=4
ORDER BY OrderNo, Cost DESC;
Rank:-
The same query is fired using RANK function retrieve a different output.
SELECT * FROM (SELECT OrderNo, ProductName, Cost, RANK()
OVER(PARTITION BY OrderNo ORDER BY Cost DESC)
Top TwoProducts
FROM OrderDetails)
WHERE Top TwoProducts <=4
ORDER BY OrderNo, Cost DESC;
To achieve this,
Create a sliding window within a group. In this case the group would be OrderNo
Compute the sum of the current row’s Cost column plus the Cost of the previous 2
rows in that group
The windowing clause allows doing exactly this. It allows defining a sliding or anchored
window of data, on which the analytic function operates, within a group.
The default window is anchored window that simply begins at the very first row of a
group and continues to the current row.
Windows can be used for:
RANGES of data values
ROWS offset from the current row
An ORDER BY clause in an analytic function adds a default window clause of RANGE
UNBOUNDED PRECEDING which means all the previous rows available in a partition are
considered.
Example:-
Suppose it is desired to determine the average of product prices of 5 products ordered
prior to the current product including the current product in the average.
This can be achieved using Row windows. Row windows allow including physical
number of rows in the window.
SELECT ProductName, OrderDate, Cost, AVG(Cost)
OVER (ORDER BY OrderDate
ROWS 5 PRECEDING) “Avg5ProductsAbove”
FROM OrderDetails
ORDER BY OrderDate;
OVER(PARTITON BY OrderNo
ORDER BY Cost ASC) AS “LOW Priced Product”,
FIRST_VALUE(ProductName)
OVER(PARTITION BY OrderNo
ORDER BY Cost DESC) AS “High Priced Product”
FROM OrderDetails
ORDER BY OrderNo, ProductName;