Oracle Database Notes For Professionals
Oracle Database Notes For Professionals
Oracle Database
Notes for Professionals
®
Database
Notes for Professionals
100+ pages
of professional hints and tricks
Disclaimer
GoalKicker.com This is an unocial free book created for educational purposes and is
not aliated with ocial Oracle® Database group(s) or company(s).
Free Programming Books All trademarks and registered trademarks are
the property of their respective owners
Contents
About ................................................................................................................................................................................... 1
Chapter 1: Getting started with Oracle Database ....................................................................................... 2
Section 1.1: Hello World ................................................................................................................................................. 2
Section 1.2: SQL Query .................................................................................................................................................. 2
Section 1.3: Hello world! from table .............................................................................................................................. 2
Section 1.4: Hello World from PL/SQL ......................................................................................................................... 3
Chapter 2: Getting started with PL/SQL ........................................................................................................... 4
Section 2.1: Hello World ................................................................................................................................................. 4
Section 2.2: Definition of PL/SQL ................................................................................................................................. 4
Section 2.3: Dierence between %TYPE and %ROWTYPE ........................................................................................ 5
Section 2.4: Create or replace a view .......................................................................................................................... 6
Section 2.5: Create a table ........................................................................................................................................... 6
Section 2.6: About PL/SQL ........................................................................................................................................... 6
Chapter 3: Anonymous PL/SQL Block ................................................................................................................ 8
Section 3.1: An example of an anonymous block ....................................................................................................... 8
Chapter 4: PL/SQL procedure ............................................................................................................................... 9
Section 4.1: Syntax ......................................................................................................................................................... 9
Section 4.2: Hello World ................................................................................................................................................ 9
Section 4.3: In/Out Parameters ................................................................................................................................... 9
Chapter 5: Data Dictionary ................................................................................................................................... 11
Section 5.1: Describes all objects in the database ................................................................................................... 11
Section 5.2: To see all the data dictionary views to which you have access ........................................................ 11
Section 5.3: Text source of the stored objects ......................................................................................................... 11
Section 5.4: Get list of all tables in Oracle ................................................................................................................. 11
Section 5.5: Privilege information .............................................................................................................................. 11
Section 5.6: Oracle version ......................................................................................................................................... 12
Chapter 6: Dates ......................................................................................................................................................... 13
Section 6.1: Date Arithmetic - Dierence between Dates in Days, Hours, Minutes and/or Seconds ................. 13
Section 6.2: Setting the Default Date Format Model ............................................................................................... 14
Section 6.3: Date Arithmetic - Dierence between Dates in Months or Years ...................................................... 14
Section 6.4: Extract the Year, Month, Day, Hour, Minute or Second Components of a Date .............................. 15
Section 6.5: Generating Dates with No Time Component ....................................................................................... 16
Section 6.6: Generating Dates with a Time Component ......................................................................................... 16
Section 6.7: The Format of a Date ............................................................................................................................. 17
Section 6.8: Converting Dates to a String ................................................................................................................. 17
Section 6.9: Changing How SQL/Plus or SQL Developer Display Dates ............................................................... 18
Section 6.10: Time Zones and Daylight Savings Time ............................................................................................. 18
Section 6.11: Leap Seconds ......................................................................................................................................... 19
Section 6.12: Getting the Day of the Week ............................................................................................................... 19
Chapter 7: Working with Dates ........................................................................................................................... 20
Section 7.1: Date Arithmetic ........................................................................................................................................ 20
Section 7.2: Add_months function ............................................................................................................................ 20
Chapter 8: DUAL table ............................................................................................................................................. 22
Section 8.1: The following example returns the current operating system date and time .................................. 22
Section 8.2: The following example generates numbers between start_value and end_value ........................ 22
Chapter 9: JOINS ......................................................................................................................................................... 23
Section 9.1: CROSS JOIN ............................................................................................................................................. 23
Section 9.2: LEFT OUTER JOIN .................................................................................................................................. 24
Section 9.3: RIGHT OUTER JOIN ................................................................................................................................ 25
Section 9.4: FULL OUTER JOIN .................................................................................................................................. 27
Section 9.5: ANTIJOIN ................................................................................................................................................. 28
Section 9.6: INNER JOIN ............................................................................................................................................. 29
Section 9.7: JOIN ......................................................................................................................................................... 30
Section 9.8: SEMIJOIN ................................................................................................................................................. 30
Section 9.9: NATURAL JOIN ....................................................................................................................................... 31
Chapter 10: Handling NULL values .................................................................................................................... 33
Section 10.1: Operations containing NULL are NULL, except concatenation ........................................................ 33
Section 10.2: NVL2 to get a dierent result if a value is null or not ....................................................................... 33
Section 10.3: COALESCE to return the first non-NULL value ................................................................................... 33
Section 10.4: Columns of any data type can contain NULLs .................................................................................. 33
Section 10.5: Empty strings are NULL ....................................................................................................................... 33
Section 10.6: NVL to replace null value ..................................................................................................................... 34
Chapter 11: String Manipulation ........................................................................................................................... 35
Section 11.1: INITCAP .................................................................................................................................................... 35
Section 11.2: Regular expression ................................................................................................................................ 35
Section 11.3: SUBSTR ................................................................................................................................................... 35
Section 11.4: Concatenation: Operator || or concat() function ................................................................................ 36
Section 11.5: UPPER ...................................................................................................................................................... 36
Section 11.6: LOWER .................................................................................................................................................... 37
Section 11.7: LTRIM / RTRIM ....................................................................................................................................... 37
Chapter 12: IF-THEN-ELSE Statement .............................................................................................................. 38
Section 12.1: IF-THEN ................................................................................................................................................... 38
Section 12.2: IF-THEN-ELSE ........................................................................................................................................ 38
Section 12.3: IF-THEN-ELSIF-ELSE .............................................................................................................................. 38
Chapter 13: Limiting the rows returned by a query (Pagination) ...................................................... 39
Section 13.1: Get first N rows with row limiting clause .............................................................................................. 39
Section 13.2: Get row N through M from many rows (before Oracle 12c) ............................................................. 39
Section 13.3: Get N numbers of Records from table ................................................................................................ 39
Section 13.4: Skipping some rows then taking some ............................................................................................... 40
Section 13.5: Skipping some rows from result .......................................................................................................... 40
Section 13.6: Pagination in SQL .................................................................................................................................. 40
Chapter 14: Recursive Sub-Query Factoring using the WITH Clause (A.K.A. Common
Table Expressions) ..................................................................................................................................................... 42
Section 14.1: Splitting a Delimited String .................................................................................................................... 42
Section 14.2: A Simple Integer Generator .................................................................................................................. 42
Chapter 15: Dierent ways to update records ........................................................................................... 44
Section 15.1: Update using Merge .............................................................................................................................. 44
Section 15.2: Update Syntax with example ............................................................................................................... 44
Section 15.3: Update Using Inline View ...................................................................................................................... 44
Section 15.4: Merge with sample data ....................................................................................................................... 45
Chapter 16: Update with Joins ............................................................................................................................. 47
Section 16.1: Examples: what works and what doesn't ............................................................................................. 47
Chapter 17: Functions ............................................................................................................................................... 49
Section 17.1: Calling Functions .................................................................................................................................... 49
Chapter 18: Statistical functions ......................................................................................................................... 50
Section 18.1: Calculating the median of a set of values ........................................................................................... 50
Chapter 19: Window Functions ............................................................................................................................. 51
Section 19.1: Ratio_To_Report ................................................................................................................................... 51
Chapter 20: Creating a Context .......................................................................................................................... 52
Section 20.1: Create a Context ................................................................................................................................... 52
Chapter 21: Splitting Delimited Strings ............................................................................................................ 53
Section 21.1: Splitting Strings using a Hierarchical Query ........................................................................................ 53
Section 21.2: Splitting Strings using a PL/SQL Function .......................................................................................... 53
Section 21.3: Splitting Strings using a Recursive Sub-query Factoring Clause ..................................................... 54
Section 21.4: Splitting Strings using a Correlated Table Expression ...................................................................... 55
Section 21.5: Splitting Strings using CROSS APPLY (Oracle 12c) ............................................................................. 56
Section 21.6: Splitting Strings using XMLTable and FLWOR expressions .............................................................. 57
Section 21.7: Splitting Delimited Strings using XMLTable ........................................................................................ 57
Chapter 22: Collections and Records ............................................................................................................... 59
Section 22.1: Use a collection as a return type for a split function ........................................................................ 59
Chapter 23: Object Types ....................................................................................................................................... 60
Section 23.1: Accessing stored objects ...................................................................................................................... 60
Section 23.2: BASE_TYPE ........................................................................................................................................... 60
Section 23.3: MID_TYPE .............................................................................................................................................. 61
Section 23.4: LEAF_TYPE ............................................................................................................................................ 62
Chapter 24: Loop ........................................................................................................................................................ 64
Section 24.1: Simple Loop ........................................................................................................................................... 64
Section 24.2: WHILE Loop ........................................................................................................................................... 64
Section 24.3: FOR Loop ............................................................................................................................................... 64
Chapter 25: Cursors ................................................................................................................................................... 67
Section 25.1: Parameterized "FOR loop" Cursor ...................................................................................................... 67
Section 25.2: Implicit "FOR loop" cursor ................................................................................................................... 67
Section 25.3: Handling a CURSOR ............................................................................................................................. 67
Section 25.4: Working with SYS_REFCURSOR ......................................................................................................... 68
Chapter 26: Sequences ............................................................................................................................................ 69
Section 26.1: Creating a Sequence: Example ............................................................................................................ 69
Chapter 27: Indexes ................................................................................................................................................... 71
Section 27.1: b-tree index ............................................................................................................................................ 71
Section 27.2: Bitmap Index ......................................................................................................................................... 71
Section 27.3: Function Based Index ........................................................................................................................... 71
Chapter 28: Hints ........................................................................................................................................................ 72
Section 28.1: USE_NL .................................................................................................................................................. 72
Section 28.2: APPEND HINT ........................................................................................................................................ 72
Section 28.3: Parallel Hint ........................................................................................................................................... 72
Section 28.4: USE_HASH ............................................................................................................................................ 73
Section 28.5: FULL ....................................................................................................................................................... 73
Section 28.6: Result Cache ......................................................................................................................................... 74
Chapter 29: Packages ............................................................................................................................................... 75
Section 29.1: Define a Package header and body with a function ......................................................................... 75
Section 29.2: Overloading .......................................................................................................................................... 75
Section 29.3: Package Usage ..................................................................................................................................... 76
Chapter 30: Exception Handling .......................................................................................................................... 78
Section 30.1: Syntax ..................................................................................................................................................... 78
Section 30.2: User defined exceptions ...................................................................................................................... 78
Section 30.3: Internally defined exceptions .............................................................................................................. 79
Section 30.4: Predefined exceptions .......................................................................................................................... 80
Section 30.5: Define custom exception, raise it and see where it comes from ..................................................... 81
Section 30.6: Handling connexion error exceptions ................................................................................................ 82
Section 30.7: Exception handling ............................................................................................................................... 83
Chapter 31: Error logging ........................................................................................................................................ 84
Section 31.1: Error logging when writing to database .............................................................................................. 84
Chapter 32: Database Links .................................................................................................................................. 85
Section 32.1: Creating a database link ...................................................................................................................... 85
Section 32.2: Create Database Link .......................................................................................................................... 85
Chapter 33: Table partitioning ............................................................................................................................. 87
Section 33.1: Select existing partitions ....................................................................................................................... 87
Section 33.2: Drop partition ........................................................................................................................................ 87
Section 33.3: Select data from a partition ................................................................................................................ 87
Section 33.4: Split Partition ......................................................................................................................................... 87
Section 33.5: Merge Partitions .................................................................................................................................... 87
Section 33.6: Exchange a partition ............................................................................................................................ 87
Section 33.7: Hash partitioning .................................................................................................................................. 88
Section 33.8: Range partitioning ................................................................................................................................ 88
Section 33.9: List partitioning ..................................................................................................................................... 88
Section 33.10: Truncate a partition ............................................................................................................................ 89
Section 33.11: Rename a partition .............................................................................................................................. 89
Section 33.12: Move partition to dierent tablespace ............................................................................................. 89
Section 33.13: Add new partition ................................................................................................................................ 89
Chapter 34: Oracle Advanced Queuing (AQ) ................................................................................................ 90
Section 34.1: Simple Producer/Consumer ................................................................................................................. 90
Chapter 35: constraints ........................................................................................................................................... 94
Section 35.1: Update foreign keys with new value in Oracle .................................................................................. 94
Section 35.2: Disable all related foreign keys in oracle .......................................................................................... 94
Chapter 36: Autonomous Transactions ........................................................................................................... 95
Section 36.1: Using autonomous transaction for logging errors ............................................................................ 95
Chapter 37: Oracle MAF ........................................................................................................................................... 96
Section 37.1: To get value from Binding .................................................................................................................... 96
Section 37.2: To set value to binding ......................................................................................................................... 96
Section 37.3: To invoke a method from binding ...................................................................................................... 96
Section 37.4: To call a javaScript function ................................................................................................................ 96
Chapter 38: level query ........................................................................................................................................... 97
Section 38.1: Generate N Number of records ........................................................................................................... 97
Section 38.2: Few usages of Level Query ................................................................................................................. 97
Chapter 39: Hierarchical Retrieval With Oracle Database 12C ........................................................... 98
Section 39.1: Using the CONNECT BY Caluse ............................................................................................................ 98
Section 39.2: Specifying the Direction of the Query From the Top Down ............................................................ 98
Chapter 40: Data Pump .......................................................................................................................................... 99
Section 40.1: Monitor Datapump jobs ....................................................................................................................... 99
Section 40.2: Step 3/6 : Create directory .................................................................................................................. 99
Section 40.3: Step 7 : Export Commands .................................................................................................................. 99
Section 40.4: Step 9 : Import Commands ............................................................................................................... 100
Section 40.5: Datapump steps ................................................................................................................................. 101
Section 40.6: Copy tables between dierent schemas and tablespaces ........................................................... 101
Chapter 41: Bulk collect ........................................................................................................................................ 102
Section 41.1: Bulk data Processing ........................................................................................................................... 102
Chapter 42: Real Application Security .......................................................................................................... 103
Section 42.1: Application ........................................................................................................................................... 103
Chapter 43: Assignments model and language ....................................................................................... 105
Section 43.1: Assignments model in PL/SQL .......................................................................................................... 105
Chapter 44: Triggers .............................................................................................................................................. 107
Section 44.1: Before INSERT or UPDATE trigger .................................................................................................... 107
Chapter 45: Dynamic SQL .................................................................................................................................... 108
Section 45.1: Select value with dynamic SQL .......................................................................................................... 108
Section 45.2: Insert values in dynamic SQL ............................................................................................................ 108
Section 45.3: Update values in dynamic SQL ......................................................................................................... 108
Section 45.4: Execute DDL statement ..................................................................................................................... 109
Section 45.5: Execute anonymous block ................................................................................................................ 109
Credits ............................................................................................................................................................................ 110
You may also like ...................................................................................................................................................... 112
About
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
http://GoalKicker.com/OracleDatabaseBook
This Oracle® Database Notes for Professionals book is compiled from Stack
Overflow Documentation, the content is written by the beautiful people at Stack
Overflow. Text content is released under Creative Commons BY-SA, see credits at
the end of this book whom contributed to the various chapters. Images may be
copyright of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affiliated with official Oracle® Database group(s) or company(s) nor Stack
Overflow. All trademarks and registered trademarks are the property of their
respective company owners
In Oracle's flavor of SQL, "dual is just a convienence table". It was originally intended to double rows via a JOIN, but
now contains one row with a DUMMY value of 'X'.
Show the number of employees in each department with at least 5 employees. List the largest departments first.
Insert values (you can omit target columns if you provide values for all columns)
SET serveroutput ON
BEGIN
DBMS_OUTPUT.PUT_LINE ('Hello World!');
END;
DECLARE
message CONSTANT VARCHAR2(32767):= 'Hello, World!';
BEGIN
DBMS_OUTPUT.put_line(message);
END;
/
Command SET serveroutput ON is required in SQL*Plus and SQL Developer clients to enable the output of
DBMS_OUTPUT. Without the command nothing is displayed.
The END; line signals the end of the anonymous PL/SQL block. To run the code from SQL command line, you may
need to type / at the beginning of the first blank line after the last line of the code. When the above code is
executed at SQL prompt, it produces the following result:
Hello, World!
The basic unit in PL/SQL is called a block, which is made up of three parts: a declarative part, an executable part,
and an exception-building part.
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<EXCEPTION handling>
END;
Declarations - This section starts with the keyword DECLARE. It is an optional section and defines all variables,
cursors, subprograms, and other elements to be used in the program.
Executable Commands - This section is enclosed between the keywords BEGIN and END and it is a mandatory
section. It consists of the executable PL/SQL statements of the program. It should have at least one executable line
of code, which may be just a NULL command to indicate that nothing should be executed.
Exception Handling - This section starts with the keyword EXCEPTION. This section is again optional and contains
exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks using
BEGIN and END.
BEGIN
NULL;
END;
/
Missing excecutable instruction leads to an error, becouse PL/SQL does not support empty blocks. For example,
excecution of code below leads to an error:
BEGIN
END;
/
END;
*
ERROR AT line 2:
ORA-06550: line 2, column 1:
PLS-00103: Encountered the symbol "END" WHEN expecting one OF the following:
( BEGIN CASE DECLARE EXIT FOR GOTO IF LOOP MOD NULL PRAGMA
RAISE RETURN SELECT UPDATE WHILE WITH <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
continue CLOSE CURRENT DELETE FETCH LOCK INSERT OPEN ROLLBACK
SAVEPOINT SET SQL EXECUTE COMMIT FORALL MERGE pipe purge
Symbol " * " in line below keyword "END;" means, that the block which ends with this block is empty or bad
constructed. Every execution block needs instructions to do, even if it does nothing, like in our example.
DECLARE
vEmployeeName Employee.Name%TYPE;
BEGIN
SELECT Name
INTO vEmployeeName
FROM Employee
WHERE ROWNUM = 1;
DBMS_OUTPUT.PUT_LINE(vEmployeeName);
END;
/
%ROWTYPE: Used to declare a record with the same types as found in the specified table, view or cursor (= multiple
columns).
DECLARE
rEmployee Employee%ROWTYPE;
BEGIN
rEmployee.Name := 'Matt';
rEmployee.Age := 31;
DBMS_OUTPUT.PUT_LINE(rEmployee.Name);
Example 1:
View with a select on one table.
Example 2:
View with a select on multiple tables.
Stored procedures are useful when same code is required by multiple applications. Having stored procedures
eliminates redundancy, and introduces simplicity to the code. When data transfer is required between the client
and server, procedures can reduce communication cost in certain situations.
You need to execute this at the SQL prompt to create the procedure in the database, or you can run the query
below to get the same result:
IN specifies that the parameter is read only and the value cannot be changed by the procedure.
The variables passed in the above example need to be typed as they are defined in the procedure parameter
section.
Section 5.2: To see all the data dictionary views to which you
have access
SELECT * FROM dict
ALL_SOURCE describes the text source of the stored objects accessible to the current user.
DBA_SOURCE describes the text source of all stored objects in the database.
ALL_TAB_COLUMNS describes the columns of the tables, views, and clusters accessible to the current user. COLS is a
synonym for USER_TAB_COLUMNS.
SELECT *
FROM all_tab_columns
WHERE table_name = :tname
SELECT *
FROM dba_role_privs
WHERE grantee= :username
1. system privileges
SELECT *
2. object grants
SELECT *
FROM dba_tab_privs
WHERE grantee = :username
SELECT *
FROM role_role_privs
WHERE role IN (SELECT granted_role FROM dba_role_privs WHERE grantee= :username)
1. system privileges
SELECT *
FROM role_sys_privs
WHERE role IN (SELECT granted_role FROM dba_role_privs WHERE grantee= :username)
2. object grants
SELECT *
FROM role_tab_privs
WHERE role IN (SELECT granted_role FROM dba_role_privs WHERE grantee= :username)
DIFFERENCE
----------
89
And:
DIFFERENCE
----------
1.0425
The difference in hours, minutes or seconds can be found by multiplying this number by 24, 24*60 or 24*60*60
respectively.
The previous example can be changed to get the days, hours, minutes and seconds between two dates using:
);
(Note: TRUNC() is used rather than FLOOR() to correctly handle negative differences.)
Outputs:
You can set this value within your current session using:
(Note: this does not change the value for any other users.)
If you rely on the NLS_DATE_FORMAT to provide the format mask in TO_DATE() or TO_CHAR() then you should not be
surprised when your queries break if this value is ever changed.
Outputs:
DIFFERENCE
----------
12
If the difference includes part months then it will return the fraction of the month based on there being 31 days in
each month:
Outputs:
Due to MONTHS_BETWEEN assuming 31 days per month when there can be fewer days per month then this can result
in different values for differences spanning the boundaries between months.
Example:
Output:
The difference in years can be found by dividing the month difference by 12.
Outputs:
Using CAST( datevalue AS TIMESTAMP ) to convert the DATE to a TIMESTAMP and then using EXTRACT( [
HOUR | MINUTE | SECOND ] FROM timestampvalue ); or
Using TO_CHAR( datevalue, format_model ) to get the value as a string.
For example:
Outputs:
(More information on the date format models can be found in the Oracle documentation.)
or:
SELECT TO_DATE(
'January 1, 2000, 00:00 A.M.',
'Month dd, YYYY, HH12:MI A.M.',
'NLS_DATE_LANGUAGE = American'
)
FROM DUAL;
(If you are converting language specific terms such as month names then it is good practice to include the 3rd nlsparam
parameter to the TO_DATE() function and specify the language to be expected.)
Oracle will implicitly cast a TIMESTAMP to a DATE when storing it in a DATE column of a table; however you can
explicitly CAST() the value to a DATE:
A DATE which is not stored in a table (i.e. generated by SYSDATE and having "type 13" when using the DUMP()
command) has 8-bytes and has the structure (the numbers on the right are the internal representation of
2012-11-26 16:41:09):
A DATE which is stored in a table ("type 12" when using the DUMP() command) has 7-bytes and has the structure (the
numbers on the right are the internal representation of 2012-11-26 16:41:09):
If you want the date to have a specific format then you will need to convert it to something that has a format (i.e. a
string). The SQL client may implicitly do this or you can explicitly convert the value to a string using TO_CHAR( DATE,
format_model, nls_params ).
(Note: if a format model is not provided then the NLS_DATE_FORMAT session parameter will be used as the default format
model; this can be different for every session so should not be relied on. It is good practice to always specify the format
model.)
Then:
Outputs:
FORMATTED_DATE
--------------
2000-01-01
2016-07-21
2016-07-21
And:
SELECT TO_CHAR(
date_value,
'FMMonth d yyyy, hh12:mi:ss AM',
'NLS_DATE_LANGUAGE = French'
) AS formatted_date
FROM table_name;
Outputs:
FORMATTED_DATE
-----------------------------
Janvier 01 2000, 12:00:00 AM
Juillet 21 2016, 08:00:00 AM
Juillet 21 2016, 19:08:31 PM
You can change how a date is displayed by changing the NLS_DATE_FORMAT parameter.
Either:
A DATE can be stored as Coordinated Universal Time (UTC) and converted to the current session time zone like this:
SELECT FROM_TZ(
CAST(
TO_DATE( '2016-01-01 12:00:00', 'YYYY-MM-DD HH24:MI:SS' )
AS TIMESTAMP
),
'UTC'
)
AT LOCAL AS TIME
If you run ALTER SESSION SET TIME_ZONE = '+01:00'; then the output is:
TIME
------------------------------------
2016-01-01 13:00:00.000000000 +01:00
and ALTER SESSION SET TIME_ZONE = 'PST'; then the output is:
TIME
------------------------------------
2016-01-01 04:00:00.000000000 PST
Outputs 5
ALTER SESSION SET NLS_TERRITORY = 'UNITED KINGDOM'; -- First day of week is Monday
SELECT TO_CHAR( DATE '1970-01-01', 'D' ) FROM DUAL;
Outputs 4
To do this independent of the NLS settings, you can truncate the date to midnight of the current day (to remove any
fractions of days) and subtract the date truncated to the start of the current iso-week (which always starts on
Monday):
Oracle also provides the built-in datatype INTERVAL which represents a duration of time (e.g. 1.5 days, 36 hours, 2
months, etc.). These can also be used with arithmetic with DATE and TIMESTAMP expressions. For example:
SELECT * FROM logfile WHERE last_updated >= SYSDATE - INTERVAL '1' HOUR;
When the calculated month has fewer days as the given date, the last day of the calculated month will be returned.
Example:
SELECT *
FROM TABLEA CROSS JOIN TABLEB;
SELECT *
FROM TABLEA, TABLEB;
+-------+---------+
| VALUE | NAME |
+-------+---------+
| 1 | ONE |
| 2 | TWO |
+-------+---------+
+-------+--------+
| VALUE | NAME |
+-------+--------+
| 3 | THREE |
| 4 | FOUR |
+-------+--------+
SELECT *
FROM TABLEA CROSS JOIN TABLEB;
Output:
+-------+--------+-------+--------+
| VALUE | NAME | VALUE | NAME |
+-------+--------+-------+--------+
| 1 | ONE | 3 | THREE |
| 1 | ONE | 4 | FOUR |
| 2 | TWO | 3 | THREE |
| 2 | TWO | 4 | FOUR |
Example:
SELECT
ENAME,
DNAME,
EMP.DEPTNO,
DEPT.DEPTNO
FROM
SCOTT.EMP LEFT OUTER JOIN SCOTT.DEPT
ON EMP.DEPTNO = DEPT.DEPTNO;
Even though ANSI syntax is the recommended way, it is likely to encounter legacy syntax very often. Using (+)
within a condition determines which side of the equation to be considered as outer.
SELECT
ENAME,
DNAME,
EMP.DEPTNO,
DEPT.DEPTNO
FROM
SCOTT.EMP,
SCOTT.DEPT
WHERE
EMP.DEPTNO = DEPT.DEPTNO(+);
+-----------+---------+
| NAME | DEPTNO |
+-----------+---------+
| A | 2 |
| B | 1 |
| C | 3 |
| D | 2 |
| E | 1 |
| F | 1 |
| G | 4 |
| H | 4 |
+---------+--------------+
| DEPTNO | DEPTNAME |
+---------+--------------+
| 1 | ACCOUNTING |
| 2 | FINANCE |
| 5 | MARKETING |
| 6 | HR |
+---------+--------------+
SELECT
*
FROM
EMPLOYEE LEFT OUTER JOIN DEPT
ON EMPLOYEE.DEPTNO = DEPT.DEPTNO;
Output:
+-----------+---------+---------+--------------+
| NAME | DEPTNO | DEPTNO | DEPTNAME |
+-----------+---------+---------+--------------+
| F | 1 | 1 | ACCOUNTING |
| E | 1 | 1 | ACCOUNTING |
| B | 1 | 1 | ACCOUNTING |
| D | 2 | 2 | FINANCE |
| A | 2 | 2 | FINANCE |
| C | 3 | | |
| H | 4 | | |
| G | 4 | | |
+-----------+---------+---------+--------------+
Example:
SELECT
ENAME,
DNAME,
EMP.DEPTNO,
DEPT.DEPTNO
FROM
SCOTT.EMP RIGHT OUTER JOIN SCOTT.DEPT
ON EMP.DEPTNO = DEPT.DEPTNO;
As the unmatched rows of SCOTT.DEPT are included, but unmatched rows of SCOTT.EMP are not, the above is
equivalent to the following statement using LEFT OUTER JOIN.
+-----------+---------+
| NAME | DEPTNO |
+-----------+---------+
| A | 2 |
| B | 1 |
| C | 3 |
| D | 2 |
| E | 1 |
| F | 1 |
| G | 4 |
| H | 4 |
+-----------+---------+
+---------+--------------+
| DEPTNO | DEPTNAME |
+---------+--------------+
| 1 | ACCOUNTING |
| 2 | FINANCE |
| 5 | MARKETING |
| 6 | HR |
+---------+--------------+
SELECT
*
FROM
EMPLOYEE RIGHT OUTER JOIN DEPT
ON EMPLOYEE.DEPTNO = DEPT.DEPTNO;
Output:
+-----------+---------+---------+--------------+
| NAME | DEPTNO | DEPTNO | DEPTNAME |
+-----------+---------+---------+--------------+
| A | 2 | 2 | FINANCE |
| B | 1 | 1 | ACCOUNTING |
| D | 2 | 2 | FINANCE |
| E | 1 | 1 | ACCOUNTING |
| F | 1 | 1 | ACCOUNTING |
| | | 5 | MARKETING |
| | | 6 | HR |
SELECT *
FROM EMPLOYEE, DEPT
WHERE EMPLOYEE.DEPTNO(+) = DEPT.DEPTNO;
Example:
SELECT
*
FROM
EMPLOYEE FULL OUTER JOIN DEPT
ON EMPLOYEE.DEPTNO = DEPT.DEPTNO;
+-----------+---------+
| NAME | DEPTNO |
+-----------+---------+
| A | 2 |
| B | 1 |
| C | 3 |
| D | 2 |
| E | 1 |
| F | 1 |
| G | 4 |
| H | 4 |
+-----------+---------+
+---------+--------------+
| DEPTNO | DEPTNAME |
+---------+--------------+
| 1 | ACCOUNTING |
| 2 | FINANCE |
| 5 | MARKETING |
| 6 | HR |
+---------+--------------+
SELECT
*
FROM
EMPLOYEE FULL OUTER JOIN DEPT
Output
+-----------+---------+---------+--------------+
| NAME | DEPTNO | DEPTNO | DEPTNAME |
+-----------+---------+---------+--------------+
| A | 2 | 2 | FINANCE |
| B | 1 | 1 | ACCOUNTING |
| C | 3 | | |
| D | 2 | 2 | FINANCE |
| E | 1 | 1 | ACCOUNTING |
| F | 1 | 1 | ACCOUNTING |
| G | 4 | | |
| H | 4 | | |
| | | 6 | HR |
| | | 5 | MARKETING |
+-----------+---------+---------+--------------+
Here the columns that do not match has been kept NULL.
+-----------+---------+
| NAME | DEPTNO |
+-----------+---------+
| A | 2 |
| B | 1 |
| C | 3 |
| D | 2 |
| E | 1 |
| F | 1 |
| G | 4 |
| H | 4 |
+-----------+---------+
+---------+--------------+
| DEPTNO | DEPTNAME |
+---------+--------------+
| 1 | ACCOUNTING |
| 2 | FINANCE |
SELECT
*
FROM
EMPLOYEE WHERE DEPTNO NOT IN
(SELECT DEPTNO FROM DEPT);
Output:
+-----------+---------+
| NAME | DEPTNO |
+-----------+---------+
| C | 3 |
| H | 4 |
| G | 4 |
+-----------+---------+
The output shows that only the rows of EMPLOYEE table, of which DEPTNO were not present in DEPT table.
Syntax
You can specify the join clause by specifying ON with a boolean expression.
The scope of expressions in the ON clause includes the current tables and any tables in outer query blocks to the
current SELECT. In the following example, the ON clause refers to the current tables:
Example:
SELECT t1.*,
t2.DeptId
FROM table_1 t1
JOIN table_2 t2 ON t2.DeptNo = t1.DeptNo
Oracle documentation:
10g
11g
12g
This is more efficient than the full join alternatives, as inner joining on employees then giving a where clause
detailing that the salary has to be greater than 2500 could return the same department numerous times. Say if the
Fire department has n employees all with salary 3000, SELECT * FROM departments, employees with the necessary
join on ids and our where clause would return the Fire department n times.
The join will be done on the fields ID and DESCR, common to both the tables:
SQL> SELECT *
2 FROM tab1
3 NATURAL JOIN
4 tab2;
ID DESCR
---------- ----------
3 three
Columns with different names will not be used in the JOIN condition:
SQL> SELECT *
2 FROM (SELECT id AS id, descr AS descr1 FROM tab1)
3 NATURAL JOIN
4 (SELECT id AS id, descr AS descr2 FROM tab2);
ID DESCR1 DESCR2
---------- ---------- ----------
1 one ONE
3 three three
If the joined tables have no common columns, a JOIN with no conditions will be done:
SQL> SELECT *
2 FROM (SELECT id AS id1, descr AS descr1 FROM tab1)
3 NATURAL JOIN
4 (SELECT id AS id2, descr AS descr2 FROM tab2);
In some case, using COALESCE with two parameters can be faster than using NVL when the second parameter is
not a constant. NVL will always evaluate both parameters. COALESCE will stop at the first non-NULL value it
encounters. It means that if the first value is non-NULL, COALESCE will be faster.
SELECT
CASE WHEN a = b THEN 1 WHEN a <> b THEN 0 ELSE -1 END comparison_without_nvl,
CASE WHEN NVL(a, -1) = NVL(b, -1) THEN 1 WHEN NVL(a, -1) <> NVL(b, -1) THEN 0 ELSE -1 END
comparison_with_nvl
FROM
(SELECT NULL a, 3 b FROM DUAL
UNION ALL
SELECT NULL, NULL FROM DUAL);
COMPARISON_WITHOUT_NVL COMPARISON_WITH_NVL
-1 0
-1 1
Output
NEW
-------------------
Hello Mr Macdonald!
SELECT REGEXP_REPLACE ('2, 5, and 10 are numbers in this example', '(\d\d)', '#')
FROM dual;
Results in:
If I want to swap parts of the text, I use \1, \2, \3 to call for the matched strings:
SELECT REGEXP_REPLACE ('swap around 10 in that one ', '(.*)(\d\d )(.*)', '\3\2\1\3')
FROM dual;
returns:
bcd
To count from the end of the string, SUBSTR accepts a negative number as the second parameter, e.g.
returns:
de
Example:
id firstname lastname
--- ----------- ----------
1 Thomas Woody
Query:
Output:
My Sentence
---------------------------------
Thomas Woody is in my database.
Example:
Query:
Output:
Expr1
---------------------------------
Thomas is in my database.
Output:
RESULT
------------
MY TEXT 123!
Outputs:
text
hello world123!
For example,
Returns:
HELLO<===>
<===>HELLO
BEGIN
v_num1 := 2;
v_num2 := 1;
BEGIN
v_num1 := 2;
v_num2 := 10;
BEGIN
v_num1 := 2;
v_num2 := 2;
SELECT val
FROM mytable
ORDER BY val DESC
FETCH FIRST 5 ROWS ONLY;
SELECT * FROM (
SELECT val
FROM mytable
ORDER BY val DESC
) WHERE ROWNUM <= 5;
WITH t AS (
SELECT col1
, col2
, ROW_NUMBER() over (ORDER BY col1, col2) rn
FROM TABLE
)
SELECT col1
, col2
FROM t
WHERE rn BETWEEN N AND M; -- N and M are both inclusive
Oracle 12c handles this more easily with OFFSET and FETCH.
SELECT * FROM
(
SELECT val FROM mytable
) WHERE rownum<=5
If we want first or last record then we want order by clause in inner query that will give result based on order.
SELECT * FROM
(
SELECT val FROM mytable ORDER BY val DESC
SELECT * FROM
(
SELECT val FROM mytable ORDER BY val
) WHERE rownum<=5
In earlier Versions
SELECT Id,
Col1
FROM (SELECT Id,
Col1,
ROW_NUMBER() over (ORDER BY Id) RowNumber
FROM TableName)
WHERE RowNumber BETWEEN 21 AND 40
In earlier Versions
SELECT Id,
Col1
FROM (SELECT Id,
Col1,
ROW_NUMBER() over (ORDER BY Id) RowNumber
FROM TableName)
WHERE RowNumber > 20
Query:
Output:
Output:
MERGE INTO
TESTTABLE
USING
(SELECT
T1.ROWID AS RID,
T2.TESTTABLE_ID
FROM
TESTTABLE T1
INNER JOIN
MASTERTABLE T2
ON TESTTABLE.TESTTABLE_ID = MASTERTABLE.TESTTABLE_ID
WHERE ID_NUMBER=11)
ON
( ROWID = RID )
WHEN MATCHED
THEN
UPDATE SET TEST_COLUMN= 'Testvalue';
UPDATE
TESTTABLE
SET
TEST_COLUMN= 'Testvalue',TEST_COLUMN2= 123
WHERE
EXISTS
(SELECT MASTERTABLE.TESTTABLE_ID
FROM MASTERTABLE
WHERE ID_NUMBER=11);
Note: If you face a non key preserved row error add an index to resolve the same to make it update-able
UPDATE
(SELECT
TESTTABLE.TEST_COLUMN AS OLD,
'Testvalue' AS NEW
FROM
TESTTABLE
INNER JOIN
MASTERTABLE
ON TESTTABLE.TESTTABLE_ID = MASTERTABLE.TESTTABLE_ID
WHERE ID_NUMBER=11) T
SET
--
--
SELECT * FROM table01 a WHERE a.code IN (SELECT b.codetable01 FROM table02 b);
--
SELECT * FROM table01 a WHERE a.code NOT IN (SELECT b.codetable01 FROM table02 b);
UPDATE
( SELECT t.val AS t_val, s.val AS s_val
FROM tgt t inner JOIN src s ON t.id = s.id
)
SET t_val = s_val
;
SQL Error: ORA-01779: cannot modify a column which maps to a non key-preserved table
01779. 00000 - "cannot modify a column which maps to a non key-preserved table"
*Cause: An attempt was made to insert or update columns of a join view which
map to a non-key-preserved table.
*Action: Modify the underlying base tables directly.
Imagine what would happen if we had the value 1 in the column src.id more than once, with different values for
src.val. Obviously, the update would make no sense (in ANY database - that's a logical issue). Now, we know that
there are no duplicates in src.id, but the Oracle engine doesn't know that - so it's complaining. Perhaps this is why
so many practitioners believe Oracle "doesn't have UPDATE with joins"?
What Oracle expects is that src.id should be unique, and that it, Oracle, would know that beforehand. Easily fixed!
Note that the same works with composite keys (on more than one column), if the matching for the update needs to
use more than one column. In practice, src.id may be PK and tgt.id may be FK pointing to this PK, but that is not
relevant for updates with join; what is relevant is the unique constraint.
UPDATE
( SELECT t.val AS t_val, s.val AS s_val
FROM tgt t inner JOIN src s ON t.id = s.id
)
SET t_val = s_val
;
ID VAL
-- ---
1 x
2 y
The same result could be achieved with a MERGE statement (which deserves its own Documentation article), and I
personally prefer MERGE in these cases, but the reason is not that "Oracle doesn't do updates with joins." As this
example shows, Oracle does do updates with joins.
DECLARE
x NUMBER := functionName(); --functions can be called in declaration section
BEGIN
x := functionName();
END;
SELECT MEDIAN(SAL)
FROM EMP
The result of MEDIAN is computed by first ordering the rows. Using N as the number of rows in the
group, Oracle calculates the row number (RN) of interest with the formula RN = (1 + (0.5*(N-1)). The final
result of the aggregate function is computed by linear interpolation between the values from rows at row
numbers CRN = CEILING(RN) and FRN = FLOOR(RN).
Since Oracle 9i you can use PERCENTILE_CONT which works the same as MEDIAN function with percentile value
defaults to 0.5
--Data
CREATE TABLE Employees (Name VARCHAR2(30), Salary NUMBER(10));
INSERT INTO Employees VALUES ('Bob',2500);
INSERT INTO Employees VALUES ('Alice',3500);
INSERT INTO Employees VALUES ('Tom',2700);
INSERT INTO Employees VALUES ('Sue',2000);
--Query
SELECT Name, Salary, RATIO_TO_REPORT(Salary) OVER () AS Ratio
FROM Employees
ORDER BY Salary, Name, Ratio;
--Output
This creates a context that can only be set by routines in the database package my_pkg, e.g.:
my_pkg.set_ctx;
VALUE
Query:
SELECT t.id,
REGEXP_SUBSTR( list, '([^,]*)(,|$)', 1, LEVEL, NULL, 1 ) AS VALUE,
LEVEL AS lvl
FROM table_name t
CONNECT BY
id = PRIOR id
AND PRIOR SYS_GUID() IS NOT NULL
AND LEVEL < REGEXP_COUNT( list, '([^,]*)(,|$)' )
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3
Sample Data:
Query:
SELECT t.id,
v.column_value AS VALUE,
ROW_NUMBER() OVER ( PARTITION BY id ORDER BY ROWNUM ) AS lvl
FROM table_name t,
TABLE( split_String( t.list ) ) (+) v
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3
Query:
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3
Query:
SELECT t.id,
v.COLUMN_VALUE AS VALUE,
ROW_NUMBER() OVER ( PARTITION BY id ORDER BY ROWNUM ) AS lvl
FROM table_name t,
TABLE(
CAST(
MULTISET(
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3
Query:
SELECT t.id,
REGEXP_SUBSTR( t.list, '([^,]*)($|,)', 1, l.lvl, NULL, 1 ) AS item,
l.lvl
FROM table_name t
CROSS APPLY
(
SELECT LEVEL AS lvl
FROM DUAL
CONNECT BY LEVEL <= REGEXP_COUNT( t.list, ',' ) + 1
) l;
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3
Sample Data:
Query:
SELECT t.id,
x.item,
x.lvl
FROM table_name t,
XMLTABLE(
'let $list := ora:tokenize(.,","),
$cnt := count($list)
for $val at $r in $list
where $r < $cnt
return $val'
PASSING list||','
COLUMNS
item VARCHAR2(100) PATH '.',
lvl FOR ORDINALITY
) (+) x;
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) (NULL)
4 f 1
4 (NULL) 2
4 g 3
SELECT t.id,
SUBSTR( x.item.getStringVal(), 2 ) AS item,
x.lvl
FROM table_name t
CROSS JOIN
XMLTABLE(
( '"#' || REPLACE( t.list, ',', '","#' ) || '"' )
COLUMNS item XMLTYPE PATH '.',
lvl FOR ORDINALITY
) x;
(Note: the # character is appended to facilitate extracting NULL values; it is later removed using SUBSTR( item, 2 ). If
NULL values are not required then you can simplify the query and omit this.)
Output:
ID ITEM LVL
---------- ------- ----------
1 a 1
1 b 2
1 c 3
1 d 4
2 e 1
3 (NULL) 1
4 f 1
4 (NULL) 2
4 g 3
Here's the function. Notice the () used as a kind of constructor, and the COUNT and EXTEND keywords that help you
create and grow your collection;
CREATE OR REPLACE
FUNCTION cto_table(p_sep IN VARCHAR2, p_list IN VARCHAR2)
RETURN t_my_list
AS
--- this function takes a string list, element being separated by p_sep
-- as separator
l_string VARCHAR2(4000) := p_list || p_sep;
l_sep_index PLS_INTEGER;
l_index PLS_INTEGER := 1;
l_tab t_my_list := t_my_list();
BEGIN
LOOP
l_sep_index := INSTR(l_string, p_sep, l_index);
EXIT
WHEN l_sep_index = 0;
l_tab.EXTEND;
l_tab(l_tab.COUNT) := TRIM(SUBSTR(l_string,l_index,l_sep_index - l_index));
l_index := l_sep_index + 1;
END LOOP;
RETURN l_tab;
END cto_table;
/
Then you can see the content of the collection with the TABLE() function from SQL; it can be used as a list inside a
SQL IN ( ..) statement:
SELECT test_id
,test_obj
FROM test_tab;
SELECT test_id
,TREAT(test_obj AS mid_type) AS obj
FROM test_tab;
SELECT test_id
,TREAT(test_obj AS base_type).to_string() AS to_string -- Parenthesis are needed after the
function name, or Oracle will look for an attribute of this name.
FROM test_tab;
Type body:
Type body:
BEGIN
v_counter := 0;
LOOP
v_counter := v_counter + 1;
DBMS_OUTPUT.put_line('Line number' || v_counter);
DECLARE
v_counter NUMBER(2); --declaration of counter variable
BEGIN
v_counter := 0; --point of start, first value of our iteration
This loop will be executed untill current value of variable v_counter will be less than ten.
The result:
The most important thing is, that our loop starts with '0' value, so first line of results is 'Current iteration of loop is
0'.
Simple example:
DECLARE
v_counter NUMBER(2); --declaration of counter variable
BEGIN
v_counter := 0; --point of start, first value of our iteration, execute of variable
FOR v_counter IN 1..10 LOOP --The point, where lower and upper point of loop statement is declared
- in this example, loop will be executed 10 times, start with value of 1
Loop FOR has additional property, which is working in reverse. Using additional word 'REVERSE' in declaration of
lower and upper limit of loop allow to do that. Every execution of loop decrement value of v_counter by 1.
Example:
DECLARE
v_counter NUMBER(2); --declaration of counter variable
BEGIN
v_counter := 0; --point of start
First advantage is there is no tedious declaration to do (think of this horrible "CURSOR" thing you had in
previous versions)
second advantage is you first build your select query, then when you have what you want, you immediately
can access the fields of your query (x.<myfield>) in your PL/SQL loop
The loop opens the cursor and fetches one record at a time for every loop. At the end of the loop the cursor
is closed.
Implicit cursors are faster because the interpreter's work grows as the code gets longer. The less code the
less work the interpreter has to do.
--
DECLARE
CURSOR curCols IS -- select column name and type from a given table
SELECT column_name, data_type FROM all_tab_columns WHERE table_name='MY_TABLE';
v_tab_column all_tab_columns.column_name%TYPE;
v_data_type all_tab_columns.data_type%TYPE;
v_ INTEGER := 1;
BEGIN
OPEN curCols;
LOOP
FETCH curCols INTO v_tab_column, v_data_type;
IF curCols%notfound OR v_ > 2000 THEN
EXIT;
END IF;
Use the CREATE SEQUENCE statement to create a sequence, which is a database object from which multiple users
may generate unique integers. You can use sequences to automatically generate primary key values.
When a sequence number is generated, the sequence is incremented, independent of the transaction committing
or rolling back. If two users concurrently increment the same sequence, then the sequence numbers each user
acquires may have gaps, because sequence numbers are being generated by the other user. One user can never
acquire the sequence number generated by another user. After a sequence value is generated by one user, that
user can continue to access that value regardless of whether the sequence is incremented by another user.
Sequence numbers are generated independently of tables, so the same sequence can be used for one or for
multiple tables. It is possible that individual sequence numbers will appear to be skipped, because they were
generated and used in a transaction that ultimately rolled back. Additionally, a single user may not realize that
other users are drawing from the same sequence.
After a sequence is created, you can access its values in SQL statements with the CURRVAL pseudocolumn, which
returns the current value of the sequence, or the NEXTVAL pseudocolumn, which increments the sequence and
returns the new value.
Prerequisites
To create a sequence in your own schema, you must have the CREATE SEQUENCE system privilege.
To create a sequence in another user's schema, you must have the CREATE ANY SEQUENCE system privilege.
Creating a Sequence: Example The following statement creates the sequence customers_seq in the sample schema
oe. This sequence could be used to provide customer ID numbers when rows are added to the customers table.
By default, if we do not mention anything, oracle creates an index as a b-tree index. But we should know when to
use it. B-tree index stores data as binary tree format. As we know that, index is a schema object which stores some
sort of entry for each value for the indexed column. So, whenever any search happens on those columns, it checks
in the index for the exact location of that record to access fast. Few points about indexing:
To search for entry in the index, some sort of binary search algorithm used.
When data cardinality is high, b-tree index is perfect to use.
Index makes DML slow, as for each record, there should be one entry in the index for indexed column.
So, if not necessary, we should avoid creating index.
SELECT *
FROM user_data
WHERE UPPER(first_name) = 'JOHN2';
Usage : use_nl(A B)
This hint will ask the engine to use nested loop method to join the tables A and B. That is row by row comparison.
The hint does not force the order of the join, just asks for NL.
The APPEND hint instructs the engine to use direct path load. This means that the engine will not use a conventional
insert using memory structures and standard locks, but will write directly to the tablespace the data. Always creates
new blocks which are appended to the table's segment. This will be faster, but have some limitations:
You cannot read from the table you appended in the same session until you commmit or rollback the
transaction.
If there are triggers defined on the table Oracle will not use direct path(it's a different story for sqlldr loads).
others
Example.
Object-level parallel hints give more control but are more prone to errors; developers often forget to use the alias
instead of the object name, or they forget to include some objects.
Let's say a query takes 100 seconds to execute without using parallel hint. If we change DOP to 2 for same query,
then ideally the same query with parallel hint will take 50 second. Similarly using DOP as 4 will take 25 seconds.
As explained in many places, "in a HASH join, Oracle accesses one table (usually the smaller of the joined results)
and builds a hash table on the join key in memory. It then scans the other table in the join (usually the larger one)
and probes the hash table for matches to it."
It is preferred against Nested Loops method when the tables are big, no indexes are at hand, etc.
Note: The hint does not force the order of the join, just asks for HASH JOIN method.
Example of usage:
CREATE TABLE fullTable(id) AS SELECT LEVEL FROM dual CONNECT BY LEVEL < 100000;
CREATE INDEX idx ON fullTable(id);
--------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 13 | 3 (0)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | 13 | | |
|* 2 | INDEX RANGE SCAN| IDX | 2 | 26 | 3 (0)| 00:00:01 |
--------------------------------------------------------------------------
SELECT /*+ full(f) */ COUNT(1) FROM fullTable f WHERE id BETWEEN 10 AND 100;
--------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 13 | 47 (3)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | 13 | | |
|* 2 | TABLE ACCESS FULL| FULLTABLE | 2 | 26 | 47 (3)| 00:00:01 |
--------------------------------------------------------------------------------
Output -
Number
------
1
2
3
4
5
6
7
8
9
10
Elapsed: 00:00:02.20
If I run the same query again now, the time to execute will reduce since the data is now fetched from cache which
was set during the first execution.
Output -
Number
------
1
2
3
4
5
6
7
8
9
10
Elapsed: 00:00:00.10
Notice how the elapsed time reduced from 2.20 seconds to 0.10 seconds.
Result Cache holds the cache until the data in database is updated/altered/deleted. Any change will
release the cache.
Package header:
END;
/
Package body:
RETURN vColour;
END;
END;
/
DECLARE
vColour VARCHAR2(100);
BEGIN
vColour := SkyPkg.GetSkyColour(vPlanet => 'Earth');
DBMS_OUTPUT.PUT_LINE(vColour);
END;
/
END TEST;
/
We call both procedures. The first with integer parameter, the second with varchar2.
SQL>
Digit: 3
PL/SQL procedure successfully completed
String: three
PL/SQL procedure successfully completed
Restrictions on Overloading
Only local or packaged subprograms, or type methods, can be overloaded. Therefore, you cannot overload
standalone subprograms. Also, you cannot overload two subprograms if their formal parameters differ only in
name or parameter mode
Modularity
Better Performance/ Funtionality
Parts of a Package
Specification - Sometimes called a package header. Contains variable and type declarations and the signatures of
the functions and procedures that are in the package which are public to be called from outside the package.
DECLARE
declaration Section
BEGIN
some statements
EXCEPTION
WHEN exception_one THEN
DO something
WHEN exception_two THEN
DO something
WHEN exception_three THEN
DO something
WHEN OTHERS THEN
DO something
END;
An exception section has to be on the end of the PL/SQL block. PL/SQL gives us the opportunity to nest blocks, then
each block may have its own exception section for example:
EXCEPTION
WHEN exception_one THEN
DO something
END;
EXCEPTION
WHEN exception_two THEN
DO something
END;
If exception will be raised in the nested block it should be handled in the inner exception section, but if inner
exception section does not handle this exception then this exception will go to exception section of the external
block.
Example
I want to update all salaries of workers. But if there are no workers, raise an exception.
EXCEPTION
WHEN no_workers THEN
raise_application_error(-20991,'We don''t have workers!');
END;
/
Exceptions are raised by database server automatically when there is a need, but if you want, you can raise
explicitly any exception using RAISE.
Procedure raise_application_error(error_number,error_message);
If you know that your database operation might raise specific exceptions those which don't have names, then you
can give them names so that you can write exception handlers specifically for them. Otherwise, you can use them
only with OTHERS exception handlers.
Syntax
DECLARE
my_name_exc EXCEPTION;
PRAGMA exception_init(my_name_exc,-37);
BEGIN
...
EXCEPTION
WHEN my_name_exc THEN
DO something
END;
PRAGMA exception_init(my_name_exc,-37); assign name to the error code of internally defined exception.
Example
We have an emp_id which is a primary key in emp table and a foreign key in dept table. If we try to remove emp_id
when it has child records, it will be thrown an exception with code -2292.
Oracle documentation says: "An internally defined exception with a user-declared name is still an
internally defined exception, not a user-defined exception."
Example
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.put_line('Duplicate value on index!');
END;
/
DECLARE
this_is_not_acceptable EXCEPTION;
PRAGMA EXCEPTION_INIT(this_is_not_acceptable, -20077);
g_err VARCHAR2 (200) := 'to-be-defined';
w_schema all_tables.OWNER%TYPE;
BEGIN
g_err := 'Global; first call:';
get_schema('Delivery-Manager-Is-Silly', w_schema);
g_err := 'Global; second call:';
get_schema('AAA', w_schema);
g_err := 'Global; third call:';
get_schema('', w_schema);
g_err := 'Global; 4th call:';
get_schema('Can''t reach this point due to previous error.', w_schema);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line('[ERR]'||g_err||'unhandled exception:'||SQLERRM);
-- you may raise this again to the caller if error log isn't enough.
-- raise;
END;
/
Remember that exception are here to handle rare cases. I saw applications who raised an exception at every access,
just to ask for the user password, saying "not connected"... so much computation waste.
Here is a way to test what goes wrong with the user used by the database link:
DECLARE
v_dummy NUMBER;
BEGIN
-- testing db link
EXECUTE IMMEDIATE 'select COUNT(1) from dba_users@pass.world' INTO v_dummy ;
-- if we get here, exception wasn't raised: display COUNT's result
DBMS_OUTPUT.put_line(v_dummy||' users on PASS db');
EXCEPTION
-- exception can be referred by their name in the predefined Oracle's list
WHEN LOGIN_DENIED
THEN
DBMS_OUTPUT.put_line('ORA-1017 / USERNAME OR PASSWORD INVALID, TRY AGAIN');
WHEN OTHERS
THEN
-- or referred by their number: stored automatically in reserved variable SQLCODE
IF SQLCODE = '-2019'
THEN
DBMS_OUTPUT.put_line('ORA-2019 / Invalid db_link name');
ELSIF SQLCODE = '-1035'
THEN
DBMS_OUTPUT.put_line('ORA-1035 / DATABASE IS ON RESTRICTED SESSION, CONTACT YOUR DBA');
Exception handling is a possibility to keep our program running even if appear runtime error resulting from
for example coding mistakes, hardware failures.We avoid it from exiting abruptly.
To test a database link connection without needing to know any of the object names in the linked database, use the
following query:
To explicitly specify a domain for the linked database service, the domain name is added to the USING statement.
For example:
USING 'tns_service_name.WORLD'
If no domain name is explicitly specified, Oracle uses the domain of the database in which the link is being created.
10g: https://docs.oracle.com/cd/B19306_01/server.102/b14200/statements_5005.htm
11g: https://docs.oracle.com/cd/B28359_01/server.111/b28310/ds_concepts002.htm
12g: https://docs.oracle.com/database/121/SQLRF/statements_5006.htm#SQLRF01205
Prerequisites: For creating a private Database link you need a CREATE DATABASE LINK privilege. For creating a
private Database link you need a CREATE PUBLIC DATABASE LINK privilege.
From ORA1:
SQL> CREATE <public> DATABASE LINK ora2 CONNECT TO user1 IDENTIFIED BY pass1 USING <tns name OF
ora2>;
Now that we have the DB link set up, we can prove that by running the following from ORA1:
Pre-requistes:
Table "A" doesn't contain data in partition "OLD_VALUES" and table "B" contains data
Table "A" contains data in partition "OLD_VALUES" and table "B" doesn't contain data
Result : data is "moved" from partition "OLD_VALUES" (contains no data after operation) to table "B"
Note : there is a quite a few additional options, features and restrictions for this operation
You should use a power of 2 for the number of hash partitions, so that you get an even distribution in partition size.
Create a queue that we can send a message to. Oracle will notify our stored procedure that a message has been
enqueued and should be worked. We'll also add some subprograms we can use in an emergency to stop messages
from being deqeued, allow dequeuing again, and run a simple batch job to work through all of the messages.
These examples were tested on Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production.
Create Queue
We will create a message type, a queue table that can hold the messages, and a queue. Messages in the queue will
be dequeued first by priority then be their enqueue time. If anything goes wrong working the message and the
dequeue is rolled-back AQ will make the message available for dequeue 3600 seconds later. It will do this 48 times
before moving it an exception queue.
Now that we have a place to put the messages lets create a package to manage and work messages in the queue.
-- prevents messages from being worked but will still allow them to be created and enqueued
END;
/
-- prevents messages from being worked but will still allow them to be created and enqueued
PROCEDURE disable_dequeue
AS
BEGIN
DBMS_AQADM.stop_queue (queue_name => queue_name_c, dequeue => TRUE, enqueue => FALSE);
END disable_dequeue;
Next tell AQ that when a message is enqueued to MESSAGE_Q (and committed) notify our procedure it has work to
do. AQ will start up a job in its own session to handle this.
BEGIN
DBMS_AQ.register (
sys.aq$_reg_info_list (
sys.aq$_reg_info (USER || '.' || message_worker_pkg.queue_name_c,
DBMS_AQ.namespace_aq,
'plsql://' || USER || '.message_worker_pkg.on_message_enqueued',
HEXTORAW ('FF'))),
1);
COMMIT;
END;
BEGIN
FOR i IN (SELECT a.table_name, c.column_name
FROM user_constraints a, user_cons_columns c
WHERE a.CONSTRAINT_TYPE = 'R'
AND a.R_CONSTRAINT_NAME = 'PK_S'
AND c.constraint_name = a.constraint_name) LOOP
END LOOP;
END;
BEGIN
FOR I IN (SELECT table_name, constraint_name FROM user_constraint t WHERE
r_constraint_name='pk_t1') LOOP
EXECUTE IMMEDIATE ' alter table ' || I.table_name || ' disable constraint ' || i.constraint_name;
END LOOP;
END;?
The following anonymous PL/SQL block shows how to call the log_errors procedure.
BEGIN
DELETE FROM dept WHERE deptno = 10;
EXCEPTION
WHEN OTHERS THEN
log_errors('Delete dept',SQLCODE, SQLERRM);
RAISE;
END;
Here "binding" indicates the EL expression from which the value is to be get.
"variable_name" the parameter to which the value from the binding to be stored
/*The above query is useful in various scenarios like generating a sequence of dates from a given date. The
following query generates 10 consecutive dates */
01-JAN-17
02-JAN-17
03-JAN-17
04-JAN-17
05-JAN-17
06-JAN-17
07-JAN-17
08-JAN-17
09-JAN-17
10-JAN-17
The CONNECT BY clause to define the relationship between employees and managers.
2. Datapump status:
Note down the job name from the import/export logs or data dictionary name and
Run attach command:
type status in Import/Export prompt
*Please replace the data in <> with appropriate values as per your environment. You can add/modify parameters as
per your requirements. In the above example all the remaining parameters are added in parameter files as stated
below: *
schemas=<schema>
directory= DATAPUMP_REMOTE_DIR
dumpfile=<dbname>_<schema>.dmp
logfile=exp_<dbname>_<schema>.LOG
Prior to user import it is a good practice to drop the schema or table imported.
Commands:
*Please replace the data in <> with appropriate values as per your environment. You can add/modify parameters as
per your requirements. In the above example all the remaining parameters are added in parameter files as stated
below: *
schemas=<schema>
directory= DATAPUMP_REMOTE_DIR
dumpfile=<dbname>_<schema>.dmp
logfile=imp_<dbname>_<schema>.LOG
schemas=<schema>
directory= DATAPUMP_REMOTE_DIR
dumpfile=<dbname>_<schema>_%U.dmp
logfile=imp_<dbname>_<schema>.LOG
parallel=5
--fetching data from table into collection and then loop through the collection and print the data.
DECLARE
table1_tbl table1_tbl_typ;
BEGIN
table1_tbl := table1_tbl_typ();
SELECT table1_t(a_1,a_2)
BULK COLLECT INTO table1_tbl
FROM table1 WHERE ROWNUM<10;
Application Privilege: An Application Privilege describes Privileges like SELECT, INSERT, UPDATE, DELETE, ...
Application Privileges can be summarized as an Aggregate Privilege.
XS$PRIVILEGE(
name=>'privilege_name'
[, implied_priv_list=>XS$NAME_LIST('"SELECT"', '"INSERT"', '"UPDATE"', '"DELETE"')]
)
XS$PRIVILEGE_LIST(
XS$PRIVILEGE(...),
XS$PRIVILEGE(...),
...
);
Application User:
BEGIN
SYS.XS_PRINCIPAL.CREATE_USER('user_name');
END;
BEGIN
SYS.XS_PRINCIPAL.CREATE_USER(name => 'user_name', schema => 'schema_name');
END;
BEGIN
SYS.XS_PRINCIPAL.SET_PASSWORD('user_name', 'password');
END;
CREATE PROFILE prof LIMIT
PASSWORD_REUSE_TIME 1/4440
PASSWORD_REUSE_MAX 3
PASSWORD_VERIFY_FUNCTION Verify_Pass;
BEGIN
SYS.XS_PRINCIPAL.SET_PROFILE('user_name', 'prof');
END;
BEGIN
SYS.XS_PRINCIPAL.GRANT_ROLES('user_name', 'XSONNCENT');
END;
(optional:)
BEGIN
SYS.XS_PRINCIPAL.SET_VERIFIER('user_name', '6DFF060084ECE67F', XS_PRINCIPAL.XS_SHA512“);
Application Role:
DECLARE
st_date TIMESTAMP WITH TIME ZONE;
ed_date TIMESTAMP WITH TIME ZONE;
BEGIN
st_date := SYSTIMESTAMP;
ed_date := TO_TIMESTAMP_TZ('2013-06-18 11:00:00 -5:00','YYYY-MM-DD HH:MI:SS');
SYS.XS_PRINCIPAL.CREATE_ROLE
(name => 'app_regular_role',
enabled => TRUE,
start_date => st_date,
end_date => ed_date);
END;
Dynamic Application Role: (gets enabled dynamical based on the authenatication state)
BEGIN
SYS.XS_PRINCIPAL.CREATE_DYNAMIC_ROLE
(name => 'app_dynamic_role',
duration => 40,
scope => XS_PRINCIPAL.SESSION_SCOPE);
END;
Regular:
XSPUBLIC
XSBYPASS
XSSESSIONADMIN
XSNAMESPACEADMIN
XSPROVISIONER
XSCACHEADMIN
XSDISPATCHER
This will assign right operand to the left operand. In PL/SQL this operation looks like this:
left_operand := right_operand;
Left operand must be always a variable. Right operand can be value, variable or function:
SET serveroutput ON
DECLARE
v_hello1 VARCHAR2(32767);
v_hello2 VARCHAR2(32767);
v_hello3 VARCHAR2(32767);
FUNCTION hello RETURN VARCHAR2 IS BEGIN RETURN 'Hello from a function!'; END;
BEGIN
-- from a value (string literal)
v_hello1 := 'Hello from a value!';
-- from variable
v_hello2 := v_hello1;
-- from function
v_hello3 := hello;
DBMS_OUTPUT.put_line(v_hello1);
DBMS_OUTPUT.put_line(v_hello2);
DBMS_OUTPUT.put_line(v_hello3);
END;
/
When the code block is executed in SQL*Plus the following output is printed in console:
There is a feature in PL/SQL that allow us to assign "from right to the left". It's possible to do in SELECT INTO
statement. Prototype of this instrunction you will find below:
INTO local_variable
WHERE comparison_instructions;
SET serveroutput ON
DECLARE
v_hello VARCHAR2(32767);
BEGIN
SELECT 'Hello world!'
INTO v_hello
FROM dual;
DBMS_OUTPUT.put_line(v_hello);
END;
/
When the code block is executed in SQL*Plus the following output is printed in console:
Hello world!
Asignment "from right to the left" is not a standard, but it's valuable feature for programmers and users. Generally
it's used when programmer is using cursors in PL/SQL - this technique is used, when we want to return a single
scalar value or set of columns in the one line of cursor from SQL cursor.
Further Reading:
Triggers are a useful concept in PL/SQL. A trigger is a special type of stored procedure which does not require to be
explicitly called by the user. It is a group of instructions, which is automatically fired in response to a specific data
modification action on a specific table or relation, or when certain specified conditions are satisfied. Triggers help
maintain the integrity, and security of data. They make the job convenient by taking the required action
automatically.
DECLARE
table_name VARCHAR2(30) := 'my_table';
id NUMBER := 1;
BEGIN
DBMS_OUTPUT.put_line(get_value(table_name, id));
END;
Table to test:
DECLARE
query_text VARCHAR2(1000) := 'insert into my_table(id, column_value) values (:P_ID, :P_VAL)';
id NUMBER := 2;
VALUE VARCHAR2(100) := 'Bonjour!';
BEGIN
EXECUTE IMMEDIATE query_text USING id, VALUE;
END;
/
DECLARE
query_text VARCHAR2(1000) := 'update my_table set column_value = :P_VAL where id = :P_ID';
id NUMBER := 2;
VALUE VARCHAR2(100) := 'Bonjour le monde!';
BEGIN
BEGIN
EXECUTE IMMEDIATE 'create table my_table (id number, column_value varchar2(100))';
END;
/
DECLARE
query_text VARCHAR2(1000) := 'begin :P_OUT := cos(:P_IN); end;';
in_value NUMBER := 0;
out_value NUMBER;
BEGIN
EXECUTE IMMEDIATE query_text USING OUT out_value, IN in_value;
DBMS_OUTPUT.put_line('Result of anonymous block: ' || TO_CHAR(out_value));
END;
/