Sie sind auf Seite 1von 40

FORMS 6i

Canvas
A canvas is a surface--inside a window container--on which you place the interface items
and boilerplate objects that end users interact with when they run the form. Type determines how
the canvas is displayed in the window to which it is assigned, and determines which properties
make sense for the canvas.

Canvas Type
Content : Default specifies that the canvas should occupy the entire content area of the window to
which it is assigned. Most canvases are content canvases.
Stacked : Specifies that the canvas should be displayed in its window at the same time as the
window's content canvas.
Vertical Toolbar : Specifies that the canvas should be displayed as a vertical toolbar at the
left side of the window to which it is assigned.
Horizontal Toolbar :Specifies that the canvas should be displayed as a horizontal toolbar under
the menu bar of the window.
Tab canvas : Made up of one or more tab pages, allows you to group and display a large amount
of related information on a single, dynamic canvas object.

Block
Represents a logical container for grouping related items into a function unit for storing,
displaying, and manipulating records. Only item objects contained in a block are visible in the
application interface.
Data Block :Data blocks are associated with data (table columns) within a database. Data blocks
can be based on database tables, views, procedures, or transactional triggers.
Control Block :Control block is not associated with the database, and the items in a control block
do not relate to table columns within a database.

Block DataSource
Data block can be based on any of the following datasources:
Table : A table is the most commonly used block datasource.A data block based on a table, also
reduces network traffic through array processing.The Query Array Size property enables array
processing for records queried, and the DML Array Size property enables array processing for
records used in DML operations.
View:
FROM clause (query datasource only) : A FROM clause may be used as the datasource for a
data block. A FROM clause is a feature of the Oracle8 Server that allows you to nest a SELECT
statement in the FROM clause of a SELECT statement. A FROM clause is a valid query block
datasource, but it is not a valid DML block datasource. The value returned from a FROM clause
is a subset of records from the original query. FROM clauses are used to perform joins, lookups,
and calculations without having to create a view on the server. FROM clauses can also be used to
prototype views and to increase performance.
Using a FROM clause as a block datasource is similar to using an updateable join-view as a block
datasource. However, a FROM clause provides more control, because the presence of a DBA is
not required to define the view. You should note that the FROM clause produces results that are
identical to an updateable join-view from the client side, but that there is no defined view on the
server.Array processing is supported to increase performance by reducing network traffic.
Procedure : Using a stored procedure as a block datasource is a more advanced option. Base a
data block on a stored procedure when you want to:
increase control and security
query and update multiple tables
perform complex computations
perform validation and DML on the server-side
encapsulate logic within a subprogram
reduce network traffic through array processing
A stored procedure returns data to a data block by using either a ref cursor or a table of records.
Ref Cursor: A ref cursor is a pointer to a server-side cursor variable. It is analogous to a pointer
in "C" in that it is an address to a location in memory. The stored procedure returns a reference to
a cursor that is open and populated by a SELECT statement to be used as a block data source.
A stored procedure that uses a reference cursor can only be used as a query block data source; it
cannot be used for DML block data source. Using a ref cursor is ideal for queries that are
dependent only on variations in SQL statements and not PL/SQL.
When deciding whether to use a ref cursor or a table of records, consider that:
A stored procedure that uses a ref cursor can only be used as a query block data source a stored
procedure that uses a table of records can be used as both a query and DML block data source
Table of records: A table of records is a PL/SQL structure that resembles an array of records.
The stored procedure constructs the array and passes back the resulting set of records to be used
as a block data source. Using a table of records is ideal for queries that are dependent on PL/SQL
and SQL. Using a table of records is extremely efficient in terms of the savings on network
traffic, because it takes a single round trip (from client to server) to execute the stored procedure,
and a single round trip for all the records returned.
Transactional trigger : Transactional triggers may be used to provide data for data blocks.
Transactional triggers are typically used when Form Builder is running against a non-ORACLE
datasource. When transactional triggers are used, Form Builder default functionality is
replaced.A transactional trigger block datasource can be used for both query and DML. Array
processing is not supported when the block datasource is based on a transactional trigger.

Relation
A master-detail relation is an association between two data blocks - a master block and a
detail block. The relation reflects one of the following:
a primary-key to foreign-key relationship between the tables on which the blocks are based
a REF pointer relationship between the tables on which the blocks are based.
When you create a master-detail relation, Form Builder generates different triggers depending on
how the Delete Record Behavior and Coordination properties are set.

Delete Record Behavior Property Resulting Triggers

Non-Isolated (the default) On-Check-Delete-Master, On-Clear-Details,


On-Populate-Details
Cascading On-Clear-Details, On-Populate-Details, Pre-Delete
Isolated On-Clear-Details, On-Populate-Details

On-Clear-Details Trigger: Every master-detail relation must have an On-Clear-Details trigger. It


fires during the clear phase of coordination, and clears all of the detail records in the detail block.
On-Check-Delete-Master Trigger Form Builder creates the On-Check-Delete-Master trigger
when the Delete Record Behavior property is set to Non-Isolated. It fires when there is an
attempt to delete a master record. The trigger queries the database to see if detail records exist for
the master record. If no details exist, the trigger deletes the master record. If detail records are
found, the trigger displays the message: Cannot delete master record when matching detail
records exist.
On-Populate-Details Trigger Form Builder creates a On-Populate-Details trigger for every
master-detail relation. It fires during the population phase of block coordination. The trigger first
checks the status of the master record and the value of its primary-key field, then navigates to the
detail block to issue the appropriate query. This trigger calls the QUERY_MASTER_DETAILS
procedure.
Pre-Delete Trigger Form Builder creates the Pre-Delete trigger when the Delete Record Behavior
property is set to Cascading. It deletes the records in the detail block's base table that correspond
to the master record that is being deleted.

Record Group
A record group is an internal Form Builder data structure that has a column/row
framework similar to a database table. However, unlike database tables, record groups are
separate objects that belong to the form module in which they are defined.
A record group built from a query can store records from database tables much like a
database view, with the added advantage that the record group is local to Form Builder, rather
than existing in the database. Also, the SELECT statement used to create and populate a query
record group can be constructed dynamically at runtime.
Query record group: A query record group is a record group that has an associated SELECT
statement. The columns in a query record group derive their default names, data types, and
lengths from the database columns referenced in the SELECT statement. The records in a query
record group are the rows retrieved by the query associated with that record group.Query record
groups can be created and modified at design time or at runtime.
Non-query record group: A non-query record group is a group that does not have an associated
query, but whose structure and values can be modified programmatically at runtime.Non-query
record groups can be created and modified only at runtime.
Static record group: A static record group is not associated with a query; instead, you define its
structure and row values at design time, and they remain fixed at runtime. Static record groups
can be created and modified only at design time.
The actual values in a record group come from one of three possible sources: the execution of a
SELECT statement that you associated with the record group at design time (query record
groups) the execution of built-in subprograms that populate the record group dynamically (query
groups and non-query groups) an array of static values that you associated with the record group
at design time (static record groups).

LOV
An LOV object is a scrollable popup window that provides the end user with either a
single or multi-column selection list.

Object Group
An object group is a container for a group of objects. You define an object group when
you want to package related objects so you can copy or subclass them in another module.You can
create object groups in form and menu modules.

Object Library
This object provides an easy method of reusing objects and enforcing standards across
the entire development organization.You can use the Object Library to create, store, maintain,
and distribute standard and reusable objects. You can rapidly create applications by dragging and
dropping predefined objects to your form.
Property Class
A property class is a named object that contains a list of properties and their settings.
Once you create a property class you can base other objects on it. An object based on a property
class can inherit the setting of any property in the class that makes sense for that object.

Visual Attributes
Visual attributes are the font, color, and pattern properties that you set for form and menu
objects that appear in your application's interface. Visual attributes can include the following
properties:
Font properties: Font Name, Font Size, Font Style, Font Width, Font Weight
Color and pattern properties: Foreground Color, Background Color, Fill Pattern,
Charmode Logical Attribute, White on Black
Every interface object has a Visual Attribute Group property that determines how the object's
individual visual attribute settings (Font Size, Foreground Color, etc.) are derived. The Visual
Attribute Group property can be set to Default, NULL, or the name of a named visual attribute
defined in the same module.
Property classes are similar to named visual attributes, but there are important differences you
should be aware of:
Named visual attributes define only font, color, and pattern attributes; property classes can
contain these and any other properties.
You can change the appearance of objects at runtime by changing the named visual attribute
programmatically; property class assignment cannot be changed programmatically.
When an object is inheriting from both a property class and a named visual attribute, the named
visual attribute settings take precedence, and any visual attribute properties in the class are
ignored.

POPUP Menu
Popup menus are context-sensitive menus attached to a form's items and canvases that
allow end users to quickly access common functions and commands.

Erase
Removes an indicated global variable, so that it no longer exists, and releases the memory
associated with the global variable. Globals always allocate 255 bytes of storage. To ensure that
performance is not impacted more than necessary, always erase any global variable when it is no
longer needed.

Trigger
Triggers are blocks of PL/SQL code that are written to perform tasks when a specific
event occurs within an application. In effect, a Form Builder trigger is an event-handler written in
PL/SQL to augment (or occasionally replace) the default processing behavior. A trigger
encapsulates PL/SQL code so that it can be associated with an event and executed and maintained
as a distinct object.

Sequence of firing of item level triggers


Pre_Text_Item
When_New_Item_Instance
Key_Next_Item
Post_Change
When_Validate_Item
Post_Text_Item
Order of firing of Query triggers
Pre_Query
Pre_Select
On_Select
Post_Select
On_Fetch
Post_Query
On_Close

Order of firing of navigational triggers


Pre_Form
When_Create_Record
Pre_Block
Pre_Record
Pre_Text_Item
When_New_Form_Instance
When_New_Block_Instance
When_New_Record_Instance
When_New_Item_Instance
When_Database_Record
Key_Next_Item
Post_Change
When_Validate_Item
Post_Text_Item
When_Validate_Record
Post_Record
Post_Block
Post_Form

Execution Hierarchy
Specifies how the current trigger code should execute if there is a trigger with the same
name defined at a higher level in the object hierarchy.
The following settings are valid for this property:
Override Specifies that the current trigger fire instead of any trigger by the same name at
any higher scope. This is known as "override parent" behavior.
Before Specifies that the current trigger fire before firing the same trigger at the next-
higher scope. This is known as "fire before parent" behavior.
After Specifies that the current trigger fire after firing the same trigger at the next-
higher scope. This is known as "fire after parent" behavior.

Any built-in subprogram that initiates navigation is restricted. This includes


subprograms that move the input focus from one item to another, and those that involve database
transactions. Restricted built-ins are illegal in triggers that fire in response to navigation.

Restricted Built-Ins Unrestricted Built-Ins


Initiates Navigation Doesn’t initiate navigation
Are illegal in triggers that fire in response to navigation Are not illegal in any trigger
Are not allowed from any pre or post navigational triggers, but can Can be called in any trigger
be called from a when-new- instance trigger
Post
Writes data in the form to the database, but does not perform a database commit. Oracle
Forms first validates the form. If there are changes to post to the database, for each block in the
form Oracle Forms writes deletes, inserts, and updates to the database.
Any data that you post to the database is committed to the database by the next
COMMIT_FORM that executes during the current Run form session. Alternatively, this data can
be rolled back by the next CLEAR_FORM.

Commit
To end your current transaction and make permanent all changes performed in the
transaction. This command also erases all save points in the transaction and releases the
transaction's locks. You can also use this command to manually commit an in-doubt distributed
transaction.
Commit processing is the way Form Builder attempts to make the data in the database
identical to the data in the form. Form Builder's normal cycle of operation is:
1 Read records from the database.
2 Allow the end user to make tentative insertions, updates, and deletions. The tentative
changes appear only in the form. The database remains unchanged.
3 Post changes to the database. Form Builder does all of its remaining processing and sends
the data to the database. After posting the data, Form Builder can only roll back the
changes (via the [Clear Form] function key or CLEAR_FORM built-in) or commit them.
4 Form Builder commits the posted changes. They become permanent changes to the
database.
The term commit processing refers to steps 3 and 4 of the above cycle. Normally these
steps occur together. In response to the [Commit] key or invocation of the COMMIT_FORM
built-in, Form Builder first posts, then commits the data to the database.Posting can occur
separately before committing. End users cannot issue posting commands, but triggers can invoke
the POST built-in.

REPORT 6i

A powerful quality of the Report Wizard is its ability to operate in re-entrant mode. This
means you can use the Report Wizard to modify an existing single- or multi-query report. The
Report Wizard is tabbed when you use it on an existing report, enabling you to quickly go to any
page. To invoke the Report Wizard in re-entrant mode, open an existing report and choose Tools,
Report Wizard.

Report Trigger
Report triggers execute PL/SQL functions at specific times during the execution and
formatting of your report. Report triggers must explicitly return TRUE or FALSE.

After Parameter Form trigger :The After Parameter Form trigger fires after the Runtime
Parameter Form is displayed. From this trigger, you can access parameters and check their
values. This trigger can also be used to change parameter values or, if an error occurs, return to
the Runtime Parameter Form.Consequently, you can use this trigger for validation of command
line parameters or other data.If the Form is suppressed, then returns to place from which you ran
the report.
After Report trigger :The After Report trigger fires after you exit the Runtime Previewer, or
after report output is sent to a specified destination, such as a file, a printer, or a mailid. This
trigger can be used to clean up any initial processing that was done, such as deleting tables. Note,
however, that this trigger always fires, whether or not your report completed successfully.The
After-Report trigger does not fire when you are in the Live Previewer.
Before Parameter Form trigger: The Before Parameter Form trigger fires before the Runtime
parameter Form is displayed. From this trigger, you can access and change the values of
parameters, PL/SQL global variables, and report-level columns. If the Runtime Parameter Form
is suppressed, this trigger still fires. Consequently, you can use this trigger for validation of
command line parameters.Displays an error message and then returns to the place from which
you ran the report.
Before Report trigger: The Before Report trigger fires before the report is executed but after
queries are parsed and data is fetched. Displays an error message and then returns to the place
from which you ran the report.
Between Pages trigger: The Between Pages trigger fires before each page of the report is
formatted, except the very first page. This trigger can be used for customized page formatting.
In the Runtime Previewer or Live Previewer, this trigger only fires the first time that you go to a
page. If you subsequently return to the page, the trigger does not fire again.Displays an error
message when you try to go to the page for which the trigger returned FALSE. The pages
subsequent to the page that returned FALSE are not formatted. If the trigger returns FALSE on
the last page, nothing happens because the report is done formatting. The Between Pages trigger
does not fire before the first page. If the trigger returns FALSE on the first page, the first page is
displayed, but, if you try to go to the second page, an error message is displayed.

System Parameters
BACKGROUND Is whether the report should run in the foreground or the background.
COPIES Is the number of report copies that should be made when the report is printed.
CURRENCY Is the symbol for the currency indicator (e.g., "$").
DECIMAL Is the symbol for the decimal indicator (e.g., ".").
DESFORMAT Is the definition of the output device's format (e.g., landscape mode for a printer)
This parameter is used when running a report in a character-mode environment,
and when sending a bitmap report to a file (e.g. to create PDF or HTML output).
DESNAME Is the name of the output device (e.g., the file name, printer's name, mail userid).
DESTYPE Is the type of device to which to send the report output (screen, file, mail,
printer, or screen using PostScript format).
MODE Is whether the report should run in character mode or bitmap.
ORIENTATION Is the print direction for the report (landscape, portrait, default).
PRINTJOB Is whether the Print Job dialog box should appear before the report is run.
THOUSANDS Is the symbol for the thousand's indicator (e.g., ",").

Lexical references
Lexical references are placeholders for text that you embed in a SELECT statement. You
can use lexical references to replace the clauses appearing after SELECT, FROM, WHERE,
GROUP BY, ORDER BY, HAVING, CONNECT BY, and START WITH.
You create a lexical reference by entering an ampersand (&) followed immediately by the
column or parameter name. A default definition is not provided for lexical references. Therefore,
you must do the following:
Before you create your query, define a column or parameter in the data model for each
lexical reference in the query. For columns, you must enter Value if Null, and, for parameters,
you must enter Initial Value. Report Builder uses these values to validate a query with a lexical
reference.
You cannot make lexical references in a PL/SQL statement.
If a column or parameter is used as a lexical reference in a query, its Datatype must be Character.
If you want to use lexical references in your SELECT clause, you should create a
separate lexical reference for each column you will substitute. In addition, you should assign an
alias to each lexical reference. This enables you to use the same layout field and boilerplate label
for whatever value you enter for the lexical reference on the Runtime Parameter Form.
If you use lexical references in your SELECT clause, you must specify the same number
of items at runtime as were specified in the report's data model. Each value you specify for your
lexical references at runtime must have the same datatype as its Initial Value. If you use lexical
references in your SELECT clause, the width of the column is derived from the Initial Value of
the parameter. Consequently, you should ensure that the Initial Value of the parameter
corresponds to the widest column that you intend to use.
A Report Builder link should not depend upon a lexical reference. That is, neither the
child column of a link or its table name should be determined by a lexical reference. To achieve
this functionality, you need to create a link with no columns specified and then enter the SQL
clause (e.g., WHERE) for the link directly in the query. For example, your parent and child
queries might be written as follows:

Parent Query: SELECT DEPTNO FROM EMP


Child Query: SELECT &PARM_1 COL_1,
&PARM2 COL_2 FROM EMP
WHERE &PARM_1 = :DEPTNO

Note how the WHERE clause makes a bind reference to DEPTNO, which was selected in
the parent query. Also, this example assumes that you have created a link between the queries in
the Data Model editor with no columns specified.

A lexical reference cannot be used to create additional bind variables after the After Form
trigger fires. For example, suppose you have a query like the following (note that the WHERE
clause is replaced by a lexical reference):
SELECT ENAME, SAL FROM EMP &where_clause
If the value of the WHERE_CLAUSE parameter contains a reference to a bind variable,
you must specify the value in the After Form trigger or earlier. You would get an error if you
supplied the following value for the parameter in the Before Report trigger:
WHERE SAL = :new_bind
If you supplied this same value in the After Form trigger, the report would run.

Bind references
Bind references (or bind variables) are used to replace a single value in SQL or PL/SQL,
such as a character string, number, or date. Specifically, bind references may be used to replace
expressions in SELECT, WHERE, GROUP BY, ORDER BY, HAVING, CONNECT BY, and
START WITH clauses of queries. Bind references may not be referenced in FROM clauses or in
place of reserved words or clauses.
You create a bind reference by entering a colon (:) followed immediately by the column
or parameter name. If you do not create a column or parameter before making a bind reference to
it in a SELECT statement, Report Builder will create a parameter for you by default.
Bind references must not be the same name as any reserved SQL keywords.

Formula Column
A formula column performs a user-defined computation on another column(s) data,
including placeholder columns.
Summary Column
A summary column performs a computation on another column's data. Using the Report
Wizard or Data Wizard, you can create the following summaries: sum, average, count, minimum,
maximum, % total. You can also create a summary column manually in the Data Model view,
and use the Property Palette to create the following additional summaries: first, last, standard
deviation, variance.

Place Holder
A placeholder is a column for which you set the datatype and value in PL/SQL that you
define. You can set the value of a placeholder column in the following places:
the Before Report Trigger, if the placeholder is a report-level column a report-level formula
column, if the placeholder is a report-level column formula in the placeholder's group or a group
below it (the value is set once for each record of the group)
You can set placeholder or formula columns to any of the following Datatypes: Character,
Number, and Date.
You can only assign the value of a placeholder column from one group. You cannot assign its
value in multiple groups.

Report Style

Tabular reports :A tabular report is the most basic type of report. Each column corresponds to a
column selected from the database.
Form-like reports :A form-like report displays one record per page, inserting field values to the
right of field labels.
Mailing label reports :A mailing label report prints mailing labels in multiple columns on each
page. You can print the labels across the page and then down, or down and then across.
Form letter reports :A form letter report contains database values embedded in boilerplate text.
(Boilerplate text is any text that you enter or import into a Report Editor.)
Group left reports :A group left report divides the rows of a table into "sets," based on a common
value in one of the columns. Use this type of report to restrict a column from repeating
the same value several times while values of related columns change.
Group above reports :A group above report contains two or more groups of data. For every value
of the master group, the related values of the detail group(s) are fetched from the
database.
Matrix reports :A matrix (crosstab) report contains one row of labels, one column of labels, and
information in a grid format that is related to the row and column labels. A distinguishing
feature of matrix reports is that the number of columns is not known until the data is
fetched from the database. To create a matrix report, you need at least four groups: one
group must be a cross-product group, two of the groups must be within the cross-product
group to furnish the "labels," and at least one group must provide the information to fill
the cells. The groups can belong to a single query or to multiple queries.
Matrix with group reports:A matrix with group report is a group above report with a separate
matrix for each value of the master group.

Flex Mode
When turned on, parent object resizes as the child object moves.

Confine Mode
The Layout model view can maintain relation between parent object and child object.
When turned on, cannot move the object outside the border of its repeating frame. When turned
off can move the child object outside its parent object.
Cursors
Oracle uses work areas to execute SQL statements and store processing information. A
PL/SQL construct called a cursor lets you name a work area and access its stored information.
There are two kinds of cursors: implicit and explicit.
Explicit: Explicit cursor attributes return information about the execution of a multi-row query.
When an explicit cursor or a cursor variable is opened, the rows that satisfy the associated query
are identified and form the active set. Rows are fetched from the active set one at a time.
Implicit: Implicit cursor attributes return information about the execution of an INSERT,
UPDATE, DELETE, or SELECT INTO statement. The values of the cursor attributes always
refer to the most recently executed SQL statement. Before Oracle opens the SQL cursor, the
implicit cursor attributes yield NULL.

Cursor Variables
PL/SQL cursor variables are like C or Pascal pointers, which hold the memory location
(address) of some object instead of the object itself. To execute a multi-row query, Oracle opens
an unnamed work area that stores processing information. To access the information, you can use
an explicit cursor, which names the work area. Or, you can use a cursor variable, which points to
the work area.
In PL/SQL, pointers have datatype REF X, where REF is short for REFERENCE and X
stands for a class of objects. Therefore, cursor variables have datatype REF CURSOR. Currently,
cursor variables are the only REF variables that you can declare.

Cursor Attributes
Every explicit cursor and cursor variable has four attributes: %FOUND, %ISOPEN
%NOTFOUND, and %ROWCOUNT. When appended to the cursor or cursor variable, return
information about the execution of a data manipulation statement. Can be used in procedural
statements but not in SQL statements.

%FOUND %ISOPEN %NOTFOUND %ROWCOUNT


OPEN before exception FALSE exception exception
after NULL TRUE NULL 0
First FETCH before NULL TRUE NULL 0
after TRUE TRUE FALSE 1
Next FETCH(es) before TRUE TRUE FALSE 1
after TRUE TRUE FALSE data dependent
Last FETCH before TRUE TRUE FALSE data dependent
after FALSE TRUE TRUE data dependent
CLOSE before FALSE TRUE TRUE data dependent
after exception FALSE exception exception

Referencing %FOUND, %NOTFOUND, or %ROWCOUNT before a cursor is opened or after it


is closed raises INVALID_CURSOR.
After the first FETCH, if the result set was empty, %FOUND yields FALSE, %NOTFOUND
yields TRUE, and %ROWCOUNT yields 0.

Bulk Bind
The assigning of values to PL/SQL variables in SQL statements is called binding. The
binding of an entire collection at once is called bulk binding. Bulk binds improve performance by
minimizing the number of context switches between the PL/SQL and SQL engines. With bulk
binds, entire collections, not just individual elements, are passed back and forth.
The keyword FORALL instructs the PL/SQL engine to bulk-bind input collections before
sending them to the SQL engine. Although the FORALL statement contains an iteration scheme,
it is not a FOR loop.
FORALL index IN lower_bound..upper_bound
sql_statement;

The index can be referenced only within the FORALL statement and only as a collection
subscript. The SQL statement must be an INSERT, UPDATE, or DELETE statement that
references collection elements.
The SQL cursor has one composite attribute, %BULK_ROWCOUNT, designed for use
with the FORALL statement.This attribute has the semantics of an index-by table. Its ith element
stores the number of rows processed by the ith execution of an INSERT, UPDATE or DELETE
statement. If the ith execution affects no rows, %BULK_ROWCOUNT(i) returns zero.

PL/SQL provides a mechanism to handle exceptions raised during the execution of a


FORALL statement. This mechanism enables a bulk-bind operation to save information about
exceptions and continue processing.To have a bulk bind complete despite errors, add the
keywords SAVE EXCEPTIONS to your FORALL statement. The syntax follows:
FORALL index IN lower_bound..upper_bound SAVE EXCEPTIONS
{insert_stmt | update_stmt | delete_stmt}

All exceptions raised during the execution are saved in the new cursor attribute
%BULK_EXCEPTIONS, which stores a collection of records. Each record has two fields. The
first field, %BULK_EXCEPTIONS(i).ERROR_INDEX, holds the "iteration" of the FORALL
statement during which the exception was raised. The second field,
%BULK_EXCEPTIONS(i).ERROR_CODE, holds the corresponding Oracle error code.
The values stored by %BULK_EXCEPTIONS always refer to the most recently executed
FORALL statement. The number of exceptions is saved in the count attribute of
%BULK_EXCEPTIONS, that is, %BULK_EXCEPTIONS.COUNT. Its subscripts range from 1
to COUNT. If you omit the keywords SAVE EXCEPTIONS, execution of the FORALL
statement stops when an exception is raised. In that case, SQL%BULK_EXCEPTIONS.COUNT
returns 1, and SQL%BULK_EXCEPTIONS contains just one record. If no exception is raised
during execution, SQL%BULK_EXCEPTIONS.COUNT returns 0.

Restrictions:
You can use the FORALL statement only in server-side programs (not in client-side
programs). Otherwise, you get the error this feature is not supported in client-side programs.
The INSERT, UPDATE, or DELETE statement must reference at least one collection
All collection elements in the specified range must exist. If an element is missing or was deleted,
you get an error
Input collections of composite values cannot be decomposed and bound to database
columns
Collection subscripts cannot be expressions.
The cursor attribute %BULK_ROWCOUNT cannot be assigned to other collections. Also, it
cannot be passed as a parameter to subprograms.
Bulk Collect
The keywords BULK COLLECT tell the SQL engine to bulk-bind output collections
before returning them to the PL/SQL engine

... BULK COLLECT INTO collection_name[, collection_name] ...

The optional LIMIT clause, allowed only in bulk (not scalar) FETCH statements, lets you limit
the number of rows fetched from the database. The syntax is

FETCH ... BULK COLLECT INTO ... [LIMIT rows];

where rows can be a literal, variable, or expression but must evaluate to a number.
Otherwise, PL/SQL raises the predefined exception VALUE_ERROR. If the number is
not positive, PL/SQL raises INVALID_NUMBER. If necessary, PL/SQL rounds the number to
the nearest integer.

Restrictions on BULK COLLECT


You can use the BULK COLLECT clause only in server-side programs (not in client-side
programs). Otherwise, you get the error this feature is not supported in client-side programs.
All targets in a BULK COLLECT INTO clause must be collections
You cannot bulk-fetch from a cursor into a collection of records
Composite targets (such as objects) cannot be used in the RETURNING INTO clause.
Otherwise, you get the error unsupported feature with RETURNING clause.
When implicit datatype conversions are needed, multiple composite targets cannot be
used in the BULK COLLECT INTO clause.
When an implicit datatype conversion is needed, a collection of a composite target (such
as a collection of objects) cannot be used in the BULK COLLECT INTO clause.

PLS_INTEGER
You use the PLS_INTEGER datatype to store signed integers. Its magnitude range is
-2**31 .. 2**31. PLS_INTEGER values require less storage than NUMBER values. Also,
PLS_INTEGER operations use machine arithmetic, so they are faster than NUMBER and
BINARY_INTEGER operations, which use library arithmetic. For efficiency, use
PLS_INTEGER for all calculations that fall within its magnitude range.
Although PLS_INTEGER and BINARY_INTEGER have the same magnitude range,
they are not fully compatible. When a PLS_INTEGER calculation overflows, an exception is
raised. However, when a BINARY_INTEGER calculation overflows, no exception is raised if the
result is assigned to a NUMBER variable. Because of this small semantic difference, you might
want to continue using BINARY_INTEGER in old applications for compatibility. In new
applications, always use PLS_INTEGER for better performance.

Comparison Operator
Can use comparison operators in the WHERE clause of a data manipulation statement to form
predicates, which compare one expression to another and always yield TRUE, FALSE, or NULL. You
can combine predicates using the logical operators AND, OR, and NOT.
Operator Description
ALL Compares a value to each value in a list or returned by a subquery and yields TRUE if all of the
individual comparisons yield TRUE.
ANY, SOME Compares a value to each value in a list or returned by a subquery and yields TRUE if any of the
individual comparisons yields TRUE.
BETWEEN Tests whether a value lies in a specified range.
EXISTS Returns TRUE if a subquery returns at least one row.
IN Tests for set membership.
IS NULL Tests for nulls.
LIKE Tests whether a character string matches a specified pattern, which can include wildcards.

Set Operator
Set operators combine the results of two queries into one result. INTERSECT returns all
distinct rows selected by both queries. MINUS returns all distinct rows selected by the first query
but not by the second. UNION returns all distinct rows selected by either query. UNION ALL
returns all rows selected by either query, including all duplicates.

Row Operators
Row operators return or reference particular rows. ALL retains duplicate rows in the
result of a query or in an aggregate expression. DISTINCT eliminates duplicate rows from the
result of a query or from an aggregate expression. PRIOR refers to the parent row of the current
row returned by a tree-structured query.

Pseudocolumns
Pseudocolumns are not actual columns in a table but they behave like columns. For
example, you can select values from a pseudocolumn. However, you cannot insert into, update, or
delete from a pseudocolumn. Also, pseudocolumns are allowed in SQL statements, but not in
procedural statements.

CURRVAL and NEXTVAL


A sequence is a schema object that generates sequential numbers. When you create a
sequence, you can specify its initial value and an increment. CURRVAL returns the current value
in a specified sequence. Before you can reference CURRVAL in a session, you must use
NEXTVAL to generate a number. A reference to NEXTVAL stores the current sequence number
in CURRVAL. NEXTVAL increments the sequence and returns the next value. If a transaction
generates a sequence number, the sequence is incremented immediately whether you commit or
roll back the transaction.

LEVEL
You use LEVEL with the SELECT CONNECT BY statement to organize rows from a
database table into a tree structure. LEVEL returns the level number of a node in a tree structure.
The root is level 1, children of the root are level 2, grandchildren are level 3, and so on. In the
START WITH clause, you specify a condition that identifies the root of the tree. You specify the
direction in which the query walks the tree (down from the root or up from the branches) with the
PRIOR operator.
ROWID
ROWID returns the rowid (binary address) of a row in a database table. You can use
variables of type UROWID to store rowids in a readable format.

ROWNUM
ROWNUM returns a number indicating the order in which a row was selected from a
table. The first row selected has a ROWNUM of 1, the second row has a ROWNUM of 2, and so
on. If a SELECT statement includes an ORDER BY clause, ROWNUMs are assigned to the
retrieved rows before the sort is done.

Mutating Table
A mutating table is a table that is currently being modified by an insert,update,delete
statement or a table that need to be updated by the effects of a declarative delete cascade
referential integrity action.(Only for row trigger).

Pragma Exception_INIT
To handle unnamed internal exceptions, you must use the OTHERS handler or the
pragma EXCEPTION_INIT. A pragma is a compiler directive, which can be thought of as a
parenthetical remark to the compiler. Pragmas (also called pseudoinstructions) are processed at
compile time, not at run time.
In PL/SQL, the pragma EXCEPTION_INIT tells the compiler to associate an exception
name with an Oracle error number. That lets you refer to any internal exception by name and to
write a specific handler for it.
You code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block,
subprogram, or package using the syntax

PRAGMA EXCEPTION_INIT(exception_name, Oracle_error_number);

where exception_name is the name of a previously declared exception. The pragma must appear
somewhere after the exception declaration in the same declarative section, as shown in the
following example:
DECLARE
deadlock_detected EXCEPTION;
PRAGMA EXCEPTION_INIT(deadlock_detected, -60);
BEGIN
...
EXCEPTION
WHEN deadlock_detected THEN
-- handle the error
END;

Collections:
A collection is an ordered group of elements, all of the same type (for example, the
grades for a class of students). Each element has a unique subscript that determines its position in
the collection. PL/SQL offers three kinds of collections: index-by tables, nested tables, and
varrays (short for variable-size arrays). Nested tables extend the functionality of index-by tables
(formerly called "PL/SQL tables").
Index-by tables, also known as associative arrays, let you look up elements using arbitrary
numbers and strings for subscript values. (They are similar to hash tables in other programming
languages.)
Nested tables hold an arbitrary number of elements. They use sequential numbers as subscripts.
You can define equivalent SQL types, allowing nested tables to be stored in database tables and
manipulated through SQL.
Varrays (short for variable-size arrays) hold a fixed number of elements (although you can
change the number of elements at runtime). They use sequential numbers as subscripts. You can
define equivalent SQL types, allowing varrays to be stored in database tables. They can be stored
and retrieved through SQL, but with less flexibility than nested tables.

Collection Methods
A collection method is a built-in function or procedure that operates on collections and is
called using dot notation. The methods EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR,
NEXT, EXTEND, TRIM, and DELETE help generalize code, make collections easier to use, and
make your applications easier to maintain.
EXISTS, COUNT, LIMIT, FIRST, LAST, PRIOR, and NEXT are functions, which appear as
part of an expression. EXTEND, TRIM, and DELETE are procedures, which appear as a
statement. EXISTS, PRIOR, NEXT, TRIM, EXTEND, and DELETE take integer parameters.
EXTEND and TRIM cannot be used with index-by tables.You cannot use collection methods in a
SQL statement.
COUNT: COUNT returns the number of elements that a collection currently contains, which is
useful because the current size of a collection is not always known. You can use COUNT
wherever an integer expression is allowed. For varrays, COUNT always equals LAST. For nested
tables, normally, COUNT equals LAST. But, if you delete elements from the middle of a nested
table, COUNT is smaller than LAST.
DELETE: This procedure has three forms. DELETE removes all elements from a collection.
DELETE(n) removes the nth element from an index-by table or nested table. If n is null,
DELETE(n) does nothing. DELETE(m,n) removes all elements in the range m..n from an index-
by table or nested table. If m is larger than n or if m or n is null, DELETE(m,n) does nothing.
EXISTS: EXISTS(n) returns TRUE if the nth element in a collection exists. Otherwise,
EXISTS(n) returns FALSE. Mainly, you use EXISTS with DELETE to maintain sparse nested
tables. You can also use EXISTS to avoid raising an exception when you reference a nonexistent
element. When passed an out-of-range subscript, EXISTS returns FALSE instead of raising
SUBSCRIPT_OUTSIDE_LIMIT.
EXTEND: This procedure has three forms. EXTEND appends one null element to a collection.
EXTEND(n) appends n null elements to a collection. EXTEND(n,i) appends n copies of the ith
element to a collection. EXTEND operates on the internal size of a collection. So, if EXTEND
encounters deleted elements, it includes them in its tally. You cannot use EXTEND with index-by
tables.
FIRST, LAST: FIRST and LAST return the first and last (smallest and largest) index numbers in
a collection. If the collection is empty, FIRST and LAST return NULL. If the collection contains
only one element, FIRST and LAST return the same index number. For varrays, FIRST always
returns 1 and LAST always equals COUNT. For nested tables, normally, LAST equals COUNT.
But, if you delete elements from the middle of a nested table, LAST is larger than COUNT.
LIMIT: For nested tables, which have no maximum size, LIMIT returns NULL. For varrays,
LIMIT returns the maximum number of elements that a varray can contain (which you must
specify in its type definition).
NEXT, PRIOR: PRIOR(n) returns the index number that precedes index n in a collection.
NEXT(n) returns the index number that succeeds index n. If n has no predecessor, PRIOR(n)
returns NULL. Likewise, if n has no successor, NEXT(n) returns NULL.
TRIM: This procedure has two forms. TRIM removes one element from the end of a collection.
TRIM(n) removes n elements from the end of a collection. If n is greater than COUNT, TRIM(n)
raises SUBSCRIPT_BEYOND_COUNT. You cannot use TRIM with index-by tables. TRIM
operates on the internal size of a collection. So, if TRIM encounters deleted elements, it includes
them in its tally.

Records
A record is a group of related data items stored in fields, each with its own name and data
type. Suppose you have various data about an employee such as name, salary, and hire date.
These items are logically related but dissimilar in type. A record containing a field for each item
lets you treat the data as a logical unit. Thus, records make it easier to organize and represent
information.
The attribute %ROWTYPE lets you declare a record that represents a row in a database
table. However, you cannot specify the data types of fields in the record or declare fields of your
own. The data type RECORD lifts those restrictions and lets you define your own records

Restrictions on Record Inserts/Updates


Currently, the following restrictions apply to record inserts/updates:
Record variables are allowed only in the following places:
On the right side of the SET clause in an UPDATE statement
In the VALUES clause of an INSERT statement
In the INTO subclause of a RETURNING clause
Record variables are not allowed in a SELECT list, WHERE clause, GROUP BY clause, or
ORDER BY clause.
The keyword ROW is allowed only on the left side of a SET clause. Also, you cannot use
ROW with a subquery.
In an UPDATE statement, only one SET clause is allowed if ROW is used.
If the VALUES clause of an INSERT statement contains a record variable, no other
variable or value is allowed in the clause.
If the INTO subclause of a RETURNING clause contains a record variable, no other variable or
value is allowed in the subclause.
The following are not supported:
Nested record types
Functions that return a record
Record inserts/updates using the EXECUTE IMMEDIATE statement.

Querying Data into Collections of Records

PL/SQL binding operations fall into three categories:


define Refers to database values retrieved by a SELECT or FETCH statement into PL/SQL
variables or host variables.
in-bind Refers to database values inserted by an INSERT statement or modified by an UPDATE
statement.
out-bind Refers to database values returned by the RETURNING clause of an INSERT,
UPDATE, or DELETE statement into PL/SQL variables or host variables.

Object Types
An object type is a user-defined composite datatype that encapsulates a data structure
along with the functions and procedures needed to manipulate the data. The variables that form
the data structure are called attributes. The functions and procedures that characterize the
behavior of the object type are called methods.
Product Specific Packages
DBMS_ALERT: Package DBMS_ALERT lets you use database triggers to alert an application
when specific database values change. The alerts are transaction based and asynchronous (that is,
they operate independently of any timing mechanism). For example, a company might use this
package to update the value of its investment portfolio as new stock and bond quotes arrive.
DBMS_OUTPUT: Package DBMS_OUTPUT enables you to display output from PL/SQL
blocks and subprograms, which makes it easier to test and debug them. The procedure put_line
outputs information to a buffer in the SGA. You display the information by calling the procedure
get_line or by setting SERVEROUTPUT ON in SQL*Plus.
DBMS_PIPE: Package DBMS_PIPE allows different sessions to communicate over named
pipes. (A pipe is an area of memory used by one process to pass information to another.) You can
use the procedures pack_message and send_message to pack a message into a pipe, then send it to
another session in the same instance. At the other end of the pipe, you can use the procedures
receive_message and unpack_message to receive and unpack (read) the message. Named pipes
are useful in many ways. For example, you can write routines in C that allow external programs
to collect information, then send it through pipes to procedures stored in an Oracle database.
UTL_FILE: Package UTL_FILE allows your PL/SQL programs to read and write operating
system (OS) text files. It provides a restricted version of standard OS stream file I/O, including
open, put, get, and close operations. When you want to read or write a text file, you call the
function fopen, which returns a file handle for use in subsequent procedure calls. For example,
the procedure put_line writes a text string and line terminator to an open file, and the procedure
get_line reads a line of text from an open file into an output buffer.
UTL_HTTP: Package UTL_HTTP allows your PL/SQL programs to make hypertext transfer
protocol (HTTP) callouts. It can retrieve data from the Internet or call Oracle Web Server
cartridges. The package has two entry points, each of which accepts a URL (uniform resource
locator) string, contacts the specified site, and returns the requested data, which is usually in
hypertext markup language (HTML) format.

Database: A collection of information, tables, and other objects organized and presented to serve a
specific purpose, such as facilitate searching, sorting, and recombining data. Databases are stored in files.

Database Management System (DBMS):A repository for the collection of computerized data files that
enables users to perform a variety of operations on those files, including retrieving, appending, editing,
updating, and generating reports.

View: An alternate way of looking at data from one or more tables in the database. A view is a virtual
table, usually created as a subset of columns from one or more tables

Data Warehouse: A database specifically structured for query and analysis. A data warehouse typically
contains data representing the business history of an organization.

Integrity: A database object bound to a column or user-defined data type that specifies what data
can be
entered in that column. Every time a user enters or modifies a value (with an INSERT or UPDATE
statement), SQL Server checks it against the most recent rule bound to the specified column, for example,
for limit checking or list checking. Data entered before the creation and binding of a rule is not checked.

Data Integrity : Accuracy and reliability of data.

Concurrency :A process that allows multiple users to access and change shared data at the same time.
SQL Server uses locking to allow multiple users to access and change shared data at the same time
without conflicting with each other

Index: In a relational database, a database object that provides fast access to data in the rows of a table,
based on key values. Indexes provide quick access to data and can enforce uniqueness on the rows in a
table. SQL Server supports clustered and non clustered indexes.
Unique Index: An index in which no two rows are permitted to have the same index value, thus
prohibiting duplicate index or key values. The system checks for duplicate key values when the index is
created and checks each time data is added with an INSERT or UPDATE statement.
Clustered Index: An index in which the logical or indexed order of the key values is the same as the
physical stored order of the corresponding rows that exist in a table.
Non clustered index: An index in which the logical order of the index does not match the physical,
stored order of the rows on disk.

Constraint: A property that can be placed on a column or set of columns in a table


Unique Constraints : Constraints that enforce entity integrity on a nonprimary key. UNIQUE constraints
ensure that no duplicate values are entered and that an index is created to enhance performance.

Relationship: A link between tables that references the primary key in one table to a foreign key in
another table.

Key: A column or group of columns that uniquely identifies a row (PRIMARY KEY), defines the
relationship between two tables (FOREIGN KEY), or is used to build an index.
Key Column :A column whose contents uniquely identify every row in a table.
Candidate Key : A unique identifier for a row within a database table. A candidate, or surrogate, key can
be made up of one or more columns. By definition, every table must have at least one candidate key, in
which case it becomes the primary key for a table automatically. However, it is possible for a table to
have more than one candidate key, in which case one of them must be designated as the primary key. Any
candidate key that is not the primary key is called the alternate key.
Common Key : A key created to make explicit a logical relationship between two tables in a database.
Composite Key : A key composed of two or more columns. A drawback of composite keys is that they
require more complex joins when two or more tables are joined.
Primary Key (PK) : The column or combination of columns that uniquely identifies one row from any
other row in a table. A primary key (PK) must be nonnull and must have a unique index. A primary key is
commonly used for joins with foreign keys (matching non primary keys) in other tables.
Foreign Key (FK) : The column or combination of columns whose values match the primary key (PK) or
unique key in the same or another table. A foreign key (FK) does not have to be unique. A foreign key is
often in a many-to-one relationship with a primary key. Foreign key values should be copies of the
primary key values; no value in the foreign key except NULL should ever exist unless the same value
exists in the primary key. A foreign key may be NULL; if any part of a composite foreign key is NULL,
the entire foreign key must be NULL.
Referential Integrity (RI) : An integrity mechanism ensuring vital data in a database, such as the unique
identifier for a given piece of data, remains accurate and usable as the database changes. Referential
integrity involves managing corresponding data values between tables when the foreign key of a table
contains the same values as the primary key of another table.

Sub Query: Sub-queries are generally used to return a single row as an atomic value, though they may be
used to compare values against multiple rows with the IN keyword.
The main advantages of subqueries are:
They allow queries that are structured so that it's possible to isolate each part of a statement.
They provide alternative ways to perform operations that would otherwise require complex joins and
unions.

Correlated Sub-Queries :Two types of sub query: correlated and non-correlated. Non-correlated
sub queries are executed once for the whole statement, correlated sub queries are executed once per row
in the parent query.
Correlated sub queries also answer multi-part questions, but are most often used to check for existence or
absence of matching records in the parent table and the related table in the sub query. A correlated sub
query refers to a column from a table in the parent query. This type of the query can often be performed
just as easily by a join query or a non-correlated sub query, but the SQL may be significantly faster when
a correlated sub-query is used.
Example:
SELECT dept.name FROM dept WHERE dept.id NOT IN
(SELECT dept_id FROM emp WHERE dept_id IS NOT NULL) ;

SELECT dept.name FROM dept,emp WHERE emp.dept_id (+) = dept.id ;

SELECT dept.name FROM dept WHERE NOT EXISTS (SELECT dept_id FROM emp WHERE
emp.dept_id= dept.id) ;

Equijoin: A join in which the values in the columns being joined are compared for equality, and all
columns are included in the results.
Self-join: A join that compares rows within the same table
Inner Join: A join in which records from two tables are combined and added to a query’s results only if
the values of the joined fields meet certain specified criteria.
Outer Join: A join that includes all rows from the joined tables regardless of whether there is a matching
row between the joined tables.
Left outer join: A type of outer join in which all rows from the first-named table (the left table, which
appears leftmost in the JOIN clause) are included. Unmatched rows in the right table do not appear.

Lock: A restriction on access to a resource in a multiuser environment. SQL Server locks users out of a
specific record, field, or file automatically to maintain security or prevent concurrent data manipulation
problems.
Deadlock: A situation when two users, each having a lock on one piece of data, attempt to acquire a lock
on the other’s piece. Each user waits for the other to release the lock. SQL Server detects deadlocks and
terminates one user’s process.
Exclusive Lock: A lock that prevents any other transaction from acquiring a lock on a resource until the
original lock on the resource is released at the end of the transaction. An exclusive lock is always applied
during an update operation (INSERT, UPDATE, or DELETE).
Shared Lock: A lock created by nonupdate (read) operations. Other users can read the data concurrently,
but no transaction can acquire an exclusive lock on the data until all the shared locks have been released.
Row Lock: A lock on a single row in a table.
Table Lock: A lock on a table including all data and indexes.
Lock Escalation: The process of converting many fine-grain locks into a fewer coarse-grain locks,
reducing system overhead.

Normalization Rules: Commonly accepted relational theory is governed by normalization rules that
identify certain attributes that must be present (or absent) in a well-designed database.
First Normal Form: A relation is said to be in First Normal Form (1NF) if and only if each attribute of
the relation is atomic. More simply, to be in 1NF, each column must contain only a single value and each
row must contain the same columns.
Second Normal Form: 2NF attempts to reduce the amount of redundant data in a table by extracting it,
placing it in new table(s) and creating relationships between those tables.
Third Normal Form: Meet the requirements of 1NF and 2NF.Remove columns that are not fully
dependent upon the primary key.

Transaction: A group of database operations combined into a logical unit of work that is either wholly
committed or rolled back. A transaction is atomic, consistent, isolated, and durable.
Commit: To save a change to a database, cube, or dimension. An SQL COMMIT statement guarantees
that all or none of the transaction’s modifications are made a permanent part of the database. A COMMIT
statement also frees resources, such as locks, used by the transaction.
Save Point: A marker that the user includes in a user-defined transaction. When transactions are rolled
back, they are rolled back only to the savepoint.
Roll Back: The ability to remove partially completed transactions after a database or other system failure.

Trigger: A stored procedure that executes when data in a specified table is modified. Triggers are often
created to enforce referential integrity or consistency among logically related data in different tables

Partitioning: To divide a table into logical subsets based on characteristics of the data. Partitioning is
used to improve application performance or reduce the potential for conflicts in multisite update
replication.

PCT FREE: The PCT free parameter sets the minimum percentage of a data block to be reserved as free
space for possible update to the rows that already exist in that block.

PCT USED: The PCT used parameter sets the minimum percentage of a block that can be used for row
data plus overhead before new rows are added to the block.

Embedded SQL: Embedded SQL statements incorporate DDL, DML, and transaction control statements
in procedural language program. Exp: OPEN,CLOSE,FETCH and EXECUTE.

RowID: For each row in the database, the ROWID pseudocolumn returns a row’s address ROWID
values contain information necessary to locate a row.
Which datablock in the data file
Which row in the datablock (first row 0)
Which data file (first files is 1)
Rowid – 10 bytes
Restricted Rowid – 6 bytes

Select sysdate from dual : 16-JUN-04

round(sysdate,'WW') Same day of the week as the first day of the year. 17-JUN-04
round(sysdate,'IW') Same day of the week as the first day of the ISO 14-JUN-04
year
round(sysdate,'W') Same day of the week as the first day of the 15-JUN-04
month
round(sysdate,'D') Starting day of the week 13-JUN-04
round(to_date('01-JUL-04'),'year') 01-JAN-05
round(to_date('01-MAR-04'),'MM') 01-MAR-04

select current_date from dual CURRENT_DATE returns the 16-JUN-04


current date in the session time
zone, in a value in the Gregorian
calendar of datatype DATE
add_months(sysdate,2) 16-AUG-04
round(months_between(sysdate,'03- 27
MAY-1977')/12)
last_day(sysdate) 30-JUN-04
to_char(sysdate,'DD-MON-YYYY 16-JUN-2004 10:52:05
hh24:mi:ss')
next_day(sysdate,'MONDAY') 21-JUN-04
new_time(sysdate,'PST', 'AST') 16-JUN-04
to_char(sysdate,'I'),to_char(sysdate,'IY'), Last 3, 2, or 1 digit(s) of ISO year
to_char(sysdate,'IYY')
to_char(sysdate,'IYYY') 4-digit year based on the ISO 2004
standard
to_char(sysdate,'W') Week of month (1-5) where week 1 3
starts on the first day of the month
and ends on the seventh.
to_char(sysdate,'WW') Week of year (1-53) where week 1 24
starts on the first day of the year
and continues to the seventh day of
the year.
to_char(sysdate,'IW') Week of year (1-52 or 1-53) based 25
on the ISO standard
to_char(sysdate,'MM') 06
to_char(sysdate,'fmMM') 6
to_char(sysdate,'D') "Day of week(1-7)" 4
to_char(sysdate,'DD') "Day of month(1-31)" 16
to_char(sysdate,'DDTH') Ordinal Number 16TH
to_char(sysdate,'DDSPTH') Spelled,ordinal number SIXTEENTH
to_char(sysdate,'DDD') "Day of year (1-366)" 168
to_char(sysdate,'DAY') "Name of day 9 characters" WEDNESDAY
to_char(sysdate,'DY') "Abbreviated name of day" WED
to_char(sysdate,'J') Julian day; the number of days 2453173
since January 1, 4712 BC. Number
specified with 'J' must be integers
to_char(sysdate,'RM') VI
SELECT 16TH of June, 2004
TO_CHAR(SYSDATE,'fmDDTH')||'of '||
TO_CHAR(SYSDATE,'fmMonth')||', '||
TO_CHAR(SYSDATE, 'YYYY') "Ides"
FROM DUAL;
SELECT TO_CHAR(SYSDATE, 16TH of June , 2004
'DDTH' )||' of '||
TO_CHAR(SYSDATE, 'Month')||', '||
TO_CHAR(SYSDATE, 'YYYY')
"Ides" FROM DUAL;

In both records dname,loc is same

To find out whether duplicate record exists

• select dname,loc from dept group by dname,loc having count(*) > 1

Duplicate record Removal :

• select * from dept a where rowid !=(select min(rowid) from dept b


where a.dname=b.dname and a.loc=b.loc);

• delete from dept a where rowid !=(select min(rowid) from dept b


where a.dname=b.dname and a.loc=b.loc)

Find out the top three sal

• select * from (select * from emp order by sal desc) where rownum <4

• select * from emp a where 4 > (select count(*) from emp b where a.sal<b.sal)

Find out the nth maximum

• select * from emp a where 6 = (select count(*) from emp b where a.sal<b.sal)

To find out Integer Part,Fractional part

• select trunc(65.45) from dual 65


• select (65.45*100)-trunc(65.45)*100 from dual 45

Privileges:
A privilege is a right to execute a particular type of SQL statement or to access another user's
object. Some examples of privileges include the right to:
Connect to the database (create a session)
Create a table
Select rows from another user's table
Execute another user's stored procedure

You can grant privileges to users explicitly


You can also grant privileges to a role (a named group of privileges), and then grant the role to
one or more users.
There are two distinct categories of privileges:
System privileges
Schema object privileges

System Privileges
A system privilege is the right to perform a particular action, or to perform an action on any
schema objects of a particular type. For example, the privileges to create tablespaces and to delete the
rows of any table in a database are system privileges. There are over 60 distinct system privileges.
You can grant or revoke system privileges to users and roles. If you grant system privileges to
roles, then you can use the roles to manage system privileges.
Only users who have been granted a specific system privilege with the ADMIN OPTION or users
with the GRANT ANY PRIVILEGE system privilege can grant or revoke system privileges to other
users.

A schema object privilege is a privilege or right to perform a particular action on a specific


schema object:

• Table
• View
• Sequence
• Procedure
• Function
• Package

The relational model.

The relational model consists of three components:

1. A Structural component -- a set of TABLES (also called RELATIONS).


2. MANIPULATIVE component consisting of a set of high-level operations which act upon
and produce whole tables.
3. A SET OF RULES for maintaining the INTEGRITY of the database.
4. Data structures are composed of two components which represent a model of the
situation being considered. These are (i) ENTITY TYPES - i.e. data group types, and (ii)
the RELATIONSHIPS between the entity types.
5. Entity types are represented by RELATIONS or BASE TABLES. These two terms are
interchangeable - a RELATION is the mathematical term for a TABLE.
6. A base table is loosely defined as an un-ordered collection of zero, one or more TUPLES
(ROWS) each of which consists of one or more un-ordered ATTRIBUTES
(COLUMNS). All tuples are made up of exactly the same set of attributes.
For the remainder of this discussion we shall use the more widely known terminology:

1. TABLE for RELATION


2. ROW for TUPLE
3. COLUMN for ATTRIBUTE
7. Each column is drawn from a DOMAIN, that is, a set of values from which the actual
values are taken (e.g. a set of car model names). More than one column in a table may
draw its values from the same domain.
8. A column entry in any row is SINGLE-VALUED, i.e. it contains exactly one item only
(e.g. a surname). Repeating groups, i.e. columns which contain sets of values rather than
a single value, not allowed.
9. Each row of a table is uniquely identified by a PRIMARY KEY composed of one or
more columns. This implies that a table may not contain duplicate rows.
10. Note that, in general, a column, or group of columns, that uniquely identifies a row in a
table is called a CANDIDATE KEY. There may be more than one candidate key for a
particular table; one of these will be chosen as the primary key.
11. The ENTITY INTEGRITY RULE of the model states that no component of the primary
key may contain a NULL value.
12. A column, or combination of columns, that matches the primary key of another table is
called a FOREIGN KEY.
13. The REFERENTIAL INTEGRITY RULE of the model states that, for every foreign key
value in a table there must be a corresponding primary key value in another table in the
database.
14. Only two kinds of table may be defined in a SQL schema; BASE TABLES and VIEWS.
These are called NAMED RELATIONS. Other tables, UNNAMED RELATIONS, may
be derived from these by means of relational operations such as JOINS and
PROJECTIONS.
15. All tables are LOGICAL ENTITIES. Of these only base tables physically exist in that
there exist physically stored records, and possible physical access paths such as indexes,
in one or more stored files, that directly support the table in physical storage. Although
standard techniques such as HASHING, INDEXING, etc. will be used for
implementation efficiency, the user of the data base should require no knowledge of
previously defined access paths.
16. Views and the results of all operations on tables - unnamed relations - are tables that exist
as LOGICAL DEFINITIONS, in terms of a view definition, or a [SELECT .. FROM ..
WHERE .. ORDER BY] sequence.
17. The term UPDATE has two meanings:
1. as a SQL operation in its own right which causes one or more columns in a table
to be altered; in this context it will always be shown in upper-case letters -
UPDATE.
2. as a generic term used to include the SQL operations INSERT, DELETE and
UPDATE; in this context it will always be shown in lower-case letters.

Normalisation
• Since each row is different, one or more columns must be present to identify it uniquely,
i.e. to act as the primary key. The definition of further normal forms relies on the primary
key and on the notion of FUNCTIONAL DEPENDENCY. The functional dependency of
attribute B on attribute A implies that for each value of A there is only one possible value
of B.
• In a 2ND NORMAL FORM (2NF) relation, all non-key attributes are functionally
dependent on every attribute value making up the key, not on a subset of those values.
• 3RD NORMAL FORM (3NF) implies, additionally, that all non-key attributes are
dependent only on the key, i.e. there is no TRANSITIVE DEPENDENCY.

4.1. Information.
All information is represented at the logical level and in exactly one way - by values in tables.

4.2. Guaranteed access.


Each datum (atomic value) in a relational database is guaranteed to be logically accessible
through a combination of table-name, primary key value and column-name.

4.3. Systematic treatment of null values.


Null values (distinct from the empty character string or a string of blank characters, and distinct
from zero or any other number) are supported in a fully relational DBMS for representing
missing information and inapplicable information in a systematic way, independent of data type.

4.4. Database description.


The database description is represented at the logical level in the same way as ordinary data, so
that authorised users can apply the same relational language to its interrogation as they apply to
the regular data.

4.5. Comprehensive sub-language.


A relational system may support several languages and various modes of terminal use (for
example the fill-in-the-blanks mode). However there must be at least one language whose
statements are expressible through some well defined syntax as character strings, and that is
comprehensive in supporting all the following items:

1. Data definition
2. View definition
3. Data manipulation (interactive and by program)
4. Integrity constraints
5. Authorisation
6. Transaction boundaries (begin, commit and rollback)

4.6. View updating.


All theoretically-updatable views are also updatable by the system. (A view is theoretically
updatable if there is a time-independent algorithm for unambiguously determining a single series
of changes to the base tables, having as their effect precisely the requested changes in the view.)
4.7. Insert and update.
The capability of handling a base table or a derived table as a single operand applies not only to
retrieval of data but also to insertion, updating, and deletion. (This allows the system to optimise
its execution sequence by determining the best access paths. It may be important in obtaining
efficient handling of transactions across a distributed database, avoiding the communications
costs of transmitting separate requests for each record obtained from remote sites.)

4.8. Physical data independence.


Application programs and terminal activities remain logically unimpaired whenever any changes
are made in either storage representations or access methods. (There must be a clear distinction
between logical and physical design levels.)

4.9. Logical data independence.


Application programs and terminal activities remain logically unimpaired when information-
preserving changes of any kind that theoretically permit unimpairment are made to the base
tables. (This rule permits logical database design to be changed dynamically, e.g. by splitting or
joining base tables in ways which do not entail loss of information.)

4.10. Integrity independence.


Integrity constraints must be definable in the relational data sub-language and storable in the
catalogue, not in the applications program. Certain integrity constraints hold for every relational
database, further application-specific rules may be added. The general rules relate to:

1. Entity integrity : no component of a primary key may have a null value.


2. Referential integrity : for each distinct non-null 'foreign key' value in the database, there
must exist a matching primary key value from the same domain.

4.11. Distribution independence.


A relational DBMS has distributional independence - i.e. if a distributed database is used it must
be possible to execute all relational operations upon it without knowing or being constrained by
the physical locations of data. This must apply both when distribution is originally introduced,
and when data is redistributed.

4.12. Non-subversion.
A low-level (single record-at-a-time) language cannot be used to subvert or bypass the integrity rules
and constraints expressed in the higher-level (multiple record-at-a-time) language.

SQL is a non-procedural database language that provides facilities for:

• database definition and object creation


• complex queries
• updating
• the handling of security and privacy constraints.
The language statements fall into three categories:

1. DATA MANIPULATION LANGUAGE (DML): Those statements that manipulate


data. See Section 5.1.
2. DATA DEFINITION LANGUAGE (DDL): Those statements that affect the structure
of database objects and involve modifications to the Data Dictionary. See Section 5.2.
3. EMBEDDED SQL: Those used to place both DDL and DML statements within a
procedural language (e.g. C or Cobol). These are dealt with in Section 5.3. which will be
covered in a later lecture

5.1. An introduction to SQL's DML statements.


5.1.1. Basic retrieval of data from database tables.

The structure of a SQL statement to retrieve data from one or more database tables is:

SELECT attribute name(s)


FROM table_name(s)
WHERE condition

For example, the following SQL statement will retrieve a list of male patients.

SELECT nhs_no, surname, forenames


FROM patient
WHERE gender = 'M'

When running SQL programs under SQL*Plus you must remember to terminate a program with
a semi-colon on the same line, or a slash on the line below the last line of the program.

5.1.2. The ORDER BY clause.

Rows may be returned sorted into a specific ascending or descending order (default is ascending)
by the use of an ORDER BY clause. For example, to sort the rows alphabetically by sex and
name the following clause may be inserted as the last clause in the SQL statement given in 5.1.1.

ORDER BY date_of_birth, surname, forenames

5.1.3. Comparison operators.

In order to retrieve data that matches particular criteria SQL provides the following operators:

= > < <= >= <>

LIKE BETWEEN (two values)

IN (a set of values) EXISTS (in a set of values)


LIKE, BETWEEN, IN and EXISTS may be modified by NOT, e.g. NOT IN.

In addition substring and wild-card matching can be specified to look inside data fields (in
contradiction to the original theory that relational values must be atomic!). For example, a search
for patients whose surnames began with 'M' might be carried using either of the following
WHERE clauses:

WHERE SUBSTR(surname, 1, 1) = 'M'

The two parameters following surname in the function represent respectively the starting position
in surname and the number of characters to include in the sub-string.

WHERE surname LIKE 'M%'

% is a wildcard (%M% would imply: 'contains an M in any position').

The comparison operator LIKE must be used when performing wildcard matching.

5.1.4. The PROJECT operation.


There is no separate PROJECT operator. To eliminate duplicate rows when performing a
PROJECT over a column-list the SELECT clause must be modified by use of DISTINCT.

For example, we might want a list of all of the different surnames from the patient table, showing
each distinct name only once. The following SQL statement:

SELECT surname
FROM patient
ORDER BY surname

would return a single column row for every patient in the table. To ensure that each distinct
surname is displayed only once, the correct result of a project over surname on patient, we would
use the SQL statement:

SELECT DISTINCT surname


FROM patient
ORDER BY surname

5.1.5. The JOIN operation.

There is no explicit JOIN operator in SQL; instead the appropriate join conditions are specified
in the WHERE clause using the operators specified in section 5.1.3. For example, to JOIN the
PATIENT and PATIENT_ADDRESS tables over nhs_no so that each patient's address can be
displayed you could write the SQL statement:

SELECT surname, address_line


FROM patient, patient_address
WHERE patient.nhs_no = patient_address.nhs_no
ORDER BY line_no

Since the joining column in each table has the same name each must be prefixed by
<table_name> followed by a period. The ORDER BY clause is required to ensure that the
address lines are displayed in the correct order.

Since sometimes table names are rather long we can specify an alias to use for one or more tables
in the FROM clause. This alias may then be used in the SQL statement instead of the full table
name where necessary. e.g. the above program could be written:

SELECT surname, address_line


FROM patient P, patient_address A
WHERE P.nhs_no = A.nhs_no
ORDER BY line_no

5.1.6. Arithmetic expressions and aggregate functions.

SQL allows the use of arithmetic expressions in queries, using conventional arithmetic operators
and functions. In addition, the standard relational functions SUM, COUNT, MAX, MIN, AVG
are available, with an optional GROUP BY clause naming control attributes. For example, to
display a count of the number of phones listed for each patient we could write:

SELECT surname, forenames, COUNT(location)


FROM patient P, patient_phone T
WHERE P.nhs_no = T.nhs_no
GROUP BY surname, forenames

NOTE: The column-list in the GROUP BY clause must include all of the items in the column-list
in the SELECT clause that precede the aggregate function.

Selections can be performed on aggregate values but the keyword used to introduce the condition
is not WHERE but HAVING. Thus to select patients who have listed more than one phone
number we could write:

HAVING COUNT(location) > 1

after the GROUP BY clause. The order of clauses is:

WHERE followed by ORDER BY followed by HAVING.

The AVG function only works on columns containing numeric values. If we wished to return the
average number of competitions entered we would need to write an SQL statement similar to the
following:
SELECT COUNT(location) / COUNT(distinct nhs_no)
FROM patient_phone

5.1.7. Nested SQL statements.


For more complex queries we can nest SQL statements; that is the WHERE clause may itself
contain SELECTs.

The result of an inner query may be passed back for use in an outer query. For example, to list all
female patients who have had previous appointments with GP(bma_no = 'GD1234-87') we could
write:

SELECT surname, forenames


FROM patient
WHERE gender = 'F'
AND nhs_no IN (
SELECT nhs_no
FROM appointment
WHERE bma_no = 'GD1234-87'
)

as opposed to the single statement:

SELECT surname, forenames


FROM patient P, appointment A
WHERE gender = 'F'
AND P.nhs_no = A.nhs_no
AND bma_no = 'GD1234-87'

Note, when using nested queries:

• A select always returns a set of rows (which may be empty or contain one or more rows.
The outer select steps through its set of rows one-by-one and performs processes the
WHERE clause with each one in turn. Since the inner query also returns a set of rows we
must use the SQL set operators 'IN' or 'EXISTS' (possibly qualified by 'NOT') as it is
meaningless to use the normal comparison operators ('=', '<>, etc.) between a single row
and a set of rows. We may only use the equality (or similar) operator in nested queries if
the result of the inner query is single valued, i.e. it is the result of an aggregate function.
• Nesting can go down to as many levels as required, and the query is always evaluated
from the inside out. This satisfies the basic principle that any query, however complex,
should be expressible by a single SQL statement, with no need for explicit assignment of
intermediate results. In practice, for complex queries, you may decide to store
intermediate values in a separate table or defined as a VIEW.

5.1.8. Aliases.
Some queries may require that a table should be joined to itself over two attributes from the same
domain, and so referred to by two different names in the same query. SQL provides an alias
facility for this purpose. For example, to return a list of different patients with the same surname
we might write the SQL statement:

SELECT A.nhs_no, A.surname, A.forenames, B.nhs_no, B.surname, B.forenames


FROM patient A, patient B
WHERE A.surname = B.surname
AND A.nhs_no <> B.nhs_no

Aliasing may be a useful option for other purposes. For example when we need to specify the
table name in the WHERE clause because the same column name exists in both tables. See
Section 5.1.5.

NOTE: This query will return two rows for each surname since it will retrieve one for each
nhs_no. The simplest way to retrieve only one row would be to use the pseudo-column ROWID
(Section 5.2.1.3), e.g.:

SELECT A.nhs_no, A.surname, A.forenames, B.nhs_no, B.surname, B.forenames


FROM patient A, patient B
WHERE A.surname = B.surname
AND A.ROWID < B.ROWID

5.1.9. Updating.

SQL also provides general updating facilities for the insertion, deletion and modification of rows
in tables. Updates may be made to whole tables, individual records, or sets of records subject to a
general SELECT condition.

Note: Update is the generic term for making modifications to the database. This includes the
SQL statements INSERT, DELETE and UPDATE. When written in lowercase it refers to its
generic sense; when written in uppercase it will refer to the SQL UPDATE command.

Example 1.

INSERT INTO patient (nhs_no, surname, forenames, gender, date_of_birth)


VALUES ('MPAQ279', 'Whittle', 'Philip', 'M', TO_DATE('11-01-67', 'DD-MM-YY')

If the (column-list) following INTO is omitted the (value-list) following VALUES must contain
an item for each column given in the order in which they appear in the table definition.

Example 2.

Assuming that a table called female_patient(nhs_no, surname, forenames) has been created, it
could be populated using the following SQL statement:

INSERT INTO female_patient


SELECT nhs_no, surname, forenames
FROM patient
WHERE sex = 'F'

NOTE: this will produce an error if (a) a value is omitted for a column that is (part of) the
primary key or (b) a row with the same primary key already exists.

Example 3.

DELETE FROM patient


WHERE surname LIKE 'M%'

Delete all rows (0, 1 or more rows) satisfying the WHERE clause

Example 4

UPDATE patient
SET gender = 'M'
WHERE nhs_no = 'MPQ234A'

NOTE: the value in the SET clause can take the form of another SELECT statement. E.g. to
transfer all GPs' appointments to GP (bma_no = 'GH12367') on 19th January 1998:

UPDATE appointment
SET bma_no = 'GH12367'
WHERE TO_CHAR(date_time, 'DD-MON-YY') IN (
SELECT TO_CHAR(date_time, 'DD-MON-YY')
FROM appointment
WHERE TO_CHAR(date_time, 'DD-MON-YY') = '19-JAN-98'
)

NOTE: This is a rather contrived example; it is not the simplest way to perform the UPDATE.

As a further example, if a patient has an appointment (appt_no = 67) with a given GP which is
subsequently allocated to patient_no 'HJK123C' with the same GP, we could update the
appointment table accordingly using the following SQL statement.

UPDATE appointment
SET nhs_no = 'HJK123C'
WHERE appt_no = 67

Note: in this case we do not need to know the GP's bma_no. If however, the reallocated
appointment is with a different GP then we would also have to alter bma_no in appointment
5.2. An introduction to DDL statements.
5.2.1. CREATE TABLE <table_name>
Describes the structure of a new table, including constraints: PRIMARY and FOREIGN KEYs
and domains. Each column name is declared along with its type and, if appropriate, its maximum
length. For example:

CREATE TABLE patient_address (


nhs_no CHAR(8),
line_no NUMBER(1) CHECK (line_no BETWEEN 1 AND 5),
address_line VARCHAR2(30),
PRIMARY KEY (nhs_no, line_no),
FOREIGN KEY (nhs_no) REFERENCES patient(nhs_no)
)

5.2.1.1. Data types.

Some valid data types that may be used are:

• NUMBER(n, m) n = total field length, m = number of decimal places. n & m are


optional.
• VARCHAR2(length) Variable length character string, length, < 256 characters
• CHAR(length) Fixed length character string, length < 256 characters.
• LONG Variable length character field, length <= 65, 535 characters.
• DATE A very flexible format to include dates and times. The date is stored in an internal
format which may be converted to character format using the TO_CHAR function and a
wide range of conversion specifiers. Conversely, character representations of dates may
be converted into internal date format using the TO_DATE function.

INSERT INTO appointment (appt_time)


VALUES (TO_DATE('11-May-1996', 'DD-MON-YYYY'))

or

SELECT TO_CHAR(appt_time, 'DD-MON-YYYY')


FROM appointment

Note: there are many different conversion formats, including times as well as dates.

5.2.1.2. Constraints.

Specifying the PRIMARY KEY as shown above automatically creates a UNIQUE INDEX on
the appropriate column(s). See Section 5.2.3. for further information about INDEXES.

To define a foreign key in this way requires that the referenced table must have previously been
created. Conversely, a table cannot be DROPPED (see Section 5.2.5. if there exist tables that
contain foreign key references to it. In the REFERENCES part of the FOREIGN KEY clause the
column(s) in the referenced table need only be specified if it (they) differ in name from the
column(s) in the table definition. In the example above:

FOREIGN KEY (nhs_no) REFERENCES patient

would have suffuced.

There may be zero, one or more FOREIGN KEY definitions. As the model stands, PATIENT
has none, PATIENT_ADDRESS has one and APPOINTMENT has two. REFERENCES clause
after the country_code column indicates that this is a FOREIGN KEY to the specified
PRIMARY KEY in the country table. Note: the country table must already exist for the foreign
key to be specified in this way.

The CHECK part of the clause allows the definition of domains using any valid SQL statement
built out of the available comparison operators.

5.2.1.3. ROWID.

When a table is created, SQL always adds another pseudo-column to the table; ROWID. This is
in fact a unique identifier for each row in the table consisting of the exact disc address of each
row in the form:

<BLOCK>.<ROW>.<DATABASE_FILE>

values are inserted into the ROWID column when a new row is successfully COMMITted to a
database table; when the insert is made permanent.

5.2.2. CREATE VIEW


This statement defines a virtual table (a named relation), using SELECT clauses to define a
relation which may not really exist in the data base. Such a table may contain virtual columns
holding computed values. The VIEW facility has three major uses:

1. to give the data base administrator power to enforce privacy constraints.


2. to define a (complex) query for use in further queries.
3. to supply a convenient interface for users who would not be capable of generating their
own queries.

For example, to create a view of the patient table consisting only of female patients:

CREATE VIEW female_patients AS


SELECT *
FROM patient
WHERE gender = 'F'

VIEW definitions are destroyed using DROP.


5.2.3. CREATE INDEX.

Creates an index for a table in a specified sort order (default: ascending). An index contains an
entry for each value that appears in the specified columns in the table (the index columns). When
primary and foreign keys are included in the table definition in the data dictionary SQL
automatically creates an index for the specified column(s) - a unique index in the case of primary
keys. Users may also create indexes on non-key columns.

• SQL can use the index to improve the performance of operations that access the table in
index column order, and to find rows with specified index column values without reading
the whole table.
• It is not a good idea to create an index on a column that has very few distinct values as it
is unlikely that using the index will improve performance over not using it. E.g. the
gender column of the patient table.
• SQL uses an index to enforce INTEGRITY CONSTRAINTS. For example, when
specifying a PRIMARY KEY in a table definition (see Section 5.2.1.) SQL automatically
creates a UNIQUE INDEX on the appropriate column(s) and declares the columns to be
NOT NULL.
• An index slows down updates of index column(s) field values, since the index as well as
the table must be updated.
• An index may use more than one index column. Rows with the same value in the first
index column are indexed on the second, and so on.
• You may create several indexes for different index columns (or different combinations of
index columns) in the same table
• Every index created for a particular table must have a unique name. Indexes created for
different tables may use the same names For example, you could create an index named
secondary for each table you own.
• UNIQUE ensures that the table will never contain two rows with the same values in all
index columns.

EXAMPLES:

To create an index on patients' phone numbers:

CREATE INDEX phone_number ON patient_phone(phone_no)

Note this index should not be unique because phone_no is not a primary key and it is possible
that more than one patient may specify the same number(s).

5.2.4. ALTER

Redefines Oracle objects. For example:

1. to modify the structure of the patient table by altering the maximum possible length of
the surname column.
ALTER TABLE patient
MODIFY (surname VARCHAR2(40))

1. to add a primary key to the GP table (if not already done at the table creation stage).

ALTER TABLE gp
ADD (PRIMARY KEY (bma_no))

5.2.5. DROP
Deletes a database object, e.g. a table, view or index.

DROP VIEW female_patient;

5.2.6. VALIDATE INDEX.


Checks the integrity of the specified index to the specified table. If the index is valid, the
command displays Index validated. If it displays any other message, something is wrong with the
index; you should DROP it and recreate it.

5.2.7. GRANT, REVOKE


These statements are used to control data sharing between users. GRANT allows a user to give to
another user the right to a particular function on their own tables, e.g. SELECT, INSERT,
DELETE or UPDATE. REVOKE withdraws privileges previously GRANTED.

5.2.8. COMMIT and ROLLBACK.


The terminal user making changes to the data base may control recovery procedures using the
commands COMMIT (data is written to the database) and ROLLBACK (changes made are
undone).

COMMIT and ROLLBACK will be discussed in more detail in the lecture on 'Transaction
Control'.

5.3. Embedded SQL.


SQL was originally intended to provide user-level access to a database, whereby queries could specify
what results were required rather than how to get them. Over the years it has grown into a complex
language for database access - in all but the most trivial cases an unsuitable medium for the true end-
user. At the same time it stills lacks the flexibility provided by a conventional procedural
programming language. We now consider extensions to SQL in situations which need a further level
of information-hiding and / or greater programming power. There is less uniformity in this area than
for pure SQL; examples here are taken from Oracle but similar facilities are found in other products
aimed at the same market.
5.3.5. Dynamic SQL
The original (1986) SQL standard required all embedded SQL to be explicitly included in
program source code so that it could be pre-processed before compilation. The later (1989)
standard (and Oracle) allows "dynamic" SQL, whereby queries may be read or constructed at
run-time, and then sent to the DBMS for parsing and execution. This involves two further
commands: PREPARE and EXECUTE. Examples are:

PREPARE statement_name
FROM host_string_variable;
EXECUTE statement_name;

Here the host_string_variable must already contain a legal SQL command, perhaps built up by
incorporating user input with a previously defined "skeleton" command. The "statement_name"
does NOT refer to a host variable - it is simply a label for reference by the associated EXECUTE
statement. After preparation, the same statement can be re-executed again and again without re-
parsing. Oracle provides a variation which combines the effect of PREPARE and EXECUTE for
simple statements.

The command:

EXECUTE IMMEDIATE host_string_variable;

causes the contents of host_string_variable to be parsed, executed, and discarded - it is


recommended for statements which contain no references to other host variables and which are
to be executed only once

6.9. Oracle Indexing


Oracle SQL CREATE INDEX allows the designer to index on any field or combination of fields,
in ascending or descending order. The key value maps to the ROWID (an address containing a
physical block number and an offset within that block), allowing direct access to the required
record. As already mentioned, declaring a UNIQUE index forces the DBMS to check that
primary keys are not duplicated - regrettably at present this physical-level mechanism is the only
way to handle the logical-level requirement for entity integrity!

Concatenated indexes deal with field combinations (maximum 16 fields), e.g. in the Wimbledon
database one might have a combined index on competition, comp_no1 and comp_no2. The order
of declaration is important for later use: if an index is declared on fields A, B, and C it can be
used for searches on A+B+C, or A+B, or A alone, but not for B+C or B or C alone. (It is possible
to index the same set of fields again in a different order.) Combined indexes help to achieve high
selectivity (see later explanation) and may make it unnecessary to access the actual data table;
e.g. the query:

SELECT b
FROM t
WHERE a=<value>
is answerable from the index alone.
The most important feature of an index is that it should be SELECTIVE - i.e. useful in queries
which get no more than 10% - 15% of rows from a table. Indexes with low selectivity cause a
table to be read more slowly than with a sequential scan - because they access records in a
random order they are likely to read each physical block more than once. A particularly
patholological example might be an index on a field with only two distinct values (e.g. Male and
Female) distributed randomly across all records in a table!

Other points in the Oracle guidelines are:

• Do not index tables with fewer than 5 data blocks - a sequential scan will be quicker,
• Do not index columns which are frequently modified - this will produce high overheads
for insertions and deletions,
• Do index columns used in ORDER BY, and in queries on MAX and MIN values. (These
can be found from the index without going to the data table itself.)

6.10. Mapping Logical Records to Physical Pages


Physical pages or blocks are units of information moved between disc and memory buffers. They
hold not only records, or table entries, but other information, for example the amount of free
space currently available in the block, and the starting position of each record. File data blocks
are normally read or written by the operating system; however since the central task of a DBMS
is to read and write data it may access storage devices directly. For instance, large Unix files are
often fragmented across the disc, and read through a fairly small buffer which can act as a
bottleneck. If the DBMS is allowed to by-pass this mechanism, the database can be set up in a
series of physically adjacent disc blocks, and I-O can be performed using larger buffers. Fewer
disc accesses are required, and the method gives a better performance on sequential scans of
large data bases.

For the database designer or administrator, some relevant choices about disc storage are:

• where to locate the blocks associated with a particular user or table,


• block sizes,
• percentage of space left free for later insertions.

Oracle will be used to illustrate these points.

6.10.1. Block Location


A basic Oracle DBA command is to create a TABLESPACE of a given size (associated with a
Unix file) and allocate it to a user. Subsequent CREATE TABLE commands may explicitly refer
to a particular tablespace, otherwise the creating user's default tablespace is allocated. If the
installation allows it, it may be advantageous to spread a tablespace, over several devices so as to
permit multiple access to different parts of the same table without disc contention. (This is a
process known as "striping"). It is useful to separate a table and an index upon it in the same
way.
6.10.2. Block Size.
Selecting a block size involves a kind of trade-off. In principle, the larger the block size, the
fewer read-write operations need be performed to access a file and therefore the more efficient is
the processing. However it requires a correspondingly large allocation of buffer space in memory
- since this is limited (and perhaps shared by many users) there is in practice an upper bound.
Moreover, large block sizes are primarily advantageous for sequential access. If rows from a
table are read randomly (e.g. using an index), they are more of a liability, since the "hit rate" per
block is likely to be worse. Programmers of pre-relational file- processing applications could
select a block size to fit an integral number of logical records, but this facility is not available in
Oracle, where block size is uniform (typically 2 - 4 kbytes) throughout the database. It is
however possible to specify a "multi-block-read-count", such that several blocks are read
simultaneously into a large buffer.

6.10.3. Free Space


The Oracle CREATE TABLE / CREATE INDEX commands have two optional clauses:
PCTFREE and PCTUSED, which affect the way physical blocks are filled with data.

PCTFREE specifies the percentage of space to leave free in each block, at the time when a table
or index is created. (The default value is 10.) The choice should be based on the volatility of the
data - if it is expected that existing records will grow in length, or many insertions will be made
into index blocks, a high PCTFREE is advisable. Likewise the need to build record clusters over
a period of time demands plenty of space for insertions. Otherwise the DBMS must chain
together non-adjacent blocks to accommodate logical records, increasing the overhead on
queries. Conversely, a largely static table or index dictates a low value for PCTFREE, since this
will take up less space and be quicker to read in a sequential scan.

PCTUSED specifies a lower limit for the percentage space used within a block. If, following a
deletion or update, the usage falls below this threshold, the block is added to a "free list" and
becomes available for new record insertions until the free space again falls below the PCTFREE
limit. The default value is 40; any user-defined choice involves a trade-off between space usage
and processing time.

6.11. Query Optimisation (Summary)


Relational operations and languages are expressed at a high level, and potentially less efficient
than systems where the database design is geared to the most frequently used access path.
Conversely, they give more scope for AUTOMATIC optimisation, either through general
strategies, or by exploiting knowledge about database structure and statistics.

6.11.1. General strategies

• Perform selections as early as patient possible, thus cutting down the size of intermediate
results,
• Combine several selections/projections together to reduce the number of scans through
the same table.
• Perform joins as late as possible, since in general these have the effect of expanding the
intermediate results.
• Look for common subexpressions and store already evaluated results ( another space/time
trade off).

6.11.2. Strategies using database knowledge

• Use indexes to handle simple aggregate functions - count, min, max, etc.
• When joining, use the smaller of the two tables as the "driving" table.

Views
Provide a single view of data derived from one or more tables or views. The view
is an alternative interface to the data, which is stored in the underlying table(s)
that make up the view.
Sequences
Provide unique numbers for column values.
Stored procedures
Contain logical modules that can be called from programs.
Synonyms
Provide an alternative name for database objects.
Indexes
Provide faster access to table rows.
Database links
Provide links between distributed databases.

Das könnte Ihnen auch gefallen