Sunteți pe pagina 1din 75

Welcome to ORACLE

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

Non- Procedural Language


Unified Language
Common Language for Relational Databases

SQL

SQL :
DDL : Data Definition Language
DML : Data Manipulation Language
TCL : Transaction Control Language

DQL : Data Query Language


DCL : Data Control Language

Database Objects

Used to manipulate data


Oracle supports different kinds of Data Objects
Tables
Views
Indexes

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.

Elements of Oracle SQL

Data Types

number(p, s)
char (size)
varchar2 (size)
long
raw
long raw
date
timestamp (fractional seconds precision)
bfile
blob
clob
nclob

Constraints

Constraint is condition that is applied over a table


Oracle Supports Five type of Constraints
Unique
Not Null
Primary key
Check
Foreign key

DDL Alter table


Altering Tables Modify column

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

DDL- Rename, Drop and Truncate


Renaming Oracle Table
syntax:
SQL> Rename <old_table_name> to <new_table_name>

Dropping a Table
syntax:
DROP TABLE table_name;
DROP table table_name cascade constraints

Truncating a Table
Syntax:
Truncate table <table_name>

It remove all the rows of the table permanently

SQL statements

Data Manipulation Language

INSERT

Full phase insertion

Partial Insertion

Insert into table_name(columnnames) values ( val1,val2,val3)

Insertion using Substitutional Parameters

INSERT INTO departments VALUES (280, 'Recreation', 121, 1700);

Insert into table_name(column names) values( &label1, &label2);

Insertion from other table

Insert into table_name select statement.


Ex:- insert into emp_new (select * from emp)
select into emp_new from emp;

Data Manipulation Language

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

Data Manipulation Language

DELETE
Syntax :
Delete from <table_name> [ where condition]
Ex : 1

Delete from emp;


Delete from emp where job=MANAGER

SQL statements

Transaction Control Language(TCL)

Commit

Rollback

Use the COMMIT statement to end your current transaction and


make permanent all changes performed in the transaction.
Use the ROLLBACK statement to undo work done in the current
transaction

Savepoint

SQL statements

Transaction Control Language(TCL)


Use the SAVEPOINT statement to identify a point in a
transaction to which you can later roll back.
Example:
UPDATE employees SET salary = 7000
WHERE last_name = 'Banda';
SAVEPOINT sp1;
UPDATE employees
SAVEPOINT sp2;

SET salary = 12000

SELECT SUM(salary) FROM employees;


ROLLBACK TO SAVEPOINT banda_sal;
UPDATE employees SET salary = 11000
COMMIT;

WHERE last_name = 'Greene';

WHERE last_name = 'Greene';

Simple SELECT
Selecting All Columns in All Rows
Syntax : Select * from table_name

Select Few Columns in All Rows


Syntax : Select * from table_name

Select with Where clause


Syntax : Select * from table_name [where Condition]

SELECT

Order by clause
Syntax : Select * from table_name order by column_name [asc / desc]

Unique/Distinct Clause
Select unique job from emp;

Select count(distinct dept) from emp

Retrieval Using SQL Operators


( IN, Between and , Like, IS)
Retrieval Using Column Alias Names
Retrieval Using Substitution Parameters

SELECT

Retrieval Using Group by:

Used to divide the rows into smaller groups


The where clause cannot be applied to the grouped
result

Retrieval Using Having Clause :

To specify conditions on groups of rows which are grouped by


Group by clause

Retrieval from Multiple tables :


( Union, Intersect,Difference and Cartesian Product)

Joins

A join is used to combine rows from multiple tables. A


join is performed whenever two or more tables is listed
in the FROM clause of an SQL statement.
There are different kinds of 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

Left Outer Join

LEFT JOIN or LEFT OUTER JOIN


The result set of a left outer join includes all the rows from the
left table specified in the LEFT OUTER clause, not just the
ones in which the joined columns match. When a row in the left
table has no matching rows in the right table, the associated
result set row contains null values for all select list columns
coming from the right table.

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

Right Outer Join


A right outer join is the reverse of a left outer join. All
rows from the right table are returned. Null values are
returned for the left table any time a right table row has
no matching row in the left table.

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

Full Outer Join

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

A query result can also be used in a condition of a where


clause. In such a case the query is called a sub query
and the complete select statement is called a nested
query.
Example:
Select * from emp where deptno=(select deptno from dept where
dname=ADMIN

Correlated sub queries

Correlated sub queries also known as a repeating


subquery. This means that the subquery is executed
repeatedly, once for each row that might be selected by
the outer query
Example : Retrieve all employees whose salary is > avg sal of the
same job employees.
Select * from emp e where sal>(select avg(sal) from emp where job=
e.job

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

Date & Time Functions


(Add_months,Last_Day,Months_between,Next_Day,Sys
date)
Conversion functions
( To_char,To_date, To_num)
Aggregate functions
(Max, Min, Count, sum, avg, stddev)

Views

A view can be used in the same way as a table


Rows can be retrieved from a view
Rows are not physically stored
Rows can even be modified with some limitations
A view is evaluated each time it is accessed
In Oracle SQL no insert, update, or delete modifications
on the complex view

Advantages of Views

Advantages of Views
Focus the Data for Users
Focus on important or appropriate data only
Limit access to sensitive data

Mask Database Complexity


Hide complex database design
Simplify complex queries, including distributed queries to

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

Viewing Existing Views


Sql > Select * from user_views;

Synonyms

A synonym is a database object created over a table


It is just alias name for a table
Used to refer long table names
Used to refer other users objects

Creating a synonym
Syntax :
SQL> create [public] synonym syn_name for [user.] tablename.

Indexes

Like any other object indexes also stored in the


database
Used to retrieve data at a faster stream
Prevents duplication of data
Null values are not stored in Indexes
Types Of Indexes
1. Unique Index
2. Non-Unique Index
3. Single column Index
4. Concatenated Index

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

A snapshot is a virtual table very equaling to that of a


view but the only difference is we cannot perform any
DML operations using a snapshot.
These are created by DBA only.
Creating a Snapshot
Syntax :
SQL> Create snapshot snap_name as select query;

Sequence Generator

A sequence generator is a database object used to generate


sequence numbers from a starting value to ending value with a
specified increment.
A sequence generator can retrieve unique values only
We can alter a sequence generator
Sequence generator values can be used in select, insert, update
statements.
Outermost query of a subquery
Creating a Sequence:
Syntax:
SQL> Create squence seq_name
Startwith N
Maxvalue M
Increment by value;

Sequence Generator

To retrieve values from sequence we can use pseudo


columns:
1. Currval : gives current sequence number
2. Nextval : Next successive sequence number
Altering a sequence:
Syntax:
Alter sequence seq_name maxvalue N increment by X;

Data Control Language- Privileges

Privilege is a right to access an object from the


database.
There are two types of privileges
Object Privileges : works on a particular object

System privileges : works on a class of objects

Object Privileges are granted by the owner of the object


System privileges are granted by the DBA.

Data Control Language- Privileges

Granting Object Privileges


Revoking Object Privileges
Granting System Privileges
Revoking System Privileges

Data Control Language- Roles


A set of privileges
User must have Create Role privilege to create a role
Predefined Roles
Connect

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

All privileges with Admin Option

User defined Roles


Users can create roles and assign to users

Exporting data in flat files

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.

SQL *Plus Commands

Cl scr
Desc
Save
Execute
List
Run
Append
Edit , Host Edit
Pause

Customizing the SQL*Plus environment

SQL*Plus offers several handy features you can use to control your
SQL*Plus session.

Set Autocommit on/off


Set Heading on/off
Set linesize size
Set Pagesize size
Set Sqlprompt prompt
Set time on/off
Set Verify on/off
Set Underline On/off
Set SqlTerminator
Set Wrap on/off

Oracle Data Dictionary

Oracle stores all information about the objects of a


particular database in a system database that is called
data dictionary.
Metadata
System views are divided into three groups: USER, ALL,
and DBA
A view of USER group will have its name starting as
USER_view_name.
USER group views have information about the objects
owned by the user.
DBA group views are only available to the DBAs.

System VIEWS
Oracle Object

Relevant Views

TABLES

USER_TABLES, CAT, TABS


USER_TAB_COLUMNS
USER_COL_COMMENTS,
USER_TAB_COMMENT
USER_OBJECTS

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 is Oracle's procedural extension to industry


standard Structured Query Language (SQL).
PL/SQL extends the SQL by adding several features,
which are common in other high level programming
languages like C, Ada etc.
It is full-fledged programming language that provides
block structure programming, strongly typed variables ,
conditional statements, loops, data encapsulation,
information hiding, exception handling etc.

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.

An anonymous block may have a named function or procedure in its


declaration section. Such function or procedure can only be called
from the execution section of the same anonymous block.

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

Input & Output Statements


Control Statements
Loops

Insert, Update, Delete & Select

Block Structure:
Begin
Insert/update/Delete statement;
Commit/Rollback;
End;

Select:
Syntax:Select col1,col2into var1,var2 from table_name where condition.

Cursors

A cursor is a mechanism by which you can assign a


name to a "select statement" and manipulate the
information within that SQL statement.
PL/SQL supports two kinds of cursors
1. Implicit Cursors
2. Explicit Cursors.

Implicit Cursors

PL/SQL defines Implicit Cursors for all recently executed


DML statements.

Attributes:
1. SQL%FOUND
2. SQL%NOTFOUND
3. SQL% ROWCOUNT

Explicit Cursors

Explicit cursors are SELECT statements that are


DECLARE explicitly in the declaration section of the
current block or in a package specification.
OPEN, FETCH, and CLOSE are used in the execution or
exception sections of the programs.

Creating Cursor

Declare a Cursor
OPEN Statement
FETCH Statement

CLOSE Statement

Explicit Cursor Attributes

%FOUND

%NOTFOUND

%ROWCOUNT

%ISOPEN

Cursor for loop

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;

WHEN OTHERS Clause


The WHEN OTHERS clause is used to trap all remaining exceptions
that have not been handled by your Named System Exceptions and
Named Programmer-Defined Exceptions.
If present it should be the last exception handler.

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

A package is a group of procedures, functions, variables


and SQL statements created as a single unit. It is used
to store together related objects.
Package Specification acts as an interface to the
package. Declaration of types, variables, constants,
exceptions, cursors and subprograms is done in
Package specifications.
Package body is used to provide implementation for the
subprograms, queries for the cursors declared in the
package specification or spec.

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];

The package body


PACKAGE BODY package_name IS
Specified members definitions..
END [package_name];

Triggers

Triggers are programs that execute in response to


changes in table data or certain database events.

Types of triggering events:


DML events fire when an INSERT, UPDATE, or DELETE
statement executes.

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

S-ar putea să vă placă și