SQL Book-1
SQL Book-1
SQL Book-1
Chapter-1
SQL INTRODUCTION
Oracle is a product from oracle which is used to store data permanently see store device.
Every organization store same type of data.
Oracle product of Oracle Corporation.
2. Customer Names
INFORMATION:
When we are processing data are achieving meaning full results it is called as
“INFORMATION”.
2. Information Of Customer
DATA STORE:
2. Flat Files
3. Database
FLAT FILES:
Data or Information stored in individual unrelated files these files are also called as
“FLAT FILES”.
User-1
User-2
File-2
File-1
If you want to store data in flat file we are most develop application program in high
level language. In flat file approach every application maintains it own file which is separate
from another application program.
Student
Sno Sname class
Record application program
Flat file
Prof id Prof name Time class
Scheduling application program
DISADVANTAGE:
1. Data Retrieval
2. Data Redundancy
3. Data Integrity
4. Data Security
5. Data Indexing
1. Data Retrieval:
If you want to retrieval data from flat file we must develop application program in high
level language. Whereas if you want to retrieval data from database then we are using
SEQUEL(Structural English Query Language).
2. Data Redundancy:
Same time we are maintaining multiple copies of the same data in different locations.
This data is also called as “REDUNDANCY DATA”. In flat file mechanism if we are
modifying data in one location. It is not affected in another location. This is called as
“INCONSISTENCY”. Flat file does not maintain consistence data.
3. Data Integrity:
Integrity means to maintain proper data if we want to maintain proper data when we
define set of rules this set of rules also called “BUSINESS RULES”. In database we are
defining business rules using constrains, trigger. Where as in flat file if we want maintain proper
data. If we most develop application program in high level language.
4. Data Security:
Data stored in flat file cannot be security. Because file does not provides rule based
security.
5. Data Indexing:
If we want to retrieve data very fastly when database provides indexing mechanism but
flat file does not support indexing mechanism.
What is Database?
It is organized collection of inter related once data is stored in DB. It can be stored
integrated and also simultaneously number of user accesses this data.
American National Standard Institute (ANSI) as establish three level architecture for DBMS.
Standards Planning and Requirement Committee (SPARC).
DBMS ARCHITECTURE:
Purchase manager
Customer
Item name
External Item name
level Price
Price
Quality
When ever we modifying internal level it is not affected conceptual level. i.e. if we are
moving db from one location to another location then conceptual level does not affected.
Physical data
EMP stored
view-1
view-2
DEPT
1.
This level describes how data internally stored in database. Physical representation of the
database on the computer database administrators only works in internal level. This level
maintain by database administrator (DBA’s).
This level describes organization view of the database. In this level only of database
develop creating database and maintain data properly.
This level users access or view of the database. Describe that part of database that is
relevant to a particular user. In this level database developer create views and giving to the
number of members.
DATA MODEL:
Hierarchical data model organizers data in tree like structure. This hierarchy is also called
parent, child hierarchy. This structure employee’s child a record can have repeating information
(generally child segments) in this model data is represented by collection of records (record
type).
Hierarchical model Relational model
In this a record type corresponding to the table in relational model and also recording
same as row in a table in relational model. This model is implemented based on ONE-TO-
MANY relationship. Based on this restriction number of child on single parent they way in this
model more number of time child segment repeated that weighs more redundant data and also
this model retrieve data very slowly from the database because this model is search data from
root node an wards if want operate hierarchical data model product that we are using procedural
language.
2005 50000
1001 Allen hr
2013 70000
1002 king sw
2013 60000
In 1970 E.F.CODD introduced relational data model. This model also implement based
on MANY-TO-MANY relationship in this model. We are storing data in two-dimensional table.
1. Collection of objects
2. Set of operations
Chapter-2
ORACLE HISTORY
In 1970 E.F.CODD write a paper “Relational model of data for large stored data banks”.
IBM INGRESS
System/R
INGRESS Larry Ellison (1977)
(Square) (1982)
Oracle Oracle
Relational Software, Incorporated (RSI)
Oracle
What is Oracle?
In 1970 E.F CODD described Oracle. Oracle is a database. Oracle database is an Object-
Relational Database Management System produced and Marketed by Oracle Corporation. Oracle
is a fourth generation Relational Database Management Systems. Oracle is a collection of data
treated as a unit. The purpose of a database is to store and retrieve related information.
ORACLE VERSIONS
Commit, Rollback
Virtual c++ (window program) (VC++)
Rewritten in ‘c’ language
Read consistency
Introduced pl/sql
Row level locks
Integrity
Stored procedures, Stored functions
Triggers
Truncate table
Datatype varchar changed into varchar2
View compilation
Dynamic SQL
ANSI/ISO SQL92
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 10
SQL MATERIAL
Ref cursor
Inline views
Dbms_job package
Bitmap indexes
Utl_file package
Object technology
Nested table,Varrays
Lobs (large objects)
Column increased per a table upto 1000
Analytical functions
Materialized views
Autonomous transaction
Bulk collection clause
Case conditional statement
Instead of triggers
Enable, disable trigger
Function based indexes
Renaming a column
ANSI joins
Flashback query
End User
Oracle db
SQL
QUERY
5.sql navigator
Username: SCOTT
Password: TIGER
Unlocked user:
Password: TIGER
Go to editor:
Sql>ed <┘
- Alt+f+x <┘
Sql> / <┘
Chapter-3
- Create
- Alter
- Drop
- Truncate
- Insert
- Update
- Delete
- Select
- Commit (Save)
- Rollback (Like undo)
- Savepoint
DATA TYPE
1. Number (P,S)
3. Date
1. Number:
2. Char:
It is used to store fixed length ALPHA numeric data in bytes. Maximum limit is
2000bytes.By default char data type having 1 bytes.
It is used to store variable length alpha numeric data maxsize is 4000 bytes.
3. Date:
It is used to store date in oracle data format. By default in oracle date format “DD-MON-
YY”.
- Create
- Alter
- Drop
- Truncate
- Rename
Create:
This command is used to create database objects like tables, views, procedures, indexes,
sequences………………………
Sql>desc tablename;
Alter:
Alter
Modify: It is used to change column datatype (or) column datatype size only.
Method-1:
If we want drop a single column at a time without using parenthesis then we are using
following syntax.
Method-2:
If we want drop a single (or) multiple column with using parentheses then we are using
following syntax.
Dropping a table:
Oracle db
Oracle db
Table
Table
Recyclebin
Table
Permanently Remove
Get it back from recycle bin:
Syntax:
To drop permanently:
To drop permanently:
Testing:
Recycle bin:
Recycle bin is a read only which stores dropped store. Whenever we are installation
oracle server then automatically so many read only table there. These read only tables are also
called as Data Dictionary.
Oracle db
Sql>create table india(sno number(5));
Recycle bin
Sql>drop table india; Object_name Original_name
Testing:
India
Sql>desc recyclebin;
Purge:
Truncate: This command is used to delete all rows permanently from the table.
Sql>desc india;
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 20
SQL MATERIAL
Renaming a table:
NOTE: In all db system by default all DDL command is automatically commit (save).
- insert
- update
- delete
Insert:
Method-1:
Sql>/
NOTE: If we want to insert particular cell values also then we are using update stmts.
Delete: It is used to delete all rows (or) particular row from the table.
Sql>rollback;
We are using delete from tablename. Then automatically total data delete from table and
also deleted a data automatically store in a buffer. We can get it back data using rollback
(without commit).
When we are using truncate from tablename all row delete permanently. It cannot get it
back this data. Because truncate is a DDL command automatically commits.
From tablename
Where condition
Group by columnname
Having condition
Order by [asc/desc];
Creating a new table from existing table (or) Coping a table from another table:
No rows selected.
Sql>desc kadapa;
NOTE: Where we are copping a table from another table constraints are not copied.
Q) Write a query to display the emp except job has clerk from emp table?
Q) Write a query to display EMP’s we are getting more than 2000 salary from emp table?
Q) Write query to display the emp who are belongs to 20,30,50,70 deptno from emp table?
SPECIAL OPERATOR:
In not null
In:
This operator is used to pick the values one by one from list of values. Generally IN
operator is used in place of OR operator. Because IN operator performance very high compare to
OR operator.
NOTE: Generally in all database system we are using multiple rows subqueries then we
must use IN operator.
NOTE: NOT IN operator does not work with null values in all database systems.
null:
NULL is an undefined, unknown, unavailable value it is not same as zero. Any arithmetic
operation performed with null value again it will becomes null.
Null+50-----------------Null
nvl():
Syntax: nvl(exp-1,exp-2)
Nvl(40,10) -----------40
=>1300+0
=>1300
Between:
This operator is used to retrieve range of values this operator is also called as BETWEEN
………AND operator.
These two operator are used in where clause only. This used to whether a column having
null value (or) not.
Q) Write a query to display emp who are not getting commission from emp table?
Q) Write a query display emp does not have manager from table?
Like: This operator is used to search data based on character data. This operator performance is
high compare to searching function. Along with LIKE operator we are using 2 special characters.
LIKE
% _ (underscore)
Q) Write a query to display emp whose ename start with ‘M’ from emp table using like
operator?
Q) Write a query to display the emp whose joining in the ‘month dec’ emp table using like
operator?
Q) Write a query to display the emp whose joining in the ‘year 81’ emp table using like
operator?
Q) Write a query to display the emp whose ename second letter would ‘L’ from emp table
using like?
If third letter:
This operator is used to concatenation data column values with literal strings.
Chapter-4
FUNCTIONS
Functions are used to solve particular talk in a problem and also functions must return a
value oracle having two types of functions.
1. Predefined Functions
2. Userdefined Functions
1. Predefined functions:
1. Number Functions
2. Character Functions
3. Date Functions
Dual:
Dual is a virtual table which contains one row and one column by default dual table
column data type is varchar2.
2.mod(m,n):
3.round(m,n): It rounds given floating point value number ‘M’ based on ‘N’.
NOTE:
Round always checks remaining number it means remaining number is above 50% then 1
is added to the rounded number.
5.ceil(),floor():
Ceil() returns nearest greatest integer where are floor() returns nearest lowest integer.
6.greatest(exp1,exp2………),least(exp1,exp2…………….):
Greatest() returns maximum value within given expression where as least returns
minimum value among given expression.
We not show maximum value so there it is the problem. To overcome this value we use
max(sal).
Character Function:
1.upper():
2.lower():
3.initcap():
It returns initial letters capital and all remaining letters are small.
4.length():
This function always returns number datatype it returns total length of the string
including spaces.
5.substr():
It will extract position of the string within the given string based on last two parameters.
Q) Write a query to display the emp’s whose ename second letter would ‘LA’ from emp
table using substr() function?
NOTE:
In all database systems we are not allowed to use group function in where clause but we
are allowed to use number, character, date function in where clauses.
6.instr():
It returns number datatype this function returns position of the delimiter (or) position of
the character (or) position of the string within given string.
NOTE: Always instr() returns position based on last two parameter but oracle server
always counts number of characters left side first position on words.
7.Lpad():
It will fills specified character on the left side of the given string. Here always second
parameters returns total length of the string this parameter must be a number.
8.Rpad():
Ans: rpad(ename,20,’-‘)||sal
smith----------------------------------------1800
allen------------------------------------------1250
king-------------------------------------------5000
9.Ltrim():
CLERK LERK
SALESMAN ALESMAN
MANAGER ANAGER
10.Rtrim():
CLERK CLE
SALESMAN SALESMA
MANAGER MANAGE
It is used to remove left and right side specified character and also leading and trailing
spaces.
NOTE: This function also used remove first letter last spaces. Trim set should have only
one character.
Ans: 4
12.Translate(), Replace():
Clerk clerk
Salesman marketing
King king
Salesman marketing
Date Functions:
1.sysdate
2.add_months()
3.last_day()
4.next_day()
5.months_between()
2.add_months():
It is used to add (or) subtract number of months to specified date based on second
parameter.
Syntax: add_months(date,number)
Syntax: last_day(data)
4.next_day():
It returns next day occurrence date from the specified date based on second parameter.
5.mon_between():
This function returns number datatype it return number of months between two specified
dates. It date1>date2 then this function returns negative value.
months_between(sysdate,hiredate)
403.481436
401.386775
401.328987
Ename round(months_between(sysdate,hiredate))
SMITH 403
ALLEN 401
KING 409
Date Arithmetic:
1.date+number
2.date-number
4.date1-date2
1.TO_CHAR() D YYYY DY
It is used to convert date type into char type i.e it is used to convert date type into date
string.
o/p: 31/07/14
NOTE: Whenever we are using to_char always first parameter must be date type.
Otherwise oracle server returns an error.
2.TO_DATE():
It is used to convert date string into date type (Oracle date format).
NOTE:
Whenever we are using to_date passed parameter return values match with default date
format return date type otherwise oracle side returns error. To overcame this problem use a
second parameter as same as first parameter format. Then oracle server only automatically
converts date string into date type.
o/p: WEDNESDAY/JUNE/05
NOTE: When to_char function if we are specifying full length format then oracle server
returns gaps if we passed string return values occupy less size than the default date format return
values to overcome this problem we must use fill mode(FM).
Q) Write a query to display emp who are joining in month DECEMBER from emp table
using to_char function?
Q) Write a query to display the emp who are joining in the year ‘81’ from emp table using
to_char function?
NOTE:
Whenever we are passing date string into oracle date functions then oracle server
internally convert date string into date type that why we are not allowed to_date explicitly. In
this case passed parameter must be default date format otherwise oracle server returns an error.
Whenever we are using round,truncate function date part can be changed based on time
portion. Whenever we are using round function oracle server internally check time portion≥12 or
noon. It time portion≥12 then one day added to the given date and also automatically time
portion set to zero.
Wherever we are using truncate also oracle server internally time portion set zero.
TESTING:
01/08/2014 00:00:00
31/07/2014 00:00:00
Q) Write a query to display the emp who are joining today from emp table?
No Rows Selected
All this group function operator over group of data and return a single value.
1. max()
2. min()
3. avg()
4. sum()
5. count(*)
6. count(columnname)
NOTE: In oracle by default all group function ignores null values except count(*)
function.
GROUP BY: This clause is used to divide similar data items into set of logical group.
This clause is used to select statement.
Q) Write a query to display no.of emp’s department wise from emp table using group by?
DEPTNO COUNT(*)
10 3
20 5
30 6
Q) Write a query to display number of emp’s job wise from emp table using group by?
JOB COUNT(*)
CLERK 4
MANAGER 3
ANALYST 2
SALESMAN 4
PRESIDENT 1
Q) Write a query to display no.of emp’s dept wise max(),min() of sal from emp table using
group by?
10 5000 1300
20 3000 800
30 2850 950
NOTE: We can also use group by clause without using group function.
RULES:
Other than group function columns specification after select those all columns must be
use after group by. Otherwise oracle server returns ERROR: not a group function expression.
NOTE:
Whenever we are using group function with another column with using after select then
database server returns an error. To overcome this problems column use group by clause.
JOB SUM(SAL)
CLERK 4150
SALESMAN 5600
MANAGER 8275
ANALYST 6000
PRESIDENT 5000
Q) Write a query to display deptno,count(*) and also those dept having more than 4 emp’s
from emp table using group by clause?
Having:
In all database systems after GROUP BY clause we are not allowed to WHERE clause.
In place of this ANSI/ISO sql introduced using HAVING clause. Generally if you want to
restrict the rows in a table then we are using WHERE clause. Where as if we want to restrict the
groups then after we are using HAVING clause. Generally we are not allowed to use GROUP
function in WHERE clause. Where has in HAVING clause we can also use GROUP function.
DEPTNO SUM(SAL)
20 10875
Q) Write a query to display year, number of emp’s in that year which more than one emp
was hide from emp table using group by clause?
YEAR COUNT(*)
1982 2
1981 10
ORDER BY:
This clause is used to arrange data in shorting order along with ORDER BY clause oracle
provided two keywords ASC/DESC. By default ORDER BY clause having ASC order.
ORDER BY
ASC DESC
NOTE: we can also use column position on ORDER BY clause to improve performance.
NOTE:
We can also use more than one column ORDER BY clause. In this based ORDER BY
clause arrange data in first column then value are same in first column those column second
column.
DEPTNO COUNT(*)
30 5
20 4
Rollup,Cube:
Oracle 8i introduced rollup,cube. These clauses are used along with GROUP BY clause
only. This clauses are used to calculate sub total,grand total automatically.
Chapter-5
JOINS
Joins are used to retrieve data from more than one table. If we are joining ‘N’ tables then
we are using N-1 joining condition oracle server having following types of joining. This 4 joins
are also called as 8i joins.
2. non-equi join
3. Self join
4. Outer join
1. Inner join
We can also retrieve data from multiple tables without using joins. In this case server
internally uses cross join. Cross joins must default data. Cross join internal uses catigear product.
If we want to display accurate data from multiple tables then we must use explicit join.
Based on equality condition we are retrieving data from multiple tables. Hare joining
conditional column must belongs to same datatype. When table having common columnname
then only we are using this join.
From tablename1,tablename2
Sql>select ename,sal,deptno,daname,loc
From emp,dept
Where emp.deptno=dept.deptno;
Sql>select ename,sal,dept.deptno,daname,loc
From emp,dept
Where emp.deptno=dept.deptno;
NOTE:
We can also create deferent names for the table in FROM clause of the joining condition.
Sql>select ename,sal,d.deptno,dname,loc
Where e.deptno=d.deptno;
NOTE:
Equi join always return matching rows only (here deptno 40 does not display if we are
using deptno also).
Q) Write a query to display we are working Chicago from emp,dept tables using joins?
NOTE:
If we want to retrieve the rows after joining condition then we are using AND operator in
8i joins where has in 9i join we are using either ‘AND’ (or) ‘WHERE’.
Q) Write a query display dname,sum(sal) from emp,dept tables using equi joins?
Dname sum(sal)
Sql>select dname,sum(sal) from emp,dept
ACCOUNTING 8750
Where emp.deptno=dept.deptno group by dname;
RESEARCH 10875
DNAME SUM(SAL)
RESEARCH 10875
SQL> select dname,sum(sal) from emp,dept
where emp.deptno=dept.deptno group by dname having count(*)>3;
DNAME SUM(SAL)
RESEARCH 10875
SALES 9400
SQL> select dname,sum(sal) from emp,dept
where emp.deptno=dept.deptno group by rollup(dname);
DNAME SUM(SAL)
ACCOUNTING 8750
RESEARCH 10875
SALES 9400
29025
2. Non-equi join:
SQL> select ename,sal,losal,hisal from emp,salgrade where sal between losal and hisal;
3. Self join:
Join in a table to itself is called as “self join”. Here joining conditional columns must
belong to same datatype. Generally if we want to compare different column in a single table (or)
if we want to single column values then we are using self join.
Whenever we are using self join we must create an alias name in from clause this alias
names must by different name. Otherwise data oracle server returns ambiguously error. This
reference name used by data based on server in query execution time only.
Q) Write a query to display the working has same job as SCOTT from emp table using self
join?
Q) Write a query to display ename,manager from emp table using self join?
Where e1.mgr=e2.empno;
Q) Write a query to display the emp and their manager in 10th department from emp table
using self join?
Q) Display the emp who are before joining their MGR from emp using self join?
Q) Write a query to display emp and their mgr who are working in the sales emp,dept
tables using self join?
Q) Write a query to display the emp who are getting same salary in different dept from
emp table using self join?
Q) Write a query to display emp who joining same month from emp table using self join?
4. Outer join:
This join is used to retrieve all rows from one table and matching rows for another table.
Generally when we are using equi join database server returns matching rows only. In oracle if
you want retrieve non-matching rows also then we are using outer join (+) operator in equi join
this is called “8i outer join”.
NOTE: In this case join operator can be used only one side at a time in joining condition
of the equi join.
Where e.deptno=+d.deptno;
1. Inner join
5. Natural join
1. Inner join:
This joins returns matching rows only. When table having common columnname then
only we are using this join this join performance very high compare to 8i equi join. Here joining
conditional column same datatype.
On e.deptno=d.deptno;
Q) Write a query to display the emp who are working in the loc Chicago from emp,dept
using 9i equi join?
Using clause:
ANSI join we are also use USING clause in place of ON clause. USING clause
performance very high compare to ON clause and also when we are using USING clause data we
returns database server returns one time only.
A B C
x y z
Sql>create table z2(a varchar2(5),b varchar2(5));
A B C A B
x y z x y
Sql>select * from z1,z2 where z1.a=z2.a and z1.b=z2.b;
Sql> select * from z1 join z2 on(z1.a=z2.a and z1.b=z2.b);
A B C A B
x y z x y
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 54
SQL MATERIAL
NOTE:
We are using USING clause we are not allowed to use aliasname and joining condition.
This join all rows from left side table and matching rows from right side table and also
return null values in place of non-matching rows display another table.
A B C
x y z
p q r
A B
x y
s t
This join always returns all rows from right side table and matching rows from left side
table and also returns null values in place of non-matching rows.
A B C A B
x y z x y
s t
4. Full outer join:
This join always returns all rows from right side table and matching rows left side table
and also returns null values in place of non-matching rows.
A B C A B
x y z x y
p q r
s t
Sql> select ename,sal,d.deptno,loc,dname from emp e natural join dept d;
ERROR: Column used in NATURAL join cannot have qualifier
5. Natural join:
Natural join return matching rows only in natural we are not allowed to joining condition
When ever table having common column then only we are using this join. This join internally
uses USING clauses. That why this join always returns common column one time only and also
we are not allowed using aliasname and joining conditional column.
A B C
x y z
Cross join:
Syntax: Syntax:
On table2.commoncol=table3.commoncol;
Chapter-6
CONSTRAINTS
Constraints are used prevents (or) invalid data entry into out table. Generally constraints
are created on table columns oracle server having following type of constraints.
1. Not null
2. Unique
3. Primary key
4. Foreign key
5. Check
1. Column Level
2. Table Level
1. Column Level:
2. Table Level:
In this method we are defining constraints on group of column that is first we are defining
all the columns and last only we are specifying constraint type along with group of column.
constraint type(col1,col2………………));
1. Not null:
Not null constraints does not support table level this constrains does not accept null
values but it accept duplicate value.
2. Unique:
This constrains defining two level that is does not accept duplicate values but if accept
null values. Whenever we are creating unique constrains oracle server automatically create on
btree index on those column.
SNO NAME
1 abc
2 xyz
Table level: sql> create table c2(sno number(5),name varchar2(15),unique(sno,name));
SQL> select * from c3;
SNO NAME
1 abc
2 xyz
SQL> insert into c3 values(2,'xyz');
ORA-00001: unique constraint violated
1 abc, 2 xyz this is not allowed.
3. Primary key:
Primary key uniquely identifier record in a table and also where can be only primary in a
table and also primary key does not accept null values and duplicate values. Whenever we are
creating primary key internally oracle server create and btree index on those column.
This is a composite primary key i.e it is combination column as single primary key.
4. Foreign key:
We want to establish relationship between tables then we are using referential integrity
constraints foreign key. One table foreign key must belong to another table primary key. Here
these two columns must belong to same datatype. Always foreign key values based on primary
key only.
Generally primary key does not excepts duplicate,null values where has foreign key
accepts duplicates,null value.
SNO SNO
2
On delete cascade
2
On delete set null
3
Rule:
Whenever we are establishing relationship between two tables oracle server violates
following two rules.
if we are try to delete a record in master table than oracle server returns a error ORA-
2292: to reference this problem first we are Child deleting children table records
Master
in a table. Than only we are deleting those record master table otherwise
used on delete cascade clause.
Whenever we are using this clause in child table record oracle server automatically delete
appropriate master,child table record on those table.
Whenever we are using this clause in child table if we are deleting primary key value in
master table then automatically foreign key value set to null in child table.
If we try to insert other than primary key value into foreign key then oracle server returns
on ERROR: ora-2291: Because always foreign key values primary key values only.
5. Check:
This constraint is used to define logical condition according to our business rules.
Name
NARASIMHA
SQL> insert into nr values('narasimha');
ERROR: ORA-02290: check constraint violated
Oracle Database
Sql>desc user_constraints;
where table_name=’EMP;
cons_name con_type
pk_emp p
fk_deptno R
NOTE: If we want to view column names along with constraint name then we are using
user_constraint_columns.
where table_name=’EMP;
cons_name col_name
pk_dept deptno
fk_emp empno
NOTE: If we want view logical condition of the check constraints then we are using
search_condition property user_constraints data dictionary.
search_condition
name=upper(name)
NOTE: All column information stored under user_tab_column data dictionary.
Ex: sql>desc user_tab_columns
Sql>select column_name from user_tab_col where table_name=’EMP’;
Column_name
Empno
Ename
-----------
Q) Write a query to display no.of columns numbers from emp using data dictionary?
Count(*)
NOTE: If we want add constraints into existing table existing columns then we are using
table level syntax method.
X1
SNO
NOTE: If we want to add a new column along with constraints then we are using column
level syntax method.
X2
N
S
A
N
M
O
E
NOTE: If we want add not null constraints existing table columns then we are using alter
with modify.
Dropping constraints:
NOTE: If we want drop primary key along with foreign key then we are using cascade
clause along with alter drop.
SNO NAME
1 A
2 B
10 C
Ex: SQL> create table dept1 as select * from dept;
SQL> alter table emp add foreign key(deptno) references dept(deptno) on delete cascade;
Chapter-7
SUBQUERY
Query within another query is called nested query (or) subquery. Generally child query
are called subquery. Subqueries are used to retrieve data from single and multiple tables by using
more than one step process. All database systems having two type of subqueries.
1. Non-correlated
2. Correlated
In non-correlated subquery child query is executes first then only parent query executed.
Where as in correlated subquery parent query executed first then only child query executed.
1. Non-correlated:
Q) Write a query to display the emp’s who are getting more than the average salary from
emp table?
This are single row subquery because there child query returns single value. In single row
subquery we are using =,<,<=,>,>=,<> operator.
Execution:
Step-1:- sql>select avg(sal) from emp;
AVG(SAL)
2073.21429
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 68
SQL MATERIAL
Parent query: A query which receives values from another query is called “PARENT QUERY”.
Q) Write a query to display the emp’s who are working salesman department from
dept,emp table using subquery?
Sql>select * from emp where deptno=(select deptno from dept where dname=’SALES’);
NOTE:
Generally using subquery we are not allowed to display child query column into parent
query to overcome this problem we must use join concept.
ENAME DNAME
ALLEN SALES
WARD SALES
----------- -----------
Q) Write a query to display the emp’s who are working SMITH dept table.
Sql>select * from emp where deptno=(select deptno from emp where ename=’SMITH’);
Q) Write a query to display senior most emp details from emp table?
Sql>select * from emp where hiredate=(select min(hiredate) from emp);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
Q) Write a query to display the emp who are working under BLAKE from emp table using
empno,mgr?
Sql>select * from emp where mgr=(select empno from emp where ename=’BLAKE’);
Q) Write a query to display lowest average salary job from emp table?
NOTE: Whenever child query contains nested group function then we must using group
by clause.
JOB AVG(SAL)
CLERK 1037.5
Sql>select deptno,min(sal) from emp group by deptno having min(sal)>(select min(sal)
from emp where deptno=20);
DEPTNO MIN(SAL)
30 950
10 1300
Q) Write a query to display the emp delete who are getting maximum sal in each dept from
emp table?
Sql>select * from emp where sal=(select max(sal) from emp group by deptno);
ERROR: ORA-01427: single-row subquery returns more than one row
This are multiple row subquery because here child query returns multiple value in
multiple rows subquery we are using IN,ALL,ANY operator.
NOTE:
Sql>select * from emp where sal in(select max(sal) from emp group by deptno);
Sql> select deptno,sal from emp where sal in(select max(sal) from emp group by deptno);
Sql>select * from emp where deptno in(select deptno from dept where
dname=’ACCORDING’ or dname=’SALES’);
TON-N Analysis:
1. Inline view
2. Rownum
Generally we are not allowed to use order by clause in child query to overcome this
problem oracle 7.2 introduced subqueries in from clause this is called as “INLINE IEW”.
In inline views we are using subquery in place tablename in parent query this subquery
execute to prier executed.
2. Rownum:
Rownum is a pseudo column which behavior table column. This pseudo used in all table.
It cannot perform DML operators. Rownum automatically assign numbers to each row in a table
at the time of selection. By default rownum having temporarily values.
ROWNUM ENAME
1 SMITH
2 ALLEN
--- -----------
Sql>select rownum,ename from emp where deptno=10;
ROWNUM ENAME
1 CLARK
2 KING
3 MILLER
Q) Write a query to display first row from emp table using rownum?
Sql>select * from emp where rownum=1;
Q) Write a query to display second row from emp table using rownum?
Sql>select * from emp where rownum=2;
No Row Selected.
NOTE: Rownum does not work with more than one positive integer. Then is it work’s
with <,<= operators.
Q) Write a query to display first 5 row from emp table using rownum?
Sql>select * from emp where rownum<=5;
Q) Write a query to display first 5 highest salary from emp table using rownum?
SQL> select ename,job,sal,deptno from (select ename,job,sal,deptno from emp order by
sal desc) where rownum<=5;
Q) Write a query to display 5th highest salary employee from emp table using rownum?
minus
select ename,job,sal,deptno from (select ename,job,sal,deptno from emp order by
sal desc) where rownum<=4;
Q) Write a query to display second row from emp table assigning rownum?
Sql>select * from emp where rownum<=2
Minus
select * from emp where rownum<=1;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Q) Write a query to display last two rows from emp table using rownum?
Sql>select * from emp
Minus
Select * from emp where rownum<=(select count(*) -2 from emp);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Q) Write a query to display the rows between 1 and 5 from emp table using rownum?
Sql>select * from emp where rownum between 1 and 5;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Q) Write a query to display the rows between 4 and 7 from emp table using rownum?
Sql>select * from emp where rownum<=7
Minus
Select * from emp where rownum<=4;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
Q) Write a query to display 5th row from emp table using rownum aliasname?
Sql> select * from (select rownum r,ename,sal from emp) where r=5;
R ENAME SAL
5 MARTIN 1250
Sql> select * from (select rownum r,ename,sal from emp) where r in(2,3,5,6,10,14);
R ENAME SAL
2 ALLEN 1600
-- ---------- -------
14 MILLER 1300
Sql>select * from (select rownum r,emp.* from emp) where r=5;
Sql> select * from (select rownum r,ename,sal from emp) where r=1 or r=(select count(*)
from emp);
R ENAME SAL
1 SMITH 800
14 MILLER 1300
Q) Write a query to display even no.of rows from emp table using rownum aliasname?
Sql> select * from (select rownum r,ename,sal from emp) where mod(r,2)=0;
Q) Write a query to display 5th highest salary from emp table using rownum aliasname?
Sql>select * from (select rownum r,sal,ename from (select * from emp order by sal desc))
where r=5;
R SAL ENAME
5 2850 BLAKE
Analytical functions also similar to GROUP functions and also these functions display
each row in a group because these functions are calculate results number of rows wise.
1. row_number()
2. rank()
3. dense_rank()
These three analytical functions automatically assigns numbers to each row in table either
group wise (or) rows wise in a table.
ROW_NUMBER() analytical function assigns different rank numbers when values same
where as RANK(),DENSE_RANK() analytical function assign same rank number then value are
same and also RANK() scrip next consecutive rank number where has DENSE_RANK() does
not scripts next consecutive number.
ROW_NUMBER():
RANK():
DEPTNO ENAME SAL R
20 SMITH 3000 1
20 SCOTT 3000 1
20 ADAMS 1200 3
DENSE_RANK():
DEPTNO ENAME SAL R
20 SMITH 3000 1
20 SCOTT 3000 1
20 ADAMS 1200 2
Sql>select * from (select deptno,ename,sal,row_number() over(partition by deptno
10 KING 5000 1
10 CLARK 2450 2
10 MILLER 1300 3
20 SCOTT 3000 1
20 SMITH 800 5
30 MARTIN 1250 5
Q) Write a query to display 2nd highest salary employee in each department from emp table
using analytical function?
10 CLARK 2450 2
20 JONES 2975 2
30 ALLEN 1600 2
Q) Write a query to display 5th highest salary employee from emp table using analytical
function?
10 CLARK 2450 5
Q) Write a query to display 2nd row from emp using analytical function?
ENAME SAL R
ALLEN 1600 2
NOTE:
We are also use analytical function without use inline view always analytical function
returns row wise group data.
LEAD(),LAG():
These two analytical functions compare next row values and returns into the current row.
Here offset returns positive integer if we are specifying 1 it returns next row immediate.
10 MILLER 1300 0
NOTE:
Lag() analytical function returns previous value into it is also same syntax as lead
function but offset returns previous row.
10 KING 5000 0
FIRST_VALUE:
First value analytical function returns first value in each group. This function excepts
only one parameter.
Q) Write query to display year number of employees in that year and in which year more
than one employee hide?
YEAR COUNT(*)
1980 1
1983 1
1982 2
1981 10
YEAR COUNT(*)
1982 2
1981 10
DEPTNO COUNT(*)
30 6
20 5
10 3
ROWID:
Rowid is a pseudo column it’s behaviors like a table column pseudo column are not
stored in tables. Whenever we are inserting data oracle server automatically generates unique
identifier number identifying each row in a table in hexadecimal format this is called as
“ROWID” (or) “ROWADDRESS”.
Generally rownum having temporarily values where as rowid having fixed value. Using
rowid we are identifying a record uniquely in a table. Using rowid we can also data retrieve very
fastly from the database.
1 AAADVOAABAAAIGCAAA SMITH
2 AAADVOAABAAAIGCAAB ALLEN
14 AAADVOAABAAAIGCAAN MILLER
1 AAADVOAABAAAIGCAAG CLARK
2 AAADVOAABAAAIGCAAI KING
3 AAADVOAABAAAIGCAAN MILLER
In subquery we can also use rowid to delete to subquery duplicate rows in a table. i.e if
you want to delete rows except one row each.
Q) Write a query to display 1st record from the emp using rowid?
SQL> select * from emp where rowid in(select min(rowid) from emp);
Q) Write a query to display last record from the emp using rowid?
SQL> select * from emp where rowid in(select max(rowid) from emp);
Q) Write a query to display 2nd record from emp table using analytical function?
Q) Write a query to display each dept from the 2nd record from emp table using analytical
function?
10 KING 5000 2
20 JONES 2975 2
30 WARD 1250 2
Q) Write a query to delete duplicate rows except one row in each group from table using
rowid?
SQL> delete from test where rowid not in(select max(rowid) from test group by sno);
4 rows deleted.
Sql>select * from test;
We can also compare multiple column of the child query with the multiple column of the
parent query. This type of query is “MULTIPLE COLUMN SUBQUERY”. In multiple column
subqueries we must specify parent query when conditionals with in parenthesis.
Q) Write a query to display the emp’s who are job,mgr match with the job,mgr of the
emp’s SCOTT from emp table?
Q) Write a query to display senior most emp’s from each job from emp table using
multiple column subquery?
Q) Write a query to display the emp’s who are getting maximum sal in each dept from emp
table using multiple row subquery?
Sql>select deptno,ename,sal from emp where sal in(select max(sal) from emp
group by deptno);
30 BLAKE 2850
20 FORD 3000
20 SCOTT 3000
10 KING 5000
Q) Write a query to display the emp’s who are getting maximum sal in each dept from emp
table using multiple row subquery?
30 BLAKE 2850
20 SCOTT 3000
10 KING 5000
Q) Write a query to display ename,dname,sal of the emp who sal,comm match with
sal,comm of the emp’s working in location “DALLAS” from emp,dept tables?
Q) Write a query to display emp’s who are getting more than the highest paid emp in 20th
dept from emp table?
Sql>select * from emp where sal>(select max(sal) from emp where deptno=20);
Q) Write a query to display emp’s who are getting more than the lowest paid emp in 20th
dept from emp table?
Sql>select * from emp where sal>(select min(sal) from emp where deptno=20);
When ever resource table having child amount of data and also child query contain
max(),min() function and if we are comparison more number of value using relational operator.
These type of queries degrades performance of the applications to overcome these problems
ANSI/ISO sql provided subquery special operators these are “ALL,ANY”. This operator is used
along with relational operator. These types of operators improve performance.
Sql>select * from emp where sal>all(select sal from emp where deptno=20);
SQL> select * from emp where sal>any(select sal from emp where deptno=10);
ALL---------max(sal) ANY-------min(sal)
NOTE:
When ever subquery special operator internally optimizer uses when we are using ANY
operator internally optimizers uses ‘OR’ logical operator.
Q) Write a query to display the emp’s who are getting more than the salaries of the
‘CLARK’ from emp table using subquery special operator?
Sql>select * from emp where sal>all(select sal from emp where job='CLERK')
order by sal desc;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
NOTE:
‘OR’ operator internally uses logical operator for ‘AND’ where has ‘ANY’ operator
logical use operator ‘OR’.
NOTE: ‘=any’ is same as ‘IN’ operator ‘=any’ performance very high compare to IN
operator. Whereas ‘<>any’ not same as ‘NOT IN’ operator.
2. CORRELATED SUBQUERY:
Generally in non-correlated subquery child query is execute first then only parent query
executed. Where as in correlated subquery parent query is executed first then only child query
executed.
In correlated subquery we must create on aliasname for the parent query table in parent
queries use the aliasname in child query where condition
Execution process:
Whenever we are subquery having correlated subquery database server get a condition
row from parent query table and then control passed into child query where condition based on
evaluation value of where clause it compares query value with parent query.
Generally non-correlated subquery child query executed only once for parent table.
Where has in correlated subqueries child query is executed for each row for a parent table.
Generally when resource table having large amount of data then we have not allowed to
subqueries because in this case correlated is low performance. Generally correlated subquery
used in denormalization process in this process we are modify one table column values based on
another table columns in this use we are using correlated update.
Non-correlated
Correlated
Outer query
Sql> select * from emp e1 where 1=(select count(*) from emp e2 where e2.sal>=e1.sal);
Q) Write a query to display 2nd highest salary from emp following table using correlated
subquery?
EMP1
Sql>create table emp1(ename varchar2(5),sal number(5));
Sql>insert into emp1 values(………………………………..);
SQL> select * from emp1;
ENAME SAL
Ename Sal
A 100 Candidate row
A 100
B 150
B 150
C 200 C 200
D 300 D 300
ENAME SAL
C 200
Phase-1:
Phase-1:
Phase-1:
Q) Write a query to display 2nd highest sal employee from emp above using correlated
subquery N-1 method?
where e2.sal>e1.sal);
ENAME SAL
C 200
NOTE: EMP1
Whenever resource table having duplicate data then we are using N-1 method in case of
N method it will be returns No Row Selected as a message to overcame this problem we must
use DISTINCT clause.
Ename Sal
Sql> insert into emp1(ename,sal)values('c',200); A 100
where e2.sal>=e1.sal);
ENAME SAL
C 200
C 200
Q) Write a query to display Nth sal employee from emp table using correlated subquery?
Sql>select * from emp e1 where &n=(select count(distinct(sal)) from emp e2
where e2.sal>=e1.sal);
Q) Write a query to display the emp’s who are getting more than the avg salary of the job’s
from emp the using correlated subquery?
Sql>select * from emp e where sal>(select avg(sal) from emp where job=e.job);
EXISTS OPERATOR:
EXISTS operator used in correlated subquery. EXISTS operator performance very high
compare to IN operator. EXISTS operator always returns Boolean value either True (or) False.
EXISTS operator is used to test whether a given set is Empty (or) Non-empty.
EXISTS operator returns true if set having value non-empty and also this operator returns
false if set is empty. These operator use WHERE clause only. Whenever we are use EXISTS
operator then we are not allowed to use colname along with these operator.
NOTE: Generally if we want CLERK one table column value into another table column
values then we for EXISTS operator.
Q) Write a query to display those dept details from dept table having emp’s in emp table
assign correlated subquery from emp,dept tables?
Sql> select * from dept d where exists(select * from emp where deptno=d.deptno);
20 RESEARCH DALLAS
30 SALES CHICAGO
NOTE: Whenever we are using EXISTS operator we can also use constant after select in
child query because EXISTS operator check child query returns Value (or) Not.
Sql> select * from dept d where exists(select 1 from emp where deptno=d.deptno);
20 RESEARCH DALLAS
30 SALES CHICAGO
Q) Write a query to display dept table does not having emp’s in emp table from emp,dept
table using correlated?
40 OPERATIONS BOSTON
Q) Write a query to display dept table does not having emp’s in emp table from emp,dept
table using correlated?
Sql>select * from dept where deptno not in(select deptno from emp);
DEPTNO DNAME LOC
40 OPERATIONS BOSTON
NOTE: Generally not in operator does not work with null values to overcome this
problem we must use not EXISTS operator along with correlated subquery.
Sql> select * from dept where deptno not in(select deptno from emp);
No Rows Selected
Sql> select * from dept d where not exists(select * from emp where deptno=d.deptno);
DEPTNO DNAME LOC
40 OPERATIONS BOSTON
Q) Write a query to display who are getting same sal as emp’s SCOTT sal from emp table
using correlated subquery in exists operator?
MERGE STATEMENT:
statements. Generally MERGE is used data warehousing applications. When we are using
MERGE statement then we must create aliasname.
On (join condition)
Insert (targettablecolnames)values(sourcecolvalues);
In MERGE statement we are using UPDATE, INSERT statement but through MERGE
statement we cannot modify ON clause.
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
1 NARASIMHA YSR
Chapter-8
VIEWS
View is a database object which is used to provide authority level of security. View does
not store data. View is also called as “VIRTUAL TABLE” (or) “WINDOW OF THE TABLE”.
Generally views are created from base table’s database administrator. Generally in all
database we want to restrict table columns from one user into another user then also we are using
views. Generally views created base tables based on base tables. Views are categories into TWO
views.
1. Simple View
SIMPLE VIEW is a view which is created from only one base table. Where as
COMPLEX VIEW is a view which is created from number of base tables.
1. Simple View:
Sql>conn scott/tiger;
1. When a simple view contains Group functions, Group by clause, Distinct, Rownum, Set
operator, Joins then we cannot perform DML operations through simple view to base table.
2. We must include base table not null column into the view then only we can perform INSERT
operation through simple view to base table.
as
select ename,job,sal,deptno from emp where deptno=10;
NOTE: Primary key include in views then insert otherwise not inserted data.
Generally when we are creating views then automatically database server storage VIEW
definition in database. In oracle if we want to VIEW definition then we are using USER_VIEWS
data dictionary.
TEXT
select "EMPNO","ENAME","JOB","MGR","HIREDATE","SAL","COMM",
"DEPTNO" from emp where deptno=10;
NOTE:
Whenever we are using group functions or expressions in simple view then we must
create column aliasname for those expressions otherwise oracle server given error.
30 2850 950
20 3000 800
10 5000 1300
30 2850 950
20 3000 800
10 5000 1300
as
select rownum “rownum”,deptno from emp where deptno=10;
In all database systems whenever we are creating a view then automatically view
definition are stored in database. If we want view definition then we must use USER_VIEWS
data dictionary.
If we want to create constraint type mechanism on views then only we are using WITH
CHECK OPTION clause. Then we are using this clause only INSERT. This clause visibility
values through base table.
as
FORCE VIEW: We can also create view without base table these types of view are called
as “FORCE VIEW”.
as
where emp.deptno=dept.deptno;
Whenever we are try to performance DML operator through compare view table some
tables column are affected some table column are not affected. Generally we can not modify
non-key preserved table columns. Complex views are created multiple base tables.
In oracle if we want to view modify table, non modify table then we using
USER_UPDATABLE_COLUMNS data dictionary.
Ex: Sql>desc
Sql>select column_name,updatable from user_updatable_columns
where table_name='V7';
COLUMN_NAME UPD
ENAME YES
SAL YES
DNAME NO
LOC NO
Whenever we are performing DML operation through complex view to base table some
table column are not affected to overcome this problem oracle introduced instead of triggers in
pl/sql. Instead of trigger are created on views by default instead of triggers are row level trigger.
TRIGGERS (PL/SQL):
Triggers are also same as stored procedure and it will automatically invoked whenever
DML operation performed on Table (or) View. All database system having two types of triggers.
In statement level triggers trigger body is executed once for DML statement where as in
row level triggers trigger body executed for each row for DML statement.
COL1
Trigger 05-SEP-14
COL1
05-SEP-14
05-SEP-14
05-SEP-14
insert update delete
NEW
05-SEP-14
OLD
Row Level Trigger:
In row level trigger body executed for each row for done. That way we must use for each
row clause in trigger specification and also data internally stored in to rollback segment
qualifiers. These are qualifiers in trigger body when we are using this qualifier trigger body then
we must use [:] then we must qualifier trigger.
Syntax: :old.colname
:new.colname
Q) Write a pl/sql row level trigger on emp table whenever user deleting data those deleted
that data stored in another?
6 rows selected
8 rows selected
INSTEAD OF TRIGGER:
Generally we cannot performance DML operations through complex view to base table to
overcome this problem oracle introduced instead of triggers.
ENAME YES
SAL YES
DNAME YES
LOC YES
MATERIALIZED VIEW:
Oracle 8i introduced materialized views. Generally views are does not store data where
as Materialized Views are store data. Generally MV is handling by database administrator. MV
is used to improve performance of the Joins (or) Aggregatable queries. MV stores result of the
query. MV is store replication of the remote database into local server (local node).
Materialized view also store’s data same like a table. But whenever we are refreshing
MV if synchronous of data based on base table.
Before we are creating materialized view database administrator must give create any
privileges otherwise oracle server returns an Error: Insufficient Privileges.
NOTE: In oracle one of the materialized view base table must have primary key.
Otherwise oracle server returns on error.
as
as
Here materialized view also behaves likes a view. Whenever we are creating materialized
view automatically MV definition permanently stores in a database same like a view definitions.
In oracle if we want MV definition then we are using USER_MVIEWS data dictionary.
Sql>desc USER_MVIEWS;
QUERY
AAADwEAAEAAAAFPAAA 1 a
AAADwEAAEAAAAFPAAB 2 b
AAADwEAAEAAAAFPAAC 3 c
AAADwEAAEAAAAFPAAD 4 d
AAADwEAAEAAAAFPAAA 1 a
AAADwEAAEAAAAFPAAB 2 b
AAADwEAAEAAAAFPAAC 3 c
AAADwEAAEAAAAFPAAD 4 d
Here view rowid’s are same as base table rowid’s. That why view does not store data.
Through the view we are viewing base table that’s why view are called as “VIRTUAL TABLE”.
AAADwHAAEAAAAFcAAA 1 a
AAADwHAAEAAAAFcAAB 2 b
AAADwHAAEAAAAFcAAC 3 c
AAADwHAAEAAAAFcAAD 4 d
Here MV rowid’s are called different from base table rowid’s. that’s why materialized
view store data.
1 A
4 D
1 a
4 d
1 A
2 B
3 C
4 D
When we are refreshing MV it synchronous data based on base table. In oracle if we want
to refresh MV then we are using refresh method from DBMS_MVIEW package.
SNO NAME
1 A
2 B
3 C
4 D
In oracle by default MV’s are complete materialized view. CRMV when we are
refreshing internally rowid’s are Re-Created. This process does not improve more performance.
If we are called modifying data in base table also that why when we are refreshing MV
frequently then this type MV are ‘D’ grade performance.
AAADwUAAEAAAAFsAAD 2450 10
AAADwUAAEAAAAFsAAE 5000 10
AAADwUAAEAAAAFsAAF 1300 10
AAADwUAAEAAAAFsAAA 2450 10
AAADwUAAEAAAAFsAAB 5000 10
Fast refresh materialized view are also called as “Incremental Refresh Materialized
View”. When we are refreshing FRMV it will improve performance of the MV’s. In FRMV
rowid are Not Changed if you are refreshing MV no.of times also. In FRMV data only
synchronous.
1 A
2 B
3 C
4 D
AAADwYAAEAAAAF8AAA 1 A
AAADwYAAEAAAAF8AAB 2 B
AAADwYAAEAAAAF8AAC 3 C
AAADwYAAEAAAAF8AAD 4 D
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 110
SQL MATERIAL
AAADwYAAEAAAAF8AAA 1 A
AAADwYAAEAAAAF8AAB 2 B
AAADwYAAEAAAAF8AAC 3 C
ON DEMAND/ON COMMIT:
1. Manually
2. Automatically
1. Manually:
We can also refresh materialized views either Manually (or) Automatically. In manually
method we are using dbms_mview package to refresh MV these method is called as “On
Demand”. By default method is On Demand method.
2. Automatically:
If you want to refresh MV without using dbms_mview package this is called as “On
Commit”. When we are using On Commit method in this case explicitly we must specify On
Commit key word clause in MV.
1 A
2 B
3 C
4 D
AAADwbAAEAAAAGMAAA 1 A
AAADwbAAEAAAAGMAAB 2 B
AAADwbAAEAAAAGMAAC 3 C
AAADwbAAEAAAAGMAAD 4 D
AAADwEAAEAAAAFPAAA 1 A
AAADwEAAEAAAAFPAAB 2 XYZ
AAADwEAAEAAAAFPAAC 3 C
AAADwEAAEAAAAFPAAD 4 D
AAADwbAAEAAAAGMAAA 1 A
AAADwbAAEAAAAGMAAB 2 B
AAADwbAAEAAAAGMAAC 3 C
AAADwbAAEAAAAGMAAD 4 D
AAADwbAAEAAAAGMAAA 1 A
AAADwbAAEAAAAGMAAB 2 XYZ
AAADwbAAEAAAAGMAAC 3 C
AAADwbAAEAAAAGMAAD 4 D
3. Hiding some information from the user i.e it 3. It stores result of the query i.e it is called as
is also called “Window Of The Table”. “Copy Of The Table”.
4. When we are modifying data in base table 4. When we are modifying data in base table
then view is immediately affected. then MV not affected immediately because
here rowid’s are different.
Chapter-9
1. GRANT
2. REVOKE
1. Grant:
Sql GRANT is a command used to provide access or privileges on the database objects to
the users.
Data security point of view oracle provided two types of admin user’s these are
1. SYS
2. SYSTEM
Creating a user:
PRIVILEGES:
System privileges are given by database administrator oracle having to system privilege.
System privileges are used to create object, alter table, create procedure, create trigger, create
any materialized, create session …………………etc.
ROLE:
Role is nothing but collection of system privileges (or) collection of object privileges.
Userdefined role are create by database administrator only.
Generally in multi user environment number of user’s works on same project in this case
some user require common set of privileges in this case only database administrator creating a
userdefined role and assigns common set of privileges in to role and then only that role given to
the number of user’s.
ADMIN_OPTION VARCHAR2(3)
ROLE PRIVILEGE
R1 CREATE SESSION
R1 CREATE TABLE
R1 CREATE SYNONYM
R1 CREATE TRIGGER
R1 CREATE PROCEDURE
PREDEFINED ROLE:
Whenever we are installing server then automatically three ROLES are created. This are
called as “Predefined Roles”.
2. Object Privileges:
Object privileges are used to performance. Some privileges object privileges is given by
either developers (or) dba. In oracle insert, update, delete, select, execute, read, write,……….
this are also called as “ALL” (or) “OBJECT PRIVILEGES”.
Who receive with grant option clause those users given same object privileges to another
user’s.
NOTE:
In all database systems ROLES does not work WITH GRANT OPTION clause. All
object privileges related to user stored under USER_TAB_PRIVS data dictionary.
Sql>desc user_tab_privs;
2. REVOKE:
NOTE:
Generally if we want to restrict table columns from one user into another user then we
creating view with required column’s then only that views given to the no.of users.
NOTE:
We can also drop view using drop view viewname. Whenever we are dropping base table
then view is invalid and also view definition are available in database in oracle. If you want view
definition then we are using USER_VIEWS data dictionary.
TEXT
select "SNO","NAME" from base
We can also create read only view using with read only option clause. Whenever we are
using this clause we cannot perform DML operation view to base table.
ERROR: cannot delete from view without exactly one key-preserved table
Chapter-10
INDEX
Oracle 8i introduced indexes. INDEX is a database object which is used retrieves data
fast from the database. This process automatically improves performance of the application.
Become INDEX columns retrieve data very fastly from the table. Generally INDEX created on
table columns. INDEX is handling by database administrator.
1. Automatically
2. Manually
1. Automatically:
In oracle whenever we are creating unique key (or) primary key then oracle server
automatically creates BTREE indexes on those columns.
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 120
SQL MATERIAL
2. Manually:
Whenever we are using select query contain WHERE clause (or) ORDER BY clause then
only oracle server searching for INDEX in the database. If INDEX are available oracle server
retrieve data very fastly the table by using INDEX SCAN() method. If INDEX not available then
oracle server uses full table scan method to retrieve data from the table.
NOTE:
Whenever WHERE clause contain <> (or) is null (or) is not null operators then oracle
server does not search for INDEX if those column already having INDEX also.
1. Btree Index:
Btree index are created on high cardinality columns. In oracle by default index are btree
index whenever we are creating btree index automatically oracle server stores actual data along
with rowid’s in leaf blocks of the btree structure. Whenever WHERE condition value available
in leaf blocks is create some retrieve data very fastly from the table along index scan method.
DEVALOPER DBA
Sql> select * from emp where ename=’KING’; Sql> select * from emp where ename=’KIMG’;
A ---------Z Root
Leaf blocks
If we want view performance of the query we must create plan table using explain plan
clause.
If we want view plan table then we must use display method from DBMS_XPLAN
method.
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost (%CPU) |Time |
Using index:
PLAN_TABLE_OUTPUT
NOTE:
If we want view column names along with index name then we are using
user_ind_columns data dictionary.
where table_name='EMP';
COLUMN_NAME INDEX_NAME
EMPNO PK_EMP
ENAME INDEX1
Oracle 8i introduced function based index. Function based index are by default btree
index. Generally whenever WHERE clause contain function (or) expressions then oracle server
does not search for index if already those columns having also to overcome this problem oracle
8i introduced extension of the btree index this are also called as “function based index”. In
function based column along with function (or) expression index.
PLAN_TABLE_OUTPUT
| Id | Operation | Name | Rows | Bytes | Cost (%CPU) |Time |
PLAN_TABLE_OUTPUT
INDEX_NAME INDEX_TYPE
PK_EMP NORMAL
INDEX1 NORMAL
VIRTUAL COLUMN:
Oracle 11g introduced virtual columns using virtual column we can store expressions
directly into database. Generally in oracle if we want to stored expressions then we are using
either function based index (or) view these two methods in directly stores stored expression in
expression to overcome this problem oracle 11g introduced virtual column to stores stored
expression directly into database using generated always as.
as(function/expression(colname);
10 20 30
NOTE:
If you want view virtual column expression then we are using DATA_DEFAULT
property from USER_TAB_COLUMNS data dictionary.
C “Á+B”
INDEX_NAME INDEX_TYPE
PK_EMP NORMAL
INDEX3 NORMAL
2. Bitmap:
Oracle 7.3 introduced bitmap index. Generally bitmap index are used in data warehousing
application. Bitmap index are created in low cardinality columns (more duplicate data) low
cardinality columns more duplicate data.
Whenever we are creating bitmap index oracle server automatically create a bitmap table
on the specified columns and using bits. Whenever user requesting using logical operator. Then
only oracle server directly operates bits within bitmap table and also resultant bitmap
automatically convert into rowid using internal bitmap function.
JOB 1 2 3 4 5 6 7 8 9 10 11 12 13 14
CLERK 1 0 0 0 0 0 0 0 0 0 1 1 0 0
SALESMAN 0 1 1 0 1 0 0 0 0 1 0 0 0 0
MANAGER 0 0 0 1 0 1 1 0 0 0 0 0 0 0
ANALYST 0 0 0 0 0 0 0 1 0 0 0 0 1 0
PRESIDENT 0 0 0 0 0 0 0 0 1 0 0 0 0 0
Chapter-11
SEQUENCES
If you want access sequence values then we are using 2 pseudo columns.
1. Currval
2. Nextval
Syntax: sequencename.currval
Syntax: sequencename.nextval
If you want generate sequence values using select statement then we must use DUAL
table.
If you want generate first sequence numbers then we must nextval pseudo column. In this
case nextval pseudo column returns starting sequence number currval pseudo column return
current value of the sequence session already having a value.
Sql> /
NEXTVAL
CURRVAL
NOTE:
We can also return currval along with nextval pseudo then we are generating first
sequence value.
start with 1
increment by 1
maxvalue 10;
NEXTVAL
Sql> /
NEXTVAL
NEXTVAL CURRVAL
3 3
NOTE:
Sequence alter
Sql> alter sequence s2
Start with 4
Maxvalue 10;
ERROR: cannot alter starting sequence number
NOTE:
Whenever we decrement the sequence we cannot instantiate below minimum value and
also start with cannot be less minimum value.
Start with 3
Increment by 1
Minvalue 5
Maxvalue 10;
When we are defined cycle whenever reach value max value next values start with
starting value.
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
10
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
Sql> /
NEXTVAL
S2 1 10 -1 N N 20 0
S1 1 15 2 N N 20 17
S3 6 10 1 N N 0 11
S4 6 8 1 Y N 0 7
CACHE/NOCACHE:
Cache is an optional clause used in sequence we access sequence number very fastly i.e
whenever we defined sequence if we want access then we run set of sequence value in cache
memory then only application access sequence values from cache not from the disk that why
cache is memory area which stores set of sequence and improve performance that why cache
value by defined by database administrators.
NOTE:
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 132
SQL MATERIAL
In oracle by default cache value is 20 and also cache minimum value is 2. Whenever
system caches then automatically generates because cache is a memory area whenever system
crush cache values are lost.
NOTE:
Whenever we are defining cache value that is less than one cycle when we are defining
cycle option otherwise oracle server returns on error to overcome this problem we can also use
no cache when no cache when we are defining cycle option. We must create primary key column
otherwise not properly inserted data and duplicate value inserting.
Chapter -12
NORMALIZATION
Normalization process automatically avoids insert, delete and update problems. In design
place of the SDLC(Software Development Life Cycle) database designers design logical model
of the database. In these logical model only database designer uses normalization process
through normal forms.
In 1970 E.F CODD had written a paper “Relational Model Of Data For Shared Data
Banks” in this paper only E.F CODD introduced first three normal forms.
Normal Forms:
Identified repeating groups and putting into separate table in more atomic forms by
default 1NF process table is an child table because here one column having duplicate data.
Electronic Shop
Order no:
Order date:
Order Customer Customer
Order no
date Address phone
Customer name:
1 - - -
Customer Not In 1NF address: Candidate Key 1NF
Customer phone:
Led
A/C
√ Add another item
Amount:
SUBMIT
A table is a 1NF and also all non-key attribute fully functionally dependent total
candidate key.
Generally 1NF deals with atomicity where as 2NF deals with relationship b/w key,non-
key attribute. When a table is in 1NF and also table contain partial non-key attribute then that
table not in 2NF.
Process:
Identified partial non-key attributes which depends on partially key attributes putting into
separate table these are called as “2NF”. In these tables only all attribute fully dependency. By
default this is on master table.
Project table: p p
8
2. fd 3. fd
Projcode hours ( ) ecode+Projcode hours ( √ )
5
P1
3
Phase-2:- fd fd
System
E101----systems p1 Sales
Phase-3:-
1. Ecode dept ( √ ) 2. Projcode dept ( )
Before normalization process above resource table having insertion, deletion, updation
problems occurred.
Insertion problem:
In the above resource table we cannot insert particular dept emp’s then we must assigning
a projects this is called as “Insertion Problem”.
Updation problem:
In the above resource table Ecode,Dept,Depthead attribute values are repeated. Whenever
on employee transferred one dept to another dept all this three attributes value modified currently
otherwise inconsistency problems occurred this called as “Updation Problem”.
Deletion problem:
In the resource table when we are tried to delete particular emp automatically dept delete
also delete this is called as “Deletion Problem”.
All this problems are automatically inserting,deleting,updating avoided then we are using
normalization process.
Order form:
Order no: PK
Cust address:
Cust phone:
Amount:
SUBMIT
Repository items
Frontend application
Item no:
Item name:
Amount:
Order details table
OK FK FK
Order Item
Quantity Discount
PK Item no Item name amount no no
1
111 LED 30000 1
112 A/C 20000 1
1
If a table in 2NF and also all non-key attributes only dependent on candidate key (or)
primary key. If non-key attributes which depends on another non-key attributes then that table
not in 3NF.
Process:
Identified non-key attributes which depends on another non-key attributes putting into
separate table this is called as “3NF Table”. By default this is an master table in this table only
all non-key attributes only dependent on Candidate key (or) Primary key.
Not in 3NF
Candidate key (not in 2NF) non-key attribute PK 2NF Master table
1NF P P
Item
Item name color price tax color Item no Price tax
no
Master black 20 0.2
2NF
Master red 20 0.2
PK 3NF
PK
Order form:
Order no:
Order date: PK
Cust address:
Cust phone:
A/C
Quantity Discount
SUBMIT
Cust phone:
OK
Functional Dependency:
If any given two tuples in a relation r then if then x(on attribute set) agrees then y(another
attribute set) cannot agrees the x->y is called as “Functional Dependency”.
Candidate key (not in 3NF) non-key attribute child table 3NF master table
Student table 2NF table PK FK PK
Curse Grade Curse Grade
Sname Grade Sname Grade Grade
id value id value
Aaa Cs111 A 4.00 Aaa Cs111 A A 4.00
Bbb Cs111 B 3.00 Bbb Cs111 B
B 3.00
Ccc Cs112 C 2.00 Ccc Cs112 C
Ddd Cs112 A 4.00 C 2.00
Ddd Cs112 A
Logical Diagram:
Grade value
Sname
Grade
Course id
(or)
√Sno
√Sno
Last attendance
CLUSTER:
Cluster is a database object which contains no.of tables together and also tables share
same data block. Clusters are created by database administrator. Clusters are used to improve
performance of JOINED query.
Cluster tables are created based on a common columnname this common columnname is
called as “Cluster key”. Clusters are created at the time of table creation only table create
complete after cluster creation not possible. In those table are available in cluster then database
server very fastly retrieve data from cluster table. In cluster rowid’s are same.
Step-1(creating a cluster):
Syntax: create cluster clustername (commoncolumnname datatype(size));
Sql> /
Enter value for deptno: 20
Sql> select * from c1;
30 REDDY INDIA
10 NARASIMHA YSR
20 SIMHA AP
ROWID
AAAD0AAAEAAAAHEAAA
AAAD0AAAEAAAAHHAAA
AAAD0AAAEAAAAHIAAA
ROWID
AAAD0AAAEAAAAHEAAA
AAAD0AAAEAAAAHHAAA
AAAD0AAAEAAAAHIAAA
We cannot drop cluster if cluster having tables to overcome this problem oracle 8i
introduced INCLUDING TABLES clause to drop cluster along with table.
Super key:
Candidate key:
(or)
Minimal super key is called “candidate key”. That is a super key does not subset of a
super key.
Primary key:
The PRIMARY KEY constraint uniquely identifies each record in a database table.
Primary keys must contain unique values. A primary key column cannot contain NULL values.
If any one of the candidate key which uniquely identified record in a table.
Foreign key:
A foreign key is a key used to link two tables together. This is sometimes called a
referencing key. Foreign Key is a column or a combination of columns whose values match a
Primary Key in a different table. You can create a foreign key by defining a FOREIGN KEY
constraint when you create or modify a table.
Alternate key:
Other than primary key, candidate key which uniquely identified those keys are “alternate
key”.
Super key:
Candidate key:
Primary key:
1. empno+skill ------------- pk
Alternate key:
1. ename+skill
2. skill+voter id
A table is in BCNF the every determinate is a candidate key when a table contain
multiple candidate keys.
When a table contain multiple candidate key and also candidate key are overlap and also
one candidate keys non-key attribute which depends on another candidate key non-key attribute
then only process BCNF process.
If a table contain single candidate key the BCNF is also same as 3NF when a table
contain more than one candidate key then deletion problem occurred to overcome this problem
we are using BCNF process. BCNF specifies relationship between candidate key it self.
Identifies one candidate key non-key attributes which depends on another candidate key
attributes non-key attributes then putted those entire attributes separate table this table is called
as “BCNF”. In this table only every determinate is a candidate key.
FD
2.Ename Ecode
Determinate ck
P1 Computers Simha 7
P2 Chemistry Reddy 9
P3 Zoology Shobha 8
P4 Botany Rani 10
BCNF
Dept Hod Projcode Dept Hours
Physics Narasimha P1 Physics 5
Computer Simha P1 Computer 7
chemistry Reddy P2 Chemistry 9
Zoology Shobha P3 Zoology 8
Botany Rani P4 Botany 10
FD
1. projcode+dept dept
FD
FD
1. Dept Hod
Determinate
2. projectcode+dept Hours ck FD
2. Hod dept
Determinate ck
If a table is in 4NF then that table does not contain more than one independent multi
valued attribute.
If a table contains more than two attribute and also identifying a record uniquely
combination attributes and also that table does contain and also one attribute set of values depend
on another attribute set of value and also same attribute set of value which depend on another
attribute set of values and also some attribute are not logically related then only database
designers uses 4NF process.
Process:
Identifies attributes which dependence on another attribute those attributes putted into
another table this table is called as “4NF table”. This table does not contain more than one
independent multi valued attribute. These tables automatically reduce redundancy.
Movie table
Candidate key
Movie Star Producer Movie Star Movie Producer
M1 S1 P1
M1 S2 P1
M1 S3 P1
M1 S4 P2
M1 S5 P2
M2 S6 P3
M2 S3 P3
M2 S2 P3
Before 4NF process in the down table whenever on get a new project then we have to
supply null values for the skill and also whenever having new skill we have to supply null values
for the project id. Whenever we are using 4NF process this problems are avoided.
Assumption:
Each employee has multiple projects and also each employee has multiple skills.
Project table
Candidate key
A table is in 5NF then that table does not contain cyclic dependency. If a table contain s
more than two attribute and also identified record uniquely using combination of all attribute and
also all attribute set of values related to one another then only using 5NF.
Generally in 4NF some attributes are not logical related where as in 5NF all attribute are
related. 5NF is also called as “Projection-join normal form”.
In this normal form we are splitting a table into no.of tables and also when we are joining
these tables resultant record must be available on resource table.
B1 Shirt Levis
B1 Jeans Arrow
B1 Shirts Peeps
Chapter-13
CONVERSIONS
Set operators:
Set operators are used to retrieve data from single (or) multiple tables. This operator is
also called as “Vertical joins”.
CLERK
MANAGER
PRESIDENT
RESEARCH
ANALYST
CLERK
MANAGER
PRESIDENT
NOTE:
In all database we are using set operators always corresponding expression must belong
to same datatype and also set operator returns first query columnname as column heading’s.
union
union
ENAME
ACCOUNTING
ADAMS
-----------
WARD
18 rows selected.
NOTE:
In oracle we can also retrieve data using set operators if corresponding expressions not
belongs to same datatype also in this case we must use corresponding type conversion function.
DEPTNO DEPTNAME
10
20
30
ACCOUNTING
GNSR
OPERATIONS
RESEARCH
10 wwwww
20 wwwww
30 wwwww
99 ACCOUNTING
99 GNSR
99 OPERATIONS
99 RESEARCH
CONVERSIONS:
2. Explicit Conversion
1. Implicit Conversion:
NOTE-1: When a sql expression contains a string representing pure numeric values then
oracle server automatically convert into string type into number type.
SAL+'100'
900
1700
--------
NOTE-2:
Whenever we are passing number into character function then oracle server internally
uses implicit conversion to convert number type into string type.
LENGTH (111)
LENGTH ('ABCD')
NOTE-3:
Whenever we are passing date string into data function then oracle server automatically
converts date string into date type but here passed parameter must be default date (number-
character-number) format.
LAST_DAY (
04-SEP-05
Implicit conversion
2. Explicit Conversion:
To_number () to_date ()
To_char () to_char ()
1. To_number()
2. To_char()
3. To_date()
1. To_number():
It is used to converting a string representing a numeric value with format into a numeric
value without format.
TO_NUMBER ('$24.6','$99.9') +3
27.6
NOTE: Only format models working otherwise your own way given not working.
2. To_char():
This is an overloading function which is used to convert number type into char type and
also date type into date string.
TO_CHAR(20
20,000.00
TO_CHAR(20
20,000.00
TO_CHAR(123456.78
$1,23,456.78
TO_CHA
######
TO_CHAR
20,000
SMITH $800
ALLEN $1,600
---------- ----------
NOTE:
By default oracle server returns local currency ‘$’ if you want return our own currency
format we are using ‘NLS_CURRENCY’ format in third format of the to_char function.
NOTE:
If we want add leading zero’s then we must use zero in the format. If we want add last
only zero’s then we are using 9 in the format.
NOTE:
If we want to display number datatype values into char format then we are using to_char
with format value.
Sql> select to_char(sysdate,'dd/mm/yyyy') from dual;
TO_CHAR(SY
18/09/2014
3. To_date():
It is used to convert date string into date type.
Sql> select to_date('12/sep/14') from dual;
TO_DATE('
12-SEP-14
NOTE:
Whenever we are using to_date passed parameter return value match with the default date
datatype return value otherwise oracle server returns an error to overcome this problem use a one
parameter formation.
NOTE:
Whenever we ar5e passing date string into date function then oracle server automatically
convert into date string into date type. But in this case passed parameter format number-
character-number otherwise use in to_date() function explicit.
LAST_DAY(
31-JAN-06
Sql> select last_day(to_date(‘11/03/06’,’DD/MM/YY’)) from dual;
LAST_DAY(
31-MAR-06
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 160
SQL MATERIAL
DECODE:
Decode is a conversion function which is used to convert one type into type. Decode
internally used equality (=) operator. It is also called same as if-----then-----elseif construct.
Syntax: decode(colname,value1,stmt1,value2,stmt2,……………stmtN)
SMITH 20 twenty
ALLEN 30 other
WARD 30 other
JONES 20 twenty
MARTIN 30 other
we can also use decode function to display row values into column values.
Sql> select job,sum(decode(deptno,10,sal)) “deptno 10”,sum(decode(deptno,20,sal))
“deptno 20” ,sum(decode(deptno,30,sal)) “deptno 30” from emp group by
job;
SALESMAN 5600
PRESIDENT 5000
ANALYST 6000
Sum(decode(job,’SALESMAN’,1,0)) “SALESMAN”,
Sum(decode(job,’MANAGER’,1,0)) “MANAGER”,
Sum(decode(job,’ANALYST’,1,0)) “ANALYST”,
Sum(decode(job,’PRESIDENT’,1,0)) “PRESIDENT”
ACCOUNTING 1 0 1 0 1
RESEARCH 2 0 1 2 0
SALES 1 4 1 0 0
ACCOUNTING 1 0 1 0 1
OPERATIONS 0 0 0 0 0
RESEARCH 2 0 1 2 0
SALES 1 4 1 0 0
NOTE:
We can also use decode function in update statement for modifying data conditionally.
Q) Write a query to modifying commission column data of employee from emp table based
on following condition?
2. if job=’SALESMAN’ then comm ---- 20% of sal and all other job’s
comm ------- 30% of sal
NOTE:
If we want count different values from a columns then we are using decode function
within group by clause. Whenever we are using decode function within group by clause then
automatically rows values convert into column values.
SALESMAN 5600
PRESIDENT 5000
ANALYST 6000
CASE STATEMENT:
Oracle 8.0 introduced CASE statement and also 8i introduced case conditional stmt. Case
is a statement which is used to decoding the values case stmt is performance very high compare
to decode function.
Case
When colcondition1 then stmt1
When colcondition2 then stmt2
----------------------------------------
Else stmt end
Chapter-14
SYNONYMS
Synonym is a database object. Synonym is an reference (or) aliasname for the original
object. Synonyms is an guide another designer,username,object name,database link synonym
provides security for another object. Synonyms are two types.
1. Public Synonyms
2. Private Synonyms
By default synonyms are private synonyms. If we want to create public synonyms then
we are using “create public synonym privileges”.
Sql>grant all on emp sql>select * from scott.emp; (√) sql>select * from scott.emp; (√)
To Simha,reddy;
Scott.emp;
For scott.emp;
to Simha;
Sql>conn Simha/Simha;
For scott.emp;
Chapter-15
TCL (Transaction Control Language)
Transaction:
It is a logical unit of work in between two points Oracle having two transaction
commands.
1. Commit
2. Savepoint
1. Commit:
This command is used to save the transaction permanently hard disk.
Syntax: COMMIT
2. Savepoint:
Syntax: SAVEPOINT
999
999
8
Sql> insert into test values(&sno);
Enter value for sno: 9
Enter value for sno: 10
Sql> delete from test where sno=10;
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 169
SQL MATERIAL
999
999
999
Chapter-16
1. Storage Area
2. Instance
1. Storage Area:
Whenever we are installing oracle server automatically three files are created in a hard
disk. These three files are also called as ‘Physical Database’. This files are stored ‘Physical
Storage Area’.
User name: N
SGA
Password: S
Database Library cache Java Large Redo log
OK T
buffer pool pool buffer
A cache Dictionary
cache
N
User
process C
Groups Member
G.NARASIMHA REDDY (B.Tech) ph no: 9014909280 Page 171
SQL MATERIAL
Data files stores database objects physically that is file stores index, procedures, tables,
function, …………….etc. Data files also rollback segment in log onwards this segment’s also
called as “Undo Segment”. All data files information stored under DBA_DATA_FILE data
dictionary. If you want view path of the data file then we are using FILE_NAME property from
DBA_DATA_FILE data dictionary;
FILE_NAME
C:\ORACLEXE\ORADATA\XE\USERS.DBF
C:\ORACLEXE\ORADATA\XE\SYSAUX.DBF
C:\ORACLEXE\ORADATA\XE\UNDO.DBF
C:\ORACLEXE\ORADATA\XE\SYSTEM.DBF
CONTROL FILES:
Control files controls all other files in storage area this file extension is .ctl. Oracle 9i
introduced minimum three control files in storage area control files also stores database. All
control files information stores under V$CONTROLFILE data dictionary. Control files are used
by database administrator in recovery process.
C:\ORACLEXE\ORADATA\XE\CONTROL2.DBF
C:\ORACLEXE\ORADATA\XE\CONTROL3.DBF
Redo log file store committed information redo log buffer. This files also used by
database administrator. In recovery process all files information log file stored under
V$LOGFILE data dictionary.
If we want view path of the log file then we are using MEMBER property from
V$LOGFILE data dictionary.
MEMBER
C:\ORACLEXE\APP\ORACLE\FLASH_RECOVERY_AREA\XE\ONLINELOG\O1_MF_2_9VHP6GDM_.LOG
C:\ORACLEXE\APP\ORACLE\FLASH_RECOVERY_AREA\XE\ONLINELOG\O1_MF_1_9VHP6DQX_.LOG
2. INSTANCE:
Whenever we are connect into the server using a client oracle server automatically on
instance created in memory area this instance having two parts.
1. SGA
2. PGA
SGA:
SGA is also called as System Global Area (or) Shared Global Area. SGA consists of set
buffer these buffers are
Whenever we are subheading SQL, PL/SQL codes into the database server that code
store in library cache within shared pool library cache. Always reduces passing that is library
cache checks syntax and semantic checking of the SQL, PL/SQL code. Whenever user
requesting data from the table oracle server process checks request table available in database
buffer cache (or) Not If request object is not available in database buffer cache the DBWR
process checks request table available in data files. When it is available then copy of the table
created in database buffer cache.
Oracle server
SGA
11111111111111
11111111111111 User
11111111111111
11111111111111
Data files
Emp
Whenever we are subheading update, delete stmt those transaction are performing redo
log buffer that is redo log of buffer copy of the table from database buffer cache after
modification whenever we are using commit,rollback those values are stored in data files,redo
log files and also redo log changes effected in database buffer cache.
Redo
SGA
Database buffer cache Redo log buffer
101010101010 101010101010
101010101010 101010101010
101010101010 101010101010
101010101010 101010101010
User
101010101010 101010101010
101010101010 101010101010
Update
DBWR Log wr
Delete
Sql> commit
Library cache also stores cache value defined in sequence object. Shared pool also
contains dictionary cache which executed DCL related data dictionary property. Java pool
executes java related object and also large pool used by database administrator in recovery
process. Server process also contains PGA which uniquely identifies each client connect to the
server. Whenever we are using DML transaction new values for the transaction also stored in
redo log buffer this values are also called as “ONOFF”. Whenever user using commit (or) 1/3 fill
of redo log buffer then automatically redo log buffer data transfer into redo log files this files are
used by database administrator in recovery process.
Buffer cache
Undo file
T1
Update 1
1 5
Redo log
Delete
2
files
Commit 3
Data files
Hard disk
Whenever we are using DML transaction old data stored in undo area within database
buffer cache and also new data stored in dirty reader within database buffer cache whenever user
using commit automatically new data permanently stored in data files and also old data stored in
undo files within hard disk. This undo file used in FLASHBACK query. Flashback query are
used by database administrator content of a table can be query based on a specific point of time.
Oracle 9i introduced flashback query to retrieve accidental data after commit transaction also.
1. Physical Structure
2. Logical Structure
3. Logical Storage Structure
1. Physical Structure:
Physical structure handle database administrator only. Physical structure contain these are
data files, control files, redo log files. This structure is visible in the operating system.
2. Logical structure:
Logical structure not visible to the operating system this structure contains database
object like Tables, Views, Index, Sequence, Procedure, Trigger, Function, Package,…………etc.
These structures handle by either Developer (or) Administrator.
1. Tablespace
2. Segment
3. Extent
4. Block
Tablespace:
Generally without starting database also we are viewing physical structure of the
database. Whereas whenever starting database then only we doing logical storage structure.
Tablespace is nothing but collection of data files. One data file belongs to one tablespace only.
Whenever we are installing oracle server automatically SIX tablespace are created. If you want
run oracle minimum TWO tablespace are required. These are SYSAUX tablespace, SYSTEM
tablespace. System tablespace contains metadata that is system tablespace all data dictionary.
Database administrator also creating tablespace explicitly uses.
USERS C:\ORACLEXE\ORADATA\XE\USERS.DBF
SYSAUX C:\ORACLEXE\ORADATA\XE\SYSAUX.DBF
UNDO C:\ORACLEXE\ORADATA\XE\UNDO.DBF
SYSTEM C:\ORACLEXE\ORADATA\XE\SYSTEM.DBF
C:\ORACLEXE\ORADATA\XE\USERS.DBF
Oracle Database
Extent 2
Segment1 Segment2
------------- --------------
------------- --------------
-------------- -------------
-------------- --------------
Segment1 Segment2
. .
Dictionary
2 bbb
Data
Tablespace Blocks
Segment is an collection of extents that forms a database object likes tables, views, index,
…………..etc.
LOCKS
Locks are a mechanism which prevents unauthorized access for our resources. All
database systems having two types lock.
Oracle 6.0 introduced row level lock. In this method we are locking set of rows using for
update clause. This clause used in select statement only using locks only that perform use DML
statement not using another user.
Whenever we are forming lock another user query the data but they cannot perform DML
operation. Whenever we are use COMMIT, ROLLBACK when lock are release.
Scott/tiger Simha/simha
where deptno=10;
NOWAIT:
Nowait is a optional clause is used in FOR UPDATE clause. Wherever we are using this
clause oracle server automatic get control into current user if another user not releasing lock in
this case oracle server returns an ERROR: ora-0054: Resource busy.
Scott/tiger Simha/simha
Sql> /
NOTE:
In all database whenever we are using DML statement automatically database server
internally uses exclusive lock. Wherever we are using COMMIT,ROLLBACK then only these
lock are released.
In this method we are locking a table. These are 2 types of table level lock using by
database developer.
1. Share Lock
2. Exclusive Lock
1. Share Lock:
Whenever we are using this lock another uses query the data but they cannot perform
DML operations and also at a time no.of user lock resource.
Scott/tiger Simha/simha
Sql> lock table emp in share mode; Sql> select * from scott.emp; ( √ )
2. Exclusive Lock:
Whenever we are using this lock another user query the data but we cannot perform DML
operations and also at a time only one user lock the resource.
Scott/tiger Simha/simha
Sql> lock table emp in exclusive mode; Sql> select * from scott.emp; ( √ )
NOTE:
In all database procedure language when we are using cursor locking mechanism
internally database server uses exclusive lock.
DEADLOCK:
In oracle whenever we are try to perform same operation in a single resource through
different session then automatically deadlock occurred. In this case oracle server returns an
ERROR: ora-0060: Deadlock detected while waiting for resource.
Scott/tiger Simha/simha
Sql> update emp set sal=sal+100 Sql> update emp set sal=sal+100 where deptno=20;
where deptno=20;
Chapter-17
TABLES
Global Temporary Tables (GTT):
Global Temporary Tables stores data temporary that is these table data stored in RAM
memory area. These tables are used by database administrator to process data very fastly
retrieve. Oracle having 2 type of global temporary table
1. Transaction Specific
2. Session Specific
1. Transaction Specific:
In this type of GTT stores data until we are using commit (or) rollback.
Sql> create global temporary table GTT(sno number(5)) on commit delete rows;
Sql> insert into GTT values(1);
Sql> insert into GTT values(2);
Sql> insert into GTT values(3);
Sql> select * from gtt;
SNO
Sql> commit;
Sql> select * from gtt;
No Rows Selected
2. Session Specific:
This Global Temporary Tables data available in particular sessions if we are giving
commit also another session cannot view that data.
Session-1:
Sql>create global temporary table GTT(sno number(5)) on commit preserve rows;
Sql> insert into GTT values(1);
Sql> insert into GTT values(2);
Sql> insert into GTT values(3);
Sql> select * from gtt;
SNO
Sql> commit;
Sql> select * from gtt;
SNO
Session-2:
No Rows Selected
NESTED TABLE:
Oracle 8.0 introduced nested table. Table within another table is called as “Nested
Table”. Nested table is a userdefined table. This is used to multiple data store in a single unit.
Generally in oracle if we want to store no.of data items then we are using index by table in
PL/SQL. But these tables not allowed to stores this table permanently in database. To overcome
this problem oracle 8.0 introduced extension of the index by table called as “Nested Table”. This
is used to store no.of data items permanently in database using SQL.
COL3 FAN
If we want to insert data into nested table columns then we must using constructor. Here
constructor name is same as typename.
FAN(nt1(101,'JAVA',500),nt1(102,'ORACLE',3000)));
1 NARASIMHA FAN (NT1 (101, 'JAVA', 500), NT1 (102, 'ORACLE', 3000))
If we want to view nested table data then we are using table operator.
from user_types;
FAN 0 0 NO
NT1 3 0 NO
PARTITIONS:
Table can be separation into number of tables is called ‘Partition’. Partitions table are
created by database performance of the application. These tables are used in backup and
recovery process. Generally partitions table created when database table having large amount of
data partition are created based on a column this is called ‘Partition Key’.
1. Range Partition
2. List Partition
3. Hash Partition
1. Range Partition:
If we want view partition then we are using following syntax. This method created based
on range of values.
--------------------------------------------------------------------------------
2. List Partition:
Oracle 9i introduced list partition. Using this partition we can also create partition based
character datatype columns. Database administrator creates on list of values.
Partition by list(name)
(partition p1 values(‘india’,’pak’),
Partition p2 values(‘usa’,’usk’),
3. Hash Partition:
In this method partition when we are specified partition number then automatically
created oracle server based on hash partition.
HIERARCHICAL QUERIES:
1. Start With
2. Connect By
3. Level
1. Start with:
2. Connect by:
This clause is used to specify relationship between hierarchical (Parent, Child) column
using prior operator.
3. Level:
Oracle provided LEVEL pseudo column. In hierarchical is pseudo column which assign
numbers to each level in tree structure.
Q) Write hierarchical query to display then employee’s who are working under KING
from emp table using hierarchy?
Sql> select level,ename from emp start with ename=’KING’ connect by prior empno=mgr;
LEVEL ENAME
1 KING
2 JONES
3 SCOTT
4 ADAMS
3 FORD
--- --------
(Or)
Sql> select level,lpad(' ',level*2)||ename from emp start with ename=’KING’
1 KING
2 JONES
3 SCOTT
4 ADAMS
3 FORD
4 SMITH
2 BLAKE
3 ALLEN
3 WARD
3 MARTIN
3 TURNER
3 JAMES
2 CLARK
3 MILLER
KING
ADAMS SMITH
NOTE:
Syntax: SYS_CONNECT_BY_PATH(columnname,’delimitername’)
1 --->KING
2 --->KING--->JONES
3 --->KING--->JONES--->SCOTT
4 --->KING--->JONES--->SCOTT--->ADAMS
3 --->KING--->JONES--->FORD
4 --->KING--->JONES--->FORD--->SMITH
2 --->KING--->BLAKE
3 --->KING--->BLAKE--->ALLEN
3 --->KING--->BLAKE--->WARD
3 --->KING--->BLAKE--->MARTIN
3 --->KING--->BLAKE--->TURNER
3 --->KING--->BLAKE--->JAMES
2 --->KING--->CLARK
3 --->KING--->CLARK--->MILLER
Q) Write a query to display the emp’s who are working under BLAKE from emp table
using hierarchy?
1 --->BLAKE
2 --->BLAKE--->ALLEN
2 --->BLAKE--->WARD
2 --->BLAKE--->MARTIN
2 --->BLAKE--->TURNER
2 --->BLAKE--->JAMES
1 --->MILLER
2 --->MILLER--->CLARK
3 --->MILLER--->CLARK--->KING
NOTE:
Prior is a unary operator which specifies parent column i.e oracle server searching data.
NOTE:
Sql> select level,ename,connect_by_isleaf from emp start with mgr is null connect by
prior empno=mgr;
1 KING 0
2 JONES 0
3 SCOTT 0
4 ADAMS 1
3 FORD 0
4 SMITH 1
NOTE:
Oracle 10g introduced CONNECT_BY_ROOT operator which returns root node in the
hierarchy.
1 KING KING
2 JONES KING
3 SCOTT KING
4 ADAMS KING
3 FORD KING
NVL():
Nvl() is predefined function which is to replace userdefined function in place of null.
Syntax: NVL(exp1,exp2)
If expression1 is null then its return expression2 otherwise its returns expression1.
NVL2():
Syntax: NVL2(exp1,exp2,exp3)
If exp1 is null then its returns exp3 otherwise its returns exp2.
60
30
Q) Write a query to update emp’s based following condition using NVL2() function?
COALESCE():
Coalesce() is an ASCII function which return first not null value in the given expression
coalesce() no.of expression.
Syntax: coalesce(exp1,exp2,……………..)
COALESCE(NULL,NULL,10,NULL,30)
10
COALESCE(NULL,30,NULL,10,NULL,50)
30
COALESCE(40,30,NULL,10,NULL,50)
40
Nvl() internally uses implicit conversion. Whereas coalesce() does not uses implicit
conversion and also coalesce() performance very high compare to nvl().
NVL ('A',S
A
Sql> select coalesce('A',sysdate) from dual;
ROLLBACK:
Rollback is nothing but undo from query in oracle when ever using rollback oracle server
automatically past undo area into dirty reader within buffer cache.
Syntax: rollback;
FLASHBACK QUERY:
Flashback query are handle by administrator using flashback query then we are retrieving
accidental data flashback query works based on undo file to retrieve data using flashback query
following two methods.
1. Using Timestamp:
100 simha
101 narasimha
102 reddy
Sql> commit;
Sql> insert into test values(11,'shobha');
Sql> select * from test;
SNO NAME
100 simha
101 narasimha
102 reddy
104 shobha
Sql> commit;
Sql> delete from test;
Sql> select * from test;
No Rows Selected
Sql> select * from test as of timestamp(systimestamp-interval '2' minute);
SNO NAME
100 simha
101 narasimha
102 reddy
104 shobha
2. Using SCN:
To retrieve data:
CURRENT_SCN
6048901
Sql> insert into ABC values(50);
Sql> select * from ABC;
SNO
50
Sql> select count(*) from ABC;
COUNT (*)
1
Sql> select count(*) from abc as of scn 6048901;
COUNT (*)
0