0% found this document useful (0 votes)
6 views

Oracle SQL Concepts

The document provides an introduction to Database Management Systems (DBMS) and Oracle SQL, covering fundamental concepts such as data, information, tables, metadata, and transactions. It details the ACID properties, normalization forms, SQL operations (DDL, DML, DRL, DCL, TCL), data types in Oracle, and various functions available in SQL. Additionally, it includes syntax examples for creating, modifying, and querying tables, as well as managing permissions and transactions.

Uploaded by

Ramalinga reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Oracle SQL Concepts

The document provides an introduction to Database Management Systems (DBMS) and Oracle SQL, covering fundamental concepts such as data, information, tables, metadata, and transactions. It details the ACID properties, normalization forms, SQL operations (DDL, DML, DRL, DCL, TCL), data types in Oracle, and various functions available in SQL. Additionally, it includes syntax examples for creating, modifying, and querying tables, as well as managing permissions and transactions.

Uploaded by

Ramalinga reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 176

Oracle SQL

1
Introduction to DBMS

What is Data ?
-- Facts, figures, statistics etc. having no particular meaning

2
Introduction to DBMS

What is Information ?
-- It is the date in the processed form/ Meaningful data

3
Introduction to Table

Collection of rows and columns is called a table

Combination of rows and columns is called a CELL.

4
Introduction to DBMS

What is Meta Data ?


-- It’s the data about data

5
Introduction to DBMS

What is Database Management System


(DBMS) ?

6
Introduction to DBMS

What is a Transaction ?

7
Introduction to DBMS

What is RDBMS ?

8
ACID Properties

Atomicity
-- All or Nothing

9
ACID Properties

Consistency
-- Valid data will be written in Database
-- When failed rollback to previous consistant state

10
ACID Properties

Isolation
-- Multiple transactions occurring at the same time does not
impact each other transaction

11
ACID Properties

Durability
-- Transactions committed to database will never lost

12
ACID Properties
Normalization

Normalization is the process of efficiently organizing data in a database

14
1st Normal Form -1NF

• Contains only atomic values


• There are no repeating groups

15
2nd Normal Form -2NF

• It is in first normal form


• Redundant data across multiple rows of a table must be moved to a separate
table

16
3rd Normal Form -3NF

• It is in second normal form


• Eliminate fields that do not depend on the primary key
Introduction to SQL

• SQL stands for structured query language.


• SQL is an standard computer language for accessing and manipulating
database systems. SQL statements are used to retrieve and update data in a
database.

Operations that can be performed using SQL


• Creation of Objects
• Insertion of data into tables
• Updating of existing data
• Deletion of data
• Retrieval of the data

18
Introduction to SQL

• Data Definition Language (DDL) -- create, alter, drop, truncate,


rename
• Data Manipulation Language (DML) -- insert, update, delete
• Data Retrieval Language (DRL) -- select
• Transaction Control Language (TCL) -- commit, rollback, savepoint
• Data Control Language (DCL) -- grant, revoke

19
Tables to be used

20
Data Types in Oracle

Built-In Data Types :


• Character Data Types
• Number Data Types
• Long and Raw Data Types
• Date Time Data Types
• Large Object Data Types

21
Data Types in Oracle – Character Data Type

Character Data Types


-- Alphanumeric Data Collections

CHAR Data Type :


• Fixed length character string
• The size should be specified
• If the size is less than the original specified size, blank pads are
applied
• Default length is 1 byte and max size is 2000 bytes

VARCHAR2 Data Type :


• Variable length character string
• The minimum size is 1byte and max size is 4000 Bytes

22
Data Types in Oracle – Number Data Type

Number Data Type :


• It stores Zero, positive, negative fixed and floating point number
numbers
• The general declaration is
NUMBER(P,S)
P – It specifies the Precision i.e. total no. of digits
S – It specifies the scale i.e. the no. of digits to the right of the
decimal
points

23
Data Types in Oracle – Long Data Type

Long Data Type :


• Stores variable length character string
• Used to store very lengthy text string
• This can be used in
-- Select lists
-- Set clauses of UPDATE statement
-- value clauses of INSERT

Limitations of using LONG Data types


• A single table can have only one LONG column
• LONG can not appear in where clause
• Indexes can not be created on LONG columns

24
Data Types in Oracle – Date Data Type

Date Data Type :


• Used to store date and time information
• The information revealed in the DATE is
Century, Year, Month, Date, Hour, Minute and second
• Default date format if DD-MON-YY and is specified in
NLS_DATE_FORMAT
• The default time accepted by oracle date is 12:00:00 AM
(Midnight)
• The default date accepted by oracle date is First day of the
current month

25
Data Types in Oracle – LOB Data Type

LOB Data Type :


• Can store large and unstructured data like Text, Images, Video
• Maximum size is 4GB

• The built in LOB Data Types are


BLOB
CLOB
NCLOB
• These data types will store the data internally
• Bfile is the LOB which stores the data externally

26
DATA DEFINITION LANGUAGE (DDL)

Create table :

Syntax :
Create table <table_name> (col1 datatype1, col2 datatype2 …coln datatypen);

Example:
create table student (no number (2), name varchar 2(10), marks number (3));

Creating a table from a table:


CREATE TABLE myemp AS SELECT * from emp;

CREATE TABLE myemp(name varchar2(10),sal number) AS SELECT


(ename,sal) FROM emp;

27
Rules of creating a table

User should have permission on CREATE TABLE command


Should be a letter and can be 1-30 Character long
Table name can contain A-Z, a-z, 0-9, _,#,$
Names can not ne oracle reserved keywords
Table names are not case sensitive

28
DATA DEFINITION LANGUAGE (DDL)

Adding new columns:


S: alter table <table_name> add <col datatype>;
E: ALTER TABLE emp ADD (city varchar2(15));

Dropping a column from a table:


S: alter table <table_name> drop <col datatype>;
E: ALTER TABLE emp DROP COLUMN city;

Modifying existing columns:


S: alter table <table_name> modify <col datatype>;
E: ALTER TABLE emp MODIFY (city varchar2(30));

Renaming a column.
S: alter table <table_name> rename column <old_col_name> to
<new_col_name>;
E: ALTER TABLE emp RENAME COLUMN ename TO empname;

29
DATA DEFINITION LANGUAGE (DDL)

Renaming tables:
S: rename <old_table_name> to <new_table_name>;
E: RENAME emp TO myemp:

Drop a table:
S: Drop table <table_name>;
E: DROP TABLE emp;

Truncate a table:
S: truncate table <table_name>;
E: TRUNCATE TABLE emp:

Making Column Unused:


S: alter table <table_name> set unused column <col>;
E: alter table student set unused column marks;

30
DATA MANIPULATION LANGUAGE (DML) - INSERT

INSERT
This will be used to insert the records into table.
We have two methods to insert.
• By value method
Syntax:
insert into <table_name> values (value1, value2, value3 …. Valuen);
Example:
insert into student values (1, ’sudha’, 100);

• By address method
Syntax:
insert into <table_name) values (&col1, &col2, &col3 …. &coln);
Example:
insert into student values (&no, '&name', &marks);

31
DATA MANIPULATION LANGUAGE (DML) - INSERT

INSERTING DATA INTO SPECIFIED COLUMNS USING


VALUE METHOD
Syntax:
insert into <table_name)(col1, col2, col3 … Coln) values (value1, value2,
value3 ….Valuen);
Example:
insert into student (no, name) values (3, ’Ramesh’);

INSERTING DATA INTO SPECIFIED COLUMNS USING


ADDRESS METHOD
Syntax:
insert into <table_name)(col1, col2, col3 … coln) values (&col1,
&col2 ….&coln);
Example:
insert into student (no, name) values (&no, '&name');

32
DATA MANIPULATION LANGUAGE (DML) - UPDATE

This can be used to modify the table data.


Syntax:
Update <table_name> set <col1> = value1, <col2> = value2 where
<condition>;
Example :
Updating all rows
UPDATE emp SET ename=’gajendra’, sal=5000;

Updating records conditionally


UPDATE emp SET ename=’gajendra’, sal=5000 WHERE deptno=10;

33
DATA MANIPULATION LANGUAGE (DML) - DELETE

This can be used to delete the table data temporarily


Syntax:
Delete <table_name> where <condition>;
Example :

Removal of all rows.


DELETE FROM emp;

Removal of specific rows.


DELETE FROM emp WHERE deptno=10;

34
DATA RETRIVAL LANGUAGE (DRL)

Used to retrieve data from tables.


SYNTAX: SELECT <COLUMSN> FROM <TABLE_NAME>
To view all rows and all columns.
SELECT * FROM emp;

To view selected columns and all rows.


SELECT ename, deptno, sal FROM emp;

To view selected rows and all columns.


SELECT * FROM emp WHERE sal>3000;

To view selected columns and selected rows.


SELECT ename, empno FROM emp WHERE comm. Is null;

Eliminating duplicate rows.


SELECT DISTINCT deptno FROM emp;

35
DATA CONTROL LANGUAGE (DCL)

Used to control access to data in a database.

To give all data manipulation permissions on a table:


GRANT ALL ON emp TO gajendra;

To give permission to view and modify records in the table to a


user:
GRANT SELECT,UPDATE ON emp TO gajendra;

To give grant with grant option:


GRANT ALL ON emp TO gajendra WITH GRANT OPTION;

36
TRANSACTION CONTROL LANGUAGE (TCL) - COMMIT

Used to control transactional processing in a database.


Commit:
COMMIT commits the current transaction. All changes made by the
transaction become visible to others and are guaranteed to be durable if a
crash occurs.

Commit is of two types.


• Implicit
• Explicit
a) IMPLICIT
This will be issued by oracle internally in two situations.
• When any DDL operation is performed.
• When you are exiting from SQL * PLUS.
b) EXPLICIT
This will be issued by the user.
Syntax:
Commit or commit work;
* When ever you committed then the transaction was completed.

37
TRANSACTION CONTROL LANGUAGE (TCL) – ROLLBACK &
SAVEPOINT
ROLLBACK :
ROLLBACK rolls back the current transaction and causes all the
updates/inserts made by the transaction to be discarded.

ROLLBACK;

Save point:

SAVEPOINT establishes a new savepoint within the current transaction.

ROLLBACK TO SAVEPOINT s1;

38
CONDITIONAL SELECTIONS AND OPERATORS

We have two clauses used in this


• Where
• Order by

USING WHERE
select * from <table_name> where <condition>;

Types of operators used in WHERE clause


Arithmetic operators
+, -, *, /
Comparison operators
=, !=, >, <, >=, <=, <>
between, not between, in, not in, null, not null, like
Comparison operators
And, Or, not

39
CONDITIONAL SELECTIONS AND OPERATORS

USING ORDER BY
This will be used to ordering the columns data (ascending or descending).

Select * from <table_name> order by <col> desc;

By default oracle will use ascending order.


If you want output in descending order you have to use desc keyword after
the column.

40
DUAL Table

ORACLE provides a "dummy" table called DUAL containing one column


and one row. It is useful for selecting miscellaneous information from
ORACLE.

Display today's date


SELECT SYSDATE FROM dual;
Display sum of 13,7
SELECT 13+7 FROM dual;
Display the current user name
SELECT USER FROM dual;

41
Functions

Functions can be categorized as follows.


• Single row functions
• Group functions

SINGLE ROW FUNCTIONS


Single row functions can be categorized into five.
These will be applied for each row and produces individual output for each
row.
• Numeric functions
• String functions
• Date functions
• Miscellaneous functions
• Conversion functions

42
Single Row Functions – Numeric Functions

• Abs • Log
• Sign • Ceil
• Sqrt • Floor
• Mod • Round
• Nvl • Trunk
• Power • Greatest
• Exp • Least
• Ln • Coalesce

43
Single Row Functions – Numeric Functions

ABS :
• ABS returns the absolute value of the given value
• Absolute value is always a positive number.
Sy : abs (value)
Ex : select abs(5), abs(-5), abs(0), abs(null) from dual;

SIGN :
• Sign gives the sign of a value.
Sy : sign (value)
Ex : select sign(5), sign(-5), sign(0), sign(null) from dual;

SQRT :
• This will give the square root of the given value.
Sy : sqrt (value)
Ex : select sqrt(4), sqrt(0), sqrt(null), sqrt(1) from dual;

44
Single Row Functions – Numeric Functions

MOD :
• This will give the remainder.
Sy : mod (value, divisor)
Ex : select mod(7,4), mod(1,5), mod(null,null), mod(0,0), mod(-7,4)
from dual;

NVL :
• This will substitutes the specified value in the place of null
values.
Sy : nvl (null_col, replacement_value)
Ex : select nvl(1,2), nvl(2,3), nvl(4,3), nvl(5,4) from dual;

POWER:
• Power is the ability to raise a value to a given exponent.
Sy : power (value, exponent)
Ex: select power(2,5), power(0,0), power(1,1), power(null,null),
power(2,-5) from dual; 45
Single Row Functions – Numeric Functions

EXP :
• This will raise e value to the give power.
Sy : exp (value)
Ex : select exp(1), exp(2), exp(0), exp(null), exp(-2) from dual;

LN :
• This is based on natural or base e logarithm.
Sy : ln (value)
Ex : select ln(1), ln(2), ln(null) from dual;

LOG :
• This is based on 10 based logarithm.
Sy : log (10, value)
Ex: select log(10,100), log(10,2), log(10,1), log(10,null) from dual;

46
Single Row Functions – Numeric Functions

CEIL :
• This will produce a whole number that is greater than or equal to
the specified value.
Sy : ceil (value)
Ex : select ceil(5), ceil(5.1), ceil(-5), ceil( -5.1), ceil(0), ceil(null) from
dual;

FLOOR :
• This will produce a whole number that is less than or equal to
the specified value.
Sy : floor (value)
Ex : select floor(5), floor(5.1), floor(-5), floor( -5.1), floor(0),
floor(null) from dual;

47
Single Row Functions – Numeric Functions

ROUND :
• This will rounds numbers to a given number of digits of
precision.
Sy : round (value, precision)
Ex: select round(123.2345), round(123.2345,2), round(123.2354,2)
from dual;

TRUNC :
• This will truncates or chops off digits of precision from a
number.
Sy : trunc (value, precision)
Ex : select trunc(123.2345), trunc(123.2345,2), trunc(123.2354,2) from
dual;

GREATEST :
• This will give the greatest number.
Sy : greatest (value1, value2, value3 … valuen)
Ex : select greatest(1, 2, 3), greatest(-1, -2, -3) from dual;
48
Single Row Functions – Numeric Functions

LEAST :
• This will give the least number.
Sy : least (value1, value2, value3 … value n)
Ex: select least(1, 2, 3), least(-1, -2, -3) from dual;
If all the values are zeros then it will display zero.
If all the parameters are nulls then it will display nothing.
If any of the parameters is null it will display nothing.

COALESCE :
• This will return first non-null value.
Sy : coalesce (value1, value2, value3 … value n)
EX: select coalesce(1,2,3), coalesce(null,2,null,5) from
dual;

49
Single Row Functions – String Functions

• Initcap • Replace
• Upper • Soundex
• Lower • Concat ( ‘ || ‘
• Length Concatenation
• Rpad operator)
• Lpad • Ascii
• Ltrim • Chr
• Rtrim • Substr
• Trim • Instr
• Translate • Decode
• Greatest
• Least
• Coalesce

50
Single Row Functions – String Functions

INITCAP :
• This will capitalize the initial letter of the string.
Sy : initcap (string)
EX: select initcap('computer') from dual;

UPPER :
• This will convert the string into uppercase.
Sy : upper (string)
EX: select upper('computer') from dual;

LOWER :
• This will convert the string into lowercase.
Sy : lower (string)
EX: select lower('COMPUTER') from dual;

51
Single Row Functions – String Functions

LENGTH :
• This will give length of the string.
Sy : length (string)
EX: select length('computer') from dual;
RPAD :
• This will allows you to pad the right side of a column with any
set of characters.
Sy : rpad (string, length [, padding_char])
EX: select rpad('computer',15,'*'), rpad('computer',15,'*#') from
dual;
LPAD:
• This will allows you to pad the left side of a column with any set
of characters.
Sy : lpad (string, length [, padding_char])
EX: select lpad('computer',15,'*'), lpad('computer',15,'*#') from
dual; 52
Single Row Functions – String Functions

LTRIM:
• This will trim off unwanted characters from the left end of string.
Sy : ltrim (string [,unwanted_chars])
EX: select ltrim('computer','co'), ltrim('computer','com') from dual;

RTRIM:
• This will trim off unwanted characters from the right end of
string.
Sy : rtrim (string [, unwanted_chars])
EX: select rtrim('computer','er'), rtrim('computer','ter') from dual;

TRIM:
• This will trim off unwanted characters from the both sides of
string.
Sy : trim (unwanted_chars from string)
EX: select trim( 'i' from 'indiani') from dual;
53
Single Row Functions – String Functions

TRANSLATE:
• This will replace the set of characters, character by character.
Sy : translate (string, old_chars, new_chars)
EX: select translate('india','in','xy') from dual;

REPLACE:
• This will replace the set of characters, string by string.
Sy : replace (string, old_chars [, new_chars])
EX:

SOUNDEX:
• This will be used to find words that sound like other words,
exclusively used in where clause.
Sy : soundex (string)
EX: select * from emp where soundex(ename) = soundex('SMIT');

54
Single Row Functions – String Functions

CONCAT :
• This will be used to combine two strings only.
Sy : concat (string1, string2)
EX: select concat('computer',' operator') from dual;

ASCII :
• This will return the decimal representation in the database
character set of the first character of the string.
Sy : ascii (string)
EX: select ascii('a'), ascii('apple') from dual;

CHR :
• This will return the character having the binary equivalent to the
string in either thedatabase character set or the national character
set.
Sy : chr (number)
EX: select chr(97) from dual;
55
Single Row Functions – String Functions

SUBSTR:

• This will be used to extract substrings.


Sy : substr (string, start_chr_count [, no_of_chars])
EX: select substr('computer',2), substr('computer',2,5),
substr('computer',3,7) from dual;
1. If no_of_chars parameter is negative then it will display nothing.
2. If both parameters except string are null or zeros then it will display nothing.
3. If no_of_chars parameter is greater than the length of the string then it
ignores and calculates based on the orginal string length.
4. If start_chr_count is negative then it will extract the substring from rightend.

56
Single Row Functions – String Functions

INSTR:

• This will allows you for searching through a string for set of
characters.
Sy : instr (string, search_str [, start_chr_count [, occurrence] ])
EX: select instr('information','o',4,1), instr('information','o',4,2)
from dual;
• If you are not specifying start_chr_count and occurrence then it will start
search from the beginning and finds first occurrence only.
• If both parameters start_chr_count and occurrence are null, it will display
nothing.

57
Single Row Functions – String Functions

DECODE:

• Decode will act as value by value substitution.


• For every value of field, it will checks for a match in a series of
if/then tests.
Sy : decode (value, if1, then1, if2, then2, ……. else);
EX: select sal, decode(sal,500,'Low',5000,'High','Medium') from
emp;
• If the number of parameters are odd and different then decode will display
• nothing.
• If the number of parameters are even and different then decode will display last
• value.
• If all the parameters are null then decode will display nothing.
• If all the parameters are zeros then decode will display zero.

58
Single Row Functions – String Functions

GREATEST:
• This will give the greatest string.
Sy : greatest (strng1, string2, string3 … stringn)
EX: select greatest('a', 'b', 'c'), greatest('satish','srinu','saketh') from
dual;

LEAST:
• This will give the least string.
Sy : greatest (strng1, string2, string3 … stringn)
EX: select least('a', 'b', 'c'), least('satish','srinu','saketh') from dual;

COALESCE:
• This will gives the first non-null string.
Sy : coalesce (strng1, string2, string3 … stringn)
EX: select coalesce('a','b','c'), coalesce(null,'a',null,'b') from dual;

59
Single Row Functions – Date Functions
• Sysdate
• Extract
• TO_CHAR
• TO_DATE
• Add_months
• Months_between
• Next_day
• Last_day
• Greatest
• Least
• Round
• Trunc
• New_time
• Coalesce

60
Single Row Functions – Date Functions

SYSDATE :
• Returns the current date and time in the Oracle Server.
Ex : select sysdate from dual;

EXTRACT:
• This is used to extract a portion of the date value.
Sy : extract ((year | month | day | hour | minute | second), date)
Ex : select extract(year from sysdate) from dual;

61
Single Row Functions – Date Functions

TO_CHAR :
• This will be used to extract various date formats.
• The available date formats as follows.
D No of days in week YEAR Fully spelled out year
DD No of days in month CC Century
Q No of quarters
DDD No of days in year
W No of weeks in month
MM No of month WW No of weeks in year
MON Three letter abbreviation of month IW No of weeks in year from ISO standard
MONTH Fully spelled out month HH Hours
RM Roman numeral month MI Minutes
DY Three letter abbreviated day SS Seconds
FF Fractional seconds
DAY Fully spelled out day
AM or PM -- Displays AM or PM depending upon time
Y Last one digit of the year of day
YY Last two digits of the year A.M or P.M -- Displays A.M or P.M depending upon time
YYY Last three digits of the year of day
YYYY Full four digit year AD or BC -- Displays AD or BC depending upon the date
SYYYY Signed year A.D or B.C -- Displays AD or BC depending upon the
date
I One digit year from ISO standard
FM -- Prefix to month or day, suppresses padding of
IY Two digit year from ISO standard month or day
IYY Three digit year from ISO standard TH Suffix to a number
IYYY Four digit year from ISO standard SP suffix to a number to be spelled out
Y, YYY Year with comma SPTH Suffix combination of TH and SP to be both
spelled out
THSP same as SPTH
62
Single Row Functions – Date Functions

Sy : to_char (date, format)


Ex :

select to_char(sysdate,'dd month yyyy hh:mi:ss am dy') from dual;

select to_char(sysdate,'dd month year') from dual;

select to_char(sysdate,'ddth DDTH') from dual;

63
Single Row Functions – Date Functions

TO_DATE :
• This will be used to convert the string into data format.
Sy : to_date (date)
Ex : select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month *
day') from dual;

ADD_MONTHS :
• This will add the specified months to the given date.
Sy : add_months (date, no_of_months)
Ex : select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from
dual;

MONTHS_BETWEEN :
• This will give difference of months between two dates.
Sy : months_between (date1, date2)
Ex : select months_between(to_date('11-aug-1990','dd-mon-yyyy'),
to_date('11-jan-1990','dd-mon-yyyy')) from dual;

64
Single Row Functions – Date Functions

NEXT_DAY:
• This will produce next day of the given day from the specified date.
Sy : next_day (date, day)
Ex : select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from
dual;

LAST_DAY :
• This will produce last day of the given date.
Sy : last_day (date)
Ex : select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from
dual;

GREATEST:
• This will give the greatest date.
Sy : greatest (date1, date2, date3 … daten)
Ex : select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-
90','ddmon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

65
Single Row Functions – Date Functions

LEAST:
• This will give the least date.
Sy : least (date1, date2, date3 … daten)
Ex : select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-
90','dd-monyy'),to_date('11-apr-90','dd-mon-yy')) from dual;

66
Single Row Functions – Date Functions

ROUND:
• Round will rounds the date to which it was equal to or greater than
the given date.
Sy : round (date, (day | month | year))
Ex : select round(to_date('24-dec-04','dd-mon-yy'),'year'),
round(to_date('11-mar-06','dd-mon-yy'),'year') from dual;
• If the month falls between JAN and JUN then it returns the first day of the current year.
• If the month falls between JUL and DEC then it returns the first day of the next year.
• If the day falls between 1 and 15 then it returns the first day of the current month.
• If the day falls between 16 and 31 then it returns the first day of the next month.
• If the week day falls between SUN and WED then it returns the previous sunday.
• If the weekday falls between THU and SUN then it returns the next sunday.
• If the second parameter was null then it returns nothing.
• If you are not specifying the second parameter then round will resets the time
to the begining of the current day in case of user specified date.
• If the you are not specifying the second parameter then round will resets the time
to the begining of the next day in case of sysdate

67
Single Row Functions – Date Functions

TRUNC:
• Trunc will chops off the date to which it was equal to or less than the
given date.
Sy : trunc (date, (day | month | year))
Ex : select trunc(to_date('24-dec-04','dd-mon-yy'),'year'),
trunc(to_date('11-mar-06','dd-mon-yy'),'year') from dual;

• If the second parameter was year then it always returns the first day of the current
year.
• If the second parameter was month then it always returns the first day of the current
month.
• If the second parameter was day then it always returns the previous sunday.
• If the second parameter was null then it returns nothing.
• If the you are not specifying the second parameter then trunk will resets the time to the
begining of the current day.

68
Single Row Functions – Date Functions

NEW_TIME :
• This will give the desired timezone’s date and time.
Sy : new_time (date, current_timezone, desired_timezone)
Ex : select to_char(new_time(sysdate,'gmt','yst'),'dd mon yyyy hh:mi:ss
am') from dual;

• AST/ADT -- Atlantic standard/day light time


• BST/BDT -- Bering standard/day light time
• CST/CDT -- Central standard/day light time
• EST/EDT -- Eastern standard/day light time
• GMT -- Greenwich mean time
• HST/HDT -- Alaska-Hawaii standard/day light time
• MST/MDT -- Mountain standard/day light time
• NST -- Newfoundland standard time
• PST/PDT -- Pacific standard/day light time
• YST/YDT -- Yukon standard/day light time

69
Single Row Functions – Date Functions

COALESCE:
• This will give the first non-null date.
Sy : coalesce (date1, date2, date3 … daten)
Ex : select coalesce('12-jan-90','13-jan-99'), coalesce(null,'12-jan-90','23-
mar-
98',null) from dual;

70
Single Row Functions – Miscellaneous Functions
• Uid
• User
• Vsize
• ROWID
• ROWNUM
• SYSDATE

71
Single Row Functions – Miscellaneous Functions

Uid :
• This will returns the integer value corresponding to the user currently logged
in.
EX : select uid from dual;

USER :
• This will returns the login’s user name.
EX : select user from dual;

VSIZE :
• This will returns the number of bytes in the expression.
EX : select vsize(123), vsize('computer'), vsize('12-jan-90') from dual;

ROWID :
• It gives location in the database where row is physically stored.
EX : SELECT ROWID, name FROM emp;

72
Single Row Functions – Miscellaneous Functions

ROWNUM:
• It gives a sequence in which rows are retrieved from the database
EX : SELECT ROWNUM, name FROM emp;

SYSDATE:
• It gives current date and time of the system
EX : SELECT SYSDATE FROM DUAL;

RANK:
• This will give the non-sequential ranking.
SELECT RANK(2975) WITHIN GROUP(ORDER BY SAL DESC) FROM
EMP;

DENSE_RANK:
• This will give the sequential ranking.
SELECT DENSE_RANK(2975) WITHIN GROUP(ORDER BY SAL DESC)
FROM EMP;

73
Single Row Functions – Conversion Functions

• Bin_to_num
• To_char
• To_date
• To_number

74
Single Row Functions – Conversion Functions

Bin_to_num
• This will convert the binary value to its numerical equivalent.
Sy: bin_to_num( binary_bits)
Ex : select bin_to_num(1,1,0) from dual;

To_number
• converts expr to a value of NUMBER datatype
Sy: To_number( string)
Ex : select To_Num(‘100’) from dual;

75
Group Functions

• Sum
• Avg
• Max
• Min
• Count

Group functions will be applied on all the rows but produces single
output.

76
Group Functions

Sum

• This will give the sum of the values of the specified column.
Sy : sum (column)
Ex : select sum(sal) from emp;

AVG

• This will give the average of the values of the specified column.
Sy : avg(column)
Ex : select avg(sal) from emp;

MAX

• This will give the maximum of the values of the specified column.
Sy : max(column)
Ex : select max(sal) from emp;

77
Group Functions

MIN

• This will give the minimum of the values of the specified column.
Sy : min (column)
Ex : select min(sal) from emp;

COUNT

• This will give the count of the values of the specified column
Sy : count(column)
Ex : select count(sal) from emp;

78
ORDER OF EXECUTION

• Group the rows together based on group by clause.


• Calculate the group functions for each group.
• Choose and eliminate the groups based on the having clause.
• Order the groups based on the specified column.

• FROM
• WHERE
• GROUP BY
• HAVING
• SELECT
• DISTINCT
• ORDER BY

79
Group by Clause:

• The GROUP BY clause can be used in a SELECT statement to


collect data across multiple records and group the results by one or
more columns.

EX: select max ( sal ), deptno from emp group by deptno;

80
HAVING Clause:

• The HAVING clause is used in combination with the GROUP BY


clause. It can be used in a SELECT statement to filter the records
that a GROUP BY returns.

EX: select max ( sal ), deptno from emp group by deptno HAVING
deptno=10;

81
Integrity Constraints

• A constraint is a property assigned to a column or the set of columns


in a table that prevents certain types of inconsistent data values from
being placed in the column(s).
• Constraints are used to enforce the data integrity
• The following categories of the data integrity exist

• Entity Integrity
• Domain Integrity
• Referential integrity
• User-Defined Integrity

82
Integrity Constraints

Entity Integrity ensures that there are no duplicate rows in a table.


• Unique
• Primary key

Domain Integrity enforces valid entries for a given column by restricting


the type, the format, or the range of possible values.
• Not null
• Check

Referential integrity ensures that rows cannot be deleted, which are


used by other records (for example, corresponding data values between
tables will be vital).
• Foreign key

User-Defined Integrity enforces some specific business rules that do


not fall into entity, domain, or referential integrity categories.

83
Integrity Constraints

Constraints are always attached to a column not a table.


We can add constraints in three ways.

• Column level -- along with the column definition


• Table level -- after the table definition
• Alter level -- using alter command

84
Domain Integrity – Check Constraint

• This is used to insert the values based on specified condition.


• We can add this constraint in all three levels.

COLUMN LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3) check (marks > 300));
• create table student(no number(2) , name varchar(10), marks
number(3) constraint ch check(marks > 300));
TABLE LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3),check (marks > 300));
• create table student(no number(2) , name varchar(10), marks
number(3), constraint ch check(marks > 300));
ALTER LEVEL
• alter table student add check(marks>300);
• alter table student add constraint ch check(marks>300);

85
Domain Integrity – Not Null Constraint

• This is used to avoid null values.


• We can add this constraint in column level only.

COLUMN LEVEL
• create table student(no number(2) not null, name varchar(10), marks
number(3));
• create table student(no number(2) constraint nn not null, name
varchar (10), marks number(3));

86
Entity Integrity – Unique Key Constraint

• This is used to avoid duplicates but it allow nulls.


• We can add this constraint in all three levels.
• A table can have more than one unique key which is not possible in
primary key.
• Unique key can not be LONG or LONGRAW data type

COLUMN LEVEL
• create table student(no number(2) constraint un unique, name
varchar(10), marks number(3));

TABLE LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3),unique(no));
• create table student(no number(2) , name varchar(10), marks
number(3),constraint un unique(no));

ALTER LEVEL
• alter table student add unique(no);
87
• alter table student add constraint un unique(no);
Entity Integrity – Primary Key Constraint

• Primary key is a column or set of columns that uniquely identifies a


row.
• Its main purpose is the record uniqueness.
• This is used to avoid duplicates and nulls.
• This will work as combination of unique and not null
• Primary key can not be LONG or LONG RAW data type.
• Only one Primary key is allowed per table.
• Unique index is created automatically if there is a primary key.
• We can add this constraint in all three levels.

88
Entity Integrity – Primary Key Constraint

COLUMN LEVEL
• create table student(no number(2) primary key, name varchar(10),
marks number(3));
• create table student(no number(2) constraint pk primary key, name
varchar(10),marks number(3));

TABLE LEVEL
• create table student(no number(2) , name varchar(10), marks
number(3), primary key(no));
• create table student(no number(2) , name varchar(10), marks
number(3), constraint pk primary key(no));

ALTER LEVEL
• alter table student add primary key(no);
• alter table student add constraint pk primary key(no);

89
Referential Integrity – Primary Key Constraint

• This is used to reference the parent table primary key column which
allows duplicates.
• Foreign key always attached to the child table.
• Parent that is being referenced has to be unique or primary key.
• Foreign key constraint can be specified on child but not on parent.
• Parent record can be deleting provided no child record exists
• Master table can not be updated if child record exists.
• We can add this constraint in table and alter levels only.

90
Referential Integrity – Primary Key Constraint

TABLE LEVEL
• create table emp(empno number(2), ename varchar(10), deptno
number(2), primary key(empno), foreign key(deptno) references
dept(deptno));
• create table emp(empno number(2), ename varchar(10), deptno
number(2), constraint pk primary key(empno), constraint fk foreign
key(deptno) references dept(deptno));

ALTER LEVEL
• alter table emp add foreign key(deptno) references dept(deptno);
• alter table emp add constraint fk foreign key(deptno) references
dept(deptno);

91
On Delete Cascade

• By using this clause you can remove the parent record even it childs
exists.
• Because when ever you remove parent record oracle automatically
removes all its dependent records from child table, if this clause is
present while creating foreign key constraint.

TABLE LEVEL
• create table emp(empno number(2), ename varchar(10), deptno
number(2), primary key(empno), foreign key(deptno) references
dept(deptno) on delete cascade);
• create table emp(empno number(2), ename varchar(10), deptno
number(2), constraint pk primary key(empno), constraint fk foreign
key(deptno) references dept(deptno) on delete cascade);
ALTER LEVEL
• alter table emp add foreign key(deptno) references dept(deptno) on
delete cascade;
• alter table emp add constraint fk foreign key(deptno) references
dept(deptno) on delete cascade;
92
DEFERRABLE CONSTRAINTS

• Each constraint has two additional attributes to support deferred


checking of constraints.
Deferred initially immediate
Deferred initially deferred
• Deferred initially immediate checks for constraint violation at the time
of insert.
• Deferred initially deferred checks for constraint violation at the time of
commit.
• create table student(no number(2), name varchar(10), marks
number(3), constraint un unique(no) deferred initially immediate);
• create table student(no number(2), name varchar(10), marks
number(3), constraint un unique(no) deferred initially deferred);
• alter table student add constraint un unique(no) deferrable initially
deferred;

set constraints all immediate;


This will enable all the constraints violations at the time of inserting.
set constraints all deferred;
93
This will enable all the constraints violations at the time of commit.
Operations with constraints

Possible operations with constraints as follows.


• Enable
• Disable
• Enforce
• Drop

Enable
This will enable the constraint. Before enable, the constraint will check
the existing data.
Ex: alter table student enable constraint un;

Disable
This will disable the constraint.
Ex: alter table student enable constraint un;

94
Operations with constraints

Enforce
• This will enforce the constraint rather than enable for future inserts or
updates.
• This will not check for existing data while enforcing data.
Ex: alter table student enforce constraint un;

Drop
• This will remove the constraint.
Ex : alter table student drop constraint un;

• Once the table is dropped, constraints automatically will drop.


• When a table is copied from other table the constraints are not copied

95
Case & Default

Case

Case is similar to decode but easier to understand while going through


coding

Ex:
Select sal,
Case sal
When 500 then ‘low’
When 5000 then ‘high’
Else ‘medium’
End case
From emp;

96
Case & Default

DEFAULT

• Default can be considered as a substitute behavior of not null


constraint when applied to new rows being entered into the table.
• When you define a column with the default keyword followed by a
value, you are actually telling the database that, on insert if a row was
not assigned a value for this column, use the default value that you
have specified.
• Default is applied only during insertion of new rows.

create table student(no number(2) default 11,name varchar(2));


insert into student values(1,'a');
insert into student(name) values('b');

97
Set Operators

There are 4 types of Set Operators


• Union
• Union all
• Intersect
• Minus

Union
This will combine the records of multiple tables having the same
structure
select * from student1 union select * from student2;

Union all
This will combine the records of multiple tables having the same
structure but including duplicates.
select * from student1 union all select * from student2;

98
Set Operators

There are 4 types of Set Operators


• Union
• Union all
• Intersect
• Minus

Intersect
This will give the common records of multiple tables having the same
structure.
select * from student1 intersect select * from student2;

Minus
This will give the records of a table whose records are not in other tables
having the same structure.
select * from student1 minus select * from student2;

99
Joins

• The purpose of a join is to combine the data across tables views, or


materialized views.
• A join is performed whenever two or more tables is listed in the FROM
clause of an SQL statement.

• Equi join
• Non-equi join
• Self join
• Natural join
• Cross join
• Outer join
Left outer join
Right outer join
Full outer join
• Inner join
• Using clause
• On clause

100
Joins

Assume that we have the following tables.


Dept
DEPTNO DNAME LOC
10 Sales Hyderabad
20 Accounts Bangalore
30 Marketing Mumbai

EMP
EMPNO ENAME JOB MGR DEPTNO
111 Saketh Analyst 444 10
222 Sudha Clerk 333 20
333 Jagan Manager 111 10
444 Madhu Engineer 222 30

101
Joins

Equi Join

• An inner join (sometimes called a simple join) is a join of two or more


tables that returns only those rows that satisfy the join condition.

• An inner join is called Equi Join when the where statement compares two
columns with the equivalence (‘=’) operator.

• These joins returns all rows from both tables where there is a match.

• Most common joins used in SQL.

select empno,ename,job,dname,loc from emp e,dept d where


e.deptno=d.deptno;

102
Joins

USING CLAUSE

select empno,ename,job ,dname,loc from emp e join dept d


using(deptno);

ON CLAUSE

select empno,ename,job,dname,loc from emp e join dept d


on(e.deptno=d.deptno);

NON-EQUI JOIN

A join which contains an operator other than ‘=’ in the joins condition.

select empno,ename,job,dname,loc from emp e,dept d where


e.deptno >
d.deptno;

103
Joins

SELF JOIN

Joining the table itself is called self join.

select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp e2


where e1.empno=e2.mgr;

NATURAL JOIN

Natural join compares all the common columns.

select empno,ename,job,dname,loc from emp natural join dept;

104
Joins

CROSS JOIN

• This will gives the cross product.


• Combines every row from the left table to the every row in the right
table.

select empno,ename,job,dname,loc from emp cross join dept;

OUTER JOIN

• Outer join gives the non-matching records along with matching


records.
• Returns all rows from the left/right/both table(s) regardless of
weather the other table have values in common.
• Enters null where data is missing.

105
Joins

LEFT OUTER JOIN

This returns all the rows from the table on the left side of the join,
along with the values from the right-hand side, or nulls if a matching
row doesn't exist.

select empno,ename,job,dname,loc from emp e left outer join dept d


on(e.deptno=d.deptno);

select empno,ename,job,dname,loc from emp e,dept d where


e.deptno=d.deptno(+);

106
Joins

RIGHT OUTER JOIN

This will display the all matching records and the records which are in
right hand side table those that are not in left hand side table.

select empno,ename,job,dname,loc from emp e right outer join dept d


on(e.deptno=d.deptno);

select empno,ename,job,dname,loc from emp e,dept d where


e.deptno(+) = d.deptno;

107
Joins

FULL OUTER JOIN

This will display the all matching records and the non-matching
records from both tables.

select empno,ename,job,dname,loc from emp e full outer join dept d


on(e.deptno=d.deptno);

INNER JOIN

This will display all the records that have matched.

select empno,ename,job,dname,loc from emp inner join dept


using(deptno);

108
Sub Queries

USING

• Nesting of queries, one within the other is termed as a sub query.


• A statement containing a sub query is called a parent query.
• Sub queries are used to retrieve data from tables that depend on
the values in the table itself.

TYPES
• Single row sub queries
• Multi row sub queries
• Multiple sub queries
• Correlated sub queries

109
Sub Queries

SINGLE ROW SUBQUERIES

In single row subquery, it will return one value.

select * from emp where sal > (select sal from emp where empno =
7566);

MULTI ROW SUBQUERIES

In multi row subquery, it will return more than one value. In such
cases we should include operators like any, all, in or not in between
the comparision operator and the subquery.

select * from emp where sal > any (select sal from emp where sal
between 2500 and 4000);
select * from emp where sal > all (select sal from emp where sal
between 2500 and 4000);
select * from emp where sal In (select sal from emp where sal
110
between 2500 and 4000);
Sub Queries

MULTIPLE SUBQUERIES

There is no limit on the number of subqueries included in a where


clause. It allows nesting of a query within a subquery.

select * from emp where sal = (select max(sal) from emp where sal <
(select max(sal) from emp));

CORRELATED SUBQUERIES

A subquery is evaluated once for the entire parent statement where as


a correlated subquery is evaluated once for every row processed by
the parent statement.

select distinct deptno from emp e where 5 <= (select count(ename)


from emp where e.deptno = deptno);

111
Inline Views

In the select statement instead of table name, replacing the select


statement is known as inline view.

Select ename, sal, rownum rank from (select *from emp order by sal);

112
VIEWS

A view is a database object that is a logical representation of a table.


It is delivered from a table but has no storage of its own and often
may be used in the same manner as a table.

A view takes the output of the query and treats it as a table, therefore
a view can be thought of as a stored query or a virtual table.

Reasons why views are created are:


• Views are used to simplify a complex query.
• When data security is required.
• Provides additional level of security by restricting access to a
predetermined set of rows and/or columns of a table.
• Hide the data complexity.

113
VIEWS

TYPES
• Simple view
• Complex view

Simple view can be created from one table where as complex view
can be created from multiple tables.

READ ONLY VIEW


a view is used to only to look at the table data then it is called read
only view.

UPDATABLE VIEW
if a view is used to look at the table data as well as INSERT, UPDATE
and DELETE table data is called updatable views

FORCE VIEW
Forces The Creation Of A View Even When The View Will Be Invalid.
No Force Is The Default
114
VIEWS

When an updatable view name is given in an INSERT, UPDATE and


DELETE statements, the modifications to data in the view will be
immediately passed to the underlying table.

For a view to be updatable, it should meet the following criteria:


• Views defined from a single table.
• If the user wants to INSERT records with the help of a view, then
the primary key column(s) and all not null column(s) must be
included in the view.

The updatable view definition must not include:


• Aggregate functions
• Distinct, group by and having clauses.
• Sub-queries.
• Union, intersect and minus clauses.

115
VIEWS

Creating a view:
Create view v_emp as select * from emp;
Create view v_emp as select ename,deptno from emp;

Selecting data set from a view:


Select * from v_emp;
Select ename, deptno from v_emp;

Force View:
Create FORCE view v_emp as select * from emp;

Destroying a view:
Drop view v_emp;

116
VIEWS

• View was created but the underlying table was dropped then we
will get the message like “ view has errors ”.
• View was created but the base table has been altered but still the
view was with the initial definition, we have to replace the view to
affect the changes.
• Complex view (view with more than one table) -- insert not possible
-- update, delete possible (not always)

117
Materialized Views

Stores data

Why Use Materialized Views?


You can use materialized views to achieve one or more of the
following goals:
• Ease Network Loads
• Create a Mass Deployment Environment
• Enable Data Sub setting
• Enable Disconnected Computing

118
Synonyms

A synonym is a database object, which is used as an alias for a table,


view or sequence.

TYPES
• Private
• Public
Private synonym is available to the particular user who creates.
Public synonym is created by DBA which is available to all the users.

ADVANTAGES
Hide the name and owner of the object.
Provides location transparency for remote objects of a distributed
database.

119
Synonyms

CREATE SYNONYM
create synonym s1 for emp;
create public synonym s2 for emp;

DROP SYNONY
drop synonym s1;

120
Sequence

• A sequence is a database object, which can generate unique,


sequential integer values.
• It can be used to automatically generate primary key or unique key
values.
• A sequence can be either in an ascending or descending order.

Create sequence <seq_name> [increment by n] [start with n]


[maxvalue n] [minvalue n] [cycle/nocycle] [cache/nocache];

• By defalult the sequence starts with 1, increments by 1 with


minvalue of 1 and with nocycle, nocache.
• Cache option pre-alloocates a set of sequence numbers and
retains them in memory for faster access.

121
Sequence

Ex:
create sequence s;
create sequence s increment by 10 start with 100 minvalue 5
maxvalue 200 cycle cache 20;

USING SEQUENCE

create table student(no number(2),name varchar(10));


insert into student values(s.nextval, ‘saketh’);

Initially currval is not defined and nextval is starting value.


After that nextval and currval are always equal.

122
Sequence

ALTERING SEQUENCE

We can alter the sequence to perform the following.


• Set or eliminate minvalue or maxvalue.
• Change the increment value.
• Change the number of cached sequence numbers.

Ex:
alter sequence s minvalue 5;
alter sequence s increment by 2;
alter sequence s cache 10;

DROPPING SEQUENCE
drop sequence s;

123
Analytical Functions

An aggregate function, as the name suggests, aggregates data from


several rows into a single result row. For example, we might use
the AVG aggregate function to give us an average of all the employee
salaries in the EMP table.

SELECT AVG(sal) FROM emp;


AVG(SAL)
----------
2073.21429

124
Analytical Functions

The GROUP BY clause allows us to apply aggregate functions to


subsets of rows. For example, we might want to display the average
salary for each department.

SELECT deptno, AVG(sal) FROM emp GROUP BY deptno ORDER BY


deptno;

DEPTNO AVG(SAL)
---------- ----------
10 2916.66667
20 2175
30 1566.66667

125
Analytical Functions

Analytic functions also operate on subsets of rows, similar to aggregate


functions in GROUP BY queries, but they do not reduce the number of rows
returned by the query. For example, the following query reports the salary for
each employee, along with the average salary of the employees within the
department.

126
SELECT empno, deptno, sal,
AVG(sal) OVER (PARTITION BY deptno) AS avg_dept_sal
FROM emp;

EMPNO DEPTNO SAL AVG_DEPT_SAL


---------- ---------- ---------- ------------
7782 10 2450 2916.66667
7839 10 5000 2916.66667
7934 10 1300 2916.66667

7566 20 2975 2175


7902 20 3000 2175
7876 20 1100 2175
7369 20 800 2175
7788 20 3000 2175

7521 30 1250 1566.66667


7844 30 1500 1566.66667
7499 30 1600 1566.66667
7900 30 950 1566.66667
7698 30 2850 1566.66667
7654 30 1250 1566.66667
127
SELECT empno, deptno, sal,
AVG(sal) OVER () AS avg_sal
FROM emp;

EMPNO DEPTNO SAL AVG_SAL


---------- ---------- ---------- ----------
7369 20 800 2073.21429
7499 30 1600 2073.21429
7521 30 1250 2073.21429
7566 20 2975 2073.21429
7654 30 1250 2073.21429
7698 30 2850 2073.21429
7782 10 2450 2073.21429
7788 20 3000 2073.21429
7839 10 5000 2073.21429
7844 30 1500 2073.21429
7876 20 1100 2073.21429
7900 30 950 2073.21429
7902 20 3000 2073.21429
7934 10 1300 2073.21429
128
USING

129
USING

130
USING

131
132
133
PL/SQL

134
PL/SQL Records
• Objects of type RECORD are called PL/SQL records
• PL/SQL records have uniquely named fields, which can belong to
different datatypes

Define a RECORD type

TYPE <typename> IS RECORD


(fieldname1 <fieldtype>
:
fieldnameN <fieldtype> ;
(%TYPE and %ROWTYPE can be used to specify <fieldtype>]

135
Cursors
• To process a SQL statement, PL/SQL opens a work area called a context
area.
• PL/SQL uses this area to execute SQL statements and store processing
information
• A PL/SQL construct called ‘Cursor’ allows you to name a context area,
access its information and in some cases, control its processing

Types of Cursors:
1. Implicit Cursors
2. Explicit Cursors

136
Cursors

Implicit Cursors :

These cursors are opened by SQL automatically when ever a select is issued
on any table

Explicit Cursors :

Defined by the user to keep track of which row is being processed, when a
query returns multiple rows

Steps for using a cursor :


• Defining a Cursor
• Open a Cursor
• Fetch Data
• Close Cursor

137
Cursors - Explicit Cursors

Defining a Cursor
A cursor is defined in the declarative part of the PL/SQL block by naming it and
associating it with a query

CURSOR <cursorname> IS
<SELECT statement>;
Example
CURSOR emp_cur IS
SELECT empno, ename, job, sal
FROM emp;

A Cursor can be manipulated using


OPEN
FETCH
CLOSE
Cursor must be declared before it can be referenced using the OPEN, CLOSE
or FETCH statements

138
Cursors - Explicit Cursors
The OPEN Statement
• Initializes or opens a cursor
• Cursor must be opened before any rows are returned by the query

OPEN <cursorname>
Example --
OPEN emp_cur;

The FETCH Statement


Can be executed repeatedly until all rows have been retrieved

FETCH <cursorname> INTO var1, …, varN;


OR
FETCH <cursorname> INTO record_variable;
Example
FETCH emp_cur INTO mrec;

139
Cursors - Explicit Cursors
The CLOSE Statement
Closes the cursor and makes the active set undefined
CLOSE <cursorname>;
Example
CLOSE emp_cur;

Once a cursor is closed, it can be reopened by using the OPEN statement

140
Cursors - Explicit Cursors
Attributes of Explicit Cursors

Every cursor has four attributes that can be used to access the cursor’s context
area
%NOTFOUND
%FOUND
%ROWCOUNT
%ISOPEN
To use these attributes, simple append them to the name of the cursor

%NOTFOUND
• evaluates to TRUE if last FETCH failed because no more rows were
available
• evaluates to FALSE if last FETCH returned a row
%FOUND
• evaluates to TRUE if last FETCH returned a row
• evaluates to FALSE if last FETCH failed because no more rows were
available

141
Cursors - Explicit Cursors

%ROWCOUNT
• Returns the number of rows FETCHed from the active set so far
%ISOPEN
• Evaluates to TRUE if an explicit cursor is open
• Evaluates to FALSE if an explicit cursor is closed

142
Cursors – Cursor For loop & Parameterized cursors

• Implicitly declares its loop index as a record of %ROWTYPE,


• Implicitly opens the cursor
• Repeatedly fetches rows of values from the active set into fields in the
record
• Implicitly closes the cursor when all rows have been processed or the loop is
exited
• The statements in the loop construct are executed once for each row that
satisfies the query associated with the cursor name
• Cursor FOR loop is used to simplify coding
No need of --
• Open cursor
• Fetch
• Exit
• Close cursor

Parameterized Cursor
The same cursor can be reopened and closed with different active sets.

143
Cursors - Implicit Cursors

Implicit Cursors
• Automatically defined and opened, by Oracle, to process each SQL
statement
• Most recently opened context area is referred to as a ‘SQL%’ cursor

Attributes of Implicit Cursors

Although OPEN, CLOSE and FETCH statements cannot be used to manipulate


the SQL% cursor, the attributes can be used to access its context area
Attributes evaluate to NULL, before the cursor is opened automatically
The following four cursor attributes can be used to access the SQL%
cursor’s context area
SQL%NOTFOUND
SQL%FOUND
SQL%ROWCOUNT
SQL%ISOPEN

144
Cursors - Implicit Cursors

SQL%NOTFOUND
evaluates to TRUE if an INSERT, UPDATE or DELETE statement affected
no rows, else it evaluates to FALSE
SQL%FOUND
logical opposite of SQL%NOTFOUND
evaluates to TRUE if an INSERT, UPDATE or DELETE affected one or
more rows, else it evaluates to FALSE

SQL%ROWCOUNT
returns the number of rows affected by an INSERT, UPDATE or DELETE
statement
SQL%ISOPEN
Oracle automatically closes an implicit cursor after executing its associated
SQL statement
For an implicit cursor SQL%ISOPEN always evaluates to FALSE

145
Collections

A collection is an ordered group of elements having the same


data type. Each element is identified by a unique subscript that
represents its position in the collection.
PL/SQL provides three collection types:

• Index-by tables or Associative array


• Nested table
• Variable-size array or Varray

146
Collections - varray

• A varray (variable-size array) is an array whose number of elements can


vary from zero (empty) to the declared maximum size
• To access an element of a varray variable, use the
syntax variable_name(index)
• The lower bound of index is 1. The upper bound is the current number of
elements
• The upper bound changes as you add or delete elements, but it cannot
exceed the maximum size.
• When you store and retrieve a varray from the database, its indexes and
element order remain stable.

Appropriate Uses for Varrays :


A varray is appropriate when:
• You know the maximum number of elements.
• You usually access the elements sequentially.

Declaration of varray

TYPE <type_name> IS VARRAY(<count>) OF NUMBER(<width>);


147
TYPE table_type IS VARRAY(5) OF NUMBER(10);
Collections - varray

A variety of methods exist for collections, but not all are relevant for every
collection type.
EXISTS(n) - Returns TRUE if the specified element exists.
COUNT - Returns the number of elements in the collection.
LIMIT - Returns the maximum number of elements for a VARRAY, or NULL for
nested tables.
FIRST - Returns the index of the first element in the collection.
LAST - Returns the index of the last element in the collection.
PRIOR(n) - Returns the index of the element prior to the specified element.
NEXT(n) - Returns the index of the next element after the specified element.
EXTEND - Appends a single null element to the collection.
EXTEND(n) - Appends n null elements to the collection.
EXTEND(n1,n2) - Appends n1 copies of the n2th element to the collection.
TRIM - Removes a single element from the end of the collection.
TRIM(n) - Removes n elements from the end of the collection.
DELETE - Removes all elements from the collection.
DELETE(n) - Removes element n from the collection.
DELETE(n1,n2) - Removes all elements from n1 to n2 from the collection.

148
Collections - varray

Multiset Operations

The below are the four multi set operations that can be performed

• MULTISET UNION
• MULTISET UNION DISTINCT
• MULTISET EXCEPT
• MULTISET INTERSECT

149
Collections – Nested table

• A nested table is like a one-dimensional array with an arbitrary number of


elements. However, a nested table differs from an array in the following
aspects:
• An array has a declared number of elements, but a nested table does not.
The size of a nested table can increase dynamically.
• An array is always dense, i.e., it always has consecutive subscripts. A
nested array is dense initially, but it can become sparse when elements are
deleted from it.
• some DML operations are possible on nested tables when they are stored in
the database

150
Collections – Nested table

Appropriate Uses for Nested Tables


A nested table is appropriate when:
• The number of elements is not set.
• Index values are not consecutive.
• You must delete or update some elements, but not all elements
simultaneously.
.

151
Collections – Associative array

• An associative array formerly called PL/SQL table or index-by table


• These behave in the same way as arrays except that have no upper bounds,
allowing them to constantly extend
• As the name implies, the collection is indexed
using BINARY_INTEGER values, which do not need to be consecutive.
• The data type of index can be either a string type or PLS_INTEGER
• Indexes are stored in sort order, not creation order
• For string types, sort order is determined by the initialization
parameters NLS_SORT and NLS_COMP.

• Is empty (but not null) until you populate it


• Can hold an unspecified number of elements, which you can access without
knowing their positions

• Does not need disk space or network operations


• Cannot be manipulated with DML statements

152
Collections - Assignments and Equality Tests

Assignments can only be made between collections of the same type. Not
types of similar structures, or with the same name in different packages, but
literally the same type.

153
Bulk Binds

Oracle uses two engines to process PL/SQL code. All procedural code is
handled by the PL/SQL engine while all SQL is handled by the SQL statement
executor, or SQL engine.

There is an overhead associated with each context switch between the two
engines. If PL/SQL code loops through a collection performing the same DML
operation for each item in the collection it is possible to reduce context switches
by bulk binding the whole collection to the DML statement in one operation.

154
BULK COLLECT

Bulk binds can improve the performance when loading collections from a
queries. The BULK COLLECT INTO construct binds the output of the query to
the collection.

Note. The select list must match the collections record definition exactly for this
to be successful.

Remember that collections are held in memory, so doing a bulk collect from a
large query could cause a considerable performance problem. In actual fact
you would rarely do a straight bulk collect in this manner. Instead you would
limit the rows returned using the LIMIT clause and move through the data
processing smaller chunks. This gives you the benefits of bulk binds, without
hogging all the server memory

155
Bulk Load - FORALL

The FORALL syntax allows us to bind the contents of a collection to a single


DML statement, allowing the DML to be run for each row in the collection
without requiring a context switch each time.

SQL%BULK_ROWCOUNT

The SQL%BULK_ROWCOUNT cursor attribute gives granular information


about the rows affected by each iteration of the FORALL statement. Every row
in the driving collection has a corresponding row in
theSQL%BULK_ROWCOUNT cursor attribute.

156
SAVE EXCEPTIONS and SQL%BULK_EXCEPTION

We saw how the FORALL syntax allows us to perform bulk DML operations, but
what happens if one of those individual operations results in an exception? If
there is no exception handler, all the work done by the current bulk operation is
rolled back. If there is an exception handler, the work done prior to the
exception is kept, but no more processing is done. Neither of these situations is
very satisfactory, so instead we should use the SAVE EXCEPTIONS clause to
capture the exceptions and allow us to continue past them. We can
subsequently look at the exceptions by referencing
theSQL%BULK_EXCEPTION cursor attribute.

157
EXCEPTIONS

• An error condition is called an Exception


• When an error occurs, an exception is raised i.e. normal execution stops and
control transfers to the exception handling part of the PL/SQL block or
subprogram
• To handle raised exceptions, separate routines called exception handlers
are written
• There are two types of exceptions
• Pre-defined exceptions (Internal Exceptions)
• User-defined exceptions
• You cannot declare an exception twice in the same block, but can declare
the same exception in two different blocks
• Exceptions declared in a block are local to that block and global to all its
sub-blocks
• Enclosing blocks cannot reference exceptions declared in a sub-block
because blocks can only reference local or global exceptions

158
EXCEPTIONS - Predefined Exceptions

• Are implicitly raised whenever a PL/SQL block violates an Oracle rule or


exceeds a system-dependent limit
• Every Oracle error has a number, but exceptions must be handled by name
• PL/SQL predefines some common Oracle errors as exceptions
• These predefined exceptions are declared globally by PL/SQL
• Some Pre-defined Exceptions
• CURSOR_ALREADY_OPEN
• NO_DATA_FOUND
• TOO_MANY_ROWS
• VALUE_ERROR
• ZERO_DIVIDE
• More than one exception can be handled in a single exception handler by
separating them with the keyword OR

EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
statements;
WHEN OTHERS THEN
statements;
END; 159
EXCEPTIONS – User - defined Exceptions

• User-defined exceptions need to be defined in the declarative part of a


PL/SQL block, subprogram or database trigger
• Declared by naming the exception and defining it as datatype EXCEPTION
• Like variables, user-defined exceptions must be given names
• Unlike variables, user-defined exceptions cannot be assigned values and
cannot be used in SQL statements
• They need to be raised explicitly using the RAISE statement
• A block should RAISE an exception only when an error makes it impossible
or impractical to finish processing
• RAISE statement for a given expression can be coded anywhere within the
scope of that expression
• An exception raised inside a handler immediately propagates to the
enclosing block, which is searched to find a handler for the newly raised
exception
• From there on, the exception propagates normally
• To re-raise an exception place a RAISE statement in its local handler

160
RAISE_application_error

This can be used to create user defined error message, which can be more
descriptive than named exceptions.

Syntax - : Raise_application_error(error number,error message);

where error number is any parameter between -20,000 and -20,999.Error


message is text that is associated with this error. The message parameter must
be less than 512 characters.

161
SQLCODE AND SQLERRM

SQLCODE → Returns the numeric value for the error code.


SQLERRM → Returns the message associated with the error number.

162
Procedure

• Provide Extensibility
• PL/SQL language can be tailored to suit the needs of the application
• Promote reusability and maintainability
• Once validated, they can be used with confidence in any number of
applications
• Simplifies maintenance/enhancement, as subprogram is only affected if
definition changes
• Provide Modularity
• Program can be broken down into manageable, well-defined logical
modules
• Supports top-down design and stepwise refinement approach to
problem solving
• Aid in abstraction
• Allow mental separation from particulars
• Stubs allow programmers to defer definition of procedures/functions
until main program is tested and debugged

163
Procedure

• Procedure performs specific action


• Stored in database and can be invoked or called by any anonymous block
• Can take parameters

Procedure has two parts


Specification
begins with keyword PROCEDURE, ends with procedure name or
parameter list
Body
begins with keyword IS, ends with keyword END followed by optional
procedure name

CREATE [OR REPLACE] PROCEDURE <procedurename>


[(parameter1, … parameterN)] IS
[local declarations]
BEGIN
executable statements;
[EXCEPTION
exception handlers]
END [<procedurename>];
164
Parameter modes for Procedure

Calling a Stored Procedure


Can call a procedure in a PL/SQL statement
Example : branch_sum(‘NYK’);
Can call a procedure from SQL*Plus
Example : EXECUTE branch_sum(‘NYK’);

Three parameter modes


• IN (Default)
• OUT
• IN OUT

165
Parameter modes for Procedure

IN
• allows values to be passed to the subprogram being called
• inside the subprogram it acts like a constant
• actual corresponding parameter can be a constant, literal, initialized
variable or expression
• can be initialized to default values

OUT parameter
• allows values to be returned to the caller of a subprogram
• inside the subprogram it acts like an uninitialized variable
• actual corresponding parameter must be a variable; it cannot be a
constant or expression
• its value cannot be assigned to another variable or reassigned to itself

166
Parameter modes for Procedure

IN OUT parameter
• allows initial values to be passed and returns updated values to the
caller
• inside the subprogram it acts like an initialized variable
• actual corresponding parameter must be a variable; it cannot be a
constant or expression
• can be assigned a value and its value can be assigned to another
variable

167
Autonomous Transaction

Autonomous Transactions provide a new method of controlling transactions in


stored procedures. Autonomous Transactions allow you to create a new sub
transaction that may commit or rollback changes independent of the parent
transaction.

168
Functions

• Subprogram that returns a value


• Have a RETURN clause
• Stored in database and can be invoked or called by any anonymous block
• Generally take parameters
• Datatype specifier in parameter declaration must be unconstrained
• Has two parts
• Specification
• begins with keyword FUNCTION, ends with RETURN clause
• Body
• begins with keyword IS, ends with keyword END followed by
optional function name

CREATE [OR REPLACE] FUNCTION <functionname> [(argument1, …


argumentN)] RETURN datatype IS
[local declarations]
BEGIN
executable statements;
[EXCEPTION
exception handlers]
END [<functionname>]; 169
Functions

The RETURN Statement

• Immediately completes execution of subprogram and returns control to caller


• In procedures
• cannot contain an expression
• returns control to the caller before normal end of procedure is reached
• In functions
• must contain an expression, evaluated when it is executed

170
Packages

• Database objects that group logically related PL/SQL types, objects and
subprograms
• They cannot be called, passed parameters to or nested
• There are two parts
• Specification
• Body

Advantages of Packages
• Modularity
• Easier Application Design
• Information Hiding
• Better performance

171
Packages

Package Specification
• Is an interface to the applications
• Declares the types, variables, constants, exceptions, cursors and
subprograms available for use
• Holds public declarations, visible to the application
• Can be thought of as an operational interface
• Scope of the declarations are local to the database schema and global to the
package
• Lists the package resources available to applications
• Created using CREATE PACKAGE command

Syntax for Package Specification –

CREATE [OR REPLACE] PACKAGE <packagename> AS


Global variables declaration;
Procedure specifications;
Function specifications;
Type Definitions;
Cursor Declarations
END [<packagename>]; 172
Packages

Package Body
• Implements the package specification
• Fully defines cursors and subprograms
• Holds implementation details and private declarations, hidden from the
application
• Can be thought of as a ‘black body’
• Can be replaced, enhanced or replaced without changing the interface
• Can be changed without recompiling calling programs
• Scope of the declarations are local to the package body
• Declared types and objects are inaccessible except from within the package
body
• Initialization part of a package is run only once, the first time the package is
referenced
Syntax for Package Body –
CREATE [OR REPLACE] PACKAGE BODY <packagename> AS
Private members (variables and procedure/functions/cursors/types)
Procedure Code;
Function Code;
Implementation of Types;
Use of Cursors;
173
Using Global variables in the members of the package.
TRIGGERS

• It is a stored PL/SQL program unit associated with a specific database table


• Oracle executes (fires) the trigger automatically whenever a given SQL
operation affects the table
• They are invoked implicitly
• They are useful for customizing a database
• They should be used only when necessary
• Can automatically generate derived column values
• Can prevent invalid transactions
• Can enforce complex security authorizations
• Can enforce referential integrity across nodes in a distributed database
• Can enforce complex business rules
• Can provide transparent event logging
• Can provide sophisticated auditing
• Can maintain synchronous table replicates
• Can gather statistics on table access
• Can derive column values automatically
• Can restrict DML operations to regular business hours

174
TRIGGERS

CREATE [OR REPLACE] TRIGGER <triggername>


BEFORE|AFTER
INSERT|DELETE|UPDATE OF <columnnames> ON <tablename>
[FOR EACH ROW]
WHEN (<condition>)
<PL/SQL Block>

• Name in the ON clause identifies the database table associated with the
trigger
• The trigger event specifies the SQL DML statement (INSERT, DELETE or
UPDATE) that affects the table
• AFTER specifies that the trigger fires after the manipulation is done
• BEFORE specifies that the trigger fires before the manipulation is done
• By default, a trigger fires once per table
• FOR EACH ROW specifies that the trigger fires once per row
• For the trigger to fire, the Boolean expression in the WHEN clause must
evaluate to TRUE
• REPLACE can be added to the CREATE statement to drop and re-create
the trigger automatically

175
TRIGGERS

• Prefix :new is a correlation name that refers to the newly updated column
value
• Within a trigger, the :new and :old values of changing rows can be
referenced
• A single trigger can handle more than one operation

176

You might also like