Documente Academic
Documente Profesional
Documente Cultură
Course Overview
SQL
SQL Basics
Datatypes
DDL Commands
Integrity Constraints
DML Commands
TCL Commands
Simple Select
Select with various Clauses
Course Overview
Joins
Sub-Queries
Correlated Subqueries
Views
Synonyms
Indexes
Snapshots
SQL * Plus Commands
Set Commands
SQL * Plus Reports
contd
Course Overview
contd
PL/SQL Programming
Basic of PL/SQL
Anonymous blocks
Insert, Update, Delete and Select Using Anonymous
Block
Cursors (Implicit and Explicit Cursors)
Exception Handling
Stored Procedures and Functions
Packages
Triggers
Oracle SQL
SQL was developed by IBM Corporation in mid 1970s
Adapted and implemented by Oracle Corporation
ANSI adopted SQL as a Standard Language for
RDBMS in OCT 1986.
Features
SQL
SQL :
DDL : Data Definition Language
DML : Data Manipulation Language
TCL : Transaction Control Language
Database Objects
Synonyms
Snapshots
Sequences
Table
Table
A place to store data of a particular type
Data is organised in tables in form of rows and columns
DDL:
Used to define data objects
We can Create, Alter, Drop, Alter , Rename and
Truncated the objects.
DDL
Table Creation
Syntax :
SQL > Create table <table_name>
( Col_name 1 datatype(size) constraint,
:
:
Col_name n datatype(size) constraint,
Table Level Constraints
);
Table Created.
Data Types
number(p, s)
char (size)
varchar2 (size)
long
raw
long raw
date
timestamp (fractional seconds precision)
bfile
blob
clob
nclob
Constraints
Syntax :
SQL> alter table <table_name> modify ( column_name datatype
[Constraint]);
Altering Tables Adding column
Syntax :
SQL> alter table <table_name> add ( column_name datatype
[Constraint]);
Altering Tables Drop column
Syntax :
SQL> alter table <table_name> drop column <column_name>
SQL statements
Dropping a Table
syntax:
DROP TABLE table_name;
DROP table table_name cascade constraints
Truncating a Table
Syntax:
Truncate table <table_name>
SQL statements
INSERT
Partial Insertion
UPDATE
Syntax:
Update <table_name> set
Col_name1= val1,
Col_name2=val2,
:
:
Col_name N=val N [ Where condition ]
Ex 1 : update emp set sal=30000;
Ex 2 : Update emp set sal= sal+sal where job=MANAGER
DELETE
Syntax :
Delete from <table_name> [ where condition]
Ex : 1
SQL statements
Commit
Rollback
Savepoint
SQL statements
Simple SELECT
Selecting All Columns in All Rows
Syntax : Select * from table_name
SELECT
Order by clause
Syntax : Select * from table_name order by column_name [asc / desc]
Unique/Distinct Clause
Select unique job from emp;
SELECT
Joins
Inner Join
Outer Join
Self Joins
Joins
Inner Join
Inner joins return all rows from multiple tables where the
join condition is met.
Inner joins can be classified into:
Equi Join
Non- Equi Join
Joins
Outer Join
This type of join returns all rows from one table and only
those rows from a secondary table where the join
condition is met.
Outer joins can be further classified into:
Left Outer Join
Right Outer Join
Full Outer Join
Joins
Example:
Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from emp e ,
dept d where e.deptno=d.deptno(+)
Joins
Example :
Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from
emp e , dept d where e.deptno(+)=d.deptno
Joins
A FULL OUTER JOIN returns all rows in both the left and right tables.
Any time a row has no match in the other table, the select list columns
from the other table contain null values.
Example:
Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from emp e , dept d
where e.deptno=d.deptno(+)
Union
Select e.empno,e.ename,e.job,d.deptno,d.dname,d.loc from emp e , dept d where
e.deptno(+)=d.deptno
Sub Query
SQL Functions
Arithmetic functions
(ABS, POWER,SQRT, ROUND, TRUNC,MOD,SIGN,LN,
CEIL, FLOOR, SIN,COS,TAN,SINH,COSH)
Character Functions
( Length, ASCII,CHR, SUBSTR,INSTR, REPLACE,
UPPER, LOWER, INITCAP)
SQL Functions
Views
Advantages of Views
Advantages of Views
Focus the Data for Users
Focus on important or appropriate data only
Limit access to sensitive data
heterogeneous data
Simplify Management of User Permissions
Improve Performance
Organize Data for Export to Other Applications
Views
Type of Views
Simple View
Complex View
Creating a view
Create [or replace] view view_name as select statement
Synonyms
Creating a synonym
Syntax :
SQL> create [public] synonym syn_name for [user.] tablename.
Indexes
Indexes
Creating Indexes
Syntax :
SQL> Create [Unique] index Index_name on table_name(col_names)
Viewing Indexes
Syntax :
SQL> select * from user_indexes;
Droping Indexes
Syntax :
SQL > Drop index Index_name;
Snapshots
Sequence Generator
Sequence Generator
Includes the following system privileges: ALTER SESSION, CREATE CLUSTER, CREATE DATABASE LINK, CREATE SEQUENCE, CREATE SESSION, CREATE
SYNONYM, CREATE TABLE, CREATE VIEW
Resource
Includes the following system privileges: CREATE CLUSTER, CREATE INDEXTYPE, CREATE OPERATOR, CREATE PROCEDURE, CREATE
SEQUENCE, CREATE TABLE, CREATE TRIGGER, CREATE TYPE
DBA
Spool
sqlplus provides the command spool to save query
results to a file. At the SQL> prompt, you say:
spool on;
And a file called foo.lst will appear in your current
directory and will record all user input and system
output, until you exit sqlplus or type:
spool off;
Note that if the file foo.lst existed previously, it will be
overwritten, not appended.
Cl scr
Desc
Save
Execute
List
Run
Append
Edit , Host Edit
Pause
SQL*Plus offers several handy features you can use to control your
SQL*Plus session.
System VIEWS
Oracle Object
Relevant Views
TABLES
CONSTRAINTS
USER_CONSTRAINTS,
USER_CONS_COLUMNS
USER_OBJECT
INDEXES
USER_INDEXES,
USER_IND_COLUMNS,
USER_OBJECT
PROCEDURE
USER_SOURCE,
USER_OBJECT
PL/SQL Programming
What Is PL/SQL?
PL/SQL
Anonymous block
Anonymous blocks do not have any name that is why we can't store
them in the database server. Of course, we can store them in a text
file and run them by executing that file in SQL*PLUS environment.
Anonymous blocks cannot be called by another block and they are
compiled at runtime.
PL/SQL
Anonymous block
Declare
--------------------------------- Declaration Section
Begin
---------------- Executable part
----------------
Exception
-------------------------Exception handling part
End
Ex:declare
employee_name emp.ename%type;
emp_salary emp.sal%type;
begin
SELECT ename, sal into employee_name, emp_salary
FROM emp
WHERE ename = 'KING';
DBMS_OUTPUT.PUT_LINE(employee_name || ' is president');
DBMS_OUTPUT.PUT_LINE('President earns : ' || emp_salary);
exception
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Some error occurs in PL/SQL block');
END;
PL/SQL Basics
Datatypes
Operators
Block Structure:
Begin
Insert/update/Delete statement;
Commit/Rollback;
End;
Select:
Syntax:Select col1,col2into var1,var2 from table_name where condition.
Cursors
Implicit Cursors
Attributes:
1. SQL%FOUND
2. SQL%NOTFOUND
3. SQL% ROWCOUNT
Explicit Cursors
Creating Cursor
Declare a Cursor
OPEN Statement
FETCH Statement
CLOSE Statement
%FOUND
%NOTFOUND
%ROWCOUNT
%ISOPEN
The cursor for Loop can be used to process multiple records. There are two benefits with
cursor for Loop
1. It implicitly declares a %ROWTYPE variable, also uses it as LOOP index
2. Cursor For Loop itself opens a cursor, read records then closes the cursor
automatically. Hence OPEN, FETCH and CLOSE statements are not necessary in it.
Example
declare
cursor c1 is select * from dept;
begin
for row in c1
loop
dbms_output.put_line(row.deptno||'
end loop;
end;
'||row.dname||' '||row.loc);
Exception Handling
Pre-defined Exceptions:
When an exception occurs (is raised) in a PL/SQL block, its execution section immediately
terminates. Control is passed to the exception section.
Every exception in PL/SQL has an error number and error message; some exceptions also have
names.
Error
Named Exception
ORA-00001
DUP_VAL_ON_INDEX
ORA-01001
INVALID_CURSOR
ORA-01012
NOT_LOGGED_ON
ORA-01017
LOGIN_DENIED
ORA-01403
NO_DATA_FOUND
ORA-01410
SYS_INVALID_ROWID
ORA-01422
TOO_MANY_ROWS
ORA-01476
ZERO_DIVIDE
ORA-01722
INVALID_NUMBER
ORA-06500
STORAGE_ERROR
ORA-06502
VALUE_ERROR
ORA-06511
CURSOR_ALREADY_OPEN
ORA-06530
ACCESS_INTO_NULL
Exception Handling
User-Defined Exceptions
PL/SQL lets you define exceptions of your own. Unlike predefined
exceptions, user-defined exceptions must be declared and must be raised
explicitly by RAISE statements.
Ex:DECLARE
out_of_balance EXCEPTION;
BEGIN
IF ... THEN
RAISE out_of_balance; -- raise the exception
END IF;
EXCEPTION
WHEN out_of_balance THEN
-- handle the error RAISE;
END;
Functions
Functions can return a value to the caller
Functions can be directly referenced in queries
The value is returned through the use of the return
keyword.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ] RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [function_name];
Stored procedures
A stored procedure is a named PL/SQL block, which is
stored in the database and can be invoked from different
environments that can access database.
Syntax :
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
Functions
Parameters
When you create a procedure or function, you may
define parameters. There are three types of parameters
that can be declared:
1. IN - The parameter can be referenced by the
procedure or function. The value of the parameter can
not be overwritten by the procedure or function.
2. OUT - The parameter can not be referenced by the
procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
3. IN OUT - The parameter can be referenced by the
procedure or function and the value of the parameter can
be overwritten by the procedure or function.
Packages
Packages
Advantages:
It allows you to group together related items, types and
subprograms as a PL/SQL module.
When a procedure in a package is called entire
package is loaded, though it happens to be expensive
first time the response is faster for subsequent calls.
Package allows us to create types, variable and
subprograms that are private or public
Packages
Syntax:
The package specification
Create or Replace PACKAGE package_name IS
[Declaration of variables and types]
[Specifications of cursors]
[Specifications of modules]
END [ package_name];
Triggers
Creating Triggers
Syntax:CREATE [OR REPLACE] TRIGGER trigger_name
BEFORE | AFTER | INSTEAD OF } trigger_event ON {table_or_view_reference |
[REFERENCING [OLD AS old] [NEW AS new] [FOR EACH ROW ][WHEN trigger_condition]
trigger_body;
Example:- The following trigger restricts doing operations on Sundays on emp table.
create or replace trigger sun_trig before insert or update or delete on emp for each row
declare
d varchar2(3);
begin
d:=to_char (sysdate,'dy');
if d=sun' then
raise_application_error(-20010,'Such operations are not allowed in Sundays, try only on weekdays...!');
end if;
end;
Useful websites
http://www.ss64.com/orad/index.html
http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96540/
sql_elements.htm
http://www.lc.leidenuniv.nl/awcourse/oracle/appdev.920/a96590/adg
09dyn.htm#26799
http://www.lc.leidenuniv.nl/awcourse/oracle/server.920/a96540/sql_
elements6a.htm#19762