Professional Documents
Culture Documents
1
CONFIDENTIAL
CONTENTS
Introduction to DBMS CODD rules SQL * PLUS COMMANDS SQL
Sub Languages Operators Functions Constraints Group by, order by and having clauses Data base objects Data dictionary in Oracle Creating users Joins Sub queries
PL/SQL
ANONYMOUS BLOCKS Cursors Triggers Procedures Functions Packages
2
CONFIDENTIAL
CMC Limited
Day 2
CMC Limited
3
CONFIDENTIAL
BASICS
Data
It is a collection of raw facts and figures
In order to use the data, the data needs to be preserved or stored in a definite location for every piece of data has an objective and a purpose Storage areas
Pen drive Floppy CD ROM drive Manual storage
Data base
Place holder for storing the data to overcome the flaws with respect to data storage in the above mentioned areas In order to store data in a data base, we need to define a data structure
Files Tables
CMC Limited
4
CONFIDENTIAL
Data is in secured
Data base will be dependent on the programming logic
CMC Limited
5
CONFIDENTIAL
CMC Limited
6
CONFIDENTIAL
Codd rules
In order to qualify a data base as RDBMS it needs to satisfy or comply with come standards referred to as codd rules No of codd rules : 12
CMC Limited
7
CONFIDENTIAL
12 Rules of Codd
1. 2. 3. 4. 5. 6. Information rule Guaranteed access rule Systematic representation of null values Active online catalog based on relational model Data sub language rule High level insert,update and delete
7.
8. 9.
CMC Limited
8
CONFIDENTIAL
Information rule
Each and every data item must be physically represented or stored in the form of rows and columns in a table
CMC Limited
9
CONFIDENTIAL
CMC Limited
10
CONFIDENTIAL
CMC Limited
12
CONFIDENTIAL
All_synonyms
User_synonyms
CMC Limited
13
CONFIDENTIAL
CMC Limited
14
CONFIDENTIAL
SQL
15
CMC Limited
CONFIDENTIAL
CMC Limited
16
CONFIDENTIAL
CMC Limited
17
CONFIDENTIAL
Logical data independence Application logic must be independent of data base ie changes made to a application logic must not effect the data base
CMC Limited
18
CONFIDENTIAL
Distribution rule
Data base must be distributed on a network
CMC Limited
19
CONFIDENTIAL
Default
Foreign key
Not null
20
CONFIDENTIAL
CMC Limited
Cl scr L
RUN
Display and execute the previous SQL command
CMC Limited
21
CONFIDENTIAL
CMC Limited
22
CONFIDENTIAL
DESCRIPTION
SQL is a non procedural query language devised by IBM in the year 1970 for implementing their DB product by name DB2
Using SQL queries, we cannot create a procedure or a function They are not storable in a data dictionary
SQL is a universally acceptable standard for implementing any proprietary data base
Oracle SQL server SYBASE FOX PRO MY SQL
CMC Limited
23
CONFIDENTIAL
SUB LANGUAGES
DATA definition language(defines a data structure)
Create Alter Truncate Drop
CMC Limited
24
CONFIDENTIAL
Create
Create table <table name> (<col> <data type>)
Eg
create table stud(sno number, sname char(10));
CMC Limited
25
CONFIDENTIAL
Alter
Modify the data type of a column
Alter table <table name> modify (<col> <data type>); alter table stud modify(sno varchar2(10));
You can increase the size of the column if the table is empty and containing data and you can decrease the size of the column if the table is empty and the data which was previously inserted is in compliance with the decreased size of the column
Add a column
alter table stud add(city varchar2(10))
Delete a column
alter table stud drop column sname alter table stud drop (sno,age)
Rename a column
alter table stud rename column city to state
CMC Limited
26
CONFIDENTIAL
Data types
Number([<size>]) Number(precision ,scale) Date Timestamp Char(<size>) Varchar2(<size>) Blob Bfile Clob
CMC Limited
27
CONFIDENTIAL
Insert
CMC Limited
28
CONFIDENTIAL
Contd
Create table at run time
create table &table_name(&col &data_type, &col1 &data_type1)
Truncate
Used for deleting data from the table Truncate table <table name> Eg
Drop
Drop table <table name>;
CMC Limited
29
CONFIDENTIAL
Update
Syntax
Update <table name> set <colname> = <new value> [where <condition>]; Eg
CMC Limited
30
CONFIDENTIAL
CMC Limited
31
CONFIDENTIAL
Performance issue
Prior to deleting the table structure, the data within the table needs to be truncated for drop only deletes the structure but the data within that structure will still reside in the memory which will go un referenced
CMC Limited
32
CONFIDENTIAL
CMC Limited
33
CONFIDENTIAL
DESCRIPTION
SYNTAX
Select <col names> from <table name> [where <condition>] Eg
Select * from emp; Select sal from emp; Select 1 from emp;
CMC Limited
34
CONFIDENTIAL
Contd..
select empno, job from emp where sal <= 1000; select sal from emp where sal >= 1000 and sal <= 2000
CMC Limited
35
CONFIDENTIAL
Sql operators
BETWEEN <min> and <max>
select sal from emp where sal between 1000 and 2000
NOT IN LIKE
SELECT * FROM EMP WHERE ENAME LIKE 'S% select * from emp where ename like '_M%
DISTINCT
select distinct(job) from emp
Is null
select comm from emp where comm is null /
CMC Limited
36
CONFIDENTIAL
Concatenation operator
select ename || ' is a ' || job || ' whose salary is ' || sal || ' from ' ||deptno from emp Eg
SMITH is a CLERK whose salary is 800 from 20
CMC Limited
37
CONFIDENTIAL
CMC Limited
38
CONFIDENTIAL
DESCRIPTION
A function is a sub program which accepts some arguments and returns a value Categories of functions
System defined functions User defined functions
Calling a function
Select function_name(<arguments>) from dual/<table name>;
CMC Limited
39
CONFIDENTIAL
String functions
Date and time functions Conversion functions
Aggregate functions
CMC Limited
40
CONFIDENTIAL
NUMERIC FUNCTIONS
Function Ceil(arg1) Floor(arg1) Description Returns succeeding integer value Returns the preceding integer value Rounds the decimal to the nearest integer value(ie 0.5 scale is taken as a standard) This will truncate the decimal places and returns the integral part Returns the power of a number Syntax select ceil(0.1) from dept select floor(-0.1) from emp
Round(arg1)
Trunc(arg1)
Power(arg1,arg2)
Sqrt(arg1) Sin.,cos,tan(arg1)
CMC Limited
41
CONFIDENTIAL
String Functions
Function Lower(arg1) Description Display data in lower case Syntax select lower(ename) from emp
Upper(arg1)
Initcap(arg1)
Substr(a1,a2,a3)
A1 string, a2 starting position of the string, a3 no of characters to be extracted including start position Combines 2 string objects
Concat(arg1,arg2) lpad
CMC Limited
42
CONFIDENTIAL
Arg1 string object/col name Arg2 no of characters to be added from the left hand side + the existing no of characters Arg3 characters to be added Arg1 string object/col name Arg2 no of characters to be added from the right hand side + the existing no of characters Arg3 characters to be added
Ltrim(arg1, arg2)
Rtrim(arg1, arg2)
CMC Limited
43
CONFIDENTIAL
CMC Limited
44
CONFIDENTIAL
Translate
No of characters to be replaced = no of new characters
CMC Limited
45
CONFIDENTIAL
Add_months(arg1,arg2)
Next_day(arg1, arg2)
Last_day(arg1)
Arg1 date
Months_between(arg1, arg2) Current_timestamp Display the current date and time in milli seconds
CMC Limited
46
CONFIDENTIAL
Aggregate functions
Sum Avg Count Min Max Any aggregate function accepts only 1 argument All the aggregate functions are independent of the type of the data to be used as an argument in those functions except for sum and average. Sum and average operate only on numeric type
CMC Limited
47
CONFIDENTIAL
Conversion functions
To_char(arg1,arg2) select to_char(sysdate, 'dd$mon$yy') from emp
Extract To_date(arg1)
CMC Limited
48
CONFIDENTIAL
Group by clause
select deptno, max(sal) from emp group by deptno Note
A column which has been defined in the group by clause need not appear in the select clause. But a column on which a aggregate function has not been invoked must and should appear in the group by clause A group by clause must and should be used in conjunction with an aggregate function in the select clause Where clause cannot be used in conjunction with a group by clause and the replacement would be the having clause Eg
select max(sal) from emp group by deptno having max(sal) > 3000
CMC Limited
49
CONFIDENTIAL
Order by
Display data in a sorted order
Ascending Descending
Syntax
Select <colname> from <table name> order by <col name> asc/desc select * from emp order by comm
CMC Limited
50
CONFIDENTIAL
Constraints
Not null
Unique
Primary key Check
Default
Foreign key
CMC Limited
51
CONFIDENTIAL
Constraint definition and column definition apper at the same place Constraint definition and column definition appear at different places
Table level
CMC Limited
52
CONFIDENTIAL
Not null
Discards entry of null values and permits duplicated entries
create table B(eno number not null)
CMC Limited
53
CONFIDENTIAL
Unique
Discards duplicated entries and permits null values
create table B(eno number unique)
CMC Limited
54
CONFIDENTIAL
Primary key
Unique and not null
Eg
create table d(eno number primary key)
Primary key and unique keys by default impose a unique index on a column in a table Primary key is a unique row identifier
CMC Limited
55
CONFIDENTIAL
Check
create table e(sno number age number check(age >= 18))
CMC Limited
56
CONFIDENTIAL
Default
Create table e(sno number, doj date default sysdate) insert into c values(default);
CMC Limited
57
CONFIDENTIAL
Not null
Unique
Primary key
Default
Check
Not null
No
Yes
Yes
No
Yes
Unique
Yes
No
No
No
Yes
Primary key
Yes
No
No
No
Yes
Default
Yes
Yes
Yes
No
Yes
CMC Limited
59
CONFIDENTIAL
Foreign key
It is a restriction which when imposed is used to validate data with respect to the table relationships Steps for implementing a foreign key
Create master table
CMC Limited
60
CONFIDENTIAL
Adding a constraint
alter table e1 add primary key(eno) Disabling a constraint
ALTER TABLE <TABLE NAME> ENABLE/DISABLE CONSTRAINT TYPE
Rename a constraint
alter table e1 rename constraint e1_nn to e2_nn;
Delete a constraint
alter table e1 drop constraint e2_nn;
CMC Limited
61
CONFIDENTIAL
Views
Synonyms Sequences
Indexes
CMC Limited
62
CONFIDENTIAL
Activities
Create
Retreive
Update Delete
CMC Limited
63
CONFIDENTIAL
Alias name
It is a temporary name through which the column of a table can be accessed Syntax
Select <col name> [as <alias name>] from <table name> select sal "#$%^&*()" from emp
CMC Limited
64
CONFIDENTIAL
Views
View is a virtual table View defintion is storable and not the data from the view Advts
User can access only specific columns of a table Up dations made on a view or on a table have to be reflected on the other data base object
Syntax
Create[or replace] view <view name> as <select statement>;
CMC Limited
65
CONFIDENTIAL
Alias name
CMC Limited
66
CONFIDENTIAL
Contd
View with string functions
create view v2 as select lower(ename) ename_ll from emp
Possibilities
Create a view on a view Create a table on a view
CMC Limited
67
CONFIDENTIAL
Synonyms
What is the difference between alias name and a synonym
Alias name is temporary and used only for display purpose with respect to a specific column in a table Synonym is a permanent name given to a table which is storable in the data dictionary
Syntax
Create synonym <synonym name> for [<user name>] . <table name> create synonym d for emp3
Up dations made on a synonym are reflected on the base table and vice versa
CMC Limited
68
CONFIDENTIAL
POSSIBILITIES
Create a synonym on a view
CMC Limited
69
CONFIDENTIAL
Sequences
It is a data base object which encourages automatic generation of numbers in a table
Syntax
Create sequence <sequence name> [start with <value>] [minvalue <value>] [maxvalue <value>] [increment by <value>][cycle cache <value>];
Attributes of a sequence
Nextval Currval
By default, a sequence object creates a cache memory which stores the values printed/generated by it
CMC Limited
70
CONFIDENTIAL
Contd
Defining the increment value for a sequence Defining cycle cache for a sequence
create sequence d6 start with 100 maxvalue 110 cycle cache 100
Drop a sequence
Drop sequence d10;
CMC Limited
71
CONFIDENTIAL
Sub queries
Display the salary of all the employees who are getting a salary greater than smith Eg
select sal from emp where sal > (select sal from emp where ename = 'SMITH')
Display the details of all the employees who are getting a salary greater than average salary
select * from emp where sal > (select avg(sal) from emp)
CMC Limited
72
CONFIDENTIAL
Joins
It is a concept through which data from multiple tables can be retrieved Joins eliminate a cross product relationship between the tables Joins
Equi join
Retreives data from multiple tables based on the equality condition provided both the tables are related Eg * * * select empno, ename, dname from emp,dept where emp.deptno = dept.deptno select empno, ename, dname,sal from emp,dept where emp.deptno = dept.deptno and sal > 1000
CMC Limited
73
CONFIDENTIAL
Users
Syntax
Create user user name identified by password
Granting privilages
grant resource,connect to tanla;
Removing permissions
revoke resource,connect from tanla;
CMC Limited
74
CONFIDENTIAL
CMC Limited
75
CONFIDENTIAL
CMC Limited
76
CONFIDENTIAL
DESCRIPTION
It is a procedural language used in conjunction with SQL to perform some activities in a data base which are not possible using the normal SQL queries The implementation of PL/SQL specification is very much benificial when compared to SQL with respect to improving the systems performance It reduces the network traffic in a distributed environment The data types of SQL and PL/SQL remain the same PL/SQL specification ensures a logical and physical data independence
CMC Limited
77
CONFIDENTIAL
Contents
Anonymous blocks
Cursors
Functions Procedures
CMC Limited
78
CONFIDENTIAL
ANONYMOUS BLOCK
This block can form a single unit for combining different sets of SQL statements so that call to be made to a data base from an external buffer or location can be only for 1 time accomplishing different types of results This block cannot be permanently stored in the data dictionary and is used only at run time
CMC Limited
79
CONFIDENTIAL
Declare <local variable declarations> Begin <output statements>; <conditional statements>; <loops>; <assignments>; <dml statements>; Exception when <error type> then raise_application_error(<error no> <message>); End;
Output statement Dbms_output.put_line(<message>); The above statement can be operational if the server output is set to an on mode Set server output on
80
CONFIDENTIAL
CMC Limited
Display a message
begin dbms_output.put_line('Exam to be conducted in the last session'); end;
Use the ampersand (&) operator to give any input at run time
CMC Limited
81
CONFIDENTIAL
begin
dbms_output.put_line(sysdate);
end; /
CMC Limited
82
CONFIDENTIAL
declare date1 date; begin date1 := &d1; dbms_output.put_line('The date is ' ||date1); end;
CMC Limited
83
CONFIDENTIAL
COMMENTS
declare date1 date; /* THIS IS A LOCAL VARIABLE */ begin date1 := &d1; dbms_output.put_line('The date is ' ||date1); end; /
CMC Limited
84
CONFIDENTIAL
ADD 2 NUMBERS
DECLARE N1 NUMBER; N2 NUMBER; N3 NUMBER; BEGIN N1 := &NUM1; N2 := &NUM2; N3 := N1+N2; DBMS_OUTPUT.PUT_LINE('THE SUM IS ' ||N3); END; /
CMC Limited
85
CONFIDENTIAL
n1 := &num1; n2 := &num2; if(n1 > n2) then dbms_output.put_line('The biggest number is '|| n1); else dbms_output.put_line('The biggest number is '|| n2); end if;
end;
CMC Limited
86
CONFIDENTIAL
Program
Write an anonymous block which will perform the operations on numbers dependending on the users choice If the choice is 1 then perform addition If choice is 2 then perform subtraction If choice is 3 then perform multiplication Else perform division
CMC Limited
87
CONFIDENTIAL
declare n1 number; n2 number; n3 number; begin n1 := &num1; n2 := &num2; n3 := &num3; if(n1 > n2 and n1 > n3) then dbms_output.put_line('The biggest number is ' ||n1); elsif(n2 > n1 and n2 > n3) then
CMC Limited
88
CONFIDENTIAL
Accept empno at run time and display the name of that employee
declare no number; ge number; begin no := &num1; select age into ge from test where eno = no; dbms_output.put_line(ge); end;
CMC Limited
89
CONFIDENTIAL
Accept the empno at run time and update the salary of that employee by 10%
declare eno emp1.empno%type; sa emp1.sal%type; begin eno := &eno; select sal into sa from emp where empno = eno; sa := sa+(10*sa/100); update emp1 set sal = sa where empno = eno; dbms_output.put_line('The updated salary is '||sa); end; /
CMC Limited
90
CONFIDENTIAL
It is an attribute which when used in conjunction with a variable name signifies that the data type of the column in a table is in compliance with the declared type of the variable in the anonymous block. The advantage of using this attribute is that if any changes are made to the table structure, the same changes are not reflected in the application logic encouraging physical data independence
Into
This operator is used to copy the data from a specific column in a table into the local variable; Syntax * Select <column name> into <output variable name> from <table name> where <column name> = <input variable name>
CMC Limited
91
CONFIDENTIAL
Accept empno at run time and display the name and salary of that employee
declare eno emp.empno%type; name emp.ename%type; sa emp.sal%type; begin eno := &employee_no; select ename,sal into name, sa from emp where empno = eno; dbms_output.put_line(name ||' '|| sa); end;
CMC Limited
92
CONFIDENTIAL
Loop
declare
x number; y number;
begin x := 1; loop y := x*2; insert into test10 values(x,y); x := x+1; exit when x >= 10; end loop; dbms_output.put_line('Insertion sucessful....');
end;
CMC Limited
93
CONFIDENTIAL
For loop
declare x number; y number; begin x := 1; for x in 1..10 loop y := x*2; insert into test10 values(x,y); end loop; dbms_output.put_line('Insertion sucessful....'); end;
CMC Limited
94
CONFIDENTIAL
Requirement
Accept empno at run time and update the salary of an employee :
If he belongs to deptno 10 then update his salary by Rs 100 If he belongs to deptno 20 then update his salary by Rs 200 If he belongs to deptno 30 then update his salary by Rs 300
CMC Limited
95
CONFIDENTIAL
declare eno emp90.empno%type; dno emp90.deptno%type; nsal emp90.sal%type; begin eno := &employee_no; select deptno,sal into dno,nsal where empno = eno; if(dno = 10) then nsal := nsal+100; elsif(dno = 20) then nsal := nsal+200; else nsal := nsal+300; end if; update emp90 set sal = nsal where empno = eno; dbms_output.put_line('Records Updated...'); end;
CMC Limited
96
CONFIDENTIAL
CMC Limited
97
CONFIDENTIAL
If a value is not assigned to any local variable then by default, a null value will be supplied by the system
declare
n number; begin dbms_output.put_line('The value is ' ||n); end; /
CMC Limited
98
CONFIDENTIAL
CMC Limited
99
CONFIDENTIAL
CMC Limited
100
CONFIDENTIAL
REQUIREMENT
Display the names of all the employees from emp table declare name emp.ename%type ;
begin
select ename into name from emp; end;
CMC Limited
101
CONFIDENTIAL
Description
The above code returns an error because into operator can fetch on a maximum basis only 1 row at a time for a particular input given at run time To fetch multiple rows from a table, we need to implement a specification referred to as cursors
CMC Limited
102
CONFIDENTIAL
Contd
Cursor is a private SQL area used for fetching the data from a table row wise ie for every SQL statement issued by the user, by default a cursor will be created for that statement
CMC Limited
103
CONFIDENTIAL
CMC Limited
104
CONFIDENTIAL
begin
open c1; loop fetch c1 into name; exit when c1%notfound; dbms_output.put_line(name); end loop; close c1; end; /
CMC Limited
105
CONFIDENTIAL
CMC Limited
106
CONFIDENTIAL
CMC Limited
107
CONFIDENTIAL
Attributes of cursors
%rowtype
This attribute can be used with cursors if you want to declare a variable which holds data from multiple columns in the same table Syntax
%rowcount
This attribute can be used with cursors to limit the display of data from tables with respect to specific number of rows
%notfound
This attribute when used with cursors determines the availability of data within a cursor
CMC Limited
108
CONFIDENTIAL
CMC Limited
109
CONFIDENTIAL
CMC Limited
110
CONFIDENTIAL
CMC Limited
111
CONFIDENTIAL
function add3(n1 number, n2 number) return number is s number; begin s := n1+n2; return s; end;
CMC Limited
112
CONFIDENTIAL
CMC Limited
113
CONFIDENTIAL
Function that accepts empno as an input and return the name of the employee
create or replace function name_disp(eno emp.empno%type) return emp.ename%type is name emp.ename%type; begin select ename into name from emp where empno = eno; return name; end;
CMC Limited
114
CONFIDENTIAL
CMC Limited
115
CONFIDENTIAL
CMC Limited
116
CONFIDENTIAL
Syntax
CMC Limited
117
CONFIDENTIAL
create or replace procedure add5(n1 number, n2 number , n3 out number) is begin n3 := n1+n2; dbms_output.put_line('The sum is ' ||n3); end;
CMC Limited
118
CONFIDENTIAL
Description
In case a parameter has been defined as an out parameter in a procedure then that parameter has to be declared as a session variable in the SQL prompt
SQL > VAR <VARIABLE> <DATA TYPE> SQL > exec <procedure name>(<val1>, <val2>, <val n>, :<out parameter>) In a procedure call, the out parameter has to be defined as a bind variable
Calling a procedure
Bind variable
CMC Limited
119
CONFIDENTIAL
CMC Limited
120
CONFIDENTIAL
Exception types
Zero divide
No_data_found
Too_many_rows
CMC Limited
121
CONFIDENTIAL
Zero_divide
declare n1 number; n2 number := 0; begin n1 := &num1; dbms_output.put_line(n1/n2); exception when zero_divide then raise_application_error(-20001, 'sorry cannot perform division'); end;
CMC Limited
122
CONFIDENTIAL
No data found
declare eno emp.empno%type; name emp.ename%type; begin eno := &employee_no; select ename into name from emp where empno = eno; dbms_output.put_line(name); exception when no_data_found then raise_application_error(-20001, 'data not available in the emp table'); end;
CMC Limited
123
CONFIDENTIAL
Too_many_rows
declare
name emp.ename%type;
begin select ename into name from emp; dbms_output.put_line(name); exception when too_many_rows then raise_application_error(-20001, 'see 1 row at a time'); end; /
CMC Limited
124
CONFIDENTIAL
CMC Limited
125
CONFIDENTIAL
DESCRIPTION
Package is a named group of functions, procedures and cursors Advantages of using a package
Resolve ambiguity in the names of functions and procedures Reusability
CMC Limited
126
CONFIDENTIAL
Package body
Note
Package specification name and package body name must be the same
CMC Limited
127
CONFIDENTIAL
CMC Limited
128
CONFIDENTIAL
CMC Limited
129
CONFIDENTIAL
Requirement
Create a package which consists of a function and a procedure The function has to add 2 numbers and return the sum The procedure has to subtract 2 numbers
CMC Limited
130
CONFIDENTIAL
Package specification
create package m1 is function sum1(n1 number, n2 number) return number; procedure sub1(n1 number, n2 number, n3 out number); end;
CMC Limited
131
CONFIDENTIAL
Package body
create package body m1 is function sum1(n1 number, n2 number) return number is s number; begin s := n1+n2; return s; end; procedure sub1(n1 number, n2 number, n3 out number) is begin n3 := n1-n2; dbms_output.put_line('The result is ' ||n3); end; end;
CMC Limited
132
CONFIDENTIAL
CMC Limited
133
CONFIDENTIAL
CMC Limited
134
CONFIDENTIAL
Description
It is an event which is fired implicitly when a DDL or DML transaction gets executed It is a type of restriction that can be placed on user operations
CMC Limited
135
CONFIDENTIAL
CMC Limited
136
CONFIDENTIAL
create or replace trigger t1 before delete on emp for each row begin raise_application_error(-20001, 'sorry cannot delete a row'); end;
CMC Limited
137
CONFIDENTIAL
create or replace trigger t2 before insert on result3 for each row begin raise_application_error(-20001, 'do not try to insert a row'); end;
CMC Limited
138
CONFIDENTIAL
CMC Limited
139
CONFIDENTIAL
CMC Limited
140
CONFIDENTIAL
NAME : S.CHANDRASEKHAR MOBILE : 9247 353820 MAIL ID : chandusivalenka@gmail.com Available time : after 9.00 P.M in the night
CMC Limited
141
CONFIDENTIAL