Sie sind auf Seite 1von 49

ORACLE 9i

Oracle 9i allows tens of thousands of concurrent users. It supports upto 512 petabytes of data (1 petabite is 1000
Terabytes), and it can handle any type of data including images, text, videos, sounds etc...
Oracle is a relational data base management system or object oriented data base management system
Data
: collection of interrelated information
Data base : where the data will be organized in the proper manner is called as data base
Data base management system: set of programs which are going to organize the data in proper manner.

FMS (file management system): In this data will be stored in the files. If we want 10th record it will search from
1st record. If we want 10000th record it will take lot of time to get and it will be difficult. For any thing we need to
write lengthy code. For example, for inserting or deleting the record we need to write the code. We cant make relatio
between the files.
Relation ships:
One to one (s1->c1, c1->s1)
One to many (s1->c1, c2) or many to one (c1, c2->s1)
Many to many (s1, s2->c1, c2)
HDBMS: (Hierarchy data base management system): Doesnt support many to many relationships.
Hod
l1
c1
s1,s2,s3

l2
c2

c3

s4,s5 s1,s2

l3
c4

c5

c6

s2,s4

s5,s6 s1,s5

(Under head of the department there will be lecturers 1,2,3,.l1 teaches c1,c2 subjects.s1,s2,s3 students study c1 subject)
If we want to change the details of s1 we have to change wherever it presents
NDBMS (Network database management system): Data will be stored in the form of sets. Data is not managed
in proper manner.
RDBMS (Relational database management system): Data will be stored in the tables in perfect manner.

The principle of the Relational Model was first outlined by DR E.F.Codd in 1970.Before Relational Model came into the
picture there were hierarchical and network models or even simple flat files. A database which is created based on
relational model is called Relational Database Management System (RDBMS).
DATA MODEL: Models are cornerstone of design. Engineers first build a model of car to work out any details
before it putting into production. The objective of the model is that should fit to no. of users, can be understood by
end user and it contain sufficient details for developer to build a database.

A Relational Model is a collection of relations. For example, If u want to store the all the information about employees, y
create several tables to store different pieces of information about your employees like employee table, department table
salary table.
CODDS RULES: (12 rules)
1. All the data should be stored in the form of table.
2. Every column should accept null values
3. Without any ambiguity we have to retrieve the data
4. We have to access the table structure by the same tools which access the data
5. Every RDBMS should have one clearly defined language to insert, delete, retrieve. the data
6. Data may be presented in the different logical combinations (views).any operation on this view should
be effected to tables
7. Any no. of rows should be effected when we perform insert, delete and update etc...
8. Data should not be effected even though storage architecture changes.
9. Data should not be effected even though table structure changes
10. Data should not be effected even though data is stored in different locations.
11. Data base should support constraints for security
12. There should be no way to modify the database structure other than the multiple row data base language (sql).
No data base will satisfy the entire codds rules. A data base which satisfies more than half of the codd rules it is good
data base.
what are keyword, clause and statement
Consider below statement;
Select emp_id, emp_name from emp;

Select and from are the keywords.


Select emp_id, emp_nameselect clause
From EMPfrom clause
A statement is combination of two or more clauses Select emp_id, emp_name from emp;

Data Types:
Number: Max 38 Numbers
number(4)-12341234
12.3412.34
number(4,2)
12.3412.34
12.34512.35
12.34412.34
1234Error

Character: 2000 characters, Alphanumeric, Fixed Length


Varchar2: 4000 Characters, Alphanumeric,Variable Length
Date:9 Characters
Long: 2GB,Alphanumeric
But we can have only one column with Long data type in table
Raw:2000 bytes,pictures and images
Long Raw:2GB,pictures and images
But we can have only one column with Long Raw data type in table
LOB(Large Objects): 4GB
CLOB:Huge amount of characters
BLOB: Images, Pictures, Sounds
Bfile: Movies

SQL STATEMENTS:
DATA RETRIEVAL LANGUAGE (DRL)
Select
(Retrieves data from the data base)
DATA MANIPULATION LANGUAGE (DML) Insert, Update, Delete, Merge
(Enters new rows, changes existing rows and removes existing rows)
DATA DEFINITION LANGUAGE (DDL)
Create, Alter, Drop, Rename, Truncate
(Setup, change and remove data structures from tables)
TRANSACTION CONTROL LANGUAGE (TCL) Commit, Rollback, Savepoint
(Manages the changes made by DML statements)
DATA CONTROL LANGUAGE (DCL)

Grant, Revoke
(Give or remove access rights to both oracle database and structures
with in it)

SELECT STATEMENT:
select empno,ename from emp displays empno, ename from emp table.
select * from emp displays total columns in emp table

CHAPTER-1
ARITHEMETIC OPERATORS:
By using arithmetic operators we can make changes to the data to be displayed.
+ - * % are the arithmetic operators.

select ename,salary*12+10000 from emp


select ename,salary+10000*12 from emp
Operator Precedence:
Means it says which operator is evaluated first
*% + Operators of the same priority are evaluated from left to right.
If one operation (1+7-3*6%3) contains above all operators:
3*6(18) evaluates first then that result will be divided by 3. 18%3=6
Next 1+7 will be evaluated 1+7=8.then will be evaluated8-6=2.

In above two statements results are different. In first statement salary*12 will be evaluated first then that result will adde
to 100000. In second statement 10000*12 will be evaluated first then that result will be added to salary.
Parentheses ( ) overrides the rules of operator precedence.
select ename, (salary+10000)*12 from emp.
Actually by the rule of precedence 10000*12 will be evaluated first. But we have given parentheses to salary+10000
So this will be evaluated first then that result will be multiplied by 12.

NULL VALUES:

Null value means it is unknown, unavailable, unassigned and inapplicable. It is not equal to either zero or space.Zero
is number and space is character. Any operation with null becomes null.
select null/mgr from emp--null
select null/0 from emp--null
SELECT 0/NULL FROM DUAL--null
select null/null from dual--invalid character
COLUMN ALIAS:
Column alias means renaming the column heading name. It immediately follows the column name. Optionally we can
give AS keyword also. If alias name contains spaces, special characters or case sensitive then it should be in double
quotations.

SELECT ename name FROM EMP;--NAME


select ename as name from emp;--NAME
select ename "name" from emp; --name
select ename *name* from emp; --error (special characters (*) should be in double quotations
select ename *name* from emp;-- *name*
select

ename "e name" from emp-- e name

CONCATENATION OPERATOR (||):


This operator is used to combine one column with another column or arithmetic operation or constant value.
For example if we want to get emp_id, emp_name in same column then we can use this operator. (If we write query as
select emp_id, emp_name from emp then emp_id,emp_name will be displayed in different columns)
select empno||ename from emp
select empno||' '||ename "emp details" from emp--to get the gap between empno and ename
selectempno||salary*10"empsalary"fromemp 116100000

LITERAL CHARACTER STRING:


Literal value is character or number or date. If it is date or character it should be enclose with single quotations.
Used to print some text along with column values.
select empno||'

'||'salary is'||' '||salary from emp

In above statement salary is is called as literal value.


DUPLICATE ROWS:
Select deptno from emp
By above statement we get duplicate values also. We can eliminate the duplicate values by using DISTINCT key
word.
select distinct deptno from emp
By using above statement we dont get duplicate values

CHAPTER-2

RESTRICTING AND SORTING DATA


WHERE CONDITION:
While retrieving the data from the database you may need to restrict the data to be displayed (you want to display some
data rather than displaying all the data).By using WHERE condition we can restrict the data.
select * from emp
By using above statement we can get all the details of emp table. But we want the details of deptno is 20.then we can
write the query as below
select * from emp where deptno=20
Character strings and date values are enclosed with single quotations.
select * from emp where ename='Vishnu'

(Vishnucharacter string)

select * from emp where creation_date='03-apr-2007' (03-apr-2007---date)


(In table it stored as 04/03/2007)
COMPARISION CONDITIONS:
Comparison condition compares one expression to another value or expression
= (equal to), < (less than),> (greater than),<=(less than or equal to),>= (greater than or equal to),<> (not equal to)
select * from emp where deptno=20
select * from emp where salary>=6000

Other comparison conditions:


Betweenand...

Between two values (inclusive)

In

match any of list values

Like

match a character pattern

Is null

is a null value

Betweenand...:
Use this to display rows based on a range of values.

select * from emp where salary between 6000 and 10000


In:
Use this to test for values in the list.
select * from emp where salary in (6000, 10000)
Like
Use the LIKE condition for valid search. For example we want to know the name which starts with B
% Represents any sequence of zero or many characters
_

Represents only one character

select * from emp where creation_date like '%07'--to know the employee detials who joined in
2007
select * from emp where ename like '_a%'to know the employee details whose second letter is
a in name.
You can use ESCAPE identifier to search actual

% or _ symbols.

select * from emp where ename like '\%%\_' escape '\'-to know the employee details whose name
Starts with % and ends with _.
Is null:
use this to test the null values
select * from emp where empno=null our wish is to find the employee detials who has no empno.
But it returns no rows. Because already we have discussed that null is unknown value. Then how can we compare the
null value with empno?
So we have to write the query as below to find the employee details that has no empno.
select * from emp where empno is null
Like this we have

Not betweenand...
Not in
Not like

Is not null

LOGICAL CONDITIONS:
A logical condition combines result of two conditions and produce single result bases on them.
And

Or

Not

And:

Returns true if both conditions are true.

Or:

Returns true if either condition is true.

Not:

Return true if condition is false

select * from emp where ename='Amar' and salary=6000


select * from emp where ename='Amar' or salary=6000
select * from emp where ename not in ('Amar','ameer') and salary not in ('6000')
Rules of precedence:
1
2
3
4
5
6
7

arithmetic operators
concatenation conditions
comparison conditions
is null, like, in, between...and...
not logical condition
and logical condition
or logical condition
Note: Parentheses override the rules of precedence.

ORDER BY CLAUSE:
The order of rows returned in a query is undefined. The order by clause can be used to sort the rows in particular order.
Asc: order the rows in ascending order (the default order).
Desc: order the rows in descending order.
The order by clause must be the last clause in the sql statement.
You can specify a column name or column position or column alias.
select * from emp where salary>5000 order by deptno

select * from emp order by deptno desc,mgr


select * from emp order by deptno desc,mgr desc

select * from emp order by 9 desc,8 desc


select ename "NAME" from emp order by name
Dual Table: Dual table is used in Oracle when you need to run SQL that does not logically have a table name
It contains the column DUMMY with the datatype varchar2(1)

CHAPTER-3
SQL FUNCTIONS
SQL functions are used to

Manipulate the data


Format dates and numbers for display
Converts column data types

SQL functions are two types:


Single row function : Operates on each row and gives the result per row
Multirow functions : Operates on group of rows and gives one result per group of rows
(Group functions)
Single row functions:
Character functions : Accept character input and return both character and numeric value
Case manipulation functions
: convert case for character string
Lower : Converts mixed case or upper case to lower case
Upper : Converts mixed case or lower case to upper case
Initcap : Converts the first letter of each word to upper case and remaining letters to lower case
Character manipulation functions
: These functions manipulate character string
Concat : It joins the two strings together
Length : Shows length of a string by a numeric value
Substr : Extracts a string of determined length
Instr
: Finds numeric position of a named character or string
Rtrim : Trims the characters from right to left
Ltrim : Trims the characters from left to right
Trim : Trims the characters from both right to left and left to right
Lpad : Pads the character value right justified
Rpad
: Pads the character value left justified
Translate : Replaces the one set of sequence of characters with another set of sequence of characters
Replace
: Replaces one string with another string
Case and
Decode
: These functions let you use IF-THEN-ELSE logic in SQL statements

Number functions
: Accept numeric input and return numeric values
Abs : Returns absolute value.
Sign : Returns sign of the value.
Mod : Returns remainder value
Ceil :
Returns highest value
Floor :
Returns lowest value
Sqrt :
Returns square root value
Power : Returns power of the value.
Round :
Rounds the value to n decimal places.
( add 1 to nth position if (n+1) th number is >=5 and n is +ve (left to right)
(add 1 to (n+1)th position if nth number is >=5 and n is -ve(right to left)
Trunc : Truncates the value to n decimal places.
Trigonometric: By using this we can know the trigonometric functions value
Date functions
: Works on the values of the DATE data type
Months_between(date1,date2) : Returns Number of months between dates
Finds the number of month between date1 and date2.the result can be positive or negative.
If date1 is
earlier than date2 then result is positive, if date1 is later than date2 the result is negative
Add_months (date, n)
: Add calendar months to date
The value of n must be integer and can be negative.
Next_day (date,char)
: Finds the date of specified day which occurs next to date specified.
Last_day (date)
: Finds the date of the Last day of the month
Round
: Date is rounded to nearest day
Trunc
: Date is truncated to nearest day

Conversion functions : Convert the value from one data type to another data type
Implicit datatype conversion: In some cases, the oracle server uses data of one datatype where it expects data of a
different data type. This can happen when the oracle server can automatically convert the data to the expected data
type. This data type conversion can be done implicitly by the oracle server, or explicitly by the user. If it is done by
oracle server it is called as implicit datatype conversion.
Varchar
Varchar
Number
Date

to
to
to
to

number
date
varchar
varchar

Explicit datatype conversion: In some cases, the oracle server uses data of one datatype where it expects data of a
different data type. This can happen when the oracle server can automatically convert the data to the expected data
type. This data type conversion can be done implicitly by the oracle server, or explicitly by the user.if it is done by
user it is called as explicit datatype conversion.
To_number : character to number
To_date
: character to date
To_char:
: number to character

date to character
General functions
:
Nvl (exp1, exp2):To convert a null value to an actual value.
exp1 is the source value or expression that may contain null
exp2 is the target value for converting the null
You can use nvl function to convert any data type, but return value (exp2) is always the
same of the exp2
Nvl2 (exp1, exp2, exp3): If the first expression is not null then second expression will be returned.if the first
expression is null the third expression will be returned
exp1 is the source value or expression that may contain null
exp2 is the value returned if exp1 is not null
exp3 is the value returned if exp1 is null
Nullif (exp1, exp2): If the two expressions are equal, the function returns null. If they are not equal the function
returns first expression. You cant specify the literal null for first expression.
Coalesce (exp1, exp2.expN): Returns the first not null expression in the list.
exp1 will be returned if it is not null
exp2 will be returned if it is not null and exp1 is null
expN will be returned if all the preceding (exp1, exp2.) expressions are null
Multirow functions (Group functions):
Avg: Returns average value
Sum: Returns sum of values
Max: Returns maximum value
Min: Returns minimum value
Count: Returns number of rows with non-null values.
Distinct: Returns non duplicate values
Group functions ignores null values in the column

Character functions:
Lower
: selectlower('BHAnuPrakAsh')fromdualbhanuprakash
Upper
: selectupper('BHAnuPrakAsh')fromdualBHANUPRAKASH
Initcap
: selectinitcap('BHAnuPrakAsh')fromdualBhanuPrakash
Concat: selectconcat('bhanu','prakash')fromdualbhanuprakash
selectconcat('bhanu','prakash','reddy')fromdualerror

concat will take only two arguments only

Length: selectlength('bhanuprakash')fromdual12
Substr:selectsubstr('bhanuprakash','5','2')fromdualup(from5thposition2
characters)

selectsubstr('bhanuprakash','2')fromdualhanuprakash
ifwedon'tgive3rdargumentittilldisplaytilllast.
selectsubstr('bhanuprakash','5','2')fromdualak
selectsubstr('bhanuprakash','5','2')fromdualerror(itwontshowerroritgivesnull
value)

Find the details whose name starts with a to r


select*fromempwheresubstr(ename,'1','1')between'A'and'R'
select*fromempwhereenamebetween'A'and'R'givesatoq

Instr: selectinstr('bhanuprakash','h',1,2)fromdual12
means in which postion h was appeared 2nd time from the 1st position
selectinstr('bhanuprakash','h')fromdual2

means in which postion h was appeared 1st time from the 1st position
selectinstr('bhanuprakash','a','2',3)fromdual3

to get the names which contains minimum one a


select*fromempwhereinstr(ename,'a',1,1)>0

to get the names which contains only one a


select*fromempwhereinstr(ename,'a',1,1)>0andinstr(ename,'a',1,2)=0

Rtrim: selectrtrim('uuuuubhanuuu','u')fromdualuuuuubhan
Ltrim: selectltrim('uuuuubhanuuu','u')fromdualbhanuuu
Trim : selecttrim('u'from'uuuuubhanuuu')fromdual
This will be useful to get the records when the name contains spaces before or after name
select*fromempwheretrim(''fromename)='bhanu'

Rpad:selectrpad('bhanu','7','*')fromdualbhanu**
Lpad: selectlpad('bhanu','7','*')fromdual**bhanu
selectlpad(rpad('bhanu','7','*'),'9','*')fromdual**bhanu**

Translate: selecttranslate('bhanuprakash','bpk','mno')fromdualmhanunraoash
Find out how many a present in your name
selectlength('bhanuprakash')length(translate('bhanuprakash','ba','b'))fromdual3

Replace: selectreplace('bhanuprakash','upra','sg')fromdualbhansgkash
Decode and Case:
Selectename,salary,decode(upper(job),'SALES',2*salary,
'MANAGER',3*salary)newsalfromemp

selectename,salary,casewhenupper(job)='SALES'then2*salary
whenupper(job)='MANAGER'then3*salaryendnewsalfromemp

If job is sales then salary will be increased to 2 times, if job is manger salary will be increased to 3 times.
If we observe results of above queries for the jobs salesman, manager only salary will be displayed in the column named
newsal (alias name) .for other jobs the salary will be null in newsal column.
We can populate the original salary if the job is not salesman or manager by below queries.
selectename,salary,decode(upper(job),'SALES',2*salary,

'MANAGER',3*salary,salary)newsalfromemp

selectename,salary,casewhenupper(job)='SALES'then2*salary
whenupper(job)='MANAGER'then3*salaryelsesalaryendnewsalfromemp

In decode function we cant use comparison operators (=,>, <,>=, <=, <>) .and we cant perform the operation on two
columns.
For example u want to display as abovetaget if salary >5000 ,
as belowtaget if salary<=5000,
as unavailable if salary is null.
You cant perform above operation by using decode. We can perform by using CASE by writing the query as below.
selectename,salary,casewhensalary>6000then'ABOVETARGET'

Whensalary<=6000then'BELOWTARGET'
else'UNAVAILABLE'
EndNEWSALfromemp

For example you want to increase the salary to 2 times if job is manager,
to increase the salary to 3 times if ename is amar operation depends on two
columns(job,ename)
You cant perform above operation by using decode. We can perform by using CASE by writing the query as below.

Selectename,job,salary,casewhenupper(job)='MANAGER'then2*salary

whenupper(ename)='AMAR'then3*salary
elsesalary
EndNEWSALfromemp

If we are performing two operations on same row then first operation will be evaluated.

For example for the employee miller the job is manager then we write above query salary is increased to 2 times not to 3
times.
Number functions:
Abs: Returns absolute value.
selectabs(12),abs(12),abs(0)fromdual12,12,0

Sign: Returns sign of the value.

selectsign(12),sign(12),sign(0)fromdual1,1,0

Mod: Returns remainder value


selectmod(5,2),mod(5,2),mod(5,2),mod(2,5),mod(0,5),mod(5,0)fromdual1,1,1,2,0,5
Iffirstargumentislessthansecondargumentthenitreturnsfirstargument.

Ceil: Returns highest value


selectceil(12.01),ceil(12.01)fromdual13,12

Floor: Returns lowest value


selectfloor(12.01),floor(12.01)fromdual12,13

Sqrt: Returns square root value



selectsqrt(25),sqrt(0)fromdual5,0
selectsqrt(25)fromdualerror

Power: Returns power of the value.


selectpower(2,3),power(2,3),power(2,3),power(2,0),power(0,2)fromdual8,
8,0.125,1,0

Round: Rounds the value to n decimal (add 1 to nth position if (n+1)th number is >=5 and n is +ve(left to right)
(add 1 to (n+1)th position if nth number is >=5 and n is -ve(right to left)
selectround(1256.3456,2),round(1256.3446,2),round(1256.4445),round(1256.6445)fromdual
1256.35,1256.34,1256,1257
selectround(1256.3456,2),round(1246.3456,2),round(1234.345,9)fromdual
1300,1200,0

Trunc: Truncates the value to n decimal


selecttrunc(1256.3456,2),round(1256.4445)fromdual1256.34,1256
selecttrunc(1256.3456,2),round(1246.3456,2)fromdual1200,1200

Trigonometric: By using this we can know the trigonometric functions value


selectsin(90*((22/7)/180))fromdual0.99
Ifwegivesin(90)ittakesasradiussofirstwehaveconvertthistoanglesby
multiplyingthevaluewith(22/7)/180

Date functions:
The oracle database server stores the date in the format of century, year, month, day, hours, minutes and seconds.
But input format of date is DD-MON-YY. Even though you insert the date in DD-MON-YY format, dates are not stored
in this format.so, although the date such as 09-aug-2007 is displayed as day, month and year there is also time and
century information associates with it. The complete date might be august 9th,2007 5:10:34 p.m.The dates year data type
always store the information as four digit number internally, two digits for the century, two digits for the year.(century
information is picked up from the sysdate) For example oracle stores the year as 2007 not as 07.
The data is internally stored as follows:
Century
year
month
day
hour
minute
second
21
07
08
05
05
10
34
Sysdate: Sysdate is a function that returns date and time. You can use the sysdate as you would use any other
column name.
selectsysdatefromdual8/21/20076:14:48PM

Arithmetic with dates:


Because the database stores date as numbers, we can perform calculations with arithmetic operators such as addition and
subtraction
Date+number

Date-number

Date-date

Date+number/24

date
date
number of days
date

adds a number of days to date


subtracts a number of days from date
subtracts one date from another
adds number of hours to date

Months_between:
selectmonths_between('11nov2007','11sep2007')fromdual2
selectmonths_between('11sep2007','14nov2007')fromdual2.096
selectmonths_between(sysdate,'11nov2007')fromdual2.096
Tofindtheexperienceoftheemployees:
selectmonths_between(sysdate,hire_date)/12fromemp

Add_months:
selectadd_months('21sep2007',2)fromdual11/21/2007
selectadd_months('21sep2007',2)fromdual7/21/2007

Next_day:
selectnext_day('23aug2007',7)fromdual8/25/2007
selectnext_day('23aug2007','saturday')fromdual8/25/2007

Last_day:
selectlast_day('23aug2007')fromdual8/31/2007

Round: (in above functions we have mention the dates as string because that functions can convert the string into date
but round and trunc cant convert, so we have to convert the string into date by using to_date function)
selectround(to_date('13aug2007'),'month')fromdual8/1/2007
selectround(to_date('15aug2007'),'month')fromdual8/1/2007
selectround(to_date('18aug2007'),'month')fromdual9/1/2007
ifdateis<=15thofthethatmonthreturnthatmonthstartingdate
ifdateis>15thofthethatmonthreturnnextmonthstartingdate
selectround(to_date('13aug2007'),'year')fromdual1/1/2008
selectround(to_date('13may2007'),'year')fromdual1/1/2007
selectround(to_date('18june2007'),'year')fromdual1/1/2007
ifthemonthis<=junereturnthatyearstartingdate
ifthemonthis>junereturnnextyearstartingdate

Trunc:
selecttrunc(to_date('13aug2007'),'month')fromdual8/1/2007
selecttrunc(to_date('15aug2007'),'month')fromdual8/1/2007
selecttrunc(to_date('18aug2007'),'month')fromdual8/1/2007
returnsstatingdateofthementionedmonth
select trunc(to_date('13-aug-2007'),'year') from dual--1/1/2007
select trunc(to_date('13-may-2007'),'year') from dual--1/1/2007

select trunc(to_date('18-june-2007'),'year') from dual--1/1/2007


returnsstartingdateofthementionedyear

Conversion functions :
Implicit datatype conversion:
For assignments (a=b), oracle can convert the following
Varchar
to
number
Varchar
to
date
Number
to
varchar
Date
to
varchar
For expression evaluation oracle can convert the following.
Varchar to number
Varchar to date
For months_between, add_months, last_day and next_day oracle converts the different datatype to date datatye.

Explicit datatype conversion:


To_char : Date to character.
j
Julian date
yyyy
gives year in digits
year
gives year in words
mm
month in digits
mon
three letter abbreviation of the month
month
full name of the month
d
day of the week
dd
day of the month in digits
dy
three letter abbreviation of the day of the week
day
full name of the day of the week
cc
current century
w
week of the month in digits
ww
week of the year in digits
Oracle can do operations on date from 01-jan-4712 b.c to 31-dec-9999 a.d
If we want to know how many days has over from 01-jan-4712 b.c to particular date then we can go for Julian date
select to_char(sysdate,'j') from dual--2454383 (sysdate:09-10-07)
sysdate:09-10-07
select to_char(sysdate,'yyyy') from dual--2007
select to_char(sysdate,'year') from dual--two thousand seven
select to_char(sysdate,'mm') from dual--10
select to_char(sysdate,'mon') from dual--oct

select to_char(sysdate,'month') from dual--october


select to_char(sysdate,'dd') from dual--09
select to_char(sysdate,'dy') from dual--tue
select to_char(sysdate,'day') from dual--tuesday
select to_char(sysdate,'cc') from dual--21
select to_char(sysdate,'w') from dual--2
select to_char(sysdate,'ww') from dual41
FM: To remove padded blanks.
Find out the employees who has joined on Sunday
select * from emp where to_char(creation_date,'day')='sunday'--no rows returned
Since, to_char(creation_date,'day') return sunday _ _ (blanks) (9 characters) because Wednesday
contains highest characters (9).so we have to remove the padded blanks by using FM
select * from emp where to_char(creation_date,'fmday')='sunday'
By this we can get the details who has joined on Sunday
Similarly for the month also.
Find out the employees who has joined in April
select * from emp where to_char(creation_date,'month')='april'--no rows returned Since,
to_char(creation_date,'month') return april _ _ _ _ (blanks) (9 characters) because September
contains highest characters(9).so we have remove the padded blanks by using FM
select * from emp where to_char(creation_date,'fmmonth')='april'
By this we can get the details who has joined in April month
To find the time:
select to_char(sysdate,'hh:mi:ss') from dual----06:08:02
select to_char(sysdate,'hh:mi:ss pm') from dual--06:08:02 pm
select to_char(sysdate,'hh:mi:ss am') from dual--06:08:02 pm
We can mention pm or am but it gives correct time (am or pm).
TH returns ordinal number
SP returns spelled out number
THSP or SPTH returns spelled out ordinal number
select to_char(sysdate,'dd') from dual--09
select to_char(sysdate,'ddth') from dual--09th
select to_char(sysdate,'ddsp') from dual--nine
select to_char(sysdate,'ddspth') from dualninth

To_char: Number to Character.


9
0
$
L
.
,

Represents as number
Forces a zero to be displayed
Places a dollar sign
Uses the local currency symbol
Prints a decimal point
Prints a thousand indicator

select to_char(50000,'$99,999.00') from dual-- $50,000.00


select to_char(50000,'$9,999.00') from dual-- ##########
Since '50000' is 5 digits, but we have specified 4 digits ( '$9,999.00')
To_date : Character to date
create table date1(empno number,joineddate varchar2(90))
insert into date1 values (2,'12-mar-2007')
select joineddate from date1--12-mar-2007
select to_date(joineddate,'dd-mm-yyyy') from date1 --3/12/2007
What is the date of 2454262 th day from Julian date (01-jan-4712bc)
select to_date('2454262','j') from dual--6/10/2007
Get the word format from number format
select to_char(to_date('10','j'),'jsp')from dual--ten
It is not applicable for 'zero'
select to_char(to_date('0','j'),'jsp')from dual--julian date must be between 1 and 5373484
To_number : Character to number
selectto_number('$1,101.000','$9,999.999')fromdual1101
RR

date format:

Current year
1995
1995
2001
2001
If the two digits of the

specified date
27-oct-95
27-oct-17
27-oct-17
27-oct-95

RR format
1995
2017
2017
1995

YY format
1995
1917
2017
2095

current year is

If the specified two digit


0.49

50-99

0.49

The return date is in the


current century

The return date is in the


century before the current one

50.99

The return date is in the


century after the current one

The return date is in the


current century

sysdate: 15-oct-2007
select to_date('22-oct-07','DD-mm-yy') from dual--10/22/2007
select to_date('22-oct-07','DD-mm-rr') from dual--10/22/2007
select to_date('22-oct-95','DD-mm-yy') from dual--10/22/2095
select to_date('22-oct-95','DD-mm-rr') from dual--10/22/1995

General functions:
Nvl:
selectemp_name,salary,comm,(salary*12)+(comm*12)"annulcompensation"fromemp
Wewritethequeryasabovetofindouttheemployeessalaryforyear.Butfor
someemployeesthesalaryvalueisnullthenforthatrowtheannualcompensation
willbenull.soconvertthenullvaluetozerobyusingnvlfunction
selectemp_name,salary,comm,nvl((salary*12),0)+(comm*12)"annulcompensation"fromemp

Nvl2:
Printas"sal+comm"ifcommissionisavailableotherswiseprintas"sal"

selectemp_name,comm,nvl2(comm,'sal+comm','sal')"income"fromemp

Nullif:

Writethequerytoknowwhosesalaryandcommisequal.If"result"returnnullthensalaryis
equaltocomm
selectemp_name,salary,comm,nullif(nvl(salary,0),comm)"result"fromemp
(somesalaryvaluesarenullthatswhyweusednvlfunction)

Coalesce:
selectemp_name,salary,comm,coalesce(salary,comm,0)"result"fromemp
returnssalaryifsalaryisnotnull
returnscomm(commission)ifcommissionisnotnullandsalaryisnull
returns0ifsalaryandcommissionarenull

Multirow functions:
select avg(salary),min(salary),max(salary),count(salary) from emp
select avg(nvl(salary,0)) from emp
select distinct(salary) from emp
select count(*) from emp
Creating groups of data:
Group by clause: Until now all the group functions have treated the table as one large group of
information.In some times you need to divide the table of information into smaller groups.
This can be done by using the group by clause.
If you include a group function in the select statement, you cannot select individual result as well. Unless
the individual columns appear in the group by clause.
You cant use an alias name in the group by clause
select deptno,avg(salary) from emp group by deptno order by avg(salary)
select deptno,job,avg(salary) from emp group by deptno,job order by avg(salary)
select deptno,job,avg(salary) from emp group by deptno order by avg(salary)
--error(not a group by expression)
we should mention the single row fucntion in group by clause
Having clause: We cant use the where clause to restrict the groups. We can use the having clause
to restrict the groups
select deptno,avg(salary) from emp where avg(salary)>1000
group by deptno order by avg(salary)
--error(group function is not allowed here)
select deptno,avg(salary) from emp group by deptno
having avg(salary)>5000
order by avg(salary)
select deptno,avg(salary) from emp where deptno<>30
group by deptno
having avg(salary)>5000
order by avg(salary)

Chapter4
Displaying data from multiple tables

Some times you need to display the data from multiple tables. For example to find employee number, deptname, location
u need to join three tables emp, dept, locations. (empno, ename, deptno are stored in emp,
deptno, dname, locno are stored in dept,
locno, locname are stored in locations)
Cartesian products: When a join condition is invalid or completely omitted, the result is a Cartesian product.
All rows in the first table are joined to all rows in the second table
select empno,ename,dname from emp,dept--104 records
(in emp there are 13 records,in dept there are 8 records.13*8=104)
Equi joins (simple joins or inner joins): An equi join is a join condition containing only equality (=) operator. To
determine employees department name you need to refer the deptno in emp, dept tables. The relation between emp and
dept is called as equi join, that is the deptno column in both tables must be equal.
To join n tables together you need a minimum of n-1 join conditions.
select emp.ename,dept.deptno,emp.salary from emp,dept
where emp.deptno=dept.deptno
order by emp.deptno
or (by using column alias)
select e.ename,d.deptno,e.salary from emp e,dept d
where e.deptno=d.deptno
order by e.deptno.
Joining more than two tables:
select e.ename,d.deptno,e.salary,l.locname from emp e,dept1 d,locations l
where e.deptno=d.deptno
and d.locno=l.locno
order by e.deptno
Nonequi joins: A nonequi join is a join condition containing something (>, =<) other than equality operator.
select e.ename,e.salary,j.grade from emp e,jobgrades j
where e.salary between j.lowsal and j.highsal
(In jobgrades table there are grades, lowsal, highsal columns)
(Remember to specify lower value first when using between)
Outerjoins (+): you can use the outerjoins to see the rows also that doesnt meet the join condition
select

e.ename,e.deptno,d.dname from emp e,dept d


where e.deptno=d.deptno order by e.deptno
Suppose there is deptno:10,20,30,40 in emp and deptno:20,30,40 in dept.if we write above query we
can get the rows matched(20,30,40) but if we want the details of ename,deptno of 10 we have to
write the query as below

select e.ename,e.deptno,d.dname from emp e,dept d


where e.deptno=d.deptno(+) order by e.deptno

Self join: Some times you need to join a table to itself. To find the names of each employees manager you need to join the emp
table to itself. For example to find the whalenss manager,
For this you have to refer the table twice
1) To find whalen in the column ename and the whalens manager id (101) in the column manager_id.
2) You look in the empno column to find the 101 and ename to find anurudh.
select e.ename,e1.ename "mangername" from emp e,emp e1
where e.mgr=e1.empno
Using sql: 1999 syntax:
Cross joins (Cartesian products):
select empno,ename,dname from emp cross join dept

Natural joins (equi joins): Natural join clause is based on the same column names having same data type in the two
tables.
If the columns having same names have different datatype, then an error is returned. The columns that have same name
in both tables have to be used with out qualifiers (aliases).
select ename,deptno from emp natural join dept
or select e.ename,deptno from emp e natural join dept
select e.ename,d.deptno from emp e natural join dept eerror
(The columns that have same name in both tables have to be used with out qualifiers (aliases))

Using clause: Natural joins use all the columns with matching names and data types to join the tables. The using clause
can be used to specify only particular columns that should be used for an equi join. The columns referenced in the using
clause should not have qualifier (table name or alias) in the entire sql statement.
In emp1 and dept1 there are deptno and locno common columns. If we write simple natural join it will be like select
e.empno,d.deptno from emp1 e,dept1 d where e.deptno=d.deptno
and e.locno=d.locno
select e.empno,deptno from emp1 e join dept1 d using (deptno)
the above query is like
select e.empno,d.deptno from emp1 e,dept1 d where e.deptno=d.deptno
select e.empno,d.deptno from emp1 e join dept1 d using (deptno)--error
select e.empno,deptno from emp1 e join dept1 d using (d.deptno)error
(The columns referenced in the using clause should not have qualifier (table name or alias) in the
sql statement)
ON clause: Natural joins use all the columns with matching names and data types to join the tables. To specify

entire

Columns to join, the on clause is used. The on clause makes code easy to understand.
select e.empno,d.deptno from emp1 e join dept1 d on (e.deptno=d.deptno)
select e.empno,deptno from emp e natural join dept d
select e.empno,deptno from emp e join dept d using (deptno)
select e.empno,d.deptno from emp e join dept d on (e.deptno=d.deptno)
Result of all above statements is equal
Joining more than two tables using on clause
select e.empno,d.deptno,l.locname from emp1 e,dept1 d,loc1 l
where e.deptno=d.deptno
and d.locno=l.locno
we can write above query as below using on clause
select e.empno,d.deptno,l.locname from emp1 e join dept1 d on e.deptno=d.deptno
join loc1 l on d.locno=l.locno
Left outer join: A join between two tables that returns the results of the inner join (equi join) as well as
unmatched rows of left tables is a left outer join
select e.empno,e.deptno,d.locno from emp1 e left outer join dept1 d on
(e.deptno=d.deptno) order by e.deptno
(select e.empno,e.deptno,d.locno from emp1 e,dept1 d
where e.deptno=d.deptno(+) order by e.deptno)
Right outer join: A join between two tables that returns the results of the inner join (equi join) as well as unmatched
rows of right tables is a right outer join
select e.empno,e.deptno,d.locno from emp1 e right outer join dept1 d on
(e.deptno=d.deptno) order by e.deptno
(select e.empno,e.deptno,d.locno from emp1 e,dept1 d
where e.deptno(+)=d.deptno order by e.deptno)
Full outer join: A join between two tables that returns the results of the inner join (equi join) as well
as unmatched rows from right and left tables.
select e.empno,e.deptno,d.locno from emp1 e full outer join dept1 d
on (e.deptno=d.deptno) order by e.empno

chapter5
Sub queries
A sub query is a select statement that is embedded in a clause of another select statement. Sub queries can be
very useful when you need to select rows from the table with a condition that depends on the data in the table
itself.
You can place the sub query in the no. of clauses, including where clause, from clause and having clause. Then sub query
often referred to as a nested select, sub select or inner select statement. Generally sub query executes
first, and its output is used to complete the query condition for the main or outer query.
For example, you want it find out which employees have salaries greater than amit salary?
To solve this problem you need, you need two queries. One to find out amit salary (sub query), and a second query to find
who earns more than that amount (main query)
Types of sub queries:
Single row sub queries: Queries that return only one row from the inner select statement. Use single row
Operators (>, <, >=, <=, <>, =) for these queries.
Multi row sub queries: Queries that return more than one row from the inner select statement. Use multi row
Operators (in, any and all) for these queries.
IN : equal to any value in the list
ANY : compare value to each value
ALL : compare value to every value
Single row sub queries:
select * from emp where salary>(select salary from emp where empno=7116)
by using group functions
select * from emp where salary>(select avg(salary) from emp)
in having clause
select deptno,avg(salary) from emp group by deptno having avg(salary)>
(select min(salary) from emp where deptno=20 )
Multi row sub queries:
select * from emp where salary>(select avg(salary) from emp group by deptno)
--error (single row subquery return more than one row)
One common error with sub queries is more than one row returned for a single row sub query. In above sql
statement sub query contains group by clause, which implies that sub query return multiple rows. In this case
the result of the sub query is 1200,15000,20000and10000.the outer query takes the result of the sub query
(1200,15000,20000and10000) and uses these results in where clause. The where clause contains equal (=)
operator (single row operator) and expecting only one value. Hence it generates the errors
To correct this error change = operator to IN
select * from emp where salary in (select min(salary) from emp group by deptno)
(select * from emp where salary in (1200,15000,20000,10000))

select * from emp where salary> any (select salary from emp where job='President')
(select * from emp where salary> any (6000,15000)=>select * from emp where salary>6000)
select * from emp where salary> all (select salary from emp where job='President')
(select * from emp where salary> all (6000,15000)=>select * from emp where salary>15000)
Null values in a sub query:
select empno from emp1 where empno not in (select manager_id from emp1 )
no rows will be returned.
We think that above sql statement display all the employees who dont have subordinates .Logically this sql statement
should have returned some rows. However, sql statement doesnt return any rows. One of the values returned by the
query is the null value, and hence the entire query returns no rows. The reason is that all conditions compare the null
value result in a null. So when ever null values are likely to be part of inner statement dont use the NOT IN operator.
The NOT IN operator is equal to <> ALL
So we can write the query as below to display all the who dont have subordinates
select empno from emp1 where empno not in (select manager_id from emp1
where manager_id is not null )

Multi column sub queries:


Till now we have discussed about sub queries which returns only one column value. And this value will be passing to
main query. If we want to return the two or more column values from sub query and pass these values to
Main sub query we need to write multi column sub queries.
Pair wise comparison sub query:
find out the employee details which manager_id,deptno is same as empno 7116,7456
select * from emp where (mgr,deptno) in (select mgr,deptno from emp where empno in (7116,7456))
both mgr and deptno will be returned by the one subquery and these values passes to main query.
Non pair wise comparison sub query:
find out the employee detials which manager_id,deptno is same as empno 7116,7456
select * from emp where mgr in (select mgr from emp where empno in (7116,7456))
and deptno in (select deptno from emp where empno in (7116,7456))
mgr and deptno value returns by different sub queries and it passes to main query.
Inline view: A subquery in the from clause of a select statement is called as inline view.
Display the details of the employees who earn more than the average salary in their department.
select e.empno,e.ename,e.salary,e.deptno from emp e ,
(select deptno,avg(salary) avgsal from emp group by deptno) e1

where e.salary>e1.avgsal and e.deptno=e1.deptno


Scalar subqueries: A subquery that returns only one column value from one row is called as
scalar subquery. If the subquery returns 0 rows, the value of the scalar subquery expression
null.If the sub query returns more than one row it returns error.
Display location as Canada if deptno is 20 other wise display as USA.
select empno,ename,deptno ,(case when deptno=(select deptno from dept where locno=100)
then 'canada' else 'usa' end) location from emp
we cant use the scalar sub queries in group by and having by clauses

DML:
Insert:
Enclose character and date value in single quotes.
Dont enclose the numbers in single quotations, because implicit conversion may take place
for numeric values assigned to number data type columns.
Entering values to every column:
insert into emp1 values(8,300,500,'tej',9)
Inserting rows with null values
implicit method: insert into emp1 (empno,deptno) values(9,400)
explicit method: insert into emp1 (empno,deptno,manager_id) values(10,500,null)
or: insert into emp1 (empno,deptno,manager_id) values(10,500,'')
Entering sysdate:
insert into dept1 values(23,23,sysdate)

is

copying rows from another table:


insert into emp1 select empno,deptno,locno,ename,mgr from emp where empno=7116
insert into empp(empname) select empname from emp where empno=116
create table employ1 (empno varchar2(90),salary number default(90) 2000)
Inserting with default value:
insert into employ1 values(2,default)
insert into employ1(empno) values(100)salary will be 2000 by default for empno 100
Instead of table name we can use select statement to insert the values.if the columns which we have selected
should be presented in the table in which we are inserting the data other wise it wont allow to insert the
data.Eventhough deptno 10 is not present in the table we can insert.
insert into (select deptno,locno from dept1 ) values (1000,600)
insert into (select deptno,locno from dept1 where deptno=10) values (1000,600)
insert into (select * from locations) values (107,'TADA')
The columns in the select clause,deptno 10 should be existed in the table then only we can insert the values
insert into (select deptno,locno from dept1 where deptno=106666 with check option) values
(1000,600)
--error(view with check option where clause violation)

Update:
Updating particular rows:
update emp1 set deptno=30 where empno=6
Updating complete column data:
update emp1 set deptno=30--(for all rows deptno will be 30)
Updating column value using sub query:
update emp set salary=(select salary from emp where empno=7231) where empno=7456
Updating rows based on another table:
update emp set deptno=(select deptno from emp1 where empno=7) where empno=7456
Updating with default value
update employ1 set salary=default where empno=2
updatebhanusetsal=default,empno=3333whereempno=100

Delete:
Deleting particular rows:

delete from emp1 where empno=6


Deleting rows based on another table:
delete from emp1 where empno in (select empno from emp where empno=7116)
Deleting complete table data:
delete from emp
Merge: you can do conditionally insert or update the table using the merge statement
merge into emp1 e1
using emp e
on (e.empno=e1.empno)
when matched then
update set e1.deptno=e.deptno
when not matched then
insert values (e.empno,e.deptno,e.locno,e.ename,e.mgr)
mergeintoemp1e1
usingempe
on(e.empno=e1.empno)
whenmatchedthen
updatesete1.deptno=e.deptno
whennotmatchedthen
insert(empno,deptno)values(e.empno,e.deptno)

The example shown matches the empno in emp1 table and empno in emp table.
If a match is found, the row in the emp1 table is updated to match the row in the emp.
If a match is not found, it is inserted into the emp1 table.
Database transactions: A database transaction consist one of the following.
DML statements
One DDL statements
One DCL statements.
Transaction consists of DML statements that make up one consistent change to the data. For example, a transfer of
funds between two accounts should include the debit to one account and the credit to one account in the same amount.
Both actions should fail or succeed together. The credit should not be committed with out debit.
Data base transactions begin when first DML statement is executed and
end with commit or rollback or
dcl or ddl statement (auto commit) issued.
State of the data before commit or roll back.
Data manipulation operations primarily affect the database buffer, there fore the previous state of the data
can be recovered.
The current user can review the results of the dml operations by querying the tables.

Other users cannot view the results of the dml operations made by current user.(the affected rows are locked)
State of the data after commit:
Data changes are made permanent in the data base.
The previous state of the data is permanently lost
All users can view the results
Locks on the affected rows will be released; those rows are available for the other users to manipulate.
All save points are erased.

State of the data after rollback:


Data changes are undone.
Previous state of the data is restored.
Locks on the affected rows are released.
delete from emp1 where empno=7116
commit
--deleted
delete from emp1 where empno=7116
rollback
--not deleted
savepoint a
delete from emp1 where empno=7116
savepoint b
insert into emp1 values(1234,1000,4000,'jans',1234)
rollback to b
--not inserted
rollback to a
--not inserted and not deleted
Create:
Table name must begin with a letter.
Must be 1 to 30 characters long.
Must not duplicate another object name.
Must not be an oracle server reserve word.
create table emp_emp(empno number,empname varchar2(9))
with default option:
create table emp_e(empno number default 2,empname varchar2(9))

Tables in the oracle data base:


User tables: Are a collection of tables created and maintained by the user. It contains user information.
Ex:Employees
Data dictionary: Is the collection of tables created and maintained by the oracle server. It contains data base
information.
The data dictionary base tables are rarely accesses by the user because the information in them is not
easy to understand. Therefore, users access data dictionary views because the information is present in a
format that is easier to understand.
There are four categories of data dictionary views.
USER_ : These views contain information about objects owned by the user.;
ALL_ : These views contain information about all of the objects accessible to the user.
DBA_ : The views are restricted views, which can be accessed only by people who have been assigned
the DBA.
V$
: These views are dynamic performance views. Store the information about data base server
performance, memory and locking.
The data dictionary views frequently used are:
USER_TABLES: Stores the names of tables owned by the user.
USER_OBJECTS: Stores object types like procedure, functions and all data base objects owned by the user.
USER_CATALOG: Stores tables, views, synonyms and sequences owned by the user.
User_catalog has synonym called CAT. You can use this synonym instead of user_catalog.

Alter:
Adding columns
alter table departments add location_name varchar2(90)
alter table departments add (sub_dept number,dept_id number)
Modifing the columns
you can increase the width of the column
you can convert the char column to varchar2 or varchar2 to char only if the columns contains
null values or if u dont decrease the size
alter table departments modify (sub_dept number(9),dept_id number(9))
alter table departments modify location_name char(200)
Droping the columns
You can drop the column even though it contains data

You can drop only one column at a time


Once column is dropped, it cant recovered (even though you use rollback)
alter table departments drop column location_name
Renaming the column name
alter table emp rename column ename to empname
DROP:
drop table used
RENAME:
rename departments to department1
TRUNCATE:
Removes all rows from the table.
Release the storage space used by that table.
You cant rollback the truncate
Truncating a table doesnt fire the delete triggers of the table
If the table is the parent of a referential integrity constraint, you cant truncate the table, disable
constraint before issuing the truncate command.
truncate table employees
GRANT: We can give the privileges to other users
REVOKE: We can take the privileges from other users which we have given by GRANT option.
Create user username (ramu) identified by password(ramu1)
Grant resource,connect to username(ramu)
We can give permissions on select, insert, delete, update, and alter to other users
Grant select, insert on emp to Krishna;
To give all permissions (select, insert, delete, update, and alter)
Grant all on emp to Krishna;
Giving permissions to multiple users
Grant all on emp to Krishna,ramu;
Taking permissions from user
Revoke insert on emp from Krishna;
Revoke all on emp from Krishna;
We can give permissions on only one table a time.

COMMENTS:
Adding comments to the table
comment on table dept is 'depatment information'
Droping comments to the table
comment on table dept is ' '
you can view the comments through the data dictionary view all_col_comments
select * from all_tab_comments WHERE table_name='DEPT'
Adding comments to the column
comment on column emp.empno is 'this is about employee number'
Droping comments to the column
comment on column emp.empno is ' '
You can view the comments of the columns through following views.
select * from all_col_comments where table_name='EMP'
select * from user_col_comments where table_name='EMP'

SET OPERATORS
The set operators combine the result of two or more component queries into one result. Queries containing
Set operators are called compound queries. All set operators have equal precedence. If sql statement contains
Multiple set operators, the oracle server evaluates them from top to bottom if there is no parentheses. (Parentheses can
override the rules of precedence)
The columns in the select list must match in data types.
Order by clause should appear only at the very end of statement.

UNION: Returns results from both queries after eliminating duplications


select empno,job,deptno from emp
union
select to_number(empno),job,to_number(deptno) from job_history
UNION ALL: Returns results from both queries including all duplications.
select empno,job,deptno from emp
union all
select to_number(empno),job,to_number(deptno) from job_history
select empno,job,deptno from emp order by empno
union all
select to_number(empno),job,to_number(deptno) from job_history error
Order by clause should appear only at the very end of statement.
select empno,job,deptno from emp
union all
select to_number(empno),job,to_number(deptno) from job_history order by empno
INTERSECT: Returns result that are common to both queries.
select empno,job,deptno from emp
intersect
select to_number(empno),job,to_number(deptno) from job_history
MINUS: Returns rows from the first query that is not present in the second query.
select empno,job,deptno from emp
minus
select to_number(empno),job,to_number(deptno) from job_history

CONSTRAINTS
By using constraints we can enforce rules on data in the table whenever a new row is inserted, deleted
or updated from that table.
Prevent the deletion of a data if there are dependencies from other tables.
If you dont name your constraint, the oracle server generates a name with the format SYS_Cn, where n is an
integer so that the constraint name is unique.
Constraints can be defined at the time of table creation or after the table has been created.
You can view the constraints names in the USER_CONTRAINTS data dictionary table.
You can view the columns on which we defined constraints in the USER_CONS_COLUMNS.
You can define the constraints at two levels.
Column level: Reference a single column and is defined with in a definition of the column, can
define any type of constraints.

Table level: Reference one or more columns and is defined separately from the definitions of the columns
in the table, can define any constraints except NOT NULL.
NOT NULL: The not null constraint ensures that the column contains no null values. Columns with out
the not null constraint can contain null values by default.
The not null constraint can be specified at only column level, not at table level
create table con1(empno number,ename varchar2(90) not null)
--system will generate the constaint name
insert into con1 values(90,null)--error:cannot insert null
select * from user_constraints where table_name='CON1'
for NOT NULL constraint CONTRAINT_TYPE =C in the above table.
create table con2(empno number,ename varchar2(90) constraint ename_notnull not null)
--constraint name (ename_notnull) has given by user.
UNIQUE: A unique constraint requires that every value in a column or set of columns be unique.That is,
no two rows of a table can have duplicate values in a specified column or set of columns. The column (set
of columns) included in the definition of unique key constraint is called the unique key. if the Unique
constraint comprises more than one column, that group of columns is called a
COMPOSITE UNIQUE KEY. Unique constraint can define at column level or table level.
Column level:
create table con3(empno number not null,ename varchar2(90) constraint ename_unique unique)
create table dd(empno number constraint bb not null constraint cc unique)
create table tab(empno number constraint con_not not null constraint con_unique unique)
Table level:
create table con4(empno number ,ename varchar2(90) , constraint ename_unique1 unique(empno,ename)
create table ccc(empno number ,ename varchar2(90) , constraint ename_unique123 unique(empno)
,constraint ename_unique321 unique(ename))
CHECK: Defines a condition that each row must satisfy.
Column level:
create table employe(ename varchar2(90) ,dept_no number,
salary number constraint sal_check check(salary>5000))
Table level:
create table employ1(ename varchar2(90) ,
salary number,dept_no number, constraint sal_check1 check(salary>5000))
PRIMARY KEY: This constraint ensures uniqueness of column or column combination and ensures that

no column that is part of primary key can contain null value.


PRIMARY KEY=NOT NULL+UNIQUE
A table can have only one primary key constraint but can have several unique constraints.
Column level:
create table con5(empno number not null,ename varchar2(90) constraint ename_primary primary
key)
Table level:
create table con6(empno number unique ,ename varchar2(90) , constraint ename_primary1 primary
key(empno,ename))
createtableemp_bhanu(enamevarchar2(90),empnonumber,constraintemp_notnull
primarykey(empno),constraintempcheck(empno>5))

FOREIGN KEY: The foreign key or referential integrity constraint, designates a column or combination of
columns as a foreign key and establishes the relation between foreign key with the primary key or unique key in the
same table or a different table.
For example dept_id has been defined as the foreign key in the employes table (dependent or child table).
It references the dept_id column of the departments table (the referenced or parent table).
A foreign key value must match with an existing value in the parent table or null.
create table departments(deptname varchar2(90) ,dept_no number constraint deptno_primary primary key)
Column level:
create table employes1(ename varchar2(90) ,dept_no number constraint deptno_reference1
references departments(dept_no))
Table level:
create table employes(ename varchar2(90) ,dept_no number, constraint deptno_reference
foreign key(dept_no) references departments(dept_no))
If we are trying to enter value in the dept_no of employes table which are not present in the dept_no of
departments table.
10, 20, 30 are the values in dept_no of departments table. If we try to give 40 value in dept_no of employes
table then it shows error.
insert into employes values ('ramana',40)
--error: integrity constraint violated-parent key not found
ON DELETE CASCADE: indicates that when the row in the parent table is deleted, the dependent rows
in the child table will also be deleted.
create table emp_emp(empno number,ename varchar2(90),dept_no number
constraint empno_foreign2 references depart(dept_no) on delete cascade)
ON DELETE SET NULL: converts foreign key values to null when parent value is removed.

create table emp_emp(empno number,ename varchar2(90),dept_no number


constraint empno_foreign2 references depart(dept_no) on delete set null)
only dept_no column will be null

ADDING THE CONSTAINTS AFTER CREATING THE TABLE


alter table emp_emp
add constraint empno_primary2 primary key(empno)
add constraint empno_check2 check (empno>1000)
add constraint empno_foreign2 foreign key(dept_no) references depart(dept_no)
add constraint ename_unique2 unique(ename)
modify ename constraint ename_notnull2 not null
alter table emp_emp
add constraint empno_foreign2 foreign key(dept_no) references depart(dept_no) on delete cascade
alter table emp_emp
add constraint empno_foreign2 foreign key(dept_no) references depart(dept_no) on delete set null
insertintoemp_empvalues(1,null,10)

after this we cant create the below constraints because of empno is 1 and ename is null already
exists.
alter table emp_emp
add constraint empno_check2 check (empno>1000)
modify ename constraint ename_notnull2 not null--error
DROPPING THE CONSTRAINTS
alter table emp_emp
drop constraint ename_notnull2
drop constraint empno_check2
If we want to drop the primary key constraint first we have to drop the foreign key constraints which
references primary key constraint.
We can drop the primary key constraint with out knowing the constraint name.
alter table DEPART
drop primary key
since there will be only one primary key for one table.
CASCADE:
Generally if we want to drop the primary key constraint first we have to drop the foreign key constraints
which references primary key constraint.

But by using cascade foreign key constraints will be dropped automatically if we drop primary key
constraint.
alter table DEPART
drop primary key cascade

DISABLING AND ENABLING THE CONSTRAINTS:


If there are no dependencies then we can disable the constraint (foreign keys) with out using cascade
also. But we should use cascade key word if we are disabling any constraint (primary key) on
which other constraint are defined
create table vis(empno number constraint vis primary key)
create table vis1(empno number constraint vis1 references vis(empno))
alter table vis
disable constraint vis --cannot disable constraint (APPS.VIS) - dependencies exist
alter table vis
disable constraint vis cascade--table altered
alter table emp_emp
enable constraint empno_foreign2
If we enable a constraint, that constraint applies to all the data in the table. All the data in the table must
fit the constraint.

DATABASE OBJECTS
TABLES: already we have discussed.
VIEWS:
AVIEW IS A LOGICAL TABLE CREATED BASED ON ONE OR MORE TABLES OR ANOTHER VIEW.
A VIEW CONTAINS NO DATA OF ITS OWN BUT IS LIKE A WINDOW THROUGH WHICH we can get the
DATA FROM TABLES
CAN BE VIEWED OR CHANGED.
THE TABLES ON WHICH A VIEW IS BASED ARE CALLED BASE TABLES.
THE VIEW IS STORED AS SELECT STATEMENT IN THE DATA DICTIONARY.

Views restrict access to the data because view can display selective columns from the table.
Views can be used to make simple queries to retrieve the results of complicated queries. For
example, views can be used to query information from multiple tables without the user
knowing how to write a join statement.
View can be used to retrieve the data from multiple tables.
Views doesnt occupy any storage space like tables.

You can see the view names in the table USER_VIEWS (or all_views)
Simple views and complex views:
Feature
Number of tables
Contain functions
Contains groups of data
DML operations through
View

Simple view
one
no
no
yes

Complex view
one or more
yes
yes
no

Simple views:
create view view_emp as
select * from emp where deptno=30
Recreates the view if it already exits.
create or replace view view_emp as
select * from emp where deptno=40
Creating a view by using alias names.
create or replace view view_emp as
select empno employee_id,empname employee_name,deptno department_no
from emp where deptno in (40,30)
or
create or replace view view_emp (employee_id,employee_name, department_no )as
select empno ,empname ,deptno
from emp where deptno in (40,30)
Complex views:
create or replace view view_emp as
select d.dname ,max(e.salary) max_sal,avg(e.salary) avg_sal
from emp e,dept d group by d.dname
(we must give qualifier and aliasname names for functions)
You cant modify, remove or add the data in a view if it contains:
Group functions
A group by clause
The distinct key word
The pseudo column rownum keyword
Columns defined by expressions.
We cant add any data if there is not null columns in the base tables that are not selected by the view

With check option: we can ensure the DML operations performed on the view stay with in the
domain of the view.

create or replace view view_emp as


select empno,empname,deptno from emp where deptno in (30,50) and empno in (7116,7456)
with check option constraint cons_view
update view_emp set empno=7116 where empno=7456
1 row updated
update view_emp set deptno=40 where empno=7116
update view_emp set empno=7115 where deptno=30
error: view with check option where clause violation
We can update deptno with 30 or 50 and empno with 7116 or 7456
With read only: We can ensure that no DML operations performed on the view. Any attempt to perform
A DML on any row in the view results in an oracle server error.
create or replace view view_emp as
select empno,empname,deptno from emp where deptno=30 and empno in (7116,7456)
with read only
delete from view_emp where deptno=30
error: cannot delete from view without exactly one key preserved table
If we drop the table after creating the view,still view exits in the table user_views.But if we access
the view it shows the error like 'view has errors. Once table got created then again we can access the
view.
We can create the view even though base table doesnt exits by using force key word.
create or replace force view view_raman as select empno,empname from raman
Removing a view: dropviewview_v
SEQUENCE: A sequence is a user created database object that can be shared by multiple users to generate
unique integers. A typical usage of sequences is to create a primary key value, which must be unique
for each row. Sequence numbers are stored and generated independently of tables. Therefore, the
same sequence can be used for multiple tables.
Syntax:

create sequence Sequence_name


Incremented by n
Start with n
Maxvalue n / no maxvalue
Minvalue n / no minvalue
Cache n / nochache
Cycle / nocycle

Sequence_name: is the name of the sequence.


Incremented by n: specifies the interval between sequence numbers, where n is integer.

Start with n: specifies the first sequence number to be generated.


Maxvalue n : specifies the maximum value the sequence can create.
no maxvalue: specifies a maximum value of 10^27 for the ascending sequence and -1 for descending sequence.
Minvalue n : specifies the minimum sequence value.
no minvalue: a minimum value of 1 for the ascending sequence and (10^26) for descending sequence.
Cycle / nocycle: specifies whether the sequence continues to generate values after reaching its maximum or
minimum value.
Cache n / nochache: specifies how many values the oracle server preallocates and keeps in memory.
(By default, oracle server caches 20 values)
create sequence empno_seq
increment by 1
start with 1
maxvalue 25
nocache
nocycle
select * from user_sequences (or all_sequences) where sequence_name='EMPNO_SEQ'
The LAST_NUMBER column in the above table displays the next available
sequence number if nochache is specified.
create sequence empno_seq2
increment by 1
start with 1
maxvalue 25
minvalue 10
nocache
nocycle
error: start with cannot be less than minvalue.
Nextval and Currval pseudocolumns:
After we create sequence, it generates sequential numbers for use in the tables. Reference the sequence
by using the nextval and currval pseudocolumns.
Nextval: Returns the next available sequence value. With the reference sequence_name.nextval, a new
Sequence number is generated
Currval: Returns the current sequence value. With the reference sequence_name.currval, current sequence
Value is displayed.
insert into employees (empid,empname)
values (empno_seq.nextval,'Ramana' )
select empid from employees1
select empno_seq.currval from dual1

insert into vis values(seq_vis.nextval)--10


select seq_vis.nextval from dual--20
insert into vis values(seq_vis.nextval)--30
Actually our intention is to insert the 20, but 30 got inserted. Since, we have used 'select
seq_vis.nextval from dual' to see the next available value. By this query sequence as generated
'20'.After this we are inserting in to table. so 30 will be inserted.
So dont use 'nextval' to see the next available number. Refer last_number column in 'user_sequences' table.
(specify nocache while creating the sequence)
immediately after creating the sequence dont use currval to see the values.It will display the error.
Creating sequence with out parameters.
createsequencesequ.(Startswith1,incrementby1)

Altering the sequence:


We can change the increment value, maximum value cycle options and cache option.
We cant change the start with value.
alter sequence empno_seq
increment by 10
maxvalue 1000
nocache
nocycle
We cant change the start with value
Max value should be >== current value.
Removing a sequence:
drop sequence empno_seq2
Gaps in sequence values can occur when :
A rollback occurs, system crashes, same sequence is used in another table.
Synonym: By using synonym we can simplify the access to the objects. We can give permanent alias name
for object.
To refer a table owned by another user, you need to prefix the table name with the name of the user
who created it. Creating the synonym eliminates the need to qualify the object name with the schema
and provides with an alternative name for the table, view, procedure or other objects.
create synonym emp for employees.
select * from user_synonyms (or all_synonyms) where table_name='EMPLOYEES'

The database administrator can create the public synonym accessible to all users. The following
example creates a public synonym named emp1 for devs schema employees table.
create public synonym emp1 for dev.employees
Dropping the synonym:
drop synonym emp
drop public synonym emp1
ROWNUM and ROWID:
ROWNUM is going to generate the sequential record numbers depends upon the query execution.
Highest 5 salaries details:
selectename,salfromempwhererownum<=5orderbysaldesc

Rownum will be assigned before results are ordered.so we need to write the query as below
Selectename,salfrom(selectename,salfromemporderbysaldesc)ewhere
rownum<=5

ROWID actually represents the physical location of the record/row in the database.
selectename,empno,salfromemp1wheresal=(selectmax(sal)fromemp1wheresal<(select
max(sal)fromemp1))

topnthsal
select*fromempewhere1=(selectcount(distinct(sal))fromempwheree.sal<=sal)
topnsals
select*fromempewhere2>=(selectcount(distinct(sal))fromempwheree.sal<=sal)
leastnthsal
select*fromempewhere1=(selectcount(distinct(sal))fromempwheree.sal>=sal)
leastnsals
select*fromempewhere2>=(selectcount(distinct(sal))fromempwheree.sal>=sal)

Materialized view:
A materialized view is a database object that contains the results of a query. Materialized views,
which store data based on remote tables are also, know as snapshots. For replication purposes,
materialized views allow you to maintain copies of remote data on your local node.

creatematerializedviewmv_empas
select*fromemp2wheredeptno=20
SELECT*FROMALL_MVIEWSwheremview_namelike'MV_EMP'
Eventhoughwedeletethedatafromemp2deletefromemp2wheredeptno=20.
Stilldatawillbeexistedinthematerializedview.

Cube and Rollback:


Both are extension to 'Group By' Clause
Cube:CUBE enables a SELECT statement to calculate subtotals for all possible combinations of a group of

dimensions. It also calculates a grand total.


Rollup:ROLLUP enables a SELECT statement to calculate multiple levels of subtotals across a specified
group of dimensions. It also calculates a grand total
createtablepets(pet_namevarchar2(10),storesvarchar2(10),numbnumber)
insertintopetsvalues('dog','hyd',10)
insertintopetsvalues('cat','hyd',10)
insertintopetsvalues('dog','sec',20)
insertintopetsvalues('rat','sec',20)
Ifwewritethequeryas
selectpet_name,stores,sum(numb)
frompets
groupby
pet_name,stores
dog,hyd,10
cat,hyd,10
dog,sec,20
rat,sec,20
ButIwanttogettotalpets(60),
indidualpetcountsdog(30).cat(10),rat(10)
numberofpetsinstoreshyd(20),sec(40)
alongwithaboveresult.
ToachiveabovethingIneedtobuildthequerywhichincludesomuchlogic.
InsteadofthatonewecanuseCubeandRollup.

selectpet_name,stores,sum(numb)
frompets
groupbycube(pet_name,stores)

PET_NAMESTORES
hyd
sec
cat
cat
dog
dog
dog
rat
rat

hyd
hyd
sec
sec

SUM(NUMB)
60.00
20.00
40.00
10.00
10.00
30.00
10.00
20.00
20.00
20.00

combinations:
pet_name
stores
pet_name,stores
grandtotal
selectpet_name,stores,sum(numb)
frompets
groupby
rollup(pet_name,stores)
PET_NAMESTORES
cat
hyd
cat
dog
hyd
dog
sec
dog
rat
sec
rat

SUM(NUMB)
10.00
10.00
10.00
20.00
30.00
20.00
20.00
60.00

combinations:
pet_name
pet_name,stores,
grandtotal
selectpet_name,state,stores,sum(numb)
frompets1
groupbycube(pet_name,state,stores)

combinations:
pet_name
state
stores
pet_name,state
pet_name,stores
state,stores,
pet_name,state,stores
grandtotal
selectpet_name,state,stores,sum(numb)
frompets1
groupbyrollup(pet_name,state,stores)
combinations:
pet_name
pet_name,state
pet_name,state,stores
grandtotal

Analyticfunctions:
Analyticfunctionsgiveaggregateresult,theydonotgrouptheresultset.
Theyreturnthegroupvaluemultipletimeswitheachrecord.
Assuchanyothernon"groupby"columnorexpressioncanbepresentinthe
selectclause
selectempno,deptno,count(*)
over(partitionbydeptno)
fromemp
EMPNO DEPTNO COUNT(*)OVER(PARTITIONBYDEPTNO)
7,782
10
2.00
7,830
10
2.00
7,788
20
6.00
7,876
20
6.00
1
20
6.00
123
20
6.00
34
20
6.00
1
20
6.00
7,846
30
2.00
7,900
30
2.00
8,796
50
1.00

ROW_NUMBER()givesarunningserialnumbertoapartitionofrecords
RANKandDENSE_RANKbothprovideranktotherecordsbasedonsomecolumnvalue
orexpression.Incaseofatieof2recordsatpositionN,RANKdeclares2
positionsNandskipspositionN+1andgivespositionN+2tothenextrecord.
WhileDENSE_RANKdeclares2positionsNbutdoesnotskippositionN+1.

select*fromemp_deptorderbydetpno,sub_deptno
EMPNO DETPNO SUB_DEPTNO SALARY
1.00
10.00
100.00 1,000.00
2.00
10.00
200.00 2,000.00
7.00
10.00
200.00 2,000.00
6.00
10.00
200.00 2,000.00
5.00
10.00
500.00 5,000.00
5.00
10.00
500.00 5,000.00
3.00
20.00
300.00 3,000.00
4.00
20.00
400.00 4,000.00

selectdetpno,sub_deptno,row_number()over(partitionbydetpno,sub_deptnoorder
bydetpno)fromemp_dept

DETPNO SUB_DEPTNO
ROW_NUMBER()OVER(PARTITIONBYDETPNO,SUB_DEPTNOORDE
10.00
100.00
1.00
10.00
200.00
1.00
10.00
200.00
2.00
10.00
200.00
3.00
10.00
500.00
1.00
10.00
500.00
2.00
20.00
300.00
1.00
20.00
400.00
1.00

selectempno,detpno,sub_deptno,rank()over(partitionbydetpnoorderby
sub_deptno)fromemp_dept
EMPNO DETPNO SUB_DEPTNO
RANK()OVER(PARTITIONBYDETPNOORDERBYSUB_DE
1.00
10.00
100.00
1.00
2.00
10.00
200.00
2.00
7.00
10.00
200.00
2.00
6.00
10.00
200.00
2.00
5.00
10.00
500.00
5.00
5.00
10.00
500.00
5.00
3.00
20.00
300.00
1.00
4.00
20.00
400.00
2.00
selectempno,detpno,sub_deptno,dense_rank()over(partitionbydetpnoorderby
sub_deptno)fromemp_dept

EMPNO DETPNO SUB_DEPTNO


DENSE_RANK()OVER(PARTITIONBYDETPNOORDER
1.00
10.00
100.00
1.00
2.00
10.00
200.00
2.00
7.00
10.00
200.00
2.00
6.00
10.00
200.00
2.00
5.00
10.00
500.00
3.00
5.00
10.00
500.00
3.00
3.00
20.00
300.00
1.00
4.00
20.00
400.00
2.00

Das könnte Ihnen auch gefallen