Вы находитесь на странице: 1из 17

Short Notes

JOIN

Oracle join is used to combine columns from two or more tables based on values of the related
columns. The related

columns are typically the primary key column(s) of the first table and foreign key column(s) of the
second table.

Note that you can join a table to itself to query hierarchical data using an inner join, left join, or right
join. This kind of join is known as self-join.

An outer join is performed when rows, which are not retrieved by an inner join, are returned.

Sometimes, you want to get only rows from the left table that do not exist in the right table. To achieve
this, you use the left join and

a WHERE clause to exclude the rows from the right table.

Oracle full outer join or full join returns a result set that contains all rows from both left and right tables,
with the matching rows from both sides

where available. If there is no match, the missing side will have nulls.

A left outer join between the source and target tables returns the results of an inner join as well

as rows from the source table excluded by that inner join. A right outer join between the source and
target

tables returns the results of an inner join as well as rows from the target table excluded by that inner
join.

If a join returns the results of an inner join as well as rows

from both the source and target tables excluded by that inner join, then a full outer join has been
performed.
The inner join is implemented using three possible join clauses that use the following keywords in
different

combinations: NATURAL JOIN, USING, and ON

While the natural join contains the NATURAL keyword in its syntax, the JOIN…USING syntax does not.
An error is

raised if the keywords NATURAL and USING occur in the same join clause.

The natural join and the JOIN…USING clauses depend on join columns with identical column names. The
JOIN…ON clause

allows the explicit specification of join columns, regardless of their column names. This is the most
flexible and

widely used form of the join clauses. The ON and NATURAL keywords cannot appear together in a join
clause.

When there are identical column names in the source and target tables you want to exclude as join
columns, the JOIN…USING format may be used

SELF JOIN

When the join columns originate from the same table, a self-join is required.

SELECT f1.name Dad, f2.name Child

FROM family f1

JOIN family f2

ON(f1.id=f2.father_id);

A transaction consists of one or more DML statements, followed by either a ROLLBACK or a COMMIT
command.
If a user issues a DDL (CREATE, ALTER, or DROP) or DCL (GRANT or REVOKE) command, the transaction
in progress

(if any) will be committed: it will be made permanent and become visible to all other users.these
commands are

terminated with a COMMIT.

The SQL standard does not allow a user to start one transaction and then start another before
terminating the first.

A transaction is a set of one or more statements that is executed as a unit, so either all of the
statements are executed,

or none of the statements is executed.

The SAVEPOINT command can be used to set markers that will stage the action of a ROLLBACK, but the
same transaction

remains in progress irrespective of the use of SAVEPOINT.

Ascending sort order is natural for most types of data and is therefore the default sort order used
whenever the

ORDER BY clause is specified. An ascending sort order for numbers is lowest to highest, while it is
earliest to

latest for dates and alphabetically for characters

The TRUNC(number, decimal precision) function drops off or truncates the number given a decimal
precision value:

look for truncate with negatives, constraints,data dictionary, ALL/ANY create as table
Oracle ALL operator is used to compare a value to a list of values or result set returned by a subquery.

In this syntax, a check constraint consists of the keyword CHECK followed by an expression in
parentheses

CREATE TABLE table_name (

...,

CONSTRAINT check_constraint_name CHECK (expresssion)

);

Oracle check constraint allows you to enforce domain integrity by limiting the values accepted by one
or more columns.

VIEWS

A view is a stored SELECT statement that can be addressed as though it were a table.

. A synonym is an alias for a table (or a view). give query a name, then you have a view. a view is a
“virtual” table whose data

is the result of a stored query, which is derived each time when you query against the view.

Unlike a table, a view does not store any data.


VIEWS- The OR REPLACE option is used to change the defination of an existing view without dropping
and recreating it.

Rows cannot be deleted through a view if the view defination contains the distinct keyword.

If you don’t want to use column aliases in the query, you must define them in the CREATE VIEWclause:

CREATE OR REPLACE VIEW customer_sales AS

SELECT

name AS customer,

SUM( quantity * unit_price ) sales_amount,

EXTRACT(

YEAR

FROM

order_date

) YEAR

FROM

orders

OR REPLACE

The OR REPLACE option replaces the definition of existing view. It is handy if you have granted various
privileges on the view.

Because when you use the DROP VIEW and CREATE VIEW to change the view’s definition, Oracle
removes the view privileges, which may not be

what you want. To avoid this, you can use the CREATE OR REPLACE clause that preserves the view
privileges.

AS defining-query
The defining query is a SELECT statement that defines the columns and rows of the view.

WITH READ ONLY

The WITH READ ONLY clause prevents the underlying tables from changes through the view.

WITH CHECK OPTION

The WITH CHECK OPTION clause protects the view from any changes to the underlying table that would
produce rows which are not included in the defining query.

. Indexes are a means of improving access times to rows in tables. If a query requires only one row, then
rather than scanning

the entire table to find the row, an index can give a pointer to the row’s exact location.

A sequence is a construct that generates unique numbers.

ON DELETE CASCADE. This means that if a row in the parent table is deleted, Oracle will search the child
table for

all the matching rows and delete them too. This will happen automatically.

The set operators used in compound queries are as follows:

■ UNION Returns the combined rows from two queries, sorting them and removing duplicates.

■ UNION ALL Returns the combined rows from two queries without sorting or removing duplicates.

■ INTERSECT Returns only the rows that occur in both queries’ result sets, sorting them and removing
duplicates.

■ MINUS Returns only the rows in the first result set that do not appear in the second result set, sorting
them
and removing duplicates

A MINUS will remove common rows:

An intersection will retrieve rows common to two queries

WITH CLAUSE

Oracle With Clause is similar to temporary tables, where you store the data once and read it multiple

times in your sql query. Oracle With Clause is used when a sub-query is executed multiple times.

You can improve the performance of the query by using with clause.

WITH clause can be used to reduce repetition and simplify complex SQL statements.

The advantage of the latter is that repeated references to the subquery may be more efficient as the
data is easily retrieved

from the temporary table, rather than being requeried by each reference.

Typically, you can use a subquery anywhere that you use an expression.

Syntax of Oracle With Clause

With query_name As

SQL query

SELECT * FROM query_name;


Think of the query_name as a temporary table and use it in your queries.

The INSTR(source string, search item, [start position],[nth occurrence of search item]) function returns a
number that

represents the position in the source string, beginning from the given start position, where the nth
occurrence of the

search item begins:

. The HAVING clause conditions restrict group-level data and must contain a group function or an
expression based on the grouping attributes.

An important difference between the HAVING clause and the other SELECT statement clauses is that it
may only be specified if a GROUP BY clause is present.

The HAVING clause limits or restricts the group-level rows as required.

read about escape and instr, with clause precendence between table and with, correlated subquery,
Having

The ESCAPE identifier instructs the Oracle server to treat any character found after the backslash
character as a regular nonspecial symbol with

no wildcard meaning.

A primary key constraint is a unique constraint combined with a not null constraint.

AWR Compare Periods report enables you to compare database performance over time.

how to compare database performance over time using Automatic Workload Repository (AWR)
Compare Periods reports
The Automatic Database Diagnostic Monitor (ADDM) is a self-diagnostic engine built into Oracle
Database. ADDM examines and analyzes data captured

in the Automatic Workload Repository (AWR) to determine possible performance problems in Oracle
Database

A subquery in the FROM clause of a SELECT statement is called an inline view. A subquery in the WHERE
clause of a SELECT statement is

called a nested subquery.

A subquery can appear on either side of a comparison operator.

A subquery can contain another subquery. Oracle Database imposes no limit on the number of
subquery levels in the FROM clause of the top-level query.

You can nest up to 255 levels of subqueries in the WHERE clause.

CORELATED SUBQUERIES

A correlated subquery has a more complex method of execution than single- and multiple-row
subqueries and is potentially much more powerful.

If a subquery references columns in the parent query, then its result will be dependent on the parent
query. This makes it impossible to evaluate

the subquery before evaluating the parent query.

A correlated subquery is a subquery that uses values from the outer query to perform tasks of inner
queries
A correlated subquery is evaluated once for each row processed by the parent statement.

Each row returned by the outer query is evaluated for the results returned by the inner query.

The nested query executes after the outer query returns the row.

Oracle performs a correlated subquery when a nested subquery references a column from a table
referred to a parent statement any number of levels above

the subquery.

A correlated subquery answers a multiple-part question whose answer depends on the value in each
row processed by the parent statement. For example, you can

use a correlated subquery to determine which employees earn more than the average salaries for their
departments.

A correlated subquery must be evaluated once for every row in the outer query. A correlated subquery
can be single- or multiple-row, if the comparison

operator is appropriate.

Use subqueries for the following purposes:

To define the set of rows to be inserted into the target table of an INSERT or CREATE TABLE statement

To define the set of rows to be included in a view or materialized view in a CREATE VIEW or CREATE
MATERIALIZED VIEW statement

To define one or more values to be assigned to existing rows in an UPDATE statement

To provide values for conditions in a WHERE clause, HAVING clause, or START WITH clause of SELECT,
UPDATE, and DELETE statements
To define a table to be operated on by a containing query

An inline view is not a real view but a subquery in the FROM clause of a SELECT statement.

read intervals to day,savepoint, single-row functions

Single row functions

Single row functions can be character functions, numeric functions, date functions, and conversion
functions. Note that these functions are used to manipulate data items. These functions require one or
more input arguments and operate on each row, thereby returning one output value for each row.
Argument can be a column, literal or an expression. Single row functions can be used in SELECT
statement, WHERE and ORDER BY clause. Single row functions can be -

General functions - Usually contains NULL handling functions. The functions under the category are NVL,
NVL2, NULLIF, COALESCE, CASE, DECODE.

Case Conversion functions - Accepts character input and returns a character value. Functions under the
category are UPPER, LOWER and INITCAP.

UPPER function converts a string to upper case.

LOWER function converts a string to lower case.

INITCAP function converts only the initial alphabets of a string to upper case.

Character functions - Accepts character input and returns number or character value. Functions under
the category are CONCAT, LENGTH, SUBSTR, INSTR, LPAD, RPAD, TRIM and REPLACE.
CONCAT function concatenates two string values.

LENGTH function returns the length of the input string.

SUBSTR function returns a portion of a string from a given start point to an end point.

INSTR function returns numeric position of a character or a string in a given string.

LPAD and RPAD functions pad the given string upto a specific length with a given character.

TRIM function trims the string input from the start or end.

REPLACE function replaces characters from the input string with a given character.

Date functions -

Date arithmetic operations return date or numeric values. Functions under the category are
MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND and TRUNC.

MONTHS_BETWEEN function returns the count of months between the two dates.

ADD_MONTHS function add 'n' number of months to an input date.

NEXT_DAY function returns the next day of the date specified.


LAST_DAY function returns last day of the month of the input date.

ROUND and TRUNC functions are used to round and truncates the date value.

Number functions - Accepts numeric input and returns numeric values. Functions under the category are
ROUND, TRUNC, and MOD.

ROUND and TRUNC functions are used to round and truncate the number value.

MOD is used to return the remainder of the division operation between two numbers.

The fm modifier is used to trim blank spaces that trail the names of the shorter days and shorter
months.

Spelled out number: 'MmSP Month Yyyysp'

Nine September Two Thousand Eight

Single Row functions - Single row functions are the one who work on single row and return one output
per row. For example, length and

case conversion functions are single row functions.Single row functions can be used in SELECT
statement, WHERE and ORDER BY clause.

Multiple Row functions - Multiple row functions work upon group of rows and return one result for the
complete set of rows.

They are also known as Group Functions.


One or more group functions may appear in the SELECT list as follows:

SELECT group_function(column or expression),… FROM table [WHERE …] [ORDER BY…]

There are two types of INTERVAL:

INTERVAL YEAR TO MONTH – stores intervals using of year and month.

INTERVAL DAY TO SECOND – stores intervals using days, hours, minutes, and seconds including
fractional seconds.

Date-Based Conditions

DATE columns are useful when storing date and time information. Date literals must be enclosed in
single quotation marks just like character data;

otherwise an error is raised. When used in conditional WHERE clauses, DATE columns are compared to
other DATE columns or to_date literals.

The literals are automatically converted into DATE values based on the default date format, which is
DD-MONRR. If a literal occurs in an expression

involving a DATE column, it is automatically converted into a date value using the default format mask.

An expression like START_DATE + 1 returns a DATE value that is 1 day later than START_DATE

Savepoint names must be distinct within a given transaction. If you create a second savepoint with the
same identifier as an earlier savepoint,

then the earlier savepoint is erased. After a savepoint has been created, you can either continue
processing, commit your work, roll back the

entire transaction, or roll back to the savepoint.

A sysdate cannot be used with a check constraint.


WITH CLAUSE

It can only be used only with the select clause

The with clause can hold more than one query

The query name in the WITH clause is visible to other query blocks in the WITH clause as well as to the
main query block.

Drop TABLE employees;

All indexes and constraints defined on the table being dropped are also dropped

if theres an uncommited transaction in the session is commited

Single Row Function

The data type returned,cab be different from the data type of the argument that is referenced

they can be used in select,where and order by clause

they can accept column names,expressions,variable names, or a supplied constants as arguments.

by default Enterprise Manager express is available for a database after database creation.

A savepoint can be used for only dml statement

FETCH clause

use the Oracle FETCH clause to limit the rows returned by a query.

The FETCH clause specifies the number of rows or percentage of rows to return.

The ONLY returns exactly the number of rows or percentage of rows after FETCH NEXT (or FIRST).
The WITH TIES returns additional rows with the same sort key as the last row fetched. Note that if you
use WITH TIES, you must

specify an ORDER BY clause in the query.If you don’t, the query will not return the additional rows.

The OFFSET clause specifies the number of rows to skip before the row limiting starts. The OFFSET
clause is optional. If you skip it, then offset is 0

and row limiting starts with the first row.

Oracle EXISTS operator

The Oracle EXISTS operator is a Boolean operator that returns either true or false. The EXISTS operator is
often used with a subquery to test for the

existence of rows:

The EXISTS operator returns true if the subquery returns any rows, otherwise, it returns false. In
addition, the EXISTS operator terminates the processing of

the subquery once the subquery returns the first row.

SELECT

FROM

table_name

WHERE

EXISTS(subquery);

Converting Numbers to Characters Using the TO_CHAR Function

The TO_CHAR function returns an item of data type VARCHAR2


Introduction to the Oracle MERGE statement

The Oracle MERGE statement selects data from one or more source tables and updates or inserts it into
a target table. The MERGE statement allows you to

specify a condition to determine whether to update data from or insert data into the target table.

First, specify the target table (target_table) which you want to update or insert into in the INTO clause.

Second, specify the source of data (source_table) to be updated or inserted in the USING clause.

Вам также может понравиться