Oracle Database PDF
Oracle Database PDF
Oracle Database PDF
Contents
1 Introduction
1.1 Installing Oracle
1.1.1 Starting script
1.1.2 Identifying system requirements
1.2 References
2 Database Interfaces
2.1 SQL*Plus
2.2 Web interface
2.3 Oracle SQL Developer
2.4 DBCA
2.5 Hello world
2.6 References
3 Tables
3.1 Architecture
3.2 Create tablespaces
3.3 Create schemas
3.4 List tables
3.5 Create tables
3.6 Available data types
3.7 Reviewing the table structure
3.8 Modify tables structure
3.9 Drop tables
3.10 Insert rows
3.11 Read a table
3.12 Update rows
3.13 Delete rows
3.14 Partitioning
3.14.1 Range
3.14.2 Hash
3.14.3 List
3.14.4 Interval
3.15 Explaining how constraints are created at the time of table creation
3.16 References
4 SELECT Statement
4.1 Listing the capabilities of SQL SELECT statements
4.2 Executing a basic SELECT statement
4.3 Describing various types of conversion functions that are available in SQL
4.4 Using the TO_CHAR, TO_NUMBER, and TO_DATE conversion functions
4.5 Applying conditional expressions in a SELECT statement
4.6 Describing various types of functions available in SQL
4.7 Using character, number, and date functions in SELECT statements
4.8 Identifying the available group functions
4.9 Describing the use of group functions
4.10 Grouping data by using the GROUP BY clause
4.11 Including or excluding grouped rows by using the HAVING clause
4.12 Writing SELECT statements to access data from more than one table using equijoins and nonequijoins
13 PL/SQL
13.1 PL/SQL
13.1.1 Introduction
13.1.2 Advantages of PL/SQL
13.1.3 Limitation
13.1.4 Basic Structure
13.1.5 PL/SQL Placeholders
13.1.5.1 PL/SQL Variables
13.1.5.2 PL/SQL Records
13.1.5.3 Scope of Variables and Records
13.1.5.4 PL/SQL Constants
13.1.6 PL/SQL Conditional Statements
13.1.7 PL/SQL Iterative Statements
13.1.8 PL/SQL Cursors
13.1.8.1 Implicit cursor:
13.1.8.2 Explicit cursor:
13.1.9 PL/SQL Exception Handling
13.1.10 PL/SQL Procedures
13.1.11 PL/SQL Functions
13.1.12 Parameters-Procedure, Function
13.1.13 PL/SQL Triggers
14 Multimedia Databases
14.1 Description
14.2 Utilization
14.3 References
15 Spatiotemporal Databases
15.1 Spatial data
15.2 Objects
15.3 Spatiotemporal data
15.4 Indexation
15.5 Link with the GIS
15.6 Examples
15.7 References
16 10g Advanced SQL
17 Joins
17.1 NATURAL JOIN
17.2 INNER JOIN
17.3 OUTER JOIN
17.3.1 FULL OUTER JOIN
17.3.2 LEFT OUTER JOIN
17.3.3 RIGHT OUTER JOIN
18 Subqueries
18.1 Operators
18.1.1 UNION [ALL]
18.1.2 MINUS
18.1.3 INTERSECT
19 Case Statements
19.1 Basic Usage
19.2 Searched Case
20 Regular Expression Support
20.1 List the benefits of using regular expressions
20.2 Use regular expressions to search for, match, and replace strings
20.2.1 REGEXP_LIKE
20.2.2 REGEXP_INSTR
20.2.3 REGEXP_SUBSTR
20.2.4 REGEXP_COUNT
21 Security
21.1 Applying the principle privilege
21.2 Managing accounts
Introduction
Oracle RDBMS is one of the most used relational database system[1]. Its request language is called the PL/SQL.
Installing Oracle
As with most software products, it must be installed; Windows, Linux and Unix versions are available for use, and there are
four editions available.
Once downloaded, the .zip file(s) must be extracted, if they are two their folders must be merged (they are named "database"),
and launch to install:
In Linux, runInstaller.sh.
In Windows, setup.exe.
Starting script
Oracle Database launches automatically at each boot, which slows the system significantly. To avoid this:
If the message "Access denied" occurs, relaunch the script with a right click, as an administrator.
The system objects naming follows the Optimal Flexible Architecture (OFA). [3]
References
1. http://db-engines.com/en/ranking
2. https://docs.oracle.com/html/B13614_01/preinsta.htm#i1067829
3. https://docs.oracle.com/cd/E11882_01/install.112/e47689/appendix_ofa.htm#LADBI1381
Database Interfaces
SQL*Plus
SQL*Plus is a command interface provided with the DBMS. On Windows it can be launched either from:
The start menu, Oracle folder, Run SQL Command Line shortcut.
The path C:\oraclexe\app\oracle\product\11.2.0\server\bin\sqlplus.exe.
But the best is to use the environment variable and to connect to the DBMS at the same time, with a shell console. By
default it can be done with:
sqlplus / as sysdba
sqlplus MyAccount/MyPassword@localhost
Web interface
A second interface is provided with the DBMS: the web interface. It can be accessed from:
For SE 12c :
https://localhost:5500/em/shell
For XE 11g :
The start menu, Oracle folder, Get Started shortcut.
The URL http://localhost:8080/apex/f?p=4950.
For XE 10g :
The start menu, Oracle folder, Database control.
http://localhost:1158/em/console/logon/logon.
The console appears after, allowing to modify the database configuration (service restart, architecture, performances,
backups...).
By clicking on Application Express, we can optionally create a new connection user account, which will be used to connect to
Oracle. Once logged, it can access to some the database manipulation tools, for example SQL Workshop\SQL Commands to
enter some SQL code.
Attention: if you create a first account with the GUI, they will need the default SQL*Plus account for GRANT.
Once installed and launched, we have to set a connection to let it be authenticated on the Oracle databases. Just fill the
account created on the web interface, to access to the data manipulation options.
For example by clicking on the top left on New (the plus icon or CTRL + N), we can open an SQL file to begin to execute
some code.
DBCA
Database Configuration Assistant (DBCA) is a graphical interface[1] available on Windows or the *nixes[2] .
Hello world
Once one SQL console of those seen previously launched, it becomes possible to execute some PL/SQL (Procedural
Language/Structured Query Language): the procedural language created by Oracle, and specific to its relational database.
BEGIN
DBMS_OUTPUT.put_line ('Hello World!');
END;
References
1. http://www.snapdba.com/2013/05/creating-an-oracle-11g-database-using-dbca-non-asm/
2. http://docs.oracle.com/cd/B16351_01/doc/server.102/b14196/install003.htm
Tables
Architecture
The Oracle architecture considers one database per server, in which we can find several tablespaces, equivalent to the MySQL
and MS-SQL databases objects, containing tables and stored procedures.
In the Windows Express version, these data are stored into C:\oraclexe\app\oracle\oradata\XE.
Create tablespaces
Once connected, it's possible to begin to create some tables directly, in the default tablespace. However before, we can add
some tablespaces in some defined files:
Create schemas
A schema is a permission accorded to a set of elements[1], like tables and stored procedures. The keyword AUTHORIZATION
specifies the user name:
List tables
SELECT owner, table_name FROM all_tables;
Create tables
Example:
Table created.
In SQL Developer, with a right click on the tables, New table..., we can generate and execute this creation in an array, which is
translated into PL/SQL in the DDL tab:
, address VARCHAR2(255)
, CONSTRAINT client1_PK PRIMARY KEY (ID) ENABLE
) TABLESPACE Wikibooks;
We can also set the table tablespace, by selecting it into the GUI, or with the keyword TABLESPACE in the creation clause.
1. Characters:
1. CHAR: 2 kB.
2. VARCHAR: 4 kB.
3. VARCHAR2: 4 kB, synonymous of VARCHAR.
4. NCHAR: 2 kB.
5. NVARCHAR2: 4 kB.
2. Numeric:
1. NUMBER.
2. BINARY_INTEGER.
3. BINARY_FLOAT.
4. BINARY_DOUBLE.
3. Date:
1. DATE.
2. TIMESTAMP.
4. RAW.
5. LONG RAW.
6. BLOB.
7. CLOB.
8. NCLOB.
9. ROWID.
10. UROWID.
11. BFILE.
12. XMLType.
13. UriType.
Drop tables
DROP TABLE client1;
Insert rows
INSERT INTO client1 (last, first, address) VALUES ('Doe', 'Jane', 'UK'), ('Doe', 'Jane', 'UK');
1 line created.
Read a table
To get its structure:
desc client1;
If the table doesn't exist, the error which occurs is: ORA-00923: FROM keyword not found where expected.
Update rows
UPDATE client1 SET address = 'US' WHERE id = 1;
Delete rows
DELETE client1 WHERE ID = 2;
Partitioning
The Oracle partitioning is a process to split a huge table into several smaller ones in order to increase its performance.
Range
Example:
Hash
Example:
List
Example:
Interval
Example:
Primary Key and Unique constraints both ensure the data is not duplicated. Primary Key also ensure the data is not null.
Oracle will automatically generate index for Primary Key and Unique constraints. A table can only have one Primary Key, but
Foreign Key ensure the data exists in the column of the parent table it refer to. Each parent record can have multiple child
records, but each child can relate to ONLY one parent record. A column with Foreign Key may not necessary to have an
index.
Foreign Key can only refer to column with Primary Key or Unique Constraint
alter table tblB add (constraint colX_FK foreign key (colX) references tblA(colX));
-- ORA-02270: no matching unique or primary key for this column-list
A table can ONLY have one Primary Key, but it can have multiple UNIQUE key. if the child table(s) require to referencing
column other than primary key, the column on the parent table must have UNIQUE constraint.
Insert data into a column with FK, the value must already exist in the column that the FK reference to.
As long as a foreign key exist, the parent table can truncate/delete the data or disable the PK or Unique constraint
desc all_constraints;
select
a.owner, a.table_name, a.constraint_name,
a.constraint_type, a.status, a.r_owner, a.r_constraint_name,
b.table_name as r_table_name, b.status as r_status
from all_constraints a
left join all_constraints b on a.owner = b.owner and a.r_constraint_name = b.constraint_name
where a.table_name like 'TBL%';
select *
from all_cons_columns
where table_name like 'TBL%';
Disable constraint that have foreign key refer to is not allowed, in order to do this, you have to disable the foreign key first.
If the data in parent table is deleted, re-enable the foreign key that contain data reference to the missing data is not allowed.
Generate a SQL statements to disable all the Foreign Key on a specified table
select
'alter table '||a.owner||'.'||a.table_name||
' disable constraint '||a.constraint_name||';' as STMT
from all_constraints a, all_constraints b
where a.constraint_type = 'R'
and a.r_constraint_name = b.constraint_name
and a.r_owner = b.owner
and b.table_name = 'TBLA';
References
1. https://docs.oracle.com/cd/B12037_01/server.101/b10759/statements_6013.htm
2. https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm
SELECT Statement
Listing the capabilities of SQL SELECT statements
A SELECT statement retrieves data from database. With a SELECT statement, you can use the following capabilities:
SELECT *
FROM hr.employees;
Escape the single quote character use alternative quote (q) operator
DESC[RIBE] table
Implicit conversion occurs when Oracle attempts to convert the values, that do not match the defined parameters of functions,
into the required data types.
Explicit data type conversion Explicit conversion occurs when a function like TO_CHAR is invoked to change the data type
of a value.
Character functions
Writing SELECT statements to access data from more than one table using
equijoins and nonequijoins
Viewing data that generally does not meet a join condition by using outer joins
List the comparison operators and logical operators that are used in a WHERE clause
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to (can also use != or ^=)
BETWEEN ... AND ... Between two values (inclusive)
IN (set) Match any value in a list
LIKE Match a character pattern '%' - zero or many; '_' - one character
IS NULL is a null value
AND returns TRUE if both conditions are true
OR returns TRUE if either condition is true
NOT returns TRUE if the condition is false
Temporarily store values with single-ampersand (&) and double-ampersand (&&) substitution
WHERE conditions
ORDER BY clauses
Column expressions
Table names
Entire SELECT statements
--any &column_name after the &&column_name will not prompt for value again
SELECT employee_id, last_name, job_id, &&column_name
FROM hr.employees
ORDER BY &column_name ;
Controlling
Start and stop iSQL*Plus
Storage Structures
The purpose of tablespaces and datafiles
Creating tablespaces
Managing tablespaces (alter, drop, generate DDL, take offline, put on line, add
data files, make read-only/read-write)
Dropping tablespaces
Administering Users
Within Oracle, users may be managed through the webpage under the administration section, and within the Database Users
subsection.
New users can be created by an administrator or a user who has a "CREATE USER" privilege using Oracle Enterprise
Manager GUI by clicking on the "Create" link in the "Users" section . Enter the username and password for the new user. You
can also set the password to expire (where the user must change the password on the next login), and whether an account is
locked (to prevent a user from connecting to the system).
In most cases, users should belong to the Connect role. If the user needs to create tables or have more advanced capability, the
user should be placed within the Resource role. Database admins should appear in the DBA role. If desired, users may be
given individual permissions within Directly Grant Privileges section.
Alternatively, users can also be created using the "CREATE USER" SQL command.
Eg: CREATE USER test IDENTIFIED BY 'naveen123' DEFAULT TABLESPACE USER_DATA PASSWORD EXPIRE
After creating the user CONNECT role needs to be granted for the user to connect to the database.
Removing users
When a user no longer needs to be present within the database, you click the drop button within the web interface.
Defining constraints
Adding constraints
Creating indexes
Managing Data
Manipulating data through SQL using INSERT, UPDATE, and DELETE
Views
Creating simple and complex views
Dictionary views
Explaining the data dictionary
Understanding synonyms
Adding comments
SQL
1. Write queries that contain a WHERE clause to limit the output retrieved
2. List the comparison operators and logical operators that are used in a WHERE clause
3. Describe the rules of precedence for comparison and logical operators
4. Use character string literals in the WHERE clause
1. Write queries that contain an ORDER BY clause sort the output of a SELECT statement
2. Sort output in descending and ascending order
the ampersand operator is used to take the input at runtime( ex:-&employeename) and if ampersand is used twice i.e && then
it will take the input of single ampersand operator and is used to provide data to the query at runtime.
* Describe the differences between single row and multiple row functions
* Manipulate strings with character function in the SELECT and WHERE clauses
* Manipulate numbers with the ROUND, TRUNC and MOD functions
* Perform arithmetic with date data
* Manipulate dates with the date functions
Implicit conversion occurs when Oracle attempts to convert the values, that do not match the defined parameters of functions,
into the required data types.
Explicit data type conversion Explicit conversion occurs when a function like TO_CHAR is invoked to change the data type
of a value.
View data that generally does not meet a join condition by using outer joins
Manipulating Data
Describe each data manipulation language (DML) statement
Syntax:
Example:
By the above query the employee table gets populated by empid:-1 , empname:-'Rahul' and empdesignation:-'Manager'.
It will update all the rows present in the table by the given value in the selected field.
We can also add queries to this command to make a real use for example,
update [table name] set [column name] = [value] where [column name]>=[value];
You can add your query after the where clause according to your need.
Example:
Defining subqueries
Controlling transactions
1. Save and discard changes with the COMMIT and ROLLBACK statements
2. Explain read consistency
The above Query will create a table named employee with which contain columns empid , empname , empdesignation
followed by their datatypes/
Primary Key and Unique constraints both ensure the data is not duplicated. Primary Key also ensure the data is not null.
Oracle will automatically generate index for Primary Key and Unique constraints. A table can only have one Primary Key, but
it can have multiple unique constraints.
Foreign Key ensure the data exists in the column of the parent table it refer to. Each parent record can have multiple child
records, but each child can relate to ONLY one parent record. A column with Foreign Key may not necessary to have an
index.
Foreign Key can only refer to column with Primary Key or Unique Constraint
alter table tblB add (constraint colX_FK foreign key (colX) references tblA(colX));
-- ORA-02270: no matching unique or primary key for this column-list
A table can ONLY have one Primary Key, but it can have multiple UNIQUE key. if the child table(s) require to referencing
column other than primary key, the column on the parent table must have UNIQUE constraint.
Insert data into a column with FK, the value must already exist in the column that the FK reference to.
As long as a foreign key exist, the parent table can truncate/delete the data or disable the PK or Unique constraint
desc all_constraints;
select
a.owner, a.table_name, a.constraint_name,
a.constraint_type, a.status, a.r_owner, a.r_constraint_name,
b.table_name as r_table_name, b.status as r_status
from all_constraints a
left join all_constraints b on a.owner = b.owner and a.r_constraint_name = b.constraint_name
where a.table_name like 'TBL%';
select *
from all_cons_columns
where table_name like 'TBL%';
Disable constraint that have foreign key refer to is not allowed, in order to do this, you have to disable the foreign key first.
If the data in parent table is deleted, re-enable the foreign key that contain data reference to the missing data is not allowed.
Generate a sql statements to disable all the Foreign Key on a specified table
select
'alter table '||a.owner||'.'||a.table_name||
' disable constraint '||a.constraint_name||';' as STMT
from all_constraints a, all_constraints b
where a.constraint_type = 'R'
and a.r_constraint_name = b.constraint_name
and a.r_owner = b.owner
and b.table_name = 'TBLA';
Grant roles
Create indexes
Understand synonyms
Add comments
Use data types that store the difference between two date-time values
Hierarchical Query
Hierarchical Query allows you the transverse through a self-reference table and display the Hierarchical structure. eg. the
employee table contain the manager id the employee.
Regular Expression
Class Expression Description
Anchoring ^ Start of a line
Character -$ End of a line
* Match 0 or more times
+ Match 1 or more times
? Match 0 or 1 time
Quantifier
{m} Match exactly m times
Character
{m,} Match at least m times
{m, n} Match at least m times but no more than n times
\n Cause the previous expression to be repeated n times
Separates alternates, often used with grouping operator ()
Groups subexpression into a unit for alternations, for quantifiers, or for backreferencing (see
Alternative and ()
"Backreferences" section)
Grouping
Indicates a character list; most metacharacters inside a character list are understood as
[char]
literals, with the exception of character classes, and the ^ and - metacharacters
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:blank:] Blank Space Characters
[:cntrl:] Control characters (nonprinting)
[:digit:] Numeric digits
[:graph:] Any [:punct:], [:upper:], [:lower:], and [:digit:] chars
Posix Character
[:lower:] Lowercase alphabetic characters
[:print:] Printable characters
[:punct:] Punctuation characters
[:space:] Space characters (nonprinting), such as carriage return, newline, vertical tab, and form feed
[:upper:] Uppercase alphabetic characters
[:xdigit:] Hexidecimal characters
An equivalence classes embedded in brackets that matches a base letter and all of its
Equivalence class = =
accented versions. eg, equivalence class '[=a=]' matches ä and â.
c Case sensitive matching
i Case insensitive matching
Match Option
m Treat source string as multi-line activating Anchor chars
n Allow the period (.) to match any newline character
PL/SQL
PL/SQL
Introduction
PL/SQL stands for Procedural Language extension of SQL. It is a combination of SQL along with the procedural features of
programming languages and it enhances the capabilities of SQL by injecting the procedural functionality, like conditional or
looping statements, into the set-oriented SQL structure.
Advantages of PL/SQL
Procedural Language Capability: PL/SQL consists of procedural language constructs such as conditional statements (if
else statements) and loops like (FOR loops).
Block Structures: PL/SQL consists of blocks of code, which can be nested within each other. Each block forms a unit of
a task or a logical module. PL/SQL Blocks can be stored in the database and reused.
Better Performance: PL/SQL engine processes multiple SQL statements simultaneously as a single block, thereby
reducing network traffic.
Exception Handling: PL/SQL handles exceptions (or errors) effectively during the execution of a PL/SQL program.
Once an exception is caught, specific actions can be taken depending upon the type of the exception or it can be
displayed to the user with a message.
Limitation
PL/SQL can only use SELECT, DML(INSERT, UPDATE, DELETE) and TC(COMMIT, ROLLBACK, SAVEPOINT)
statements, DDL (CREATE, ALTER, DROP) and DCL(GRANT, REVOKE) cannot be used directly. Any DDL/DCL
however, can be executed from PL/SQL when embedded in an EXECUTE IMMEDIATE statement.
Basic Structure
Each PL/SQL program consists of SQL and PL/SQL statements which form a PL/SQL block. A PL/SQL Block consists of
three sections:
Declaration Section: This section is optional and it starts with the reserved keyword DECLARE. This section is used to
declare any placeholders like variables, constants, records and cursors, which are used to manipulate data in the execution
section.
Execution Section: This section is mandatory and it starts with the reserved keyword BEGIN and ends with END. This
section is where the program logic is written to perform any task. The programmatic constructs like loops, conditional
statement and SQL statements form the part of execution section.
Exception Section: The section is optional and it starts with the reserved keyword EXCEPTION. Any exception in the
program can be handled in this section, so that the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains
exceptions that cannot be handled, the block terminates abruptly with errors.
Every statement in the above three sections must end with a ; (semicolon). PL/SQL blocks can be nested within other PL/SQL
blocks. Comments can be used to document code.
/* multi-lines comments */
-- single line comments
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/SQL Placeholders
Placeholders are temporary storage area. Placeholders can be any of Variables, Constants and Records. Oracle defines
placeholders to store data temporarily, which are used to manipulate data during the execution of a PL SQL block.
Depending on the kind of data you want to store, you can define placeholders with a name and a datatype. Few of the
datatypes used to define placeholders are as given below.
Number(n,m), Char(n), Varchar2(n), Date, Long, Long Raw, Raw, Blob, Clob, Nclob, Bfile
The placeholders, that store the values, can change through the PL/SQL Block.
PL/SQL Variables
The below example declares two variables, one of which is a not null.
DECLARE
emp_id varchar2(10);
salary number(9,2) NOT NULL := 1000.00;
The value of a variable can change in the execution or exception section of the PL/SQL Block. We can assign values to
variables in the two ways given below.
variable_name:= value;
SELECT column_name
INTO variable_name
FROM table_name
[WHERE condition];
The example below will get the salary of an employee with id '12345' and display it on the screen.
DECLARE
var_emp_id varchar2(10) = 'A12345';
var_salary number(9,2);
BEGIN
SELECT salary
INTO var_salary
FROM employee
WHERE emp_id = var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('Employee ' || var_emp_id || ' earns salary ' || var_salary);
END;
/
NOTE: The slash '/' indicates to execute the above PL/SQL Block.
PL/SQL Records
Records are composite datatypes, which contains a combination of different scalar datatypes like char, varchar, number etc.
Each scalar data types in the record holds a value. A record can store values of a row in a table.
A datatype can be declared in the same way as you create a table, like col_name_1. If a field is based on a column from
database table, you can define the datatype as col_name_2. You can also use %type method to declare datatype of variable
and constant. Similar to %type, if all the fields of a record are based on the columns of a table, it can be declared by
using %rowtype method.
record_name table_name%ROWTYPE;
For Example:
DECLARE
TYPE rec_employee IS RECORD
(emp_id varchar2(10),
emp_last_name employees.last_name%type,
emp_dept employees.dept%type,
salary number(9,2)
);
DECLARE
rec_employee employees%ROWTYPE;
Declaring the record as a ROWTYPE Advantages: 1) Do not need to explicitly declare variables for all the columns in a table.
2) If the column specification in the database table is altered, the code does not need to update.
Disadvantage: 1) When a record is created as a ROWTYPE, fields will be created for all the columns in the table and memory
will be used to create the datatype for all the fields.
Assign values to record Similar to variable, you can assign value to record either by direct assign or through the SELECT
statements
record_name.col_name := value;
var_name := record_name.col_name;
PL/SQL allows the nesting of Blocks within Blocks i.e, the Execution section of an outer block can contain inner blocks.
Variables which are accessible to an outer Block are also accessible to all nested inner blocks; however, the variables declared
in the inner blocks are not accessible to the outer blocks.
Local variables - These are declared in a inner block and cannot be referenced by outer blocks.
Global variables - These are declared in an outer block and can be referenced by its itself and by its inner blocks.
In the below example, two variables are created in the outer block and assigning their product to the third variable created in
the inner block. The variables 'var_num1' and 'var_num2' can be accessed anywhere in the block; however, the variable
'var_result' is declared in the inner block, so it cannot be accessed in the outer block.
DECLARE
var_num1 number;
var_num2 number;
BEGIN
var_num1 := 100;
var_num2 := 200;
DECLARE
var_result number;
BEGIN
var_result := var_num1 * var_num2;
END;
/* var_result is not accessible to here */
END;
/
PL/SQL Constants
As the name implies a constant is a value used in a PL/SQL Block that remains unchanged throughout the program. A
constant is a user-defined literal value. You can declare a constant and use it instead of actual value.
For example:
DECLARE
comm_pct CONSTANT number(3) := 10;
You must assign a value to the constant while declaring it. If you assign a value to the constant later, Oracle will prompt
exception.
PL/SQL supports programming language features like conditional statements, iterative statements.
IF condition_1 THEN
statement_1;
statement_2;
[ELSIF condtion_2 THEN
statement_3;]
[ELSE
statement_4;]
END IF;
An iterative statements are used when you want to repeat the execution of one or more statements for specified number of
times. There are three types of loops in PL/SQL:
1. Simple Loop A Simple Loop is used when a set of statements is to be executed at least once before the loop terminates. An
EXIT condition must be specified in the loop, otherwise the loop will get into an infinite number of iterations. When the EXIT
condition is satisfied the process exits from the loop.
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
Note: a) Initialize a variable before the loop body. b) Increment the variable in the loop. c) Use a EXIT WHEN statement to
exit from the Loop. If you use a EXIT statement without WHEN condition, the statements in the loop is executed only once.
2. While Loop A WHILE LOOP is used when a set of statements has to be executed as long as a condition is true. The
condition is evaluated at the beginning of each iteration. The iteration continues until the condition becomes false.
WHILE <condition>
LOOP statements;
END LOOP;
Note: a) Initialize a variable before the loop body. b) Increment the variable in the loop. c) EXIT WHEN statement and EXIT
3. FOR Loop A FOR LOOP is used to execute a set of statements for a pre-determined number of times. Iteration occurs
between the start and end integer values given. The counter is always incremented by 1. The loop exits when the counter
reaches the value of the end integer.
Note: a) The counter variable is implicitly declared in the declaration section, so it's not necessary to declare it explicitly. b)
The counter variable is incremented by 1 and does not need to be incremented explicitly. c) EXIT WHEN statement and EXIT
statements can be used in FOR loops but it is seldom used.
PL/SQL Cursors
A cursor contains information on a select statement and the rows of data accessed by it. This temporary work area is used to
store the data retrieved from the database, and manipulate this data. A cursor can hold more than one row, but can process
only one row at a time. The set of rows the cursor holds is called the active set.
Implicit cursor:
When you execute DML statements like DELETE, INSERT, UPDATE and SELECT..INTO statements, implicit statements are
created to process these statements.
Oracle provides few attributes called as implicit cursor attributes to check the status of DML operations. The cursor attributes
available are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN.
For example, When you execute INSERT, UPDATE, or DELETE statements the cursor attributes tell us whether any rows are
affected and how many have been affected. When a SELECT... INTO statement is executed in a PL/SQL Block, implicit
cursor attributes can be used to find out whether any row has been returned by the SELECT statement. PL/SQL returns an
error when no data is selected.
The status of the cursor for each of these attributes are defined in the below table.
The return value is FALSE, if DML statements like INSERT, DELETE and UPDATE at least one
row and if SELECT ….INTO statement return at least one row.
SQL%NOTFOUND
The return value is TRUE, if a DML statement like INSERT, DELETE and UPDATE do not affect
even one row and if SELECT ….INTO statement does not return a row.
SQL%ROWCOUNT Return the number of rows affected by the DML operations INSERT, DELETE, UPDATE, SELECT
SQL%ISOPEN Always return FALSE
In the above PL/SQL Block, the salaries of all the employees in the 'employee' table are updated. If none of the employee's
salary are updated we get a message 'None of the salaries where updated'. Else we get a message like for example, 'Salaries for
100 employees are updated' if there are 100 rows in 'employee' table.
Explicit cursor:
An explicit cursor is defined in the declaration section of the PL/SQL Block. It must be created when you are executing a
SELECT statement that returns more than one row. Even though the cursor stores multiple records, only one record can be
processed at a time, which is called as current row. When you fetch a row the current row position moves to next row.
Declaration
For example:
DECLARE
CURSOR cur_emp IS
SELECT *
FROM employees
WHERE salary > 10000;
Using Cursor When a cursor is opened, the first row becomes the current row. When the data is fetched it is copied to the
record or variables and the logical pointer moves to the next row and it becomes the current row. On every fetch statement,
the pointer moves to the next row. If you want to fetch after the last row, the program will throw an error. When there is more
than one row in a cursor we can use loops along with explicit cursor attributes to fetch all the records.
OPEN cursor_name;
FETCH cursor_name INTO record_name|variable_list;
CLOSE cursor_name;
Note:
We can fetch the rows in a cursor to a PL/SQL Record or a list of variables created in the PL/SQL Block.
If you are fetching a cursor to a PL/SQL Record, the record should have the same structure as the cursor.
If you are fetching a cursor to a list of variables, the variables should be listed in the same order in the fetch statement as
the columns are present in the cursor.
When we try to open a cursor which is not closed in the previous operation, it throws exception.
When we try to fetch a cursor after the last operation, it throws exception.
For Example:
DECLARE
rec_emp employees%rowtype;
CURSOR cur_emp IS
SELECT *
FROM employees
WHERE salary > 10000;
BEGIN
OPEN cur_emp;
FETCH cur_emp INTO rec_emp;
dbms_output.put_line (rec_emp.first_name || ' '
|| rec_emp.last_name);
CLOSE emp_cur;
END;
Oracle provides some attributes known as Explicit Cursor Attributes to control the data processing while using cursors. We use
these attributes to avoid errors while accessing cursors through OPEN, FETCH and CLOSE Statements.
DECLARE
CURSOR cur_emp IS
SELECT first_name, last_name, salary FROM employees;
rec_emp cur_emp%rowtype;
BEGIN
IF NOT cur_emp%ISOPEN THEN
OPEN cur_emp;
END IF;
LOOP
FETCH cur_emp INTO rec_emp;
EXIT WHEN cur_emp%NOTFOUND;
dbms_output.put_line(cur_emp.first_name || ' ' ||cur_emp.last_name
|| ' ' ||cur_emp.salary);
END LOOP;
END;
/
The cursor attribute %ISOPEN is used to check if the cursor is open, if the condition is true the program does not open the
cursor again. The cursor attribute %NOTFOUND is used to check whether the fetch returned any row. If there is no row
found, the program would exit. Typically, when the cursor reach the last row, no more row can be fetched.
DECLARE
CURSOR cur_emp IS
SELECT first_name, last_name, salary FROM employees;
rec_emp cur_emp%rowtype;
BEGIN
IF NOT cur_emp%ISOPEN THEN
OPEN cur_emp;
END IF;
FETCH cur_emp INTO sales_rec;
WHILE cur_emp%FOUND THEN
LOOP
dbms_output.put_line(cur_emp.first_name || ' ' ||cur_emp.last_name
|| ' ' ||cur_emp.salary);
FETCH cur_emp INTO sales_rec;
END LOOP;
END;
/
Using %FOUND to evaluate if the first fetch statement returned a row, if TRUE, the program moves into the while loop. Inside
the loop, use fetch statement again to process the next row. If the fetch statement is not executed once before the while loop,
the while condition will return false in the first instance and the while loop is skipped.
Cursor with a FOR Loop: When using FOR LOOP, you do not need to declare a record or variables to store the cursor values,
do not need to open, fetch and close the cursor. These functions are accomplished by the FOR LOOP automatically.
DECLARE
CURSOR cur_emp IS
SELECT first_name, last_name, salary FROM employees;
rec_emp cur_emp%rowtype;
BEGIN
FOR rec_emp in cur_emp
LOOP
dbms_output.put_line(cur_emp.first_name || ' ' ||cur_emp.last_name
|| ' ' ||cur_emp.salary);
END LOOP;
END;
/
When the FOR loop is processed a record 'rec_emp' of structure 'cur_emp' gets created, the cursor is opened, the rows are
fetched to the record 'rec_emp' and the cursor is closed after the last row is processed. By using FOR Loop, you can reduce
the number of lines in the program.
PL/SQL Procedures
When calling store procedure from the PL/SQL Block, you simply use the store procedure name to call. If you prefix the
'EXECUTE' keyword in front of the store procedure name, you will receive an error.
my_sproc;
EXECUTE my_sproc;
PLS-00103: Encountered the symbol "my_sproc" when expecting one of the following:
:= . ( @ % ; immediate
The symbol ":=" was substituted for "my_sproc" to continue.
PL/SQL Functions
Parameters-Procedure, Function
PL/SQL Triggers
Multimedia Databases
Description
Oracle Multimedia is a services suite provided with Oracle Database (excluding the Express version where it can't be
added[1]) since the version 8 (in 1997), to manage the multimedia databases.
It's composed by the package ORDSYS ("ORD" for object-relational data) allowing the multimedia objects management into
the database[2]. This package includes several classes[3]:
ORDMultimedia: abstract superclass storage the common attributes and methods to the classes ORDAudio, ORDImage,
and ORDVideo[4].
ORDAudio: sound properties storage.
ORDDoc: heterogeneous properties storage.
ORDImage: images properties storage.
ORDVideo: videos properties storage.
ORDSource: multimedia BLOB or BFILE (accessible in HTTP) properties storage[5].
DICOM (Digital Imaging and Communications in Medicine[6]).
Attributes
ORDAudio[7] ORDDoc[8] ORDImage[9] ORDVideo[10]
description source source description
source format height source
format mimeType width format
mimeType contentLength contentLength mimeType
comments comments fileFormat comments
encoding contentFormat width
numberOfChannels compressionFormat height
sampleSize mimeType frameResolution
compressionType frameRate
audioDuration videoDuration
numberOfFrames
compressionType
numberOfColors
bitRate
Utilization
CREATE TABLE MyImages (
id INTEGER PRIMARY KEY,
image ORDSYS.ORDImage
);
References
1. "Managing Oracle Multimedia Installations". http://www.comp.dit.ie/btierney/Oracle11gDoc/appdev.111/b28415
/ap_instl_upgrd.htm.
2. "Gestion avancée d'image sous Oracle avec Java" (in French). http://fildz.developpez.com/tutoriel/oracle-
java/ordimage/.
3. "Common Methods and Notes for Oracle Multimedia Object Types". https://docs.oracle.com/cd/E11882_01/appdev.112
/e10776/ch_comref.htm#AIVUG3000.
4. "Common Methods and Notes for Oracle Multimedia Object Types". https://docs.oracle.com/html/A67296_01
/im_mmref.htm#998184.
5. Lynne Dunckley, Larry Guros (8 avril 2011). Digital Press. ed. Oracle 10g Developing Media Rich Applications.
https://books.google.fr/books?id=-dbeFbCswAYC&pg=PA60&
dq=ORDSYS++ORDAudio+ORDDoc+ORDImage+ORDVideo+ORDSource&hl=fr&
sa=X&ved=0ahUKEwj7z9jC5OPKAhVHMhoKHXsYCr8Q6AEIJjAB#v=onepage&q=ORDSYS
%20%20ORDAudio%20ORDDoc%20ORDImage%20ORDVideo%20ORDSource&f=false.
6. "Medical Imaging and Communication". https://docs.oracle.com/database/121/IMDCM/ch_intro.htm#IMDCM1100.
7. "ORDAudio". https://docs.oracle.com/cd/B19306_01/appdev.102/b14297/ch_audref.htm.
8. "ORDDoc". https://docs.oracle.com/cd/B28359_01/appdev.111/b28414/ch_docref.htm.
9. "ORDImage". https://docs.oracle.com/cd/B28359_01/appdev.111/b28414/ch_imgref.htm.
10. "ORDVideo". https://docs.oracle.com/cd/B28359_01/appdev.111/b28414/ch_vidref.htm.
Spatiotemporal Databases
43 sur 73 03/06/2016 02:34
Oracle Database/Print version - Wikibooks, open books for an open world https://en.wikibooks.org/w/index.php?title=Oracle_Database/Print_ver...
Spatial data
When typing the fields, some represent graphical objects, and so are considered as "Spatial" (cf. spatial database).
Consequently, they are manipulated with different requests than for the text.
With Oracle, its implemented since the version 7, in an extension of the Enterprise EditionDownload (http://www.oracle.com
/technetwork/database/options/spatialandgraph/downloads/index-093371.html), provided objects with the prefix SDO for Spatial Data
Option.
Objects
To store the spatial objects, we use the field type SDO_GEOMETRY, and the seven methods to manipulate it[1]:
1. Get_Dims
2. Get_GType
3. Get_LRS_Dim
4. Get_WKB
5. Get_WKT
6. ST_CoordDim
7. ST_IsValid
Spatiotemporal data
We use a predicate to foresee the stored objects movement[3]. However, the spatiotemporal databases need frequent updates.
Indexation
Les modes d'indexation choisis par Oracle pour les données spatiales sont l'arbre R[4], l'arbre Q, et le Z-order[5].
GRASS GIS[6]
QGIS
If the software need an ODBC data source to access to the Oracle databases:
1. Launch %windir%\system32\odbcad32.exe.
2. Add a system source. The Oracle driver can be chosen in the list if the DBMS is installed.
3. Fill the TNS service name with the name which can be found into C:\oraclexe\app\oracle\product\11.2.0\server\network
\ADMIN\tnsnames.ora.
4. Then write the password of the connection created with SQL*Plus.
Examples
http://download.oracle.com/otndocs/products/spatial/pdf/au_melbourne06_start.pdf
http://download.oracle.com/otndocs/products/spatial/pdf/GeocodingInOracleUsing_HERE_MapContent.pdf
References
1. "SDO_GEOMETRY Object Type". https://docs.oracle.com/cd/B19306_01/appdev.102/b14255
/sdo_objrelschema.htm#i1004087.
2. "Spatial Operators". https://docs.oracle.com/cd/B19306_01/appdev.102/b14255/sdo_operat.htm.
3. "Authorizing Access to Dynamic Spatial-Temporal Data". http://www.oracle.com/technetwork/articles/vanvelden-
spatial-095837.html.
4. "Spatial Concepts". https://docs.oracle.com/html/A88805_01/sdo_intr.htm.
5. "ZOrder Method". http://docs.oracle.com/cd/E20213_01/doc/win.112/e17727/dcmethods006.htm.
6. "Geographic Resources Analysis Support System (GRASS): More Than a Mapping Tool". http://www.oracle.com
/technetwork/articles/mitasova-grass-092663.html.
Joins
Join queries combine rows from two or more tables, views, or materialized views. If multiple tables are listed in the query's
FROM clause the Oracle Database performs a join. Columns from any of the tables may be listed in the select list. Columns
that exist in both tables, however, must be qualified, in order to avoid ambiguity.
The following query returns the mortgage information for all payments received from customers during the year 2007.
NATURAL JOIN
The NATURAL JOIN joins two tables which contain a column or multiple columns with the same name and data-type.
The following query joins the customer table to the invoice table with a natural join, the natural join utilizes the customer_id
that is present on both the customer table and the invoice table. It returns the customer and invoice data for invoices that have
not had any payments made on them.
INNER JOIN
Most of the commonly used joins are actually INNER JOINs. The INNER JOIN joins two or more tables, returning only the
rows that satisfy the JOIN condition. Here are some examples of INNER JOINs.
This joins the customer and order table, connecting the customers to their orders. The result contains a combined list of
customers and their orders, if a customer does not have an order, they are omitted from the result.
OUTER JOIN
The OUTER JOIN joins two or more tables, returning all values whether or not the join condition is met. When a value exists
in one table but not the other, nulls are used in the place of the columns that are joined to a record without a JOIN companion.
There are three specific types of outer joins: FULL OUTER JOIN, LEFT OUTER JOIN and RIGHT OUTER JOIN.
With the FULL OUTER JOIN the query will return rows from either of the tables joined, whether or not there is any matching
data on the table joined. If no matching data exists, nulls are placed into the fields where data would have otherwise existed.
In the following example, the data in a table is synced with the data that is regularly imported into a data import table via SQL
Loader. A stored procedure is then used to see if anything was added, updated or removed and the rows are merged
accordingly.
With the LEFT OUTER JOIN the query will return rows only if the row exists in the table specified on the left side of the join.
When no matching data is found from the table on the right side of the join, nulls are placed into the fields where the data
would have otherwise existed.
The following example will return all of the customers and their associated cases if they have one. If the customer has no case
then it will only return the data for the customer.
With the RIGHT OUTER JOIN the query will return rows only if the row exists in the table specified on the right side of the
join. When no matching data is found from the table on the left side of the join, nulls are placed into the fields where the data
would have otherwise existed.
The following example will return a list of trucks and their cargo. If a truck has no cargo then a null will be put in place of the
field specifying the cargo's load_id.
Subqueries
Operators
UNION [ALL]
The UNION operator outputs the items that exist in both result sets. The UNION ALL operator outputs all of the items in the
two sets, whether or not both sets contain the item.
The following query returns all customers from San Francisco whose balance is 100000 and 500000.
MINUS
The query after the MINUS operator is removed from the result set of the queries before the operator.
In the following example, the first part of the query gets all of the customers. In the second part of the inactive customers are
taken out. Finally, in the third part of the query, customers with zip codes between 80000 and 90000 removed from the set.
INTERSECT
The INTERSECT operator only returns the results that are present in both of the queries.
The following example returns all of the customers who have a balance due in Los Angeles.
Case Statements
The following queries are equivalent, they return all of the customers from Switzerland. The CASE statement translates the
single character status flags "A" and "I" to "ACTIVE" and "INACTIVE" If a value is NULL then it returns the string "NULL"
Basic Usage
The simplest form of a CASE statement specifies the variable and then the possible values to check for.
SELECT customer_id,
CASE status
WHEN 'A' THEN 'ACTIVE'
WHEN 'I' THEN 'INACTIVE'
ELSE 'NULL'
END
FROM customer
WHERE country_name = 'SWITZERLAND';
Searched Case
The searched CASE expression is the more advanced form of case. Instead of specifying the value to be checked at the
beginning, each WHEN statement has a comparison that is checked.
SELECT customer_id,
CASE
WHEN status = 'A' THEN 'ACTIVE'
WHEN status = 'I' THEN 'INACTIVE'
ELSE 'NULL'
END
FROM customer
WHERE country_name = 'SWITZERLAND';
Regular Expression
Class Expression Description
Anchoring ^ Start of a line
Character $ End of a line
* Match 0 or more times
+ Match 1 or more times
? Match 0 or 1 time
Quantifier
{m} Match exactly m times
Character
{m,} Match at least m times
{m, n} Match at least m times but no more than n times
\n Cause the previous expression to be repeated n times
| Separates alternates, often used with grouping operator ()
Groups subexpression into a unit for alternations, for quantifiers, or for
Alternative and ()
backreferencing (see "Backreferences" section)
Grouping
Indicates a character list; most metacharacters inside a character list are understood
[char]
as literals, with the exception of character classes, and the ^ and - metacharacters
[:alnum:] Alphanumeric characters
[:alpha:] Alphabetic characters
[:blank:] Blank Space Characters
[:cntrl:] Control characters (nonprinting)
[:digit:] Numeric digits
[:graph:] Any [:punct:], [:upper:], [:lower:], and [:digit:] chars
Posix Character [:lower:] Lowercase alphabetic characters
[:print:] Printable characters
[:punct:] Punctuation characters
Space characters (nonprinting), such as carriage return, newline, vertical tab, and
[:space:]
form feed
[:upper:] Uppercase alphabetic characters
[:xdigit:] Hexidecimal characters
An equivalence classes embedded in brackets that matches a base letter and all of its
Equivalence class = =
accented versions. eg, equivalence class '[=a=]' matches ä and â.
c Case sensitive matching
i Case insensitive matching
Match Option
m Treat source string as multi-line activating Anchor chars
n Allow the period (.) to match any newline character
ignore white space
x
characters
REGEXP_LIKE
REGEXP_LIKE performs complex regular expression pattern matching and supports much greater range of string patterns
than LIKE. this function is introduced in 10g.
last name begin with T and the 2nd character is either 'o' or 'u'
SELECT last_name
FROM hr.employees
WHERE REGEXP_LIKE(last_name, '^T[ou]');
select last_name
from hr.employees
where REGEXP_LIKE( last_name, '^T.*r$' );
SELECT first_name
FROM hr.employees
WHERE REGEXP_LIKE (first_name, '^Ste(v|ph)en$');
last name contain double vowel characters (ie. 'aa', 'ee', 'ii', 'oo', 'uu') and the matching is non-case sensitive
SELECT last_name
FROM hr.employees
WHERE REGEXP_LIKE (last_name, '([aeiou])\1', 'i');
REGEXP_INSTR
REGEXP_INSTR performs complex regular expression pattern matching and supports much greater range of string patterns
than INSTR. this function is introduced in 10g.
REGEXP_SUBSTR
REGEXP_SUBSTR performs complex regular expression pattern matching and supports much greater range of string patterns
than SUBSTR. this function is introduced in 10g.
extract the 1st character if the last name start with 'A' or 'C'
REGEXP_COUNT
REGEXP_COUNT performs count against a value and it is different from the aggregate COUNT function. This function is
introduced in 11g.
Security
Applying the principle privilege
Managing accounts
Granting roles
syntax:GRANT role TO user example: GRANT dba TO scott
Net Services
Using Database Control to create additional listeners
Using the Oracle Net Manager to configure client and middle-tier connections
Shared Servers
Identifying when to use Oracle Shared Servers
A shared server can treat several users processes. [1]
References
1. https://docs.oracle.com/cd/B28359_01/server.111/b28310/manproc001.htm
Performance Monitoring
On the oracle database Web administration tool, there is a usage monitor shown on the right-hand side of the screen. This
displays both the Storage used by Oracle and the current Memory in use. It also lists the total sessions and users.
For a more detailed view of server settings, Enter the Administration section, and open the Monitor.
Proactive Maintenance
Setting warning and critical alert thresholds
Undo Management
Managing deadlocks
Identifying the importance of checkpoints, redo log files, and archived log files
Backups
Creating consistent database backups
Managing backups
Recovery
Recovering from loss of a control file
Using RMAN:
If flash recovery area is configured and control file auto backup is on then:
This will restore the control file to the location specified by the initialization parameter CONTROL_FILES mentioned in
initialization parameter.
If flash recovery area is configured and control file auto backup is off then:
This will restore the control file to the location specified by the initialization parameter CONTROL_FILES mentioned in
initialization parameter.
This will restore the control file to the location specified by the initialization parameter CONTROL_FILES mentioned in
initialization parameter.
If no flash recovery area is configured, no recovery catalog is available and RMAN backup piece is available at default
location then:
XML Cheatsheet
Oracle XML Reference
Oracle possesses a variety of powerful XML features. A tremendous amount of documentation exists regarding Oracle's XML
features. This resource is intended to be a cheat sheet for those of us who don't have time to wade through the hundreds of
pages of documentation, but instead wish to quickly understand how to create simple XML output and input XML into a
database.
DBMS_XMLGEN
Overview
See also:
Functions
getXML()
Gets the XML document by fetching the maximum number of rows specified. It appends the XML document to the CLOB
passed in. Use this version of GETXML Functions to avoid any extra CLOB copies and to reuse the same CLOB for
subsequent calls. Because of the CLOB reuse, this GETXML Functions call is potentially more efficient.
Syntax:
DBMS_XMLGEN.GETXML (
ctx IN ctxHandle,
tmpclob IN OUT NCOPY CLOB,
dtdOrSchema IN number := NONE)
RETURN BOOLEAN;
Generates the XML document and returns it as a temporary CLOB. The temporary CLOB obtained from this function must be
freed using the DBMS_LOB.FREETEMPORARY call:
DBMS_XMLGEN.GETXML (
ctx IN ctxHandle,
dtdOrSchema IN number := NONE)
RETURN CLOB;
Converts the results from the SQL query string to XML format, and returns the XML as a temporary CLOB, which must be
subsequently freed using the DBMS_LOB.FREETEMPORARY call:
DBMS_XMLGEN.GETXML (
sqlQuery IN VARCHAR2,
dtdOrSchema IN number := NONE)
RETURN CLOB;
Example:
The following procedure parses the fields in the employee table into XML and saves the XML as CLOB rows in a table.
END LOOP;
END dump_pcd;
setRowSetTag()
Sets the name of the root element of the document. The default name is ROWSET. Setting the rowSetTag to NULL will stop
this element from being output. An error is produced if both the row and the rowset are NULL and there is more than one
column or row in the output. The error is produced because the generated XML would not have a top-level enclosing tag.
Syntax:
DBMS_XMLGEN.setRowSetTag (
ctx IN ctxHandle,
rowSetTag IN VARCHAR2);
Example:
Sample output:
This encloses the entire XML result set in the tag specified by the second parameter.
<ALL ROWS>
<ROW>
<NAME>John Doe</NAME>
</ROW>
<ROW>
<NAME>Jane Doe</NAME>
</ROW>
...
</ALL ROWS>
setRowTag()
This function sets the name of the element each row. The default name is ROW. Setting this to NULL suppresses the ROW
element itself. This produces an error if both the row and the rowset are NULL and there is more than one column or row in
the output. The error is returned because the generated XML must have a top-level enclosing tag.
Syntax:
DBMS_XMLGEN.setRowTag (
ctx IN ctxHandle,
rowTag IN VARCHAR2);
Example:
This tells the XML generator to enclose the columns of each row in an AUTHOR tag.
Sample output:
<ROWSET>
<AUTHOR>
<NAME>John Doe</NAME>
</AUTHOR>
<AUTHOR>
<NAME>Jane Doe</NAME>
</AUTHOR>
...
</ROWSET>
Examples
Dumping a Query Result as XML
<?xml version=''1.0''?>
<ROWSET>
<EMPLOYEE>
<EMPLOYEE_ID>30</EMPLOYEE_ID>
<LAST_NAME>SCOTT</LAST_NAME>
<SALARY>20000<SALARY>
</EMPLOYEE>
<EMPLOYEE>
<EMPLOYEE_ID>31</EMPLOYEE_ID>
<LAST_NAME>MARY</LAST_NAME>
<AGE>25</AGE>
</EMPLOYEE>
</ROWSET>
SQL Cheatsheet
This "cheat sheet" covers most of the basic functionality that an Oracle DBA needs to run basic queries and perform basic
tasks. It also contains information that a PL/SQL programmer frequently uses to write stored procedures. The resource is
useful as a primer for individuals who are new to Oracle, or as a reference for those who are experienced at using Oracle.
A great deal of information about Oracle exists throughout the net. We developed this resource to make it easier for
programmers and DBAs to find most of the basics in one place. Topics beyond the scope of a "cheatsheet" generally provide a
link to further research.
Oracle XML Reference—the XML reference is still in its infancy, but is coming along nicely.
SELECT
The SELECT statement is used to retrieve rows selected from one or more tables, object tables, views, object views, or
materialized views.
SELECT *
FROM beverages
WHERE field1 = 'Kona'
AND field2 = 'coffee'
AND field3 = 122;
SELECT INTO
Select into takes the values name, address and phone number out of the table employee, and places them into the variables
v_employee_name, v_employee_address, and v_employee_phone_number.
This only works if the query matches a single item. If the query returns no rows it raises the NO_DATA_FOUND built-in
exception. If your query returns more than one row, Oracle raises the exception TOO_MANY_ROWS.
SELECT name,address,phone_number
INTO v_employee_name,v_employee_address,v_employee_phone_number
FROM employee
WHERE employee_id = 6;
INSERT
The INSERT statement adds one or more new rows of data to a database table.
DELETE
UPDATE
updates the column invoice as paid when paid column has more than zero.
SEQUENCES
Sequences are database objects that multiple users can use to generate unique integers. The sequence generator generates
sequential numbers, which can help automatically generate unique primary keys, and coordinate keys across multiple rows or
tables.
CREATE SEQUENCE
For example:
ALTER SEQUENCE
It is sometimes necessary to create a query from a string. That is, if the programmer wants to create a query at run time
(generate an Oracle query on the fly), based on a particular set of circumstances, etc.
Care should be taken not to insert user-supplied data directly into a dynamic query string, without first vetting the data very
strictly for SQL escape characters; otherwise you run a significant risk of enabling data-injection hacks on your code.
Here is a very simple example of how a dynamic query is done. There are, of course, many different ways to do this; this is
just an example of the functionality.
PROCEDURE oracle_runtime_query_pcd IS
TYPE ref_cursor IS REF CURSOR;
l_cursor ref_cursor;
v_query varchar2(5000);
v_name varchar2(64);
BEGIN
v_query := 'SELECT name FROM employee WHERE employee_id=5';
OPEN l_cursor FOR v_query;
LOOP
FETCH l_cursor INTO v_name;
EXIT WHEN l_cursor%NOTFOUND;
END LOOP;
CLOSE l_cursor;
END;
String operations
Length
Length returns an integer representing the length of a given string. It can be referred to as: lengthb, lengthc, length2, and
length4.
length( string1 );
Instr
Instr returns an integer that specifies the location of a sub-string within a string. The programmer can specify which
appearance of the string they want to detect, as well as a starting position. An unsuccessful search returns 0.
Replace
Replace looks through a string, replacing one string with another. If no other string is specified, it removes the string specified
in the replacement string parameter.
Substr
Substr returns a portion of the given string. The "start_position" is 1-based, not 0-based. If "start_position" is negative, substr
counts from the end of the string. If "length" is not given, substr defaults to the remaining length of the string.
returns "pl/sql" since the "p" in "pl/sql" is in the 8th position in the string (counting from 1 at the "o" in "oracle")
returns "cheatsheet" since "c" is in the 15th position in the string and "t" is the last character in the string.
returns "cheat" since "c" is the 10th character in the string, counting from the end of the string with "t" as position 1.
Trim
These functions can be used to filter unwanted characters from strings. By default they remove spaces, but a character set can
be specified for removal as well.
DDL SQL
Tables
Create table
For example:
Add column
For example:
Modify column
For example:
Drop column
For example:
Constraints
Displaying constraints
SELECT
table_name,
constraint_name,
constraint_type
FROM user_constraints;
The following statement shows all referential constraints (foreign keys) with both source and destination table/column
couples:
SELECT
c_list.CONSTRAINT_NAME as NAME,
c_src.TABLE_NAME as SRC_TABLE,
c_src.COLUMN_NAME as SRC_COLUMN,
c_dest.TABLE_NAME as DEST_TABLE,
c_dest.COLUMN_NAME as DEST_COLUMN
FROM ALL_CONSTRAINTS c_list,
ALL_CONS_COLUMNS c_src,
ALL_CONS_COLUMNS c_dest
WHERE c_list.CONSTRAINT_NAME = c_src.CONSTRAINT_NAME
AND c_list.R_CONSTRAINT_NAME = c_dest.CONSTRAINT_NAME
AND c_list.CONSTRAINT_TYPE = 'R'
GROUP BY c_list.CONSTRAINT_NAME,
c_src.TABLE_NAME,
c_src.COLUMN_NAME,
c_dest.TABLE_NAME,
c_dest.COLUMN_NAME;
The syntax for creating a check constraint using a CREATE TABLE statement is:
For example:
The syntax for creating a unique constraint using a CREATE TABLE statement is:
For example:
For example:
Deleting constraints
For example:
INDEXES
An index is a method that retrieves records with greater efficiency. An index creates an entry for each value that appears in
the indexed columns. By default, Oracle creates B-tree indexes.
Create an index
UNIQUE indicates that the combination of values in the indexed columns must be unique.
COMPUTE STATISTICS tells Oracle to collect statistics during the creation of the index. The statistics are then used by the
optimizer to choose an optimal execution plan when the statements are executed.
For example:
In this example, an index has been created on the customer table called customer_idx. It consists of only of the
customer_name field.
In Oracle, you are not restricted to creating indexes on only columns. You can create function-based indexes.
For example:
An index, based on the uppercase evaluation of the customer_name field, has been created.
To assure that the Oracle optimizer uses this index when executing your SQL statements, be sure that
UPPER(customer_name) does not evaluate to a NULL value. To ensure this, add UPPER(customer_name) IS NOT NULL to
your WHERE clause as follows:
Rename an Index
For example:
If you need to collect statistics on the index after it is first created or you want to update the statistics, you can always use the
ALTER INDEX command to collect statistics. You collect statistics so that oracle can use the indexes in an effective manner.
This recalcultes the table size, number of rows, blocks, segments and update the dictionary tables so that oracle can use the
data effectively while choosing the execution plan.
For example:
In this example, statistics are collected for the index called customer_idx.
Drop an index
For example:
DBA Related
User Management
Creating a user
For example:
Granting privileges
For example:
Change password
For example:
There are two methods of backing up and restoring database tables and data. The 'exp' and 'imp' tools are simpler tools geared
towards smaller databases. If database structures become more complex or are very large ( > 50 GB for example) then using
the RMAN tool is more appropriate.
This command is used to import Oracle tables and table data from a *.dmp file created by the 'exp' tool. Remember that this a
command that is executed from the command line through $ORACLE_HOME/bin and not within SQL*Plus.
imp KEYWORD=value
imp HELP=yes
An example:
PL/SQL
Operators
(incomplete)
Arithmetic operators
Addition: +
Subtraction: -
Multiplication: *
Division: /
Power (PL/SQL only): **
Examples
Comparison operators
Examples
SELECT name, salary, email FROM employees WHERE salary > 40000;
String operators
Concatenate: ||
create or replace procedure addtest( a in varchar2(100), b in varchar2(100), c out varchar2(200) ) IS begin C:=concat(a,'-',b);
Date operators
Addition: +
Subtraction: -
Types
Scalar type (defined in package STANDARD): NUMBER, CHAR, VARCHAR2, BOOLEAN, BINARY_INTEGER,
LONG\LONG RAW, DATE, TIMESTAMP(and its family including intervals)
Composite types (user-defined types): TABLE, RECORD, NESTED TABLE and VARRAY
For example
name Books.title%type; /* name is defined as the same type as column 'title' of table Books */
Note:
1. Anchored variables allow for the automatic synchronization of the type of anchored variable with the type of <obj>
when there is a change to the <obj> type.
2. Anchored types are evaluated at compile time, so recompile the program to reflect the change of <obj> type in the
anchored variable.
Collections
A collection is an ordered group of elements, all of the same type. It is a general concept that encompasses lists, arrays, and
other familiar datatypes. Each element has a unique subscript that determines its position in the collection.
my_book_rec book_rec%TYPE;
my_book_rec_tab book_rec_tab%TYPE;
...
my_book_rec := my_book_rec_tab(5);
find_authors_books(my_book_rec.author);
...
Dramatically faster execution speed, thanks to transparent performance boosts including a new optimizing compiler,
better integrated native compilation, and new datatypes that help out with number-crunching applications.
The FORALL statement, made even more flexible and useful. For example, FORALL now supports nonconsecutive
indexes.
Regular expressions are available in PL/SQL in the form of three new functions (REGEXP_INSTR,
REGEXP_REPLACE, and REGEXP_SUBSTR) and the REGEXP_LIKE operator for comparisons. (For more
information, see "First Expressions" by Jonathan Gennick in this issue.)
Collections, improved to include such things as collection comparison for equality and support for set operations on
nested tables.
see also:
Stored logic
Functions
[EXCEPTION
exception_section]
END [function_name];
For example:
Procedures
A procedure differs from a function in that it must not return a value to the caller.
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
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [IN|OUT|IN OUT] [DEFAULT value] [,parameter]) ]
cursor student_cur is
select studentId, studentName
from course
where course.courseId = courseId;
student_rec student_cur%ROWTYPE;
BEGIN
OPEN student_cur;
LOOP
FETCH student_cur INTO student_rec;
EXIT WHEN student_cur%NOTFOUND;
numberOfStudents := numberOfStudents + 1;
END LOOP;
CLOSE student_cur;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR- '||SQLERRM);
END GetNumberOfStudents;
anonymous block
DECLARE
x NUMBER(4) := 0;
BEGIN
x := 1000;
BEGIN
x := x + 100;
EXCEPTION
WHEN OTHERS THEN
x := x + 2;
END;
x := x + 10;
dbms_output.put_line(x);
EXCEPTION
WHEN OTHERS THEN
x := x + 3;
END;
There are three basic syntaxes for passing parameters to a stored procedure: positional notation, named notation and mixed
notation.
The following examples call this procedure for each of the basic syntaxes for parameter passing:
Positional notation
Specify the same parameters in the same order as they are declared in the procedure. This notation is compact, but if you
specify the parameters (especially literals) in the wrong order, the bug can be hard to detect. You must change your code if the
procedure's parameter list changes.
Named notation
Specify the name of each parameter along with its value. An arrow (=>) serves as the association operator. The order of the
parameters is not significant. This notation is more verbose, but makes your code easier to read and maintain. You can
sometimes avoid changing code if the procedure's parameter list changes, for example if the parameters are reordered or a new
optional parameter is added. Named notation is a good practice to use for any code that calls someone else's API, or defines an
API for someone else to use.
create_customer(p_address => '301 Anystreet', p_id => 33, p_name => 'James Whitfield', p_phone => '251-222-3154');
Mixed notation
Specify the first parameters with positional notation, then switch to named notation for the last parameters. You can use this
notation to call procedures that have some required parameters, followed by some optional parameters.
Table functions
Flow control
Conditional Operators
and: AND
or: OR
not: NOT
Example
IF salary > 40000 AND salary <= 70000 THEN() ELSE IF salary>70000 AND salary<=100000 THEN() ELSE()
If/then/else
IF [condition] THEN
[statements]
ELSEIF [condition] THEN
[statements}
ELSEIF [condition] THEN
[statements}
ELSEIF [condition] THEN
[statements}
ELSEIF [condition] THEN
[statements}
ELSEIF [condition] THEN
[statements}
ELSEIF [condition] THEN
[statements}
ELSEIF [condition] THEN
[statements}
ELSE
[statements}
END IF;
Arrays
Associative arrays
Example
Very simple example, the index is the key to accessing the array so there is no need to loop through the whole table
unless you intend to use data from every line of the array.
The index can also be a numeric value.
DECLARE
-- Associative array indexed by string:
-- Printed results:
Population of Megalopolis is 1000000
Population of Midland is 750000
Population of Smallville is 2001
DECLARE
-- Record type
TYPE apollo_rec IS RECORD
(
commander VARCHAR2(100),
launch DATE
);
-- Associative array type
TYPE apollo_type_arr IS TABLE OF apollo_rec INDEX BY VARCHAR2(100);
-- Associative array variable
apollo_arr apollo_type_arr;
BEGIN
DBMS_OUTPUT.PUT_LINE(apollo_arr('Apollo 11').commander);
DBMS_OUTPUT.PUT_LINE(apollo_arr('Apollo 11').launch);
end;
/
-- Printed results:
Neil Armstrong
16-JUL-69
APEX
String substitution
* In SQL: :VARIABLE
* In PL/SQL: V('VARIABLE') or NV('VARIABLE')
* In text: &VARIABLE.
External links
PSOUG reference (http://www.psoug.org/reference/)
More Wikibooks
Introduction to SQL