Beruflich Dokumente
Kultur Dokumente
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;
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
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.
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.
CHAPTER-2
(Vishnucharacter string)
In
Like
Is null
is a null value
Betweenand...:
Use this to display rows based on a range of values.
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:
Or:
Not:
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
CHAPTER-3
SQL FUNCTIONS
SQL functions are used to
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
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)
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
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
selectsign(12),sign(12),sign(0)fromdual1,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
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
Date-number
Date-date
Date+number/24
date
date
number of days
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
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.
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
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
50-99
0.49
50.99
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
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 )
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
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:
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.
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
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.
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
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.
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
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.
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.
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