Oracle 10g Material Final 1
Oracle 10g Material Final 1
Oracle 10g Material Final 1
External Tables can be accessed for files outside the database, as if the rows in the files
were rows in the table.
An Oracle Instance Comprises of
Relational Tables
Object Relational Tables
Index Organized Tables
External Tables
Partitioned Tables
Materialized Views
Temporary Tables
Clustered Tables
Dropped Tables
The Access to the data in the tables is tuned by indexes, they are
1)
2)
3)
4)
5)
6)
B+ Tree Index es
Bitmap Indexes
Reverse Key Indexes
Function Based Indexes
Partitioned Index es
Text Indexes
Oragle 10 g Material
Table Spaces :
It consist of one or more data files
A data file can be a part of one and only one table space
As per 10g minimum table space is created are
In 10g a bigfile tablespace can be created , which can grow to the size of tera bytes
The Oracle managed files concept can be used to simplify the creation and maintenance
of data files
Temporay Tablespace :
The actual table space is permanent , but the segments saved in the table space are
temporary
It is used to support sorting operations such as index creation and joint processing.
Tables can be either Dictionary Managed / Logically Managed
Oracle maintains a Bitmap in each dat a file of the table space to trace space availability
AUTOMATED STORAGE MANAGEMENT (ASM) :
It automates the layout of datafiles and other operating system level files , used by the
database
It is done by distributing the files across all available disks.
It supports multiplexing features, minimizing the possibility of data data loss
As new disks are added , the database files are automatically redistribut ed access all
disks in the defined groups for optimal performance
AUTOMATIC UNDO MANAGEMENT :
The transaction are support ed by dynamically creating and managing undo segments
It helps in maintaining prior images of the changed Blocks and Rows
The UNDO segments are managed directly without the intervention of the DBA
Flashback version Queries can be executed to see the different versions of a row as it
changed during a specified time interval.
DROPPED DATA :
The Recycle Bin concept was introduced with Oracle Database 10g
This concept impacts the space requirements for the table spaces and datafiles
This architecture greatly simplifies rec overies of accidentally dropped tables
The concept may considerably increase the space used in the database
The PURGE Command is used to remove old ent ries from the recycle bin
PL/SQL :
It is the most critical component of all the application implementations
The component can be used to create stored proc edures and functions
Using this component the stored procedures and functions can be collected into single
unit called packages
Using the sam e component the Dat abase trigger can also be designed.
Oragle 10 g Material
2)
DYNAMIC SQL :
Using this concept SQL can be generat ed at runtime and pass it to procedures which
execute it.
3)
SQL * PLUS :
It provides simple interface to the Oracle database.
It supports Rudimentary Reporting and is the best tool for scripting.
It provides consistent interface for
1.
2.
4)
5)
XML :
Oracles XML interfaces and XML types can be used to support inserting and ret rieving of
data via XML.
6)
7)
Oracle can be used to create and access object oriented structures, including user defined
data types, methods, large objects object tables nested tables.
Data Pump :
Data Pump import and Data Pump Export, enhance the manageability and performanc e.
Data Pump can be used to quickly extract data and move it to different databases whi le
altering the schema and changing the rows.
8)
SQL * LOADER :
It is used to load flat files quickly into Oracle Tables.
A single flat file can be loaded into multiple tables during the same load, and loads can be
parallel zed.
9)
10 ) UTL MAIL :
It is a package introduced in Oracle 10g.
It allows a PL/SQL application developer to see e-mails without having to know how to use
the underlying SMTP Protocal stack.
Oragle 10 g Material
TYP ES OF EDITIONS :
1)
Oracle Spatial
Oracle OLAP
Oracle Label Security
Oracle Data Mining
2) Standard Edition :
It provides some subset features of Enterprise Edition.
It includes features that are needed by a small business entity .
3) Personal Edition :
It allows for the development of applications which run on either the standard or Enterprise
Edition.
The Edition is not suitable for Production Environment.
DATABAS E MANAGEMENT SYSTEMS :
DBMS is a program which takes care of
Storing of Information.
Retrieving of Information.
Modification of Information.
Deletion of Information.
Type of Databases
** Hierarchical
** Network
** Relational
** Object Relational
** Object Oriented
A Relational dat abas e uses relations or two dimensional tables to store information.
Oragle 10 g Material
DATA MODELS :
The Data Models help in exploring ideas and improve the understanding of the database design.
PURPOS E OF DATA MODELS :
** Communicate
** Categoriz e
** Describe ** Specify
** Evolve
** Analyze
** Imitate
** Investigate
It
It
It
It
ABOUT ORACLE 8 :
It is the first object capable database.
It provides a new engine which supports
It provides OLTP applications, with sharing of runtime dat a structures, large buffer caches and
deferrable constrains.
It supports Client Server and Web based application whic h are distributed and multitired.
It can scale tens and thousands of concurrent users.
Oragle 10 g Material
ABOUT ORACLE 8i :
Oragle 10 g Material
A FIELD :
It can be found at the Intersection of a row and a column.
A Field can have only one value, or may not have a value at all, the absence of value in
Oracle is repres ented as NULL.
RELATI NG MULTIPLE TABLES :
Each table contains data that describes exactly only one entity.
Date about different entities is stored in different tables.
RDBMS enables the dat a in one table to be related to another table by using the foreign keys.
A Foreign Key is a column or a set of Column that refer to a Primary Key in the same table or
another table.
ALTER
DROP
TRUNCA TE
DELETE
UPDATE
ROLLBACK
SAVEPOINT
REVOKE
Oragle 10 g Material
VIEW
Tables in ORACLE 8 / 9 / 10 :
Tables can be crated at any time, even when the users are using the dat abase.
Size of the table need not be specified.
The structure of the table can be modified online.
Rules to Create A Table :
The user should have permission or CREA TE TABLE command, and storage area.
The Table name should begin with a letter and can be 1 30 characters long.
Names can contain :
** A Z
** a - z
** 0 9
** - , $ , #
Names can not be duplicated for another object in the same ORACLE Server.
Names cannot be oracle servers reserved word
Names are not case sensitive
Create Table Statement :
Syntax :
SQL > CREA TE Table < Table_Name >
(
Column_Name1 < Data type > (Width),
Column_Name2 < Data type > (Width),
:
:
Column_Namen < Data type > (Width)
);
Oragle 10 g Material
* Literals
* Format Models
* Nulls
* Database Objects
Words
Free Form Text
Database Character set
National Character set
They are less restrictive than other data types an have very few properties
The data is stored in strings with byte values
The information can belong to either
ORA CLE supports both single byte & multi byte character sets.
The different character data types are :
CHAR
NCHA R
VARCHAR2
NVARCHA R2
CHAR DATATYP E :
Oragle 10 g Material
NCHAR DATATYP E :
It is first time defined in ORA CLE 9i, and contains Unicode data only.
The columns maximum length is determined by the National Character set definition.
The Maximum size allowed is 2000 Byte s and size has to be specified.
If the data is shorter than the actual size then the blank pads are applied.
Varchar Datatype :
It specifies the variable length character string.
The Minimum size is 1 Byte and the Maximum size is 4000 Byte s.
It occupies only that space for which the data is supplied.
Nvarchar Datatype :
It is first time defined in ORA CLE 9i.
It is defined for Unicode only date.
The minimum for the size is 1 Byte and maximum is 4000 Byte s.
NUMBER DATATYP ES :
Number Data Type :
It stores zero, positive and negative fixed and floating point numbers.
The range of magnitude is
1.0 * 10
-130
to 9.9 ..9 * 10
125
10
Oragle 10 g Material
* Year
* Month
* Date
* Hour
* Minute
* Second
* Month
* Minute
* Second
* Year
11
* Hour
Oragle 10 g Material
RAW and LONG RAW data types are intended for storage of binary dat a or Byte Strings.
RAW and LONG RAW are variable length dat a types
They are mostly used to store graphics, sounds documents etc.
The ORACLE converts the RAW & LONG RAW data int o Hexadecimal form.
Each Hexadecimal character represents four bits of RAW data.
* CLOB
* NCLOB
It enables access to binary file LOBs whic h are stored in the file systems outside ORA CLE.
A BFILE column or the attributes stores the BFILE locator.
The BFILE locator maintains the directory alias and the filename.
The Binary File LOBs do not participate in transactions and are not recoverable.
The maximum size is 4 GB.
12
Oragle 10 g Material
Conventional INSERT
Direct path INSERT
In Conventional Insert statement, ORA CLE reuses free space in the table into which the data in
being inserted and maint ains referential integrity constraints.
In Direct-path insert , ORACLE appends the inserted data after existing data in the Table, the f ree
space is not reused.
13
Oragle 10 g Material
Syntax :
INSERT INTO < TABLE-NAME > ( COL1, COL2, .. )
VALUES ( VALUE1, VALUE2,....) ;
Examples:
INSERTING DATA INTO ALL COLUMNS OF A TABLE :
SQL> INSE RT INTO S TUDE NTS
VALUES (123, SAMPATH, KUMAR, 29 -JA N-80, 30-MA R-95, 25000,M) ;
In this case the values should be provided to all the columns that exist inside the table.
The order in which the values are declared in the values clause should follow the same order as
that of the original table order.
The char, varchar and data type data should be declared in single quotes.
IMPLICIT
E XPLICT
SQL> INSE RT INTO S TUDE NTS (StudNo, Fname, Lname, DOB, DOJ, Fees, Gender)
VALUES (1234,Kris hna, NULL, 28 -FEB-04, NULL, M) ;
INSERTING SPECIAL VALUES :
SYSDATE FUNCTION
It is a Pseudo column provided by the oracle.
The function returns the current date & time.
SQL>
14
Oragle 10 g Material
USER FUNCTION :
It is special function, which rec ords the current USER Name.
SQL> INSERT INTO Students (StudNO, Fname, Lname, DOJ, DOB, Fees)
Values (1234, Suresh, User, Sysdate, 25-jan-80, 30000) ;
SUBSTITUTION VARI ABLES :
These variables are used to stored values temporarily.
The values can be stored temporarily through
1. Single Ampersand (&)
2. Double Ampersand (&& )
3. DEFINE and ACCEP T Commands
The Single Ampersand substitution variable applies for each instanc e when the SQL statem ent is
create or executed.
The Double Ampersand substitution variables applied for all instances until that SQL statement is
existing.
USING SINGLE AMP ERS AND SUBSTITUTION VARTIABLE :
SQL> INSE RT INTO Students (StudID, Fname, LName, Dob, Fees)
VALUES (&StudNo, Name, &Last Name, Date of Birth, 25000) ;
Using the A CCEP T Command of SQL *Plus, the prompts can be customized.
ACCEP T Command stores the values in a variable.
PROMP T Command displays the Customized text.
After creating a script using the substitutions variable to a file it can called with A CCEP T and
PROMP T with greater meaning.
EXAMPLE:
ACCEP T Stud_id PROMP T Please Enter the Student Number:
ACCEP T Fir_name PROMP T Please Ent er the First Name:
ACCEP T Cou_fees PROMP T Please Enter the Course Fees:
SQL> INSE RT INTO Students (StudNo, Fname, Fees)
VALUES (&Stud_id ,&Fir_name, &Cou_fees) ;
EXAMPLE:
ACCEP T Department_Id PROMP T Please Enter the Department Number:
ACCEP T Department_Name PROMP T Please Enter the Department Name:
ACCEP T Location PROMP T Please E nter the Location:
15
Oragle 10 g Material
At SQL prompt type the full name of the path where the file has to be created.
Give the name of the file with . sql extension.
If the file has to be replaced with the same existing name then use REPLA CE
ALL clause.
EXAMPLE:
SQL> SAVE D:\My Dir\SQLscript\Insert prompt.sql
SQL> SAVE D:\My Dir\SQLscript\Insert prompt.sql REPLACE ALL
QUERYI NG THE DATA FROM TABLES :
QUERY: It is an operation that retrieves data from from one or more tables or views.
SELECT STATEMENT:
The SELECT statement is used to retrieve dat a from one or more tables , object tables , views,
object views or management views.
PREREQUISITES :
The user must have the SELE CT privileges on the specified object.
The SELECT A NY TABLE allows to select the data from any recognized object.
CAP ABILITI ES IF SQK SEKECT STATEMENT :
The SELECT statement can be used to select or Retrieve data from the object using any one of
the following criteria.
o
SELECTION :
PROJECTION :
It chooses the columns in a table that are expected to ret urn by a query.
JOIN :
It chooses the data in from one or more numbers of tables by creating a link
between them.
16
Oragle 10 g Material
EMP
Column Name
Data Type
-----------------------------------------------------Empno
Ename
Deptno
Job
Sal
Comm
Mgr
Hiredate
Table 2 :
NUMBER
VARCHAR
NUMBER
VARCHAR
NUMBER
NUMBER
NUMBER
DATE
DEPT
Column Name
Data Type
-----------------------------------------------------Deptno
Dname
Loc
NUMBER
VARCHAR
VARCHAR
Table 3 : SALGRADE
Column Name
Data Type
-----------------------------------------------------Hi sal
Losal
Grade
NUMBER
NUMBER
NUMBER
17
Oragle 10 g Material
18
Oragle 10 g Material
ARITHMETI C OP ERATORS :
The Arithmetic operators can be used to create expressions on NUMBER and DA TE data.
The Arithmetic operators supported are ..
o
Addition
Subtraction
Multiply
Divide
The Arithmetic operators can be used in any clause of a SQL statement. Except the FROM
clause.
SQL * Plus ignores Back Spaces before and after the Arit hmetic operator.
Sql > Select empno, ename, sal, sal + 500 from emp;
Sql > Select empno, ename, sal, sal 1000 from emp;
Operator Precedence :
Multiplication and Division take priority over addition and subt ractions ( * / + - )
Operators of the same priority are evaluat ed from left to right.
To prioritize evaluation and to increase clarity parent hesis can be implemented.
Sql > Select empno, ename, sal, ( 12 * sal ) + 100 from Emp;
Sql > Select empno, ename, sal, 12 * ( sal + 500 ) from Emp;
Handling Null Values :
NULL : It is a value which is
Unavailable
Unassigned
Unknown
Inapplicable
A NULL is not same as zero or blank space.
If a row lacks the data for a particular column, than that value is said to be NULL or to contain
NULL.
Sql > Select ename, job, sal, comm From Emp ;
If any column value is an Arithmetic expression is NULL, the overall result is also NULL.
The above situation is termed as NULL propagation and has to be handled very carefully.
Sql > Select ename, job, sal, comm, 12 * Sal + comm From Emp ;
Sql > Select ename, job, sal, comm, 12 * sal + comm from Emp ;
19
Oragle 10 g Material
NVL Function :
The NV L function is used to convert a NULL value to an actual value.
Syntax :
NVL ( Expr1 , Expr2 )
NVL Function can be used to convert any data type, the return value is always the same as the
data type of Expr1.
The Data types of the Sourc e and Destination must match
o
o
o
NVL ( Comm , 0 )
NVL ( Hiredate , 01-JUN-99)
NVL ( Job , Not Assigned)
Sql > Select Ename, Sal, Comm, Sal + NVL ( Comm, 0 ) From Emp;
Sql > Select Ename, Sal, Comm, ( Sal * 12 ) + NVL (Comm , 0 ) From Emp;
Sql > Select Ename, Sal, Comm, ( Sal + 500 ) + NVL ( Comm , 0 ) From Emp;
** Table Alias
Dept no AS
Dname AS
Loc
AS
From Dept;
Department Id ,
Department Name ,
Place
20
Oragle 10 g Material
Sql> Select
Hisal As
Losal As
Grade
From Salgrade ;
Maximum Range ,
Minimum Range ,
LITERALS IN ORACLE :
A Literal and a Constant value are synonyms to one another and refer to a fix ed data value.
The types of Literals recognized by Oracle are
o
o
o
o
Text Literals
Integer Literals
Number Literals
Interval Literals
Text Literals :
It specifies a text or character literal.
It is used to specify values whenever text or CHAR appear in
** Expression
** Condition
** SQL Function
** SQL Statements.
mployee Information
Managers Specification
N n char Literal
21
Oragle 10 g Material
Until it is instructed SQL * Plus displays the results of a query wit hout eliminating duplic ate rows.
To eliminate the duplicate rows in the result, the DIS TINCT keyword is used.
Multiple columns can be declared after the DIS TINCT qualifier.
The DIS TINCT qualifier affects all the selected columns, and represents a distinct combination of
the columns.
Sql > Select DISTINCT Deptno From Emp ;
Sql > Select DISTINCT Job , Deptno From Emp ;
Sql > Select DISTINCT Deptno , Job From Emp ;
Filtering of Records :
The number of rows returned by a query can be limited using the WHERE clause.
A WHERE Clause contains a condition that must be met and should directly follow the From
Claus e.
Syntax :
SELECT [ Distinct ] { * | Column [ alias ] , .} From Table [ WHERE Condition(s) ] ;
The WHERE clause can compares
**
**
**
**
Values in Columns
Literal Values
Arithmetic Expressions
Functions
22
Oragle 10 g Material
** > =
** < =
AND
**
OR
**
NOT
AND Operator :
It Returns TRUE if both or all component conditions are TRUE.
It Returns FALSE if either is FALSE, else returns unknown.
Truth Table :
AND
TRUE
FALS E
NULL
TRUE
NULL
FALS E
NULL
NULL
NULL
Sql > Select Empno, Ename, Job, Sal From Emp Where Sal > = 1100 AND
Job = CLE RK ;
Sql > Select Empno, Ename , Job , Sal From Emp Where Deptno = 10
AND Job = MANAGE R ;
Sql > Select Ename, Sal , Job From Emp Where Sal > = 1500 AND Sal > 5000 ;
23
Oragle 10 g Material
Sql > Select Ename, Sal, Job From Emp Where ( Sal > = 1500 A ND Sal < = 5000 )
AND Job = MANAGE R ;
OR Operator :
It returns TRUE if either component conditions is TRUE
It returns FALSE if both are FALSE, else returns unknown
Truth Table :
OR
TRUE
FALS E
NULL
TRUE
FALS E
NULL
NULL
NULL
NULL
Sql > Select Empno, Ename, Job, Sal From Emp Where S al > = 1100 OR
Job = CLERK ;
Sql > Select Empno, Ename, Job, Sal From Emp Where Deptno = 10
OR Job = MANAGE R ;
Sql > Select Ename, Sal, Job From Emp Where Sal > = 1500 OR Sal > = 5000 ;
Sql > Select Ename, Sal, Job, Deptno From Emp Where Dept no = 10 OR Deptno = 20 ;
Sql > Select Ename, Sal, Job From Emp Where Job = CLE RK OR Job=MANAGE R ;
Sql > Select Ename, Sal, Job From Emp Where ( Sal < = 2500 OR Sal > = 5000 ) OR
Job = MANAGER ;
NOT Operator :
It returns TRUE if the following condition is FALSE.
It returns FALSE if the following condition is TRUE.
If the condition is Unknown, it returns Unk nown.
Truth Table :
TRUE
NOT
FALS E
NULL
NULL
24
Oragle 10 g Material
25
Oragle 10 g Material
Sql > Select Ename, Sal, Job From Emp Where Sal Between 1000 AND 1500 ;
Sql > Select Ename, Sal, Job From Emp Where Sal NOT Between 1000 AND 1500 ;
Sql > Select Ename, Sal, Job From Emp Where Job Between MANAGE R AND
SALESMAN ;
Sql > Select Ename, Sal, Job From Emp Where Job NOT Between MANAGE R AND
SALESMAN ;
Sql > Select Ename, Sal, Job, Hiredate From Emp Where Hiredate Between
17-FEB -1981 A ND 20-JUN-1983 ;
Sql > Select Ename, Sal, Job, Hiredate From Emp Where Hiredate NOT B etween
17-FEB -1981 A ND 20-JUN-1983 ;
IN Operator ; NOT IN Operator :
The Operator is used to test for values in a specified list.
The Operator can be used upon any datatype.
Sql > Select Ename, Sal, Job From Emp Where Ename IN( FORD, ALLEN ) ;
Sql > Select Ename , Sal, Job From Emp Where Ename NOT IN( FORD , ALLE N ) ;
Sql > Select Ename, Sal, Deptno From Emp Where Dept no IN( 10 , 30 ) ;
Sql > Select Ename, Sal, Deptno From Emp Where Dept no NOT IN( 10 , 30 ) ;
Sql > Select Ename, Sal, Hiredate From Emp Where
Hiredate IN( 20-FE IB-1981 , 09-JUN-1981 ) ;
Sql > Select Ename, Sal, Hiredate From Emp Where
Hiredate NOT IN( 20-FEIB -1981 , 09-JUN-1981 ) ;
IS NULL Operator ; IS NOT NULL Operator :
The Operator tests for NULL values
lt is the only operator that can be sued to test for NULLs.
NULL means the value is unavailable, Unassigned, Unknown, or inapplicable.
Sql > Select Ename, Deptno, Comm From Emp Where Comm IS NULL ;
Sql > Select Ename, Deptno, Job From Emp Where Mgr IS NULL ;
26
Oragle 10 g Material
Sql > Select Ename, Deptno, Comm From Emp Where Comm IS NOT NULL ;
Sql > Select Ename, Deptno, Comm From Emp Where Mgr IS NOT NULL ;
LIKE Operator ;
Ordering Information :
The Order of rows returned in a query result is undefined.
The ORDE R BY Clause can be us ed to sort the rows
The ORDE R BY Clause should be the last clause in the order of all clauses in the SELE CT
statement.
An expression or an alias can be specified to sort.
Default ordering of Data is Ascending
** Numbers
1 999
** Dates
Earliest Late st
** Strings
A Z ; NULLS Last.
27
Oragle 10 g Material
Syntax :
SELECT Expr From Table Name [ WHERE Condition(s) ]
[ ORDE R BY { Column, Expr } [ ASC / DESC ] ] ;
The default ordering upon a column is Ascending, to change the default ordering DESC should
be used after the column name.
Sorting can be implemented on column aliases, and can also be implemented upon multiple
columns.
The controversy of sorting is broken only when there arises a conflict of consistency upon the
data in a column.
Sql > Select Ename, Job, Deptno, Hiredate From Emp ORDER BY Hiredate ;
Sql > Select Ename, Job, Deptno, Hiredate From Emp ORDER BY Hiredate DES C ;
Sql > Select Ename, Job, Sal From Emp Where Job = MANAGE R ORDER BY Sal ;
Sql > Select Ename, Job, Sal From Emp Where Sal > = 2500 ORDER BY Job,
Ename DESC ;
Sql > Select Empno, Ename, Sal, Sal * 12 Annsal From Emp ORDER BY Annsal ;
Sql > Select Empno, Ename, Sal From Emp ORDER BY Deptno, Sal, Hiredate ;
Sql > Select Empno, Ename, Sal From Emp Where Sal > = 2000 ORDE R BY Hiredate,
Sal DESC ;
The single row functions can appear in
**
**
**
**
SELECT List
WHERE List
START W ITH Claus e
CONNE CT BY Clause
** NUMBE R
** DATE
** CONVE RSION
28
Oragle 10 g Material
Syntax :
Func_Name ( Column / Expr, [ Arg1, Arg2, ] )
Single Row Functions Features :
: Operate on values of date data type, can return bot h Date and
Number.
Conversion Function : Covert a value from one data type to another.
General Functions
29
Oragle 10 g Material
30
Oragle 10 g Material
Syntax :
If m is 0 , it is treated as 1.
If m is positive, Oracle counts from the beginning of char to find the first character.
If m is Negative, Oracle counts backwards from the end of the Character.
If n is Omitted , Oracle returns all characters to the end of Char.
If n is less than 1 or 0 , A NULL is returned.
Floating point numbers passed as arguments to Substr are automatically converted to Integers.
Syntax : SUBSTR ( Col / Expr, m, n )
Sql > Select Substr ( ABCDEFGH , 3, 4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH , -5, 4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH , 0 ,4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH , 4 ) From Dual ;
Sql > Select Substr ( ABCDEFGH, 4, 0 ) From Dual ;
Sql > Select Substr ( ABCDEFGH, 4 , -2 ) From Dual ;
Sql > Select Ename, Job From Emp Where Substr ( Job, 4, 3 ) = Upper( age ) ;
Sql > Select Concat ( Initcap ( Ename ) ,
Concat ( is a , Concat ( Initcap (S ubstr ( Job, 1, 3 ) ), Eater. ) ) )
From Emp Where Substr ( Job , 4, 3 ) = Upper ( Age ) ;
LENGTH Function :
Returns the number of characters in a value.
If the char has data type CHA R, the length includes all trailing blanks.
If the char is NULL , it return NULL .
31
Oragle 10 g Material
Syntax :
LPAD Function :
Pads the character value right justified to al total width of n character positions.
The default padding character is space.
Syntax : LPAD ( Char1, n, Char 2 )
Sql > Select Lpad ( Page 1, 15, *. ) From Dual ;
32
Oragle 10 g Material
33
Oragle 10 g Material
It returns a char with all occurrences of each character in From replaced by its corresponding
character in To .
Characters in char that are not in From are not replaced.
The argument From can contain more characters than To.
If the extra characters appear in Char, they are removed from the ret urn value.
Sql > Select Job, Translate ( Job, P, ) From Emp Where Job = PRESIDE NT ;
Sql > Select Job, Translate ( Job, MN, DM ) From Emp Where Job = MANAGE R ;
Sql > Select Job, Translate ( Job, A, O ) From Emp Where Job = SALESMAN ;
CHR Function :
It returns a character having the binary equivalent to n .
It returns the equivalent for n in database character set or national character set.
Syntax : CHR ( n )
Sql > Select Chr ( 67 ) || Chr (65 ) || Chr ( 84 ) Sample From Dual ;
Sql > Select Chr ( 16705 Using NCHAR_CS ) From Dual ;
34
Oragle 10 g Material
ASCII Function :
It returns the decimal representation in the character database set of the first characters of the
Char.
Syntax :
ASCII ( Char )
TRUNCATE Function :
Syntax : TRUNC ( n, m )
It returns n trunc ated to m decimal places.
If m is omitted, n is truncated to 0 places.
n can be negative to truncate m digits left to the decimal point.
Sql > Select Trunc ( 15.79, 1) From Dual ;
Sql > Select Trunc ( 15.79, -1 ) From Dual ;
Sql > Select Trunc ( 45.923, 2 ) , Trunc ( 42.923 ), Trunc ( 45.923, -1 ) From Dual ;
CEIL Function :
Syntax : CEIL ( n )
Returns the smallest integer great er than or equal to n .
The adjustment is done to the highest nearest decimal value.
Sql > Select Ceil ( 15.7 ) From Dual ;
Sql > Select Ceil ( 14.27 ) , Ceil ( 14.2 ) , Ceil ( 14 ) From Dual ;
35
Oragle 10 g Material
FLOOR Function :
Syntax : FLOOR ( n )
Returns the largest integer less than or Equal than n .
The adjustment is done to the lowest nearest decimal values.
Sql > Select Floor ( 15.7 ) From Dual ;
Sql > Select Floor ( 14.27 ) , Floor ( 14.2 ) , Floor ( 14 ) From Dual ;
MODULUS Function :
Syntax : MOD ( m, n )
It returns remainder m divided by n .
It returns m if n is 0.
Sql > Select Mod ( 11, 4 ) , Mod ( 10 , 2 ) From Dual ;
POWER Function :
Syntax : POWER ( m, n )
Returns m raised to the nth power.
The base m and the exponent n can be any numbers.
If m is negative, n must be an integer
Sql > Select Power ( 3, 2 ), Power ( -3, 2 ) From Dual ;
Sql > Select Power ( 3, -2 ) , Power ( -3, -2 ) From Dual ;
Sql > Select Power ( -3. 5, -2 ), Power ( 3, -2.5 ) From Dual ;
Sql > Select Power ( -3. 5, 2.5 ) , Power ( 3.5, -2.5 ) From Dual ;
SQUARE ROOT Function :
Syntax : SQRT ( n )
It returns square root of n.
The value of n cannot be negative
SQRT returns a real result.
Sql > Select Sqrt ( 25 ) From Dual ;
ABSOLUTE Function :
Syntax : ABS ( n )
It returns the abs olute value of n.
Sql > Select Abs ( -15 ) From Dual ;
36
Oragle 10 g Material
Sql > Select Sal, Comm, Sal Comm, Abs ( Sal Comm ) From Emp
Where Comm = 1400 ;
SIGN Function :
Syntax :
It
If
If
If
SIGN ( n )
** Year
** Minutes
** Seconds
** Month
** Day ** Hours
SYSDATE :
It is a date function that ret urns current date and time .
SYSDATE is generally selected upon a DUMMY Table.
Sql > Select SYSDATE From Dual ;
Date Arithmetic :
As database stores dates as numbers, Arithmetic operations can be implemented.
Number constants can be added or subtracted upon dates.
The operations that can be applied are
o
o
o
o
Date
Date
Date
Date
37
Oragle 10 g Material
Sql > Select Ename, ( Sysdate Hiredate ) / 7 Weeks From Emp Where Deptno = 10 ;
DATE Functions :
Add_Months Function :
Syntax : ADD_MONTHS ( D, n )
It returns the dat e d plus n months
The argumennt n can be any integer
Sql > Select Sysdate , Add_mont hs ( Sysdate, 2 ) From Dual ;
Sql > Select Sal,l Hiredate, Add_months ( Hiredate, 2 ) From Emp Where
Dept no = 20 ;
Months_Between Function :
Syntax : Months_Between ( D1, D2 )
It returns number of months bet ween dates d1 and d2.
If d1 is later than d2, the result is Positive, else Negative.
If d1 is and d2 are either the same days of the months or both last days of the months,
the result is always an integer.
Sql > Select Empno, Hiredate, Mont hs_Between ( Sysdate , Hiredate ) From Emp
Where Months_Bet ween ( Sysdate, Hiredate ) < 2000 ;
Sql > Select Ename, Months_Between ( Sysdate , Hiredate ) From Emp ;
Next_Day Function:
Syntax : Next_day( d, Char )
It returns the dat e of the first week day named by char, that is later than the date d.
The CHAR must be a day of the week in the sessions date language.
The day of the week can be full name or the abbreviation.
Sql > Select Sysdate, Next_day ( Sysdate, WED ) From Dual ;
Sql > Select Sal, Hiredate, Next_day ( Hiredate, MONDAY ) From Dual ;
Last_Day Function :
Syntax : Last_day ( d )
It returns the dat e of the last day of the month that contains d.
Mostly used to determine how many days are left in the current month .
Sql > Select Sysdate, Last_day ( Sysdate ) Last, Last_day ( Sysdate ) Sysdate
Daysleft From Dual ;
Rounding of Date s :
38
Oragle 10 g Material
IN EXPRESSIONS
* Number Varchar2
* Date Varchar2
Explicit Data type Conversion :
SQL provides three functions to convert a value from one data type to another.
39
Oragle 10 g Material
* To_Char
* To_Date
* To_Number
Sql > Select To_char ( 1234 , 9.9EEEE ) , To_char ( 1234, 9.99EEEE ) From Dual ;
G 9G999 :
40
Oragle 10 g Material
o
o
9999S :
o
41
Oragle 10 g Material
Sql > Select To_char ( 1000, S9999 ), To_char ( -1000, S9999 ) From Dual ;
Sql > Select to_char ( 1000, 9999S ) , To_char ( -1000, 9999S ) From Dual ;
Sql > Select Sal, To_char ( Sal, S99999 ) , To_char ( Sal, 99999S ) From Emp ;
Sql > Select Sal, Comm, To_char ( Comm - Sal, S99999 ) , To_char ( Comm Sal ,
99999S) From Emp ;
X XXXX :
xxxx :
o
o
o
42
Oragle 10 g Material
9990 :
Returns Trailing Zeros.
Sql > Select To_char ( 1000, 0999999 ) , To_char ( 1000, 09999990 ) From Dual ;
Sql > Select Sal, To_char( Sal, $099,999.99 ) From Emp ;
9 9999 :
o
Return value with a specified number of digits with a leading space when positive or
leading minus when negative.
Sql > Select To_char ( 1000 600 , 99999 ) , To_char( 600 1000 , 99999 )
From Dual ;
Sql > Select To_char ( 20.25 20, 99999 ) From Dual ;
C C9999 :
o
For input format models, format items cannot appear twice, and format items that
represent similar information cannot be combined.
Capit alization in a spelled out word, abbreviation, or Roman numeral follows capitalizati on in the
corresponding format element.
Punctuation such as hyphens, slashes, commas, periods and colons.
AD or A.D. / BC or B. C. :
o
43
Oragle 10 g Material
Sql > Select Sal, Hiredate, To_c har ( Hiredate, A.D. ) From Emp ;
AM or A.M. / PM or P.M. :
o
Sql > Select To_char ( Sysdate, A.M. ) , To_char ( Sysdate, PM) From Dual ;
Sql > Select Sal, Hiredate, To_c har ( Hiredate, AM ) From Emp ;
CC / SCC :
o
44
Oragle 10 g Material
45
Oragle 10 g Material
Sql > Select Ename, Hiredate, To_char ( Hiredate, Q ) From Emp Where
To_char ( Hiredate, Q ) = 4 ;
J Returns the JULIA N DAY.
i. It is the Number of days since January 1, 4712 BC.
ii. Numbers specified with J must be int egers.
Sql > Select Sysdate, To_char ( Sysdate, J ) From Dual ;
Sql > Select Ename, To_char ( Hiredate, J-DDD-DD-DD ) From Emp ;
MM returns the digit numeric abbreviation of the Month.
Sql > Select Sysdate, To_char ( Sysdate, MM-YYYY ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hi redate, MM-YYYY ) From Emp Where
To_char ( Hiredate , MM ) = 12 ;
MON Returns the Abbreviated Name of the Month.
Sql > Select Sysdate, To_char ( Sysdate, MM-MON ) From Dual ;
MONTH Spells the Name of the Month, padded to a length of 9 c haracters .
Sql > Select Sysdate, To_char ( Sysdate, MON -MONTH ) From Dual ;
Sql > Select Enbame, Hiredate, To_char ( Hiredate, MONTH, YYYY ) From Emp ;
HH / HH12 Returns the Hour of the day in twelve hour clock mode.
Sql > Select Sysdate, To_char (Sysdate, HH ), To_char (Sysdat e, HH12, AM )
From Dual ;
Sql > Select Ename, Hiredate , To_c har ( Hiredate, HH12 : AM ) From Emp ;
HH24 Returns the Hour of the day in twenty four hour clock mode . ( 0 23 )
Sql > Select Sysdate, To_char ( Sysdate, HH24 ) From Dual ;
MI Returns the Minutes from the given date ( 0 53 ) .
Sql > Select Sysdate, To_char ( Sysdaste, MI ), To_char ( Sysdate, HH:MI ) From Dual;
Sql > Select Ename, Sal, To_char ( Hiredate, HH:MI ) From Emp Where Job=CLE RK ;
RM
46
Oragle 10 g Material
From Dual ;
Sql > Select Sysdate, To_char ( Sysdate, DD-MONTH-YYYY, HH:MI:SS A.M. )
From Dual ;
Sql > Select Ename, Sal, Hiredate, To_c har ( Hiredate, HH24:MI:SS ) From Emp
Where Dept no In( 10, 30 ) ;
SSSS Display Seconds past Midnight ( 0 86399 ) .
Sql > Select Sysdate, To_char ( Sysdate, SSSS ) From Dual ;
Sql > Select Ename, Hiredate, To_char ( Hiredate, DD-MM-YY, HH:MI:SS, SSSS )
From Emp ;
The Punctuation marks that can be used in Date formats are
- ;
/ ;
! ;
. ;
; ;
: ;
text
50 - 99
50 - 99
Ex : DDTH 20
Sql > Select Sysdate, To_char ( Sysdate, DDTH, MONTH, YYYY ) From Dual ;
Sql > Select Ename, Sal, Hiredate, To_c har ( Hiredate, DDTH, MONTH, YYYY )
From Emp ;
o
SP Spells Numbers.
Ex : DDSP TWENTY
Sql > Select Sysdate, To_char ( Sysdate, DDSP , MONTH, YYYY ) From Dual ;
Sql > Select Ename, Sal, To_char ( Hiredat e, DDSP, MONTH, YYYY ) From Emp ;
47
Oragle 10 g Material
Sql > Select Sysdate, To_char ( Sysdate, DDSP TH, MONTH, YYYY ) From Dual ;
Sql > Select Ename, Sal, To_char ( Hiredat e, DDSP TH, MONTH, YYYY ) From Emp ;
Sql > Select Sysdate, To_char ( Sysdate, DDSP TH MONTH YYYYSP ) From Dual ;
Date Format Elements Re strictions :
o
o
The suffixes when added to date ret urn value always in English.
Date suffixes are valid only on output, henc e cannot be used to insert a date int o the
database.
It Converts a char, value of CHA R or VA RCHAR2 dat a type containing a Number in the
format specified by the optional format model fmt, to a value of NUMBER data type .
48
Oragle 10 g Material
49
Oragle 10 g Material
o
o
These functions operate on sets of rows to give one result per group.
The sets may be the whole table or the table split into groups.
DIS TINCT makes the function consider only non duplicat e values.
ALL makes the function to consider every value including duplicates.
Syntax : Group_Function_Name ( Distinct / ALL / n )
o
o
o
o
The data types for arguments may CHA R, VARCHAR, NUMBE R OR DA TE.
All group functions except COUNT( * ) ignore NULL values. To substitute a value for
NULL values, use the NVL function.
When a group function is declared in a SELECT list , no single row columns should be
declared.
When a group function is declared in a SELECT list, other columns can be declared, but
they should be grouped columns, and all the non functional columns should be declared
into a GROUP BY clause.
Average Function :
Syntax : AVG ( DIS TINCT / ALL / n )
o
o
Sql > Select AVG ( Sal ) , AVG ( DIS TINCT Sal ) From Emp ;
Sql > Select AVG ( Comm ) , AVG ( DIS TINCT AVG ) From Emp ;
SUM Function :
Syntax : SUM ( DIS TINCT / ALL / n )
o It returns the Sum of the values of n.
o It ignores NULL values.
o
Sql > Select Sum ( Sal ), Sum ( DIS TINCT Sal ) From Emp ;
Sql > Select Sum ( Comm ) , Sum ( DIS TINCT Comm ) From Emp ;
MAXimum Function :
Syntax : MAX ( DIS TINCT / ALL / n )
o
o
Sql > Select Max ( Sal ), Max ( DISTINCT Sal ) From Emp ;
Sql > Select Max ( Comm ) , Max ( DIS TINCT Comm ) From Emp ;
50
Oragle 10 g Material
MINimum Function :
Syntax : MIN ( DIS TINCT / ALL / n )
o
o
Sql > Select Min ( Sal ) , Min ( DISTINCT Sal ) From Emp ;
Sql > Select Min ( Comm ), Min ( DIS TINCT Comm ) From Emp ;
Standard Deviation Function :
Syntax : STDDEV ( DIS TINCT / ALL / n )
o
o
Sql > Select Stddev ( Sal ) , Stddev ( DIS TINCT Sal ) From Emp ;
Sql > Select Stddev ( Comm ), Stddev ( DIS TINCT Comm ) From Emp ;
Variance Function :
Syntax : VARIANCE ( DIS TINCT / ALL / n )
o
o
Sql > Select Variance ( Sal ) , Variance ( Distinct Sal ) From Emp ;
Sql > Select Variance ( Comm ), Variance ( DIS TINCT Comm ) From Emp ;
COUNT Function :
Syntax : COUNT ( * / DIS TINCT / ALL / n )
o
o
o
o
51
Oragle 10 g Material
The Group By Clause is used to decide the rows in a table into groups.
Syntax :
Having Clause :
Syntax :
52
Oragle 10 g Material
o
o
o
The HAV ING Clause can precede Group By Clause, But it is more logical to declare it
before Group By.
Group By Claus e can be us ed, without a Group Function in the SELECT list.
If rows are restricted based on the result of a group function, we must have a Group By
Claus e as well as the Having Claus e.
Sql > Select Deptno, A vg ( Sal )_From Emp Group By Deptno Having
Max ( Sal ) > 2900 ;
Sql > Select Job, Sum ( Sal ) Payroll From Emp Where Job NOT LIKE SALES%
Group By Job Having Sum ( Sal ) > 5000 Order By Sum ( sal ) ;
Sql > Select Deptno, Min ( Sal ), Max ( Sal ) From Emp Where Job = CLE RK
Group By Deptno Having Min ( Sal ) < 1000 ;
Sql > Select Deptno, Sum ( Sal ) From Emp Group By Deptno Having
Count ( Deptno ) > 3 ;
Sql > Select Deptno, A vg ( Sal ) , Sum ( Sal ), Max ( Sal ), Min ( Sal ) From Emp
Group By Dept no Having Count ( * ) > 3 ;
Sql > Select Deptno, A vg ( Sal ) Sum ( Sal ) From Emp Group By Deptno
Having A vg ( Sal ) > 2500 ;
Sql > Select Deptno, Job, Sum ( Sal ) , A vg ( Sal ) From Emp Group By Deptno, Job
Having A vg ( Sal ) > 2500 ;
Nesting of Group Functions :
o
Sql > Select Max ( Avg ( Sal ) ) From Emp Group By Dept no ;
Sql > Select Max ( Sum ( Sal ) ) , Min ( Sum ( Sal ) ) From Emp Group By Deptno ;
Sql > Select Max ( Sum ( Sal ) ) , Min ( Avg ( Sal ) ) From Emp Group By Job ;
Miscellaneous Functions :
o
GREATEST Function :
Syntax : GREATEST ( Expr1, Expr2, .)
53
Oragle 10 g Material
LEAST Function :
Syntax :
USER Function :
Syntax : USER
It returns the Current Oracle users within the VA RCHAR2 data type.
The function cannot be used in the condition of the CHECK Constraint .
UID Function :
Syntax : UID
USERENV Function :
Syntax :
USERENV ( Option )
54
Oragle 10 g Material
VISIZE Function :
Syntax :
VSIZE ( Expr )
SOUNDEX Function :
Syntax : SOUNDEX (CHAR )
It returns a character string containing the phonetic representation of char.
It allows comparison of words that are spelled differently, but sound alike in enlish.
Sql > Select Ename From Emp Where Soundes ( Ename ) = Soundex ( SMITH) ;
Sql > Select Ename, Job From Emp Where Soundes ( Job ) = Soundex ( CLERK ) ;
DATA INTEGRITY IN DATA BASES :
Data Integrity :
It is a state in which all the date values stored in the data base are collect.
Enforcing Data Integrity ensures the quality of the data in the data base.
CATEGORIES OF DATA INTIGRITY :
Enti ty Integrity :
It defines a row as a UNIQUE entity for a particular table
Entity integrity enforces the integrity of the identifies columns, or the P RIMA RY KEY of
a table.
Domain Integrity :
Domain Integrity validates the entries for a given column.
It can enforced through.
Restricting type ( Data Types )
By Format ( CHECK Constraint )
By Range of Possible Values ( FORE IGN KEY, CHECK, DEFA ULT, NOT NULL )
55
Oragle 10 g Material
Referential Integrity :
It preserves the defined relationship between tables when records are ent ered or deleted.
It ensures that key values are consistent across tables.
When referential integrity is enforced, it prevents from ..
* Adding records to a related table if there is no associated record in the
Primary Table.
* Changing values in a Primary Table that res ult in Orphaned records in a
related table.
* Deleting records from a Primary Table if there are matching related records.
User_Defined Integrity :
It allows to define specific business rules that do not fall into any one of the other int egrity
categories.
CONSTRAINTS :
Constraints are used to define an Integrity Constraint, as rule that restricts the values in a
data base.
As per Oracle these are Six Types of Constraints :
1)
2)
A UNIQUE Constraint
3)
4)
5)
A CHECK Constraint
6)
A REF Constraint
2)
Table Level : They are declared as part of the table definition. The style is
called as OUT_OF_LINE specification.
CREA TE Table
ALTE R Table
56
Oragle 10 g Material
CREA TE View
ALTE R View
USER_DEFINED OB JECT
VARRAY
REF
LOB
Exceptions :
o
o
NOT NULL Constraint are supported for a column or attributes whose type is
USER_DEFINED object VARRAY, REF, LOB .
NOT NULL, FOREIGN KEY, and REF Constraints are supported on a column of
type REF.
UNIQUE Constraints :
The UNIQUE Constraint designates a column as a UNIQUE Key.
57
Oragle 10 g Material
OBJECT * BFILE
) ;
SQL > Create table Promotions2
(
Promo_ID
PromoName
PromoCategory
PromoCost
PromoB egDate
PromoE ndDate
Number ( 6 )
Varchar2( 20 ) ,
Varchar2 ( 15 ) ,
Number ( 10 , 2 ) ,
Date ,
Date ,
Number ( 6 ) ,
Varchar2( 30 ) ,
Number ( 4 ) ,
Varchar2( 100 ) ,
Varchar2( 10 ) ,
58
Oragle 10 g Material
RailAccess
Parking
Vclearance
Varchar2( 10 ) ,
Varchar2( 10 ) ,
Number ( 4 ) ,
OBJECT * BFILE
The size of a P RIMA RY KEY cannot exceed approx. one Database Block .
A composite PRIMA RY KEY cannot have more than 32 columns.
The same column or combination of columns cannot be designated both as PRIMA RY
KEY and UNIQUE KEY.
PRIMA RY KEY cannot be specified when creating a SubTable or SubView in an
Inheritance Hierarchy.
The PRIMA RY KEY can be specified only for the top level( ROOT )Table or View
Example :
Sql > Create Table Locations
(
LocationID
Number ( 4 ) Constraint Loc_ID_PK PRIMARY KEY,
StAddress
Varchar2( 40 ) NOT NULL ,
PostalCode
Varchar2( 6 ) Constraint PC_NN NOT NULL ,
City
Varchar2 ( 30 ) Constraint City_NN NOT NULL
) ;
59
Oragle 10 g Material
) ;
Sql > Create Table Sales Info
(
ProdID
CustID
SaleDate
SaleDesc
Number ( 6 ) ,
Number ( 6 ) ,
Date NOT NULL ,
Long NOT NULL ,
OBJECT * BFILE
The Referenced Unique / Primary Key Constraint on the Parent Table on View must
already be deleted.
A Composite Foreign Key cannot have more than 32 columns.
The Child and Parent Tables must be on the same database.
To enable Referential Int egrity across nodes of a distribut ed databas e Database
Triggers are used.
REFERENCES Clause :
The References Clause Should be used when the Foreign Key Constraint is INLINE.
When the Constraint is OUT OF LINE, we must specify the Foreign Key , Key words.
60
Oragle 10 g Material
ON DELETE Clause :
The ON DELE TE Claus e determines how oracle automatically maintains
REFERE NTIAL INTEGRITY if the REFERE NCE D PRIMA RY or UNIQUE KEY value
is removed.
CASCA DE option can be specified if we want ORA CLE to remove Dependent
FORE IGN KEY values.
Specify SET NULL if we want Oracle to convert dependent FORE IGH KEY values to
NULL.
ON DE LE TE Clause cannot be specified for a view constraint.
Steps to be Followed for Creating Foreign Key Constraint are as Follows :
Step 1 : Create Primary Masters / Pure Masters
These are Tables which contains only Primary Key Columns.
Sql > Create Table Dept
(
Deptno
Number( 2 ) Constraint Deptno_Pk PRIMA RY KEY,
Dname
Varchar2( 20 ) Constraint Dname_NN NOT NULL,
Location
Varchar2( 20 ) Constraint Loc_NN NOT NULL
) ;
Step 2 : Create Detailed / Child Table
These are Tables which can contain Primary Key of their own as well as Foreign
Keys referring to other Primary Masters or to them selves.
These tables are als o called as dependent tables or Referential tables.
Sql > Create Table Employee
(
EmployeeID
Number ( 6 )
Constraint Emp_ID_PK PRIMA RY KEY ,
Ename
Varchar2 ( 30 )
Constraint Ename_NN NOT NULL ,
Designation
Varchar2 ( 30 )
Constraint Desig_NN NOT NULL ,
ManagerID
Number ( 6 )
Constraint Mgr_ID_FK_S elf
REFERENCES Employee ( EmployeeID )
ON DELETE SE T NULL ,
HireDate
Date
Constraint HireDate_NN NOT NULL ,
Commission
Number ( 7, 2 ),
Dept ID
Number ( 2 )
Constraint Dept ID_FK
REFERENCES Dept( Deptno )
ON DELE TE CASCA DE
) ;
61
Oragle 10 g Material
Number ( 4 )
Constraint SampIDRef_FK
REFERENCES SampMaster1( SampID1 ) ,
SampIDRef2
Number ( 4 )
Constraint SampIDRef2_FK
REFERENCES SampMaster2( SampID2 ) ,
SampNameRef Varchar2 ( 20 ) ,
SampDateRef Date ,
Constraint SampRef_Comp_PK
PRIMA RY KEY ( SampIDRef1, SampIDRef2 )
) ;
CHECK Constraint :
It defines a condition that each row must satisfy.
To satisfy the constraint, each row in the table must make the condition either TRUE or
UNK NOWN.
ORA CLE does not verify that CHE CK conditions are not mutually exclusive.
Restrictions :
The Condition of a CHE CK Constraint can refer to any column in the table, but it cannot
refer to columns of other tables.
The constructs that cannot be included are ..
62
Oragle 10 g Material
o
o
o
o
A single column can have multiple CHE CK constraint that reference the column in the
definition.
There is no limit to the number of CHE CK constraints that can be defined on a column.
The CHECK constrains can be defined at the column level or Table level.
Example :
Sql > Creat e Table Dept
(
Dept no Number ( 2 ) Constraint CHK _Deptno
CHE CK ( Deptno BETWEEN 10 A ND 99 ) ,
Dname Varc har2( 15 ) Constraint CHK _Dname_up
CHE CK ( Dname = UPPER ( Dname ) )
DISABLE ,
Loc
Varchar2 ( 15 ) Constraint CHK _Loc
CHECK ( Loc IN( DALLAS, BOS TON,
NEW YORK , CHICA GO ) )
) ;
Mgr
Number ( 4 )
Constraint PR_Empno PRIMARY KEY ,
Varchar2( 25 ) NOT NULL
Constraint CHK_Ename
CHE CK ( Ename = UPPER ( Ename ) ) ,
Varchar2( 30 )
Constraint Job_NN NOT NULL ,
Constraint CHK_Job
CHE CK ( Job = UPPER ( Job ) ) ,
Number ( 4 ) ,
HireDate
Date
Sal
Comm
Number ( 7, 2 )
Constraint Sal_NN NOT NULL ,
Constraint CHK_Sal
CHE CK ( Sal BETWEE N 2000 AND 100000 ) ) ,
Number ( 7, 2 ) ,
Dept no
Number ( 2 ) ,
Ename
Job
63
Oragle 10 g Material
DEFAULT Option :
The DEFA ULT Option is given to maintain a default value in a column.
The option prevents NULL Values from entering the Columns, if a row is inserted without a value
for a column.
The DEFA ULT value can be a literal, an expression or a SQL Function.
The DEFA ULT Expression must match the data type of the Column.
Adding Constraints to a Table :
A constraint can be added to a table at any time after the table was created by using ALTE R
TABLE Statement, using ADD Clause.
Syntax :
Sql > ALTER TABLE < Table_Name >
ADD [ Constraint < Constraint _Name > ]
Cons_Type ( Column_Name ) ;
The Constraint Name syntax is optional, but recommended.
Guidelines :
We can ADD, DROP , ENABLE, or DISABLE a Constraint , but modify the structure.
A NOT NULL can be added to existing column by using the MODIFY Clause of the ALTE R
TABLE Statement.
NOT NULL can be defined only when the table contains no rows.
Example :
Sql > ALTER Table Emp A DD Constraint Emp_Mgr_FK FOREIGN KEY ( Mgr )
REFERENCES Emp ( Empno ) ;
DROPPING Constraints :
To Drop a constraint identify the constraint name from the USER_CONS TRAINTS and
USER_CONS_COLUMNS Data dictionary views.
The ALTE R TABLE Statement is used wit h the DROP Clause.
The CAS CADE Option of the DROP Clause causes any dependent constraints also to be
dropped.
When a constraint is dropped, the constraint is no longer enforced and is no longer available in
the data dictionary.
Syntax : ALTER Table < Table_Name >
DROP PRIMARY KEY / UNIQUE ( Column ) /
CONS TRA INT Constraint_Name [ CASCA DE ] ;
Example :
Sql > ALTER Table Dept DROP P RIMA RY KEY CASCA DE ;
Sql > ALTER Table Emp DROP CONS TRAINT Emp_Mgr_FK ;
64
Oragle 10 g Material
DISABLING Constraints :
The constraints can be disabled without dropping it or rec reating it.
The ALTE R TABLE Statement is used wit h the DISABLE Clause.
Syntax :
Guidelines :
The DISABLE Clause can be used both in CREA TE TABLE and the ALTE R TABLE
statement.
The CAS CADE clause disables dependent integrity constraints.
Examples :
Sql > ALTER Table Emp DISABLE CONS TRA INT Emp_Empno_PK CASCA DE ;
ENABLING Constraints :
The Constraints can be enabled wit hout dropping it or re -creating it.
The ALTE R TABLE statement with the ENABLE Clause.
Syntax :
Guidelines :
Enabling a Constraint applied to all the data in the table.
When an UNIQUE or PRIMARY KEY Constraint is ENABLED, the UNIQUE or P RIMARY
KEY Index is automatically created.
The ENABLE Claus e can be us ed both in CREA TE TAB LE as well as ALTER TAB LE
Statements.
Examples :
Sql > ALTER Table Emp ENABLE CONS TRA INT Emp_Empno_FK ;
VIEWING Constraints :
To View all Constraints on a table by Querying the USER_CONS TRAINTS table.
The Codes that are revealed are
o
o
C
D
CHECK
PRIMARY KEY
REFERENTIAL INTEGRITY
UNIQUE KEY
65
Oragle 10 g Material
Example :
Sql > SELECT CONS TRA INT_NAME, CONS TRA INT_TYPE, SEARCH_CONDITION
FROM USER_CONS TRAINTS WHERE TABLE _NAME = EMP ;
JOINS :
A Join is query that combines rows from two or more tables, views, or Materialized views.
A Join is performed whenever multiple tables appear in the queries FROM Clause.
The Queries SELECT list can select any columns from any of these tables.
The common column names within the tables should qualify all references to these columns.
JOIN CONDTIONS :
Many Join Queries contain WHERE Claus e, which compares two columns, eac h from a different
table.
The applied condition is called a Join Condition.
To execute a Join
o
Oracle combines pairs of rows, each containing one row from each table, for which the
Join condition evaluated to TRUE.
The Columns in the Join Conditions need not be part of the SELECT list.
The WHERE Claus e of Join Query can also contain other conditions that refer to columns of only
one table.
To Execute a Join of three or more tables
o
Oracle first Joins two of the tables based on the Join Conditions comparing these
columns and then Joins the result to anot her.
JOIN 1
TABLE 1
TABLE 2
JOIN 2
RESULT
66
TABLE 3
Oragle 10 g Material
RESULT
The Oracle Optimizer determines the older in which Oracle Joins tables based on the
o
o
o
JOIN Condition
INDEX ES on Tables
STATISTICS for the Tables.
The LOB Columns cannot be specified in the WHERE Clause, When the WHERE Clause
contains any JOINS.
Syntax : Table1.Column1 = Table2.Column2 .
Guidelines :
When writing a SELE CT statement that Joins tables, precede the Column Name with the
Table Name for clarity and enhance database Access.
If the same column name appears in more than one table, the column name must be prefixed
with the table name.
To Join n tables together, we need a minimum of n -1 Join Conditions .
The above rule does not apply , if the table contains a concatenated P rimary Key.
EQUIJOINS / SIMPLE JOINS / INS ER JOINS :
An EQUIJOIN is a Join with a Join Condition containing an equality operator.
It combines rows that have equivalent values for the specified columns.
The total size of columns in the equi join condition in a single table may be limited to the size of a
data block minus some overhead.
The size of the data block is specified by the initialization parameter DB _BLOCK_S IZE .
Example :
Sql > Select Emp.Empno, Emp.Ename, Emp.Deptno , Dept.Deptno, Dept. Dname,
Dept.Loc From Emp, Dept Where Emp.Deptno = Dept. Deptno ;
Qualifying Ambiguous Column Names :
The names of the column names should be qualified in the WHERE Clause, with the table
name to avoid ambiguity.
If there are no common column names between the two tables, the qualification is not
necessary.
Example :
Sql > Select Empno, Ename, Emp. Dept no , Loc From Emp, Dept Where
Emp.Deptno = Dept.Deptno AND Job = UPPE R ( manager ) ;
USING TABLE ALIAS ES :
67
Oragle 10 g Material
Guidelines :
A table alias can be upto 30 character in length.
If a Table Alias is used for a particular Table Name in the From Clause, then that Table Alias
must be substituted fro the Table Name through out the SELECT statement.
A Table Alias should be meaningful .
A Table Alias is valid only for the Current SELECT statement .
Examples :
Sql > Select E.Empno, E,Ename, D.Deptno, D.Dname From Emp E, Dept D
Where E.Deptno = D.Deptno ;
Sql > Select E.Ename, E.Job, D. Deptno, D. Dname , D.Loc From Emp E, Dept D
Where E.Deptno = D.Deptno AND E.Job IN(A NALYS T, MANAGE R ) ;
Sql > Select E.Ename, E.Job, D. Dname , D.Loc From Emp E , Dept D
Where E.Deptno = D.Deptno AND D. Dname < > BOSTON ;
SELF JIONS :
E1.Ename || s Managers is ||
E2.Ename Employees And Managers
From Emp E1, Emp E2
Where E1.Mgr = E2.Empno ;
CARTESIAN PRODUCTS :
The CA RTES IAN PRODUCT is a Join Query, that that no Join Condition.
During Cart esian Product Oracle Combines each row of one table with each row of the other.
It tends to generate a large number of rows and the result is rarely useful.
Example :
Sql > Select Ename, Job, Dname From Emp, Dept ;
68
Oragle 10 g Material
Sql > Select Ename, Job, Dname From Emp, Dept Where Job = MANAGER ;
NON EQUI JOIN :
It is a Join Condition that is executed when no column is one table corresponds directly to a
column in the ot her table.
The Data in the tables in directly not related but indirectly or logically related through proper
values.
Example :
Sql > Select E.Ename , E.Sal , S.Grade From Emp E, SalGrade S
Where E.Sal BE TWEEN S.Losal AND S.Hisal ;
Sql > Select E.Ename, E.Sal, S.Grade From Emp E, SalGrade S
Where ( E.Sal > = S.LoSal AND E.Sal < = S.HiSal ) AND S.Grade = 1 ;
OUTER JOI NS :
An Outer Join extends the result of a simple Join.
An OUTE R Join ret urns all rows that satisfy the Join Condition and also those rows from one
table for which no rows from the other satisfy the Join Condition.
To perform an OUT Join of tables A and B and returns all rows from A, apply the outer join
operator ( + ) to all columns of B.
For all rows in A that have no matching rows in B, Oracle ret urns NULL for any select list
expressions containing columns of B.
Syntax :
Sql > Select Table1. Column, Table2. Column From Table1, Table 2
Where Table1.Column ( + ) = Table2. Column ;
Sql > Select Table1. Column, Table2. Column From Table1, Table 2
Where Table1.Column = Table2.Column ( + ) ;
Rules And Re strictions :
The ( + ) operator can appear only in the WHE RE Clause.
The ( + ) operator can appear in the context of the left correlation in the From Clause, and
can be applied only to a column of a Table or View.
If A and B are joined by multiple join conditions, we must use the ( + ) operator in all of these
conditions.
The ( + ) operator can be applied only to a column, not to an arbitrary expressions.
A condition containing the ( + ) operat or cannot be combined with another condition using the
OR Logical Operator.
A condition cannot use the IN Comparison operator to compare a column marked with the ( +
) operator with an expression.
A condition cannot compare any column marked with the ( + ) operator with a
sub query.
69
Oragle 10 g Material
Examples :
Sql > Select E.Ename , D.Deptno, D. Dname From Emp E, Dept D
Where E.Deptno ( + ) = D.Dept no Order By E.Deptno ;
Sql > Select E.Ename, D.Deptno , D.Dname From Emp E, Dept D
Where E.Deptno ( + ) = D.Dept no AND E.Deptno ( + ) = 10
Order By E.Deptno ;
Sql > Select E.Ename, D.Deptno, D. Dname From Emp E, Dept D
Where E.Deptno = D.Deptno ( + ) And E.Deptno ( + ) = 10
Order By E.Deptno ;
JOINING Data From More Than One Table :
JOINS can be established on more than two tables.
The Join is first executed upon the two most relevant tables and then the result is applied upon
the third table.
Example :
Sql > Selecgt C.Name, O.OldID, I. ItemID, I. Itemtot, O. Total
From Customer C, Ord O, Item I
Where C.CustID = O.CustID A ND
O.OldID = I.OldID A ND
C.Name = TKB SPORT SHOP ;
SUB QUERI ES / NESTED S ELECT / SUB SELECT / INNER SELCT :
70
Oragle 10 g Material
The inner query or the sub query returns a value that is used by the outer query on the main
query.
USAGE ..
They are practically very useful when we need to select rows from a table with a condition
that depends on the dat a in the table itself.
Syntax :
Select Select_List From Table_Name
Where Table_Name
( Select Select_List From Table_Name ) ;
The Expr . Operator can be of
o
TYPES OF S UB QUERIES :
Single Row Sub Query :
o
These Queries return only one Row from the inner SELECT Statement.
These Queries return more than one Row from the inner SELE CT Statement.
These Queries return more than one Column from the inner SELE CT Statement.
Guidelines To Follow ..
* Multiple Row
71
Oragle 10 g Material
72
Oragle 10 g Material
The Sub Queries that return more than one row are called as MULTIP LE ROW SUB QUERIES.
In This case a multiple row operator should be used.
The multiple row operators expect one or more values.
The multiple row operator are IN , ANY, ALL,
o
IN
ANY
ALL
S
Y
N
O
N
Y
S
Examples :
Sql > Select Ename, Sal, Deptno From Emp
Where Sal In( Select Min ( Sal ) From Emp Group By Deptno ) ;
Sql > Select Ename, Sal, Deptno From Emp
Where Sal In ( Select Max ( Sal ) From Emp Group By Deptno ) ;
Sql > Select Ename, Sal , Deptno , Job From Emp
Where Sal In( Select Max ( Sal ) From Emp Group By Job ) ;
73
Oragle 10 g Material
In Pair Wise comparisons each candidate row in the SELECT statement must have both the
same values associated with each column in the group.
The Non Pair Wise comparison also called cross product, we can use a WHE RE Clause with
multiple conditions.
In Non Pair Wise comparison, the candidate row must match the multiple conditions in the
WHERE Clause but the values are compared individually.
74
Oragle 10 g Material
Example :
Sql > Select Order_ID, Product_ID, Quantity From It em
Where Product_ID IN(S elect Product_ID From Item
Where Order_ID = 605 )
AND Quantity IN(Select Quantity From Item
Where Order_ID = 605
AND Order_ID < > 605 ;
Handling NULL Values in Sub Queries :
If one of the values returned by the inner query is NULL value, then the entire query returns No
Rows.
All Conditions that compare a NULL Value res ult is a NULL .
Whenever a NULL could be part of a Sub Query, it is better not to use NOT IN Operator
As it is equivalent to ! = NULL .
Example :
Sql > Select E.Ename From Emp E
Where E.Empno IN( Select M.Mgr From Emp M ) ;
75
Oragle 10 g Material
From Emp ;
Sql > Select E.Emp_Count, D.Dept_Count
From ( Select Count ( * ) Emp_Count From Emp ) E,
( Select Count( * ) Dept_Count From Dept ) D ;
Sql > Select A.Deptno Department Number ,
( A.Num_Emp / B.Total_Count ) * 100 %Employees ,
( A.Sal_Sum / B.Total_Sal ) * 100 %Salary
From ( Select Deptno, Count( * ) Num_Emp,
Sum ( Sal ) Sal_Sum From Emp
Group By Deptno ) A ,
( Select Count ( * ) Total_Count,
Sum( Sal ) Total_Sal From Emp ) B ;
CORRELATED SUB QUERIES :
It is another way of performing Queries upon the data wit h a simulation of Joins.
In this the information from the outer SELE CT statement participates as a condition in the INNE R
SELECT statement.
Syntax :
Select Select_List From Table1 F_Alias1
Where Expr. Operator
( Select Column_List From Table2 F_Alias2
Where F_Alias1.Column Operator F_Alias 2.Column ) ;
Example :
Sql > Select Deptno, Ename, Sal From Emp X
Where Sal > ( Select A vg( Sal ) From Emp
Where x.Deptno = Deptno )
Order By Deptno ;
Steps Performed :
First the Outer Query is executed.
Passes the qualified column value to the inner gueries WHERE Clause.
Then the inner query or candidate query is executed., and the result is passed to the outer
queries WHERE Clause.
Depending on the supplied value the condition is qualified for the specific record.
EXISTS Operator in Correlated Sub Queries :
The E XIS TS Operator tests for existence of rows in a subquery.
It returns TRUE if a subquery returns at least one row.
Example :
Sql > Select Deptno, Dname From Dept D
Where E XIS TS ( Select * From Emp E Where D.Deptno = E.Deptno ) ;
Sql > Select Deptno, Dname From Dept D
Where NOT E XIS TS ( Select * From Emp E Where D.Deptno = E.Deptno ) ;
76
Oragle 10 g Material
START WITH
CONNECT BY : It is used to specify the relationship bet ween parent rows and
child rows of the hierarchy.
WHERE
Steps Folowed :
ORACLE selects the root row ( s ) of the hierarchy, whic h satisfy the condition of the S TA RT
WITH Clause.
ORACLE selects the child rows of each root row. Each child row must satisfy the condition of the
CONNE CT BY Clause, with respect to one of the root rows.
ORACLE selects successive generations of child rows.
ORACLE selects children by evaluating the CONNECT BY condition with respect to a current
parent row.
If the query contains a WHERE Claus e, ORA CLE removed all rows from the hierarchy that do not
satisfy the condition of the WHE RE Clause .
General Representation :
Root
1
2
1
3
Child
9
7
4
10
12
11
77
Oragle 10 g Material
Leafs
Restrictions :
o
o
o
KING 7839
JONES 7566
SCOTT 7788
ADAMS 7876
BLAKE 7698
FORD 7902
CLARK 7782
ALLEN 7499
SMITH 7369
MILLER 7934
WARD 7521
MARTIN 7654
TURNER 7844
JAMES 7900
LEVEL 1 :
Root / Parent
Level 2 :
Root / Parent
Root / Parent
Level 3 :
Child / Leaf
Parent / Child
Parent / Child
Level 4 :
Child / Leaf
Child / Leaf
78
Child / Leaf
Oragle 10 g Material
Note : To Define Hierarchical Queries Properly we must use the following Clauses.
o
o
STA RT WITH
CONNE CT BY
CONNECT BY Clause :
o
o
o
o
o
This clause specifies the Relationship between Parent and Child Rows, in a hierarc hical
query.
This caluse contains a condition that defines a relationship
This condition can be any condition as defined by the syntax decription.
Within the condition, some part of the condition must use the PRIOR operator, which
refers to the Parent row.
The forms of PRIOR operators is
o
o
The Clause can contain other conditions to further filter the rows selected by the query.
It cannot cont ain a Sub Query.
Example :
Sql > Select Ename, Empno, Mgr, Job From Emp
CONNECT BY PRI OR Empno = Mgr ;
PSEUDO Columns :
Pseudo columns behave like a table column, but is not actually stored in a table.
Upon Pseudo columns only SELECTs can be implemented, But INSERT, UPDA TE or DELE TE
Cannot be implemented.
The A vailable Pseudo Columns are
79
Oragle 10 g Material
o CURRVAL
o NEXTVAL
o LEV EL
o ROWID
o ROWNUM
CURRVAL And NEXTV AL :
These Pseudo columns are applied upon the SEQUE NCE SchemaObject.
CURRVAL returns the Curent Value of a Sequence.
NEXTVAL Increments the sequence and returns the Next Value.
The CURRV AL And NEXTVAL can be used only in
o
o
o
Restrictions :
The CURRVAL and NE XTVAL cannot be used in ..
o
o
o
o
o
o
o
o
A Sub Query
A Views Query or S NAPSHOTs Query.
A SELECT Statement with the DIS TINCT operator
A SELECT Statement with a GROUP BY or ORDER BY Clause.
A SELECT Statement that is combined with another SELE CT Statement with
UNION, INERSE CT, MINUS SE T Operator.
The WHERE Claus e of a SELECT Statement
The DEFA ULT Value of Column in a CREA TE TABLE or ALTE R TABLE
Statement
The Condition of a CHE CK Constraint.
80
Oragle 10 g Material
To refer to the Current or Next Value of a SEQUENCE in the Schema of another used. The
following privileges should be available
o
o
SCHEMANAME.S EQUENCENAME.CURRV AL
SCHEMANAME.S EQUENCENAME.NEXTV AL
CREATI NG S EQUENCES :
Purpose :
An object from which multiple users may generat e Unique Integers.
Can be used to generate PRIMARY KEY values automatically.
Syntax :
CREATE SEQUENCE SequenceName
INCREMENT BY Integer
START WITH Integer
MAXVAL Interger / NOMAX VALUE
MINVAL Integer / NOMIN VALUE
CYCLE / NOCYCLE
CACHE Integer / NOCACHE
ORDER / NOORDER ;
INCREMENT BY :
o
o
o
o
MINVALUE :
o
NOMINV ALUE :
o
26
MAXVALUE :
81
Oragle 10 g Material
NOMAXVAULE :
o
27
STARTWITH :
o
o
CYCLE :
o
Specifies the sequence will continue to generat e values after reaching either maximum or
minimum value.
NOCYCLE :
o
Specifies the SEQUENCE cannot genral more values after the targeted limit.
CACHE :
o
NOCACHE :
o
ORDER :
o
NOORDER :
o
Does not guarantee the sequence Number without Pre order Default .
Sample Table :
Sql > Create Table Sample
(
SampID
SampName
SampDate
Number ( 4 )
Constraint SampID_PK Primary Key,
Varchar2( 25 ) ,
) ;
Creation of Incremental Sequence with NoCycle :
Sql > Create SEQUE NCE SampleS eq
INCREMENT By 1
STA RT WITH 0
MA XVALUE 5
82
Oragle 10 g Material
NOCACHE
NOCYCLE ;
Acti vating and Attaching the Sequence to a Table :
Sql > Insert into Sample ( SampID, SampName, SampDate )
Values ( SampleSeq.NextVal, Sample, 31-A UG-05 ) ;
Note :
o
o
Follow the Insert statement as previous and check the Inserted Values by executing the
SELECT statement on Sample Table.
Level Pseudocolumn :
o
This Pseudocolumn return 1 for ROOT Node, 2 for a child of a ROOT and so on.
83
Oragle 10 g Material
Modifying a Sequence :
o
o
The ALTE R Command can be used to change the present status of a SEQUENCE.
The ALTE R SEQUE NCE Command can be used to change ..
Increment Value
Maximum Value.
Minimum Value
Cycle Option
Cache Option
Syntax :
ALTER S EQUENCE SequenceName
[ INCREMENT BY n ]
[ { MAXVALUE n / NOMA XVALUE } ]
[ { MINVALUE n / NOMINVALUE } ]
[ { CYCLY / NOCY CLE } ]
[ { CACHE n / NOCACHE } ] ;
Example :
Sql > ALTER SEQUENCE SampleS eq
MA XVALUE 10
CACHE
NOCYCLE ;
Confirming Sequences :
All SEQUENCES that have been created are documted in the dta dictionary.
The data dictionary in which the information of SEQUENCES are stored is USER_OB JECTS.
The sttings of the SEQUENCE can be confirmed by SELECTING on USER_SEQUENCES.
Sqll >
STA RT WITH
CONNE CY BY
84
Oragle 10 g Material
85
Oragle 10 g Material
/* Wrong Way */
Sql > Select * From ( Select * From Emp ORDE R BY Sal DESC )
Where RowNum < 6 ; /* Proper Way */
ROWID P seudoColumn :
This Pseudo Column ret urns a Rwos Address for each row in the database.
ROWID Values copntain information necessary to locate a row
o
o
o
The Rows in different tables that are stored together in the same cluster can have the same
Rowid.
The Date type of the Values belonging to the RowID are of ROW ID Data type.
Use s of ROWID Values :
86
Oragle 10 g Material
UNION
MINUS
* INTERSECT
* UNION ALL
SET operatiors can copmbine two or more queries into one result.
The ORDE R BY Caluse when iomplemented should be applied only upon the column Numbers in
the SELECT list.
UNION Operator :
The UNION Operat or merges the outputs of two or more queries into a single set of rows and
columns.
Syntax :
Select Statement 1
UNION
Select Statement 2
[ ORDE R BY Clause ]
The Queries are all executed independently but their output is merge.
Only final query ends with a semicolon.
Examples :
Sql > Select Job From Emp
Where Dept no = 20
UNION
Select Job From Emp
Where Dept no = 30 ;
87
Oragle 10 g Material
Points to Ponder :
The two select statement may not contain an ORDE R BY Clause, the final result of the entire
UNION operation can be ordered.
The number of columns retrieved by the first SELECT statement must be equal t o the number of
columns retrieved by the second SELECT, and Data types must match.
The columns used for ordering must be defined through a number.
Sql > Select Empno, Ename From Emp
Where Dept no = 10 ;
UNION :
Sql > Select Empno, Ename From Emp
Where Dept no = 30
ORDER BY 1 ;
Sql > Select Empno, Ename, Job From Emp
Where Dept no = ( Select Deptno From Dept
Where Dname = SALES )
UNION
Select Empno, Ename, Job From Emp
Where Dept no = ( Select Deptno From Dept
Where Dname = ACCOUNTING )
ORDER BY 1 ;
UNION ALL :
It is similar to UNION, where UNION suppresses the deplicates.
If the duplicate records have also to be displayed then UNION ALL is used.
Sql > Select Empno, Ename From Emp
Where Dept no = 10
UNION ALL
Select Empno, Ename From Emp
Where Dept no = 30
ORDER BY 1 ;
INTERS ECT Operator :
This operator returns the rows that are common bet ween two sets of rows.
Syntax :
Select Statement 1
INTE RSECT
Select Statement 2
[ ORDE R BY Clause ] ;
Example :
Sql > Select Job From Emp
Where Deptno = 20
INTERS ECT
Select Job From Emp
88
Oragle 10 g Material
Where Dept no = 30 ;
Sql > Select Job From Emp Where Deptno = 20
INTERS ECT
Select Job From Emp Where Dept no = 30 ;
MINUS Operator :
This operators returns the rows Unique to the first query.
Syntax :
Select Statement 1
MINUS
Select Statement 2
[ ORDE R BY Clause ] ;
Example :
Sql > Select Job From Emp Where Deptno = 20
MINUS
Select Job From Emp Where Deptno = 10 ;
Sql > Select RowNum, Ename From Emp Where RowNum < 7
MINUS
Select RowNum, Ename From Emp Where RowNum < 6 ;
VIEWS IN ORACLE :
VIEW :
LOBs
* Object Types
Nested Tables
* Varrays
* REFs
Object View is a view of a user defined type, where each row contains objects, and each object
with a object Identifier.
PREREQUISITES :
Should have CREA TE VIEW or CREA TE ANY V IEW System privilege.
To create a subview, we need UNDER A NY VIEW system privilege or UNDER OB JE CT privilege
on the SUPE RVIEW.
89
Oragle 10 g Material
The OWNE R of the Schema should have SELE CT, INSERT, UP DA TE or DELE TE Rows from all
tables or Views on which the VIEW is based.
The above privileges must be granted the privileges directly, rather than a role.
Syntax :
Create [ OR REPLACE ] VIEW
[ { FORCE / NOFORCE } ] VIEW ViewName
[ ( AliasName [ , AliasName ..] ) ] As SubQuery
[ WITH { CHE CK OP TION / READ ONLY }
CONS TRA INT ConstraintName ] ;
OR REPLACE :
o
FORCE :
o
Specifies the V IEW has to be creat ed even if the base tables does not exist.
NOFORCE :
o
Specifies the View Should not be created if the base table does not Exis t, which is
default.
Alias_Name :
o
Specifies that only rows that would be retrieved by the SubQuery can be INSE RTE D,
UPDA TE D or DELE TE D.
CONSTRAINT :
o
Constraint_Name specifies the name of the WITH CHECK Option or READ ONLY
Constraint.
RESTRI CTIONS :
If a View has INSE RTED of Triggers, then only View created on it must have INS TE A D OF
Triggers, even if the Views are Inherantly Updatable.
An Alias cannot be specified when creating an OB JE CT View.
TYP ES OF VIEWS :
Simple Views :
90
Oragle 10 g Material
Complex Views :
o
o
o
o
Simple Views :
o
Example :
Sql > Create VIEW Employees As
SELECT Empno ID Number ,.
Ename Name ,
Sal Basic Salary ,
Job Designation
From Emp ;
Selecting Data From A View :
Sql > Select Name, Job From Employees ;
Sql > Select ID Number , Ename, Basic Salary * 12
From Employees ;
Sql > Select ID Number , Name ,
To_Char ( Basic Salary , 99,99,999.99 ) Monthly
Basic Salary * 12 Annual
From Employees
Where Basic Salary > 2500 ;
Complex Views :
o
o
Example :
Sql > Create VIEW EmpInfo As
Select E.Empno
EmployeeID,
E.Ename
Name ,
D.Deptno
DepartmentID ,
D.Dname
Deparatment Name
From Emp E, Dept D
91
Oragle 10 g Material
92
Oragle 10 g Material
The Steps or operations performed by the Oracle Server, when data is accessed using a VIEW
are
o
o
o
Retrieves the VIEW definition from the Data Dictionary table USER_VIEWS.
Checks the Access privileges for the view base table.
Converts the view query into an equivalent opration on the underlying base tabl e or
tables.
Modifying A View :
OR REP LACE Option is used to Modify an existing V IEW with a new definition.
A VIEW can be altered without Dropping, recreating, and regranting object privileges.
The assigned column Aliases in the CREA TE VIEW Clause, are listed in the same order as the
columns in the SubQuery.
Creating Views with Columns Declarations :
When a VIEW is being crated, we can specify the Names of the Columns, that it can project,
along with the V IEWs definition.
Example :
Sql > Create VIEW DeptSalSummary
( DepartmentName ,
MinimumSalary ,
MaxSalary ,
AverageSalary,
SalarySum
) As
Select D.Dname, Min (E.Sal ) , Max ( E.Sal ) , Avg ( E.Sal ) , Sum ( E.Sal )
From Emp E, Dept D
Where E.Deptno = D.Deptno
Group By D.Dname ;
Sql > Create VIEW InsertDept10 As
Select * From Emp
Where Dept no = 10 ;
93
Oragle 10 g Material
Dropping a View has no affect on the tables upon which the View is created.
VIEWS or APPLICA TIONS based on deleted Views become invalid.
We need DROP ANY VIEW privilege to remove the V IEWS.
Syntax :
DROP VIEW ViewName ;
Example :
DROP VIEW InsertDept ;
INLINE VIEWS :
An INLINE VIEW is a SubQuery with an ALIAS ( Called as CORRELA TION NAME ), that can be
used within a SQL Statement.
An INLINE VIEW is similar to using a named SubQuery in the FROM Clause of the Main Query.
An INLINE VIEWE is not a Schema Object.
An INLINE VIEW in the FROM Clause of a SELE CT statement defining Dat a Source for the
SELECT statement.
Examples :
Sql > Select E1.Ename , E1.Sal , E1.Deptno, E2.MaxSal
From Emp E1 , ( Select Deptno, Max ( Sal ) MaxSal
From Emp GROUP BY Deptno ) E2
Where E1. Dept no = E2.Deptno
AND
E1.Sal < E2.MaxSal ;
GROUP Function
A GROUP By Clause
The ROWNUM PESUDO COLUMN
The DIS TINCT Key Word
The Columns defined by Expressions.
Data can be added through a view, unless it contains any of the above rules and there are NOT
NULL Columns, and wit hout DEFA ULT V alue.
Example :
Sql > Create View Insert Dept ( DeptID,
DeptName ,
Place
) AS
Select Deptno, Dname, Loc From Dept ;
94
Oragle 10 g Material
Example :
Sql > Create Or Replace VIEW EDept30
AS
Select * From Emp Where Deptno = 30
WITH CHE CK OP TION CONS TRA INT EDept30ChkView ;
95
Oragle 10 g Material
INITIALLY DEFERRED :
It Indicat ed that Oracle should check this CONS TRA INT at the end of S UBSEQUE NT
transactions.
Note :
INTIALLY DEFERRED i s not valied if the CONS TRA INT is declared to be
NOTDEFERRABLE
NOT DE FREEABLE CONS TRA INT is AUTOMA TICALLY INITIA LLY IMMEDIA TE and can
never be INITIALLY DE FERRED.
VALIDATE / NOTV ALIDATE :
The Behavior of VALIDA TE and NOVALIDA TE always depends on whether the CONS TRA INT is
ENABLED / DISABLED, either E XPLICITLY or by DEFA ULT.
RELY CLAUS E :
RELY and NORELY are valid only when we are modifying an existing CONS TRINT.
RELY :
It activates an existing CONS TRA INT is NOVALIDA TE mode for query rewrite, in an
unenforced query rewrit e Int egrity mode.
DEFERRABLE Clause :
The DEFE RRABLE and NOTDEFE RRAB LE parameters indicate whet her or not, in the
subsequent transaction, constraint checking can be deferred until the end of the transction using
the SET CONS TRA INT statement.
The default is NOT DEFE RRAB LE.
NOTDEFERRABLE :
It indicates that in subsequent transctions, wee cannot use the SET CONS TRA INT(s) Clause
to defer checking the CONS TRAINT UNTIL the trans action is committed.
The checking of a NOTDEFERRABLE CONS TRA INT can Never be DEFE RRE D to the end
of the transactions.
DEFERRABLE :
It indicated that in subsequent transctions we can use the SE T CONS TRAINT(s ) Clause to
defer checking the CONS TRA INT until aft er the transaction is committed.
The setting is effect lets the user to disable the CONS TRA INT temporarily while making
changes to the database that might violate the CONS TRA INT until all the changes are
complete.
To alter the CONS TRAINTS Deferability, we must DROP the CONS TRAINT and recereate it.
Restriction On The DEFERRABLE Clause :
The parameters cannot be specified for a V IEW CONS TRA INT.
96
Oragle 10 g Material
INITIALLY Clause :
It established the default checking behavior for CONS TRA INTS that are DEFERRABLE.
The INITIALLY setting can be overridden by a SET CONS TRA INT(s) statement in a
subsequent Transaction.
Initially Immediate :
It indicated that Oracle should check this CONS TRA INT at the end of each
subsequent SQL statement .
It is the default setting.
We cannot specify the Using_Indes _Clause the Exceptions_Clause or the ON
DELE TE Clause of the Reference_Clause.
VIEW CONS TRA INTS cannot be defined on attribute of an object column.
Sql > Create View EmpSalary
(
EmpID, Ename, Email UNIQUE RELY DISAB LE NOVALIDA TE ,
Constraint ID_PK PRIMA RY KEY ( EmpID ) RELY DISABLE
NOVALIDA TE ) AS
Select Empno, Ename, Email From Emp ;
Constraint State specifies how and when ORACLE should enforce the
CONS TRA INT.
The constraint state clauses can be specified in any order, but each state can be
specified only once.
Restriction on RELY Clause :
We cannot set a NOT NULL CONS TRA INT to RELY.
Example :
Sql > Create Table Games ( Scores Number Check ( Scores > = 0 ) ) ;
Note : In the above case the default constraint is NOT DEFERRABLE
INTITALLY IMME DIA TE constraint CHE CK.
Sql > Create Table Games1
(
Scores Number ,
Constraint Sco_Num_Unq UNIQUE ( Scores )
INITIALLY DEFERRE D DEFE RRABLE ) ;
WORKI NG WITH INDEX ES :
INDEX :
It is a Schema object which contains an entry for each value that appears in the indexed
column(s ) of the table or cluster.
It provides Direct, Fast Access to Rows.
Type s of INDEX ES :
NORMAL INDEX ES :
97
Oragle 10 g Material
o
o
BITMAP INDEX ES :
o
PARTITIONED INDEX ES :
o
They contain partitions containing an entry for eac h value that appears in the Indexed
columns of the table.
DOMAIN INDEXES :
o
They are INDE XES which are instances of an application specific index of type
Indextype.
PRE REQUISITES :
An INDE X on REF tyhpe columns Or attributes have to be declared with a SCOPE Clause.
Simple Index Example :
98
Oragle 10 g Material
Syntax :
Create [ UNIQUE ] INDE X IndexName
or
[ BITMAP ] ON
TableName ( Column_name [ , ColumnName .] )
TABLESPA CE TableSpaceName ;
Unique :
* Specify UNIQUE to indicate that the value of the column or columns upon
which the Index is based must be UNIQUE.
Restrictions :
* We cannot specify both UNIQUE and BITMAP.
* UNIQUE Cannot be specified for a domain Index.
BITMAP :
Specify BITMAP to indic ate that INDE X has to be careated with a BITMAP for each DIS TINCT
KEY.
BITMAP Indexes store the RowIDs associated with a key value as a BITMAP.
Each BIT in the B ITMAP corresponds to a possible RowID.
Restrictions :
BITMAP cannot be specified when creating a global partit ioned Index.
BITMAP SECONDA RY INDE X canot be created on an INDE X ORGA NIZE D TABLE unless the
INDE X ORGANIZE D table has a mapping table Associated with it.
We cannot specify both UNIQUE and B ITMAP.
BITMAP cannot be specified for a DOMAIN INDE X.
CLUTER INDEX CLAUSE :
It identifies the CLUS TE R for which a CLUS TER INDE X has to be created.
CLUS TER INDE X Cannot be created for a HASH CLUS TER.
TABLE INDEX CLAUS E :
It identifies the TABLE upon which the INDE X is being defined.
An INDE X on a NES TED TABLE COLUMN can be created by creating the INDE X on the
NES TED storage Table.
CREATI NG UNIQUE INDEX ES :
Sql > Create UNIQUE INDE X EmpEmailIDxUNQ ON Emp ( Email ) ;
99
Oragle 10 g Material
Specification of An INDEX :
INDE X IS A Schema Object.
100
Oragle 10 g Material
INDE X is used by the ORACLE SERVE R to speed up Retrieval of rows by using a Poiter.
INDE X Reduces the Disk I / O by using rapid path Access method to locate the data quickly.
INDE XEs are Independent of the table it INDE XES, both logically and physically.
INDE X is used and maintained automatically by the ORA CLE SERVER.
INDE XEs can be creat ed or Dropped at any time and have no effect on the base tables or other
INDE XES.
When a table is droopped, the Corresponding INDE XES are also dropped.
INDEX Creation is of Two Types :
1 ) Automatic
2 ) Manual
One Table more than one Index can be created, But this does not mean that, more the Indexes
lead to more faster performance.
Each DML operations that is committed on a table wit h Indexes means that the Indexes must be
updated.
WHEN TO CREATE AN INDEX :
The Column is used frequently in the WHERE Clause or ina Join Condition.
The Column contains a wide range of values.
The column contains a large number of NULL values.
Two or more columns are frequently used together in a WHERE clause or Join Condition.
The table is large and most queries are ex pected to retrieve less than 2 4 % of the rows.
DATABAS E SECURITY :
The SECURITY upon databases is applied by defining and describing separate SCHEMA
OBJECTS and GRA NTING required PRIV ILEGES upon them.
In ORACLE the Privileges can be ranted as well as Revolved.
GRANT COMMAND :
Syntax :
GRANT < PRIVILAGES NAME > , ,,,,,,,
ON
< Object_Name > To < User Name >
GRA NT command is used when we waqnt the dat abase to be shared with other users.
The other users are GRA NTED with certain type of rights.
GRAB T cinnabd cab be issued not only on TABLE OB JE CT, but also on V IEWS, SYNONYMS,
INDE XES, SEQUENCES etc.,
101
Oragle 10 g Material
Example :
Sql > GRANT SELE CT ON EMP TO ENDUSERS ;
Sql > GRANT INSERT, SELE CT, DELE TE ON EMP TO OPERA TORS ;
Sql > GRANT INSERT ( Empno, Ename, Job ) ON Emp To E ndUsers ;
REVOKE COMMAND :
Syntax :
REVOKE < PRIVILEGE NAME > , .. ON < OBJECT NAME . TO < USER NAME .
REVOKE is usede when we want one database to stop sharing the information with other users.
REVOKE privileges is assigned not only on table onject, but also Views, Synonyms, Index es
etc,
Example :
Sql > REVOKE INSERT , DELE TE ON EMP FROM Operators ;
Type s of Privileges :
System Privileges :
o
Object Privileges :
o
USER_TAB_P RIV_MADE
GRANTEE
TABLE_NAME
GRANTOR
PRIVILEGE
GRANTABLE
HIERARCHY
USER_TAB_P RIVS_RECD
OWNER
TABLE_NAME
102
Oragle 10 g Material
GRANTOR
PRIVILEGE
GRANTABLE
HIERARCHY
Example :
Sql > CONNECT SA TIS H / YELLANKI
Sql > SELECT * From SCOTT.EMP ;
ROLE CREATION
GRANTI NG PRIVILEGES TO ROLES
GRANTI NG ROLES TO US ERS or OBJECTS
Syntax :
CREATE ROLE < Role Name > IDE NTIFIE D BY < Password > ] ;
Example :
Sql > CREATE ROLE Sales_Mangers IDE NTIFIE D BY SalesAudit ;
103
Oragle 10 g Material
GRANTED_ROLE
DEFAULT_ROLE
OS_GRANTED
Checking System Privileges Granted to A ROLE :
The Schema Object ROLE_SYS-P RIVS specifies the SYS TEM PRIVILEGES Granted to a
ROLE.
The columns present are.
* ROLE
* PRIVILEGE
Checking Object Privileges Granted to a Role :
* ADMIN_OPTION
The Schema Object , ROLE_TAB_P RIVS specifies the OB JECT P RIV ILE GES granted to a
ROLE.
The columns present are
ROLE
OWNER
PRIVILEGE
GRANTABLE
TABLE_NAME
COLUMN_NAME
Revoking a ROLE :
Sql > REVOKE Sales_Managers From Scott ;
Revoking Privileges From A ROLE :
Sql > REVOKE ALL ON Emp From Sales _Managers ;
Dropping A Role :
Syntax :
104
Oragle 10 g Material
Example :
PUBLI C SYNONYM
We should have CREA TE PUBLIC SY NONYM privilege, and it can be accessed by all USERS.
Example :
Sql > Create PUBLIC S YNONYM EmpInfo FOR S COTT.Emp ;
105
Oragle 10 g Material
General Implementation :
Example :
Sql > Select Deptno, Sum ( Sal ) From Emp
Group By RollUp ( Deptno ) ;
Sql > Select Job, Sum ( Sal ) From Emp
Group By RollUp ( Job ) ;
Passing Multiple Columns To RollUp :
When multiple columns are passed to ROLLUP, the ROLL UP , groups the rows into blocks with
the same column values.
Example :
Sql > Select Deptno, Job, Sum ( Sal ) Salary From Emp
Group By RollUp ( Deptno, Job ) ;
Sql > Select Job, Deptno, Sum ( Sal ) Salary From Emp
Group By RollUp ( Job, Dept no ) ;
Sql > Select Job, Deptno, A vg ( Sal ) A verage From Emp
Group By RollUp ( Job, Dept no ) ;
Note :
o
o
NULL Values in the output of ROLLUP operations typically mean that the row contains
subtotal or grant total information.
Use the Nvl ( ) Function for proper meaning.
CUBE :
It is an extension similar to ROLLUP.
CUBE allows to take a specified set of grouping columns and crate sub totals for all possible
cominatins of them.
The result of CUBE is a summary that shows subtotals for every cominiation of columns or
expressions in the GROUP BY clause .
The implementation of CUBE is also called as n-dimensional CROSS_TAB ULA TION.
Example :
Sql > Deptno, Job, Sum ( Sal ) Salary From Emp
Group By CUBE ( Deptno, Job ) ;
Sql > Job, Deptno , Sum ( Sal ) Salary From Emp
Group By CUBE ( Job, Deptno ) ;
Applying Grouping ( ) Function :
The GROUP ING ( ) Function accepts a column and returns 0 or 1.
GROUP ING ( ) Function returns 1 when the column value is NULL, and returns 0 when the
column value is NOT NULL.
GROUP ING ( ) Function is used only upon queries that use ROLLUP or CUBE.
106
Oragle 10 g Material
GROUP ING ( ) Function is useful when we want to display a value when a NULL would otherwise
be ret urned.
Example :
Sql > Select GROUP ING ( Dept no ) , Deptno , Sum ( Sal ) From Emp
Group By RollUp ( Dept no ) ;
Sql > Select GROUP ING ( Job ) , Job , Sum ( Sal ) From Emp
Group By RollUp ( Job ) ;
DECODE Function :
The function has no restrictuon on the input and output data type.
Example :
Sql > Select Ename, DECODE ( Deptno, 10 , ACCOUNTING ,
20 , RESEARCH ,
30 , SALES ,
40 , OPERATIONS ,
OTHER ) Departments
From Emp ORDER BY Departments ;
Sql > Select Ename || Takes Care of ||
DECODE ( Job, ANA LYS T , ANALYSIS ,
CLERK , FIRING ,
MANAGER , MANAGING ,
PRESIDE NT , ADMINIS TRA TION ,
SALESMAN , SALES ) Responsibilities
From Emp ;
Sql > Select Ename, Job, DE CODE ( Job ,
CLE RK , E ,
SALESMAN , D ,
ANALYS T , C ,
MANAGER , B ,
PRESIDENT , A ,
O ) GRADES
FROM EMP ORDE R BY JOB ;
107
Oragle 10 g Material
Hiredate,
Hiredate,
Hiredate,
Hiredate,
YYYY ) ,
YYYY ) ,
YYYY ) ,
YYYY ) ,
1980,1, 0 ) )
1981,1, 0 ) )
1982,1, 0 ) )
1983,1, 0 ) )
1980 ,
1981 ,
1982 ,
1983
Sql > Select Job, Sal, DECODE ( Job, ANALYS T , Sal * 1.1 ,
CLE RK , Sal * 1.15 ,
MANAGER , Sal * 1.2 , Sal
) REVISE D SALARY
From Emp ;
Count ( DE CODE ( Deptno, 10 , * , NULL ) ) D10_COUNT ,
Sum( DE CODE ( Deptno, 10 , Sal , NULL ) ) D10_S al ,
Count ( DE CODE ( Deptno, 20 , * , NULL ) ) D20_COUNT ,
Sum( DE CODE ( Deptno, 20 , Sal , NULL ) ) D20_S al ,
Count ( DE CODE ( Deptno, 30 , * , NULL ) ) D30_COUNT ,
Sum( DE CODE ( Deptno, 30 , Sal , NULL ) ) D30_S al
From Emp ;
108
Oragle 10 g Material
109
Oragle 10 g Material
Example :
Sql > Select Ename, Deptno ,
CASE
WHEN Deptno = 10 THE N
WHEN Deptno = 20 THE N
WHEN Deptno = 30 THE N
WHEN Deptno = 40 THE N
ELSE Not Specified
END
From Emp ;
ACCOUNTING
RESEARCH
SALES
OPERA TIONS
110
Oragle 10 g Material
Query Rewrite :
Materialized Views improve query performance by PRE CALCULA TING Expensive JOIN
and AGGRE GA TION operations on the DA TABASE PRIOR to Execution time and stores
the results in the DA TABASE.
The Query OP TIMIZER can make use of MA TERIALIZE D VIEWS by automatically
recognizing when an Existing MA TERIALIZE D VIEW can and should be used to satisfy a
Request.
After above process is completed then the QUERY OP TIMIZE R transparently rewrites
the request to use the MA TERIALIZE D VIEW.
QUE RIES are then directed to the MA TERIALIZE D VIEW and not to the underlying
DE TAIL TABLES or VIEWS.
REWRITING QUE RIES to yuse MA TERIALIZE D VIEWS rather than detail relations,
results in a significant performance gain.
PREREQUISITES FOR MATERIALI ZED VIEWS PRIVILEGES :
Sql > GRANT QUERY REWRITE TO SCOTT ;
Sql > GRANT CREA TE MA TERIALIZE D VIEW TO SCOTT ;
Sql > ALTER SESSION SE T QUERY _REWRITE _ENABLE D = TRUE ;
Set the InitSid.ORA File :
111
Oragle 10 g Material
AS
SELECT Dname, Job, Sum ( Sal )
From Emp E , Dept D
Where E.Deptno = D.Deptno
Group By Dname, Job ;
112
Oragle 10 g Material
Sql > Select Deptno, Job, GROUP_ID ( ) , Sum ( Sal ) From Emp
Group By Deptno, RollUp ( Deptno, Job )
Having GROUP _ID ( ) = 0 ;
ANALYTIC FUNCTIONS :
The Built in Analytic Functions enable to perform complex calculations.
Analytic Functions Categories :
o
Ranking Functions :
They Enable to calculate Ranks, Percentiles and n-tiles .
Window Functions :
Enable to calculate cumulative and Moving Aggregates.
113
Oragle 10 g Material
Reporting Functions :
Enable to Calcuate area like market Shares.
TEST TABLES :
ITEM TYPES TABLE :
Used to store the names of the Item Types that are stocked by the store.
114
Oragle 10 g Material
DIVISIONS TABLE :
Used to store different divisions existing.
Sql > Create Table Division
(
Divid Char ( 3 )
Constraint DividPK PRIMA RY KEY,
DivName Varchar2 ( 15 ) NOT NULL
) ;
JOBS TABLE :
Used to store different Job Catogories Existing in the Organization.
Sql > Create Table Jobs
(
JobID Char ( 3 )
Constraint JobIDPK PRIMA RY KEY,
JobName Varchar2 ( 20 )
Constraint JobNameNN NOT NULL
) ;
EMPLOYEES TABLE :
Used to store the details of the Employ ees working in the stores.
Sql > Create Table EmpStores
(
EmpID INTEGE R
Constraint EmpStoresPK PRIMA RY KEY ,
Sal Number ( 6, 0 ) ,
FirstName Varchar2 ( 10 )
Constraint FnameNN NOT NULL ,
LastName Varchar2 ( 20 )
Constraint LnameNN NOT NULL ,
JobID Char ( 3 )
Constraint JobIDFK
Referenc es Jobs ( JobID ) ,
Divid Char ( 3 )
Constraint DivIDFK
Referenc es Division ( Divid )
) ;
115
Oragle 10 g Material
PARTITION BY CLAUS E :
The Clause is used to divide groups into subgroups.
Sql > Select ItemTypeID, Month, Sum ( SaleAmt ) ,
RANK ( ) OVE R ( PARTITION BY Month ORDER BY Sum ( SaleAmt )
DESC ) RANK
From AllSales
Where Year = 2003 AND SaleAmt IS NOT NULL
GROUP BY ItemTypeID, Mont h
ORDER BY ItemTy peID, Month ;
APPLYI NG ROLLUP, CUBE AND GROUPI NG SETS :
Sql > Select ItemTypeID, Sum ( SaleAmt ) ,
116
Oragle 10 g Material
117
Oragle 10 g Material
PERCENTILE_DIST( ) :
It examines the cumulative distribution values in each group until it finds one that
is greater than or equal to x.
PERCENTILE_CONT( ) :
It examines the percent rank values in each group until it finds one that is greater
than or Equal to x.
118
Oragle 10 g Material
From AllSales
Where Year = 2003
GROUP BY ItemTypeID ;
AVG ( )
COUNT ( )
FIRST_VALUE ( )
MAX ( )
MIN ( )
LAST_V ALUE ( )
CALCULATING CUMULATIVE S UM :
Sql > Select Month, Sum ( SaleAmt ) Mont hlyAmt ,
Sum ( Sum ( SaleAmt ) ) OVE R
( ORDER BY Mont h
ROWS BETWEEN UNBOUNDE D
PERCE DING A ND CURRE NT ROW )
CumulativeAmount
From AllSales
Where Year = 2003
Group By Month
Order By Month ;
UnBounded Preceding :
o
Specifies that the window starts at the first row of the partition.
UnBounded Following :
o
Specifies that the window starts at the last row of the partition.
Current Row :
o
119
Oragle 10 g Material
AVG ( )
COUNT ( )
VARI ANCE ( )
MAX ( )
MIN ( )
STDDEV ( )
RATIO_TO_REP ORT ( )
Sql > Select Month, ItemTypeID, Sum ( Sum ( SaleAmt ) )
OVER ( PARTITION BY Month ) Tot_Month_Amt ,
Sum ( Sum ( SaleAmt ) )
OVER ( PARTITION BY ItemTypeID ) Tot _Pesd_Ty pe_Amt )
From AllSales
Where Year = 2003 AND Month < = 3
GROUP BY Month, ItemTypeID
ORDER BY Month, ItemTypeID ;
120
Oragle 10 g Material
121
Oragle 10 g Material
PREREQUISITES :
The Table must be in the own Schema.
UPDA TE object privilege should be available.
Syntax :
UPDATE < Table_Name >
SET < Specification >
WHERE Clause ;
Examples :
Sql > UPDATE EMP
SET Comm = NULL
WHERE Job = CLE RK ;
122
Oragle 10 g Material
RETURNING CLAUS E :
The returning clause is introduc ed from 10g.
It is used to Return a value from a AGGREGA TE Function.
The Clause can be specified for tables and Materialized Views and for Views with a single base
table.
Restrictions :
Example 1 :
Sql > VARIABLE Sumsal Number
Sql > UPDATE Emp Set Sal = Sal * 1.1
Where Dept no = 10
RE TURNING Sum ( Sal ) INTO :SumSal ;
Sql > PRINT SumSal ;
Example 2 :
Sql > VARIABLE Salary NUMBER ;
Sql > VARIABLE DeptNum NUMBER ;
Sql > VARIABLE Name VARCHAR2 ( 10 ) ;
Sql > UPDATE Emp
SET Job = SALES MAN ,
123
Oragle 10 g Material
124
Oragle 10 g Material
Prerequisites :
To DELE TE rows from a table, the table must be in the users shema.
To DELE TE rows from a Materialized View, DELE TE Object privilege is a must.
DELE TE any Table system privilege allows to DELE TE rows from any table or table partition or
form the Base Table of any View.
Syntax :
DELETE [ FROM ] < Table_Name >
[ WHERE Condition ] ;
Example :
Sql > DELETE From Emp
Where Ename = SMITH ;
Sql > DELETE From Emp
Where Hiredate > To_Date ( 01-01-1997 , DD-MM-YYYY ) ;
Sql > DELETE From SalGrade ;
Sql > DELETE From Emp
Where Dept no = ( Select Deptno From Dept
Where Dname = SALES ) ;
Sql > DELETE From ( Select * From Emp )
Where Job = SALESMAN AND Comm < 300 ;
USING RETURNING CLAUS E :
Sql > VARIABLE Salary NUMBER ;
Sql > DELETE From Emp
125
Oragle 10 g Material
A DDL Statement or a DCL statement is automatically committed and hence implicitly ends a
transaction.
EXPLICIT TRANS ACTION CONTROL STATEMENTS :
The logic of Transaction can be controlled by using
o
COMMIT :
It ends the current transaction by making all pending data changes permanent.
E very data change made during the transaction is temporary until the transaction is committed.
Data Manipulation operations primarily affect state of the data can be recovered.
The current user can review the results of the data manipulation operation by querying the tables.
Other USERS cannot view the results of the data manipulation operations made by the current
user.
The ORACLE SERVER institutes read consistency to ensure that each USER sees dat a as it
existed at the last COMMIT.
STATE OF THE DATA AFTER COMMIT IS ISSUED :
Data changes are written to the database
The previous state of the data is permanently lost
126
Oragle 10 g Material
Syntax :
ALTER TABLE < Table_name >
ADD ( ColumnName DataType [ DEFAULT Expr ]
[ , ColumnName DataType ] ) ;
ALTER TABLE < TableName >
MODIFY ( ColumnName Datatype
[ DEFAULT Expr ]
[ , Column Datatype ] ) ;
STATE OF THE DATA AFTER ROLLBACK :
ROLLBACK
TO
If a second SAVEPOINT is created with the same name as an earlier SAVEPOINT, the Earlier
SAVEPOINT is Deleted.
ADDING A COLUMN TO A TABLE :
The ADD Clause is used to add Columns.
127
Oragle 10 g Material
MODIFYING A COLUMN :
A column Datatype, size and Default value can be changed.
A change to the Default value affects only subsequent insertions to the table.
Guidelines to MODIFY a Column :
We can Increase the width or precision of a Numeric Column
We can Decrease the width of a column if the column contains only NULL values and if the table
has no rows.
We can change the dat atype if the column cont ains NULLs
We can convert a CHAR column to the VARCHA R2 datatype or convert a VARCHAR2 column to
the CHAR datatype if the column cont ains NULL values or if the Size is not changes.
A change to the default value of a column affects only subsequent insertions to the table.
DROPPING A COLUMN :
A column can be dropped from a table by using the ALTE R TAB LE statement.
The DROP Column Clause is used for this purpose and the feature is enabled from
Oralce 8i Onwards.
Guidelines to DROP a Column :
128
Oragle 10 g Material
DROPPING A TABLE :
It removes the definition of the Oracle Table.
The Command not only drops the table but the entire Database is lost along wit h the associated
Indexes.
Syntax :
DROP TABLE < Table_Name > ;
Example :
DROP TAB LE Dept30 ;
GUIDELI NES TO DROP TABLE :
The data is totally deleted from the table
Any views and synonyms will remain that are invalid
Any pending transactions are committed.
Only the create of the table is a user with DROP any table privilege can remove a table
The drop table statement once executed is irreversible ..
CHANGING THE NAME OF AN OBJECT :
The rename command can be used to change the name of a
Table
View
Sequence
Synonym
To rename the object we must be the owner of the object
Syntax :
RENAME < old name > TO < new name > ;
Sql > Rename Dept TO Department.
TRUNCATI NG A TABLE :
It is used it remove all rows from a table and to release the storage space used by the specific
table.
The truncate table will not facilitate for rollback
129
Oragle 10 g Material
Syntax :
TRUNCATE TABLE < Table Name > ;
Sq l> TRUNCATE Table Department ;
we must be the owner of the table for truncating
APPLYI NG COMMENTS UPON A TABLE :
The comments command is used to add comments to a table or a column or view etc.
Each comment can be upto 2000 bytes
The data dictionary is which comments are stored are
ALL_COL_COMME NTS
USER_COL_COMMENTS
ALL_TAB _COMMENTS
USER_TAB_COMME NTS
Syntax:
COMMENT ON Table < Table Name > / column < Tablename. Column >
is Text ;
Sql > COMMENT ON Table Emp is the table storing employee information ;
DROPING A COMMENT :
A comment is dropped from the database by setting it to an empty string.
Sql > COMMENT ON Table Emp is ;
Syntax :
Create Table < Table Name >
As
Select columns
From Table_Name ;
[ Where Condition ] ;
The create table As selectcommand will not work if one of the selected columns use long
data type.
When the new table is described it reveals that it has INHERITED the column definition from
the existing table.
Using this style we can include all columns using Asterisk is a subset of columns from table.
The new table can contain invented columns which are the product of function of the
combination of other columns
130
Oragle 10 g Material
The column definition will adjust to the size necessary to contain the data is the invented
columns.
Sql > Create Table Sampdept as Select * from dept;
Sql > Create Table Sampdept1(Deptid , Deptname , Place) As Select * From Dept;
Sql > Create Table Sampdept2 as Select Deptno ,Dname From Dept;
131
Oragle 10 g Material
132
Oragle 10 g Material
Deptno Number(2) ,
Sal Number(8,2) ,
Constraint Deptnofk_Hash
Foreign Key( Deptno )
Referenc es Dept ( deptno ) )
PARTITION BY HASH( Deptno )
PARTITIONS 10;
Sql > Create Table Empt ablehash ( Empno Number(6)
Constraint Empnopk Primary key,..)
PARTITION BY HAS H(Dept no)
PARTITION 2 S TRORE IN
(Deptnopart1ts , Deptnopart2ts ) ;
WORKI NG WITH LIST PARTITIONING :
In list partitioning we specify oracle all the possible values and designated the partition into which
the corresponding rows should be inserted
Sql>Creat e Table Empsamplelist
(Emp Number(4)
Constraint Empnopk Primary Key,
Ename Varchar2(20) ,
Sal Number(8,3) ,
Hiredate Date ,
Deptno Number(2) ,
Job Varchar2(15) ,
Constraint Deptnofk Foreign Key ( Dept no )
References Dept ( Deptno ) )
PARTITION Jpart1 VALUES (P RESIDE NT,ANALIS T) ,
PARTITION Jpart2 Values(MA NAGE R,SALESMAN,CLECK) ) ;
133
Oragle 10 g Material
134
Oragle 10 g Material
135
Oragle 10 g Material
The REF function by itself does not give any useful information
DEREF FUNCTION :
The DE REF function takes a reference value i.e, the OID generated for a reference and return
the value of the row object
Sql > Create Table Studentincharges ( Inchargename Varchar2(30),
Studentincharc ge REF Student ) ;
The StudentIncharge column references the data that is stored elsewhere
The REF function points the StundentInchage column to a row object of the student data type.
As mcastudent is an object table of the student data types the studentIncharge column can point
to the row object within the mcastudent object table
The studentIncharge table can be described as an ordinary table .
Sql > DESC StudentIncharge ;
Seeing full details of the reference
Sql > SET DESCRIBE DEP TH 2 ;
Sql > DESC Student Incharge ;
INSERTING RECORDS INTO REFERENCE TABLES :
To insert rec ords into reference tables we have to use the REF function
136
Oragle 10 g Material
Sql > INSERT INTO Student Incharges SELECT S UBRAMA NYAM SHRMA REF(A )
From Mcastudents A where Name=SA TISH K UMAR ;
137
Oragle 10 g Material
DANGLI NG REF: It is a record which has an OID pointing to a record in an object table for
which the reference record is not existing in the original object table
As oracle generates a OID for the row object which can be referenced by any other row from
other object table when the row object is DELE TED the OID is lost and the oracle doesnt reuse
the OID numbers
Henc e if a new record for SA TIS H KUMA R is inserted this is given a ane OID value ,but the
studentIncharge record still points to the old value
In a relational system the join bet ween two tables in dependent only on the current data
In an OOP system the join is between objects ,hence the fact that two objects having the same
data does not mean they are same
138
Oragle 10 g Material
139
Oragle 10 g Material
ADMIN
ADMINTABLE
ARTIS T
IMAGE TABLE
THEME
UPLOA D
UPLOA DS
USERS
TABLE
TABLE
TABLE
TABLE
TABLE
TABLE
TABLE
TABLE
VARCHAR2(20)
VARCHAR2(30)
VARCHAR2(20)
VARCHAR2(25)
VARCHAR2(12)
VARCHAR2(15)
VARCHAR2(2)
VARCHAR2(12)
VARCHAR2(255)
VARCHAR2(255)
NUMBE R(5)
VARCHAR2(15)
VARCHAR2(10)
VARCHAR2(255)
Name
Null?
Type
-----------------------------------------------------------------------------------------IMAGE ID
FILE NAME
ARTIS TID
IMAGE NAME
LOCA TION
NUMBE R(5)
VARCHAR2( 30 )
VARCHAR2( 20 )
VARCHAR2( 20 )
NUMBE R( 3 )
140
Oragle 10 g Material
VARCHAR2( 20 )
VARCHAR2( 12 )
VARCHAR2( 25 )
NUMBE R( 10 )
VARCHAR2( 25 )
VARCHAR2( 15 )
VARCHAR2( 20 )
VARCHAR2( 20 )
VARCHAR2( 20 )
VARCHAR2( 20 )
Kalyan
141
Oragle 10 g Material
From the studentov OB JECT View that has been created, and the rows in students table can be
accessed via OIDs we have to CREA TE REFERE NCE VALUES in studentBooks that reference
students
Once the Refs are create we can use DEREF function to Access the students data from student
Books
Sql > CREA TE VIEW StudentBooksov As SELECT MAKE_REF( StudentOv , StudID )
studID, LibTranNo, Book Tittle, LendingDate From StudentBooks ;
MAKE_REF FUNCTION :
It creates REFE RENCES whic h are called PKREFs from an existing view to another view
PKREFs are named so as they are based on PRIMARY KEYS
The function takes as an arguments(s) as the name of the OBJE CT VIEW being REFERE NCE D
and the name of the column or columns that form the FOREIGN KEY in the Local Table
Since MAKE_REF creates a view the result of an operation must be given a COLUMN ALIAS
QUERYI NG THROUGH OBJECT VIEWS :
We use the DEREF function to SELECT the value of the referenced data
The concept is almost all same as that of OBJE CT VIEWS
Sql > SELCT DE REF(SB.StudID) FROM StudentBookOVSB Where
Book Tittle=THERMO DY NAMICS ;
STEPS PERFORMED :
The Query finds the record in the StudentBooks table for which the LendingDate is the Current
System Date .
Taking the studid value from that record evaluates its reference
The evaluated reference studid is pointed to the PKOID value in the studentOv OBJE CT VIEW
using MAKE_RE F.
The StudentOV OB JECT View ret urned the record whose PKOID matched the REFE RENCED
value
The DE REF function then gets activat ed returning the value of the referenced row
The query return rows from students even through the USE R actually queried on StudentBooks
THINGS TO NOTE :
Object views of column objects enable to work with table as if they were both relational tables
and object relational table
When OBJE CT views are extended to row OB JECT they enable to generated OID values based
on established FOREIGN KY| PRIMARY KEY relationship
OBJECT Views allow us to continue to use the existing constraints and standard
INSE RT,DE LE TE UPDA TE and SELE CT statements
They help in using OOP features such as REFERE NCES against the Object TABLES
They provide an Technological Bridge for migrating to an oops db architecture
Oracle performs JOINS that resolve the references defined in the database
When references\d data is retrieved it beings the entire row object that was referenced
To reference the dat a we need to establish POIDs in the table that is PRIMA RI KEY table
relationship
Use MAKE_REF to generat e references in the table that is FORE IGN KEY table relations hip
142
Oragle 10 g Material
Once the above specifications are completed we can work with the data as if it were stored in
OBJECT TAB LES.
143
Oragle 10 g Material