Sie sind auf Seite 1von 18

 VIEWS

 INDEXES
 NESTED QUERIES
 PLSQL
 TRIGGERS
 CURSORS

SQL Views
A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen.
Views do not contain data of their own. They are used to restrict access to the database or to hide data
complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSERT,
UPDATE, DELETE affects the data in the original table upon which the view is based.
The Syntax to create a sql view is
CREATE VIEW view_name

AS

SELECT column_list

FROM table_name [WHERE condition];

view_name is the name of the VIEW.


The SELECT statement is used to define the columns and rows that you want to display in the view.

For Example: to create a view on the product table the sql query would be like
CREATE VIEW view_product

AS

SELECT product_id, product_name

FROM product;

Views can provide advantages over tables:

 Views can represent a subset of the data contained in a table. Consequently, a view can limit the degree of
exposure of the underlying tables to the outer world: a given user may have permission to query the view, while
denied access to the rest of the base table.
 Views can join and simplify multiple tables into a single virtual table.
 Views can act as aggregated tables, where the database engine aggregates data (sum, average, etc.) and presents
the calculated results as part of the data.
 Views can hide the complexity of data. For example, a view could appear as Sales2000 or Sales2001,
transparently partitioning the actual underlying table.
 Views take very little space to store; the database contains only the definition of a view, not a copy of all the
data that it presents.
 Depending on the SQL engine used, views can provide extra security.
 Views are very important from the data security point of view. Because using view you can
expose only the data relevant to the users depending on his or her role. For e.g. A clerk in a firm
need not know about the salary of the every employee in the organization, on the contrary the
management might need access to this information. So we create different view’s for clerk and
management team, exposing only the relevant information.

SQL Indexes

The indexes are special objects which built on top of tables. The indexes can do an operation like SELECT,
DELETE and UPDATE statement faster to manipulate a large amount of data. An INDEX can also be called a table
and it has a data structure. An INDEX is created on columns of a table. One table may contain one or more INDEX
tables.

Note: The CREATE INDEX command is not a part of the ANSI SQL standard, and thus its syntax varies among
vendors.

What does SQL INDEX do?

The SQL INDEX does the following :

 INDEXES can locate information within a database very fast.

 An INDEX makes a catalog of rows of a database table as row can be pointed within a fraction of the time
with a minimum effort.

 A table INDEX is a database structure which arranges the values of one or more columns in a specific
order.

 The performance of an INDEX can not be recognized much when dealing with relatively small tables.

 INDEX can work properly and quickly for the columns that have many different values.

 It takes a long time to find an information for one or combination of columns from a table when there are
thousands of records in the table. In that case, if indexes are created on that column, which are accessed
frequently, the information can be retrieved quickly.

 The INDEX first sorts the data and then it assigns an identification for each row.

 The INDEX table having only two columns, one is a rowid and another is indexed-column (ordered).
 When data is retrieved from a database table based on the indexed column, the index pointer searches the
rowid and quickly locates that position.in the actual table and display, the rows sought for.

Syntax:

CREATE [UNIQUE] INDEX <index name> ON <table name> (<column(s)>);


Parameters:

Name Description

UNIQUE Defines the index as a unique constraint for the table and disallows any duplicate values into the
indexed column or columns of the table.

index_name Name of the index table.

table_name Name of a base table.

column(s) Name of the columns of the table.

Example : SQL CREATE INDEX

Sample table : customer

To create an index on 'custcity' column of the table 'customer', the following SQL statement can be used :
CREATE INDEX custcity

ON customer(cust_city);

SQL CREATE INDEX using more columns


To create an index on combination of 'custcity' and 'cust_country' columns of the table 'customer', the following
SQL statement can be used :

CREATE INDEX custcity_country

ON customer(cust_city,cust_country);

SQL CREATE UNIQUE INDEX


A UNIQUE INDEX comes only once in a table. This INDEX assures that value of a column or value of a
combination of one or more columns can not appear more than once in a table.

Example :
Sample table: customer

To create a unique index on 'cust_code' column in the table 'customer', the following SQL statement can be used

CREATE UNIQUE INDEX custcode


ON customer(cust_code);

How to distinguish between index and views

VIEW:

 A VIEW is a data object which contains no data. Its contents are the resultant of the base table. They are operated just

like the base table but they don’t contain any data of their own.

 A VIEW is similar to a table but may contain data from one or more tables connected with each other through a
common set of criteria.

 A VIEW is a physical object but it is a logical table. A VIEW just refers to data which stored in base tables.

 A VIEW is also one of the database objects.

 A VIEW can be used in any SELECT statement like a table.

 A VIEW provides security for both data and table of a database. Suppose by mistake a table is dropped, it can't be

recovered. but if a view dropped, it can be created again.

INDEX:

 An INDEX is also a table. So it has a data structure.

 INDEXES are pointers that represent the physical address of a data.

 An INDEX is created on columns of a table.

 An INDEX makes a catalog based on one or more columns of a table.

 One table may contain one or more INDEX tables.

 An INDEX can be created on a single column or combination of columns of a database table.

SQL | SEQUENCES
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to produce
unique values on demand.
 A sequence is a user defined schema bound object that generates a sequence of numeric values.
 Sequences are frequently used in many databases because many applications require each row in a table to
contain a unique value and sequences provides an easy way to generate them.
 The sequence of numeric values is generated in an ascending or descending order at defined intervals and
can be configured to restart when exceeds max_value.
Example
Following is the sequence query creating sequence in ascending order.
 Example 1:
 CREATE SEQUENCE sequence_1
 start with 1
 increment by 1
 minvalue 0
 maxvalue 100

Above query will create a sequence named sequence_1.Sequence will start from 1 and will be incremented by
1 having maximum value 100. Sequence will repeat itself from start value after exceeding 100.

Example to use sequence : create a table named students with columns as id and name.
CREATE TABLE students
(
ID number(10),
NAME char(20)
);

Now insert values into table

INSERT into students VALUES(sequence_1.nextval,'Ramesh');


INSERT into students VALUES(sequence_1.nextval,'Suresh');

where sequence_1.nextval will insert id’s in id column in a sequence as defined in sequence_1.


Output:
______________________
| ID | NAME |
------------------------
| 1 | Ramesh |
| 2 | Suresh |
----------------------

A view is nothing more than a SQL statement that is stored in the database with an associated name. A view is
actually a composition of a table in the form of a predefined SQL query.

A view can contain all rows of a table or select rows from a table. A view can be created from one or many tables
which depends on the written SQL query to create a view.

Views, which are a type of virtual tables allow users to do the following −
 Structure data in a way that users or classes of users find natural or intuitive.

 Restrict access to the data in such a way that a user can see and (sometimes) modify exactly what they
need and no more.

 Summarize data from various tables which can be used to generate reports.

Granting and Revoking Permissions

Objects that are created by a user are owned and controlled by that user. If a user wishes to
access any of the objects belonging to another user, the owner of the object will have to give
permissions for such access. This is called Granting of Privileges. Privileges once given can be
taken by the owner of the object. This is called Revoking of Privileges.
Granting Privileges Using the GRANT Statement
The GRANT statement provides various types of access to database objects such as tables, views
and sequences and so on.
Syntax:
GRANT <Object Privileges>
ON <Object Name>
TO <User Name>
[WITH GRANT OPTION]
REVOKING PRIVILEGES GIVEN
Revoking Permissions Using the REVOKE Statement
The REVOKE statement is used to deny the grant given on an object.
Syntax:
REVOKE <Object Privileges>
ON <Object Name>
FROM <User Name>;

Nested_QUERIES
A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause. A subquery is used to return data that will be used in the main query
as a condition to further restrict the data to be retrieved.
Nested Queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.
Nested Queries with the SELECT Statement:
Nested Queries are most frequently used with the SELECT statement. The basic syntax is as
follows:
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
WHERE column_name OPERATOR
(SELECT column_name [, column_name FROM table1 [, table2 ]
[WHERE])

Example:

Consider the CUSTOMERS table having the following records:

ID NAME AGE ADDRESS SALARY


1 Ramesh 35 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00

Now, let us check following subquery with SELECT statement:


SQL> SELECT * FROM CUSTOMERS
WHERE ID IN (SELECT ID FROM CUSTOMERS
WHERE SALARY > 4500) ;

This would produce the following result:

ID NAME AGE ADDRESS SALARY


4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
7 Muffy 24 Indore 10000.00

Introduction to PL/SQL

Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages,
when used as a conventional programming language.
1. SQL does not have any procedural capabilities i.e. SQL does not provide the
programming techniques of condition checking, looping and branching that is vital for
the data testing before its permanent storage.
2. SQL statements are passed to the Oracle Engine one at a time. Each time an SQL
statement is executed, a call is made to the engine’s resources. This adds to the traffic on
the network, thereby decreasing the speed of the data processing, especially in a multi-
user environment.
3. While processing an SQL sentence if an error occurs, the Oracle engine displays
its own error messages. SQL has no facility for programmed handling of errors that arise
during the manipulation of data.
Although, SQL is a very powerful tool, its set of advantages prevent, it from being a fully
structured programming language. For a fully structured programming language, Oracle provides
PL/SQL.

As the name suggests, PL/SQL is a superset of SQL. PL/SQL is a block structured language that
enables developers to combine the power of SQL with procedural statements. PL/SQL bridges
the gap between database technology and procedural programming languages.

ADVANTAGES OF PL/SQL

1. PL/SQL is development tool that not only supports SQL data manipulation but also
provides facilities of conditional checking, branching and looping.
2. PL/SQL sends an entire block of SQL statements to the Oracle engine all in one go.
Communication between the program block and the Oracle engine reduces considerably,
reducing network traffic. Since the Oracle engine got the SQL statements as a single
block, it processes this code much faster than if it got the code one sentence at a time.
There is a definite improvement in the performance time of the Oracle machine. As an
entire block of SQL code is passed to the Oracle engine at one time for execution, all
changes made to the data in the table are done or undone, in one go.
3. PL/SQL also permits dealing with errors as required, and facilities displaying user-
friendly messages, when errors are encountered.
4. PL/SQL allows declaration and use of variables in blocks of code. These variables can be
used to store intermediate results of query for later processing, or calculate values and
insert them into an Oracle table later. PL/SQL variable can be used anywhere, either in
SQL statements or in PL/SQL blocks.
5. Via PL/SQL , all sorts of calculations can be done quickly and efficiently without the use
of Oracle engine. This considerably improves transaction performance.
6. Applications written in PL/SQL are portable to any computer hardware and operating
systems, where Oracle is operational. Hence, PL/SQL code blocks written for a DOS
version of Oracle will run on its Linux/Unix version, without any modifications at all.
THE GENERIC PL/SQL BLOCKS
Every programming environment allows the creation of structure , logical blocks of code that
describe processes, which have to be applied to data. Once these blocks are passed to the
environment, the processes described are applied to data, suitable data manipulation takes place,
and use full output is obtained.

PL/SQL permits the creation of structured logical blocks of code that describes processes which
have to be applied to data. A single PL/SQL code block consists of a set of SQL statements,
clubbed together , and passed to the Oracle engine entirely. This block has to be logically
grouped together for the engine to recognize it as a singular code block. A PL/SQL block has a
definite structure, which can be divided into sections. These sections of a PL/SQL blocks are:
 The Declare section,
 The Master Begin and End section that also contains an Exception section.

1. Declare Section- Code blocks start with a declaration section, in which, memory
variables and other Oracle objects can be declared, and if required initialized. Once
declared, they can be used in SQL statements for data manipulation.
2. Begin Section- It contains of the set of SQL and PL/SQL statements, which describes
processes that have to be applied to table data. Actual data manipulation looping and
branching constructs are specified in this section.
3. Exception Section- This section deals with handling of errors that arise during execution
of the data manipulation statements, which make up the PL/SQL code block. Errors can
arise due to syntax, logic and/or validation rule violation.
4. End Section- This marks the end of a PL/SQL block.

Character set
The basic character set includes the following:
 Uppercase alphabets {A-Z}
 Lowercase alphabets {a-z}
 Numerals{0-9}
 Symbols () + - * / < > = ! ; : . ‘ @ % ,“ # $ ^ & _\{}?[]
Words used in PL/SQL block are called lexical units. Blank spaces can be freely inserted
between lexical units in a PL/SQL blocks. The blank spaces have no effect on the PL/SQL
blocks.
The ordinary symbols used in PL/SQL blocks are :
() + - * / < > = ; : % ’ “ []
Compounds symbols used in PL/SQL blocks are:
< > != ~= ^= <= >= := ** .. || << >>

Literals
A literal is a numeric value or a character string used to represent itself.
 Numeric Literal- These can be either integers or floats. If a float is being represented,
then the integer part must be separated from the float part by a period.
 String Literal- These are represented by one or more legal characters and must be
enclosed within single quotes. The single quote character can be represented, by
writing it a twice in a string literal. This is definitely not the same as the double quote.
 Character String- These are string literals consisting of single characters.
 Logical (Boolean) Literal- These are predetermined constants. The values that can be
assigned to this datatype are: TRUE, FALSE, NULL.

PL/SQL Datatypes
The default data types that can be declared in Pl/SQL are number (for storing numeric data), char
(for storing character data), date (for storing date and time format), boolean (for storing TRUE,
FALSE or NULL). number, char and date data types can have NULL values.
The %TYPE attribute provides for further integration. PL/SQL can use the %TYPE attribute to
declare variable based on definitions of columns in a table. Hence, if a column’s attributes
change, the variable’s attributes will change as well. This provide for data independence, reduces
maintainence costs , and allows programs to adapt to changes made to the table.
%TYPE declares a variable or constant to have the same data type as that of a previously defined
variable or of a column in a table or in a view. When referencing a table, a user may name the
table and the column, or the name of the owner, the table and the column.
NOT NULL causes creation of a variable or a constant that cannot be assigned a null value. If an
attempt is made to assign the NULL to a variable or a constant that has been assigned a NOT
NULL constraint, Oracle senses the exception condition automatically and an internal error is
returned.

Variables
Variables in PL/SQL blocks are named variables. A variable name must begin with a character
and can be followed by a maximum of 29 characters.
Reserved words cannot be used as variables names unless enclosed with double quotes. Variable
must be separated from each other by atleast one space or by punctuation mark.
Case is insignificant when declaring variable name. a space cannot be used in a variable name. a
variable of any datatype either native to the Oracle Engine such as number, date, char and so on
or native to PL/SQL such as Boolean can be dedclared.
Assigning value to a variable can be done in 2 ways:
1. Using the assignment operator :=
2. Selecting or fetching table data values into variables

Constants
Declaring a constant is simi9lar to declaring a variable except that the keyboard constant must be
added to thje variable name and the value assiogned immediately. Thereafter, no further
assignments to the constant are possible, while the constant is within the scope of the PL/SQL
block.

Logical Comparisons
PL/SQL supports the comparison between variables and the constants in sSQL na Pl/SQL
statements. These comparisons, often called Boolean expressions, generally consists of simple
expressions separated by relational operators(<,>,=,<>, <=,>=) that can be connected by logical
operators(AND, OR, NOT). A boolean expression will always evaluate to TRUE, FALSE or
NULL.
Cursors
The oracle engine uses a work area to execute SQL statements and store information.A cursor is
a PL/SQL construct that allows us to name these work areas,and to access their stored
information. The data that is stored in the cursor is called The Active data Set.
Eg: When a user fires a select statement as :
SELECT empno, ename, job, sal FROM emp WHERE deptno=10;
All the rows returned by the query are stored in the cursor at the server and will be as displayed
at the client end.
Types of Cursors: There are two types of cursors:
1. Implicit cursor
2. Explicit cursor
Implicit cursor : Implicit cursors are declared by PL/SQL implicitly for all SQL statements.
They are opened and managed by Oracle Engine internally. So there is no need to open and
manage by the user, these are operations, which are performed automatically.
IMPLICIT CURSOR HANDLING
Implicit cursors named “SQL” are declared by PL/SQL implicitly for all SQL statements.
IMPLICIT cursors attributes can be used to access information about the status of the last insert,
update, delete or single row select statements. This can be done by preceding the implicit cursor
attribute with the cursor name (i.e SQL).The value of the cursor attribute always refers to the
most recently executed SQL statement, wherever the statement appears.
Implicit Cursor Attributes
Attributes Description
SQL%ISOPEN It is always false because Oracle automatically closes an
implicit cursor after executing its SQL statement.
SQL%FOUND It is true if the most recently executed DML statement was
successful.
SQL%NOTFOUND It is true if the most recently executed DML statement was
not successful.
SQL%ROWCOUNT It returns the no. Of rows affected by an
INSERT,UPDATE,DELETE or single row select statement
Explicit cursor: Explicit cursors are user defined cursors for processing of multiple records
returned by a query. These are declared explicitly, along with other identifiers to be used in a
block, and manipulated through specific statement within the block’s executable actions. Explicit
cursors are user defined cursors, defined in the DECLARE section of the PL/SQL block. The
User defined cursor needs to be opened, before reading of the rows can be done, after which the
cursor is closed. Cursor marks the current position in an ACTIVE set.
EXPLICIT CURSOR HANDLING
The following steps are involved in using an explicit cursor and manipulating data in its active
set:
 Declare a cursor mapped to a SQL select statement that retrieves data for processing.
 Open the cursor.
 Fetch data from the cursor one row at a time into memory variables.
 Process the data held in the memory variables as required using a loop.
 Exit from the loop after processing is complete.
 Close the cursor.
Cursor Declaration
During declaration of a cursor, cursor name is given and also defines the structure of the query to
be performed within it. The CURSOR statement is used to declare explicit cursor.
Syntax:
CURSOR <cursor_name> IS <select statement>;
Where as <select statement> includes most of the usual clauses, but INTO clause is not allowed.
Opening a cursor
Here query execution is done. It also binds any variables that are referenced. After opening the
cursor the rows returned by the query are available for fetching.
Syntax:
OPEN <cursor_name>;
This statement is used within the executable actions of the block. It also establishes an active set
of rows. When cursor is opened it point to the first row in the active set.
Fetching of individual rows
After the cursor is opened the current row is loaded into variables. The current row is the row at
which the cursor is currently pointing. The retrieval of data into PL/SQL variables is done
through FETCH statement.
Syntax:
FETCH <cursor_name> into <variables>;
Example: Consider a PL/SQl code to display the empno, ename, job of employees of
department no. 10.
DECLARE
CURSOR C1 IS SELECT EMPNO,ENAME,JOB FROM EMP WHERE DEPTNO=10;
REC C1%ROWTYPE; /*rec is a row type variable for cursor c1 record,
containing empno,ename and job*/
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO REC;
EXIT WHEN C1%NOT FOUND;
DBMS_OUT.PUT_LINE('EMPNO' ||REC.EMPNO);
DBMS_OUT.PUT_LINE('ENAME' ||REC.ENAME);
DBMS_OUT.PUT_LINE('JOB' ||REC.JOB);
END LOOP;
CLOSE C1;
END;

TRIGGERS
Database triggers are database objects created via the SQL*Plus tool on the client and stored on
the server in the oracle engine’s system table. These database objects consist of the following
distinct sections:
1. A name database event.
2. A PL/SQL block that will execute when the event occurs.
The occurrence of database event is strongly bound to table data being changed.
Use of Database Triggers
Once the Oracle engine supports database triggers it provides the highly customizable database
management system. Some of the uses to which the database triggers can be put, to customize
management information by the oracle engine are as follows:
1. A trigger can permit DML statements against the table only if they are issued, during
regular business hours or on predetermined weekdays.
2. A trigger can also be used to keep an audit trail of a table (i.e. to store the modified and
deleted records of the table) along with the operation performed and the time on which
the operation was performed.
3. It can be used to prevent invalid transactions.
4. Enforce complex security authorizations.
Types of Triggers
1. Row Triggers
A row trigger is fired each time a row in the table is affected by the triggering statement. For
example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once
for each row affected by the UPDATE statement. If the triggering statement affects no rows, the
trigger is not executed at all. Row trigger should be used when some processing is required
whenever a triggering statement affects a single row in a table.
2. Statement Triggers
A statement trigger is fired once on behalf of the triggering statement, independent of the number
of rows the triggering statement affects(even if no rows are affected).Statement triggers should
be used when a triggering statement affects rows in a table but the processing required is
completely independent of the number of rows affected.
3. Before V/S After Triggers
When defining a trigger it is necessary to specify the trigger timing, i.e. specifying when the
triggering action is to be executed in relation to the triggering statement. BEFORE and AFTER
apply to both row and the statement triggers.
4. Before Triggers
BEFORE trigger execute the trigger action before the triggering statement. These types of
triggers are commonly used in the following situations:
i. BEFORE triggers are used when the trigger action should determine whether or not the
triggering statement should be allowed to complete. By using a BEFORE trigger ,user can
eliminate unnecessary processing of the triggering statement.
ii. BEFORE trigger are used to derive specific column values before completing a triggering
INSERT or UPDATE statement.
5. After Triggers
After trigger executes the trigger action after the triggering statement is executed. These types of
triggers are commonly used in following statements:
i. AFTER Trigger executes the trigger action after the triggering statement is executed.
These types of triggers are commonly used in the following situations:
ii. If a BEFORE trigger is already present, an AFTER trigger can perform different
actions on the same triggering statement.
Syntax for creating a Trigger
CREATE OR REPLACE TRIGGER[Schema.]<Trigger Name>
{BEFORE,AFTER}
{DELETE,INSERT,UPDATE[OF Column,…..]}
[FOR EACH ROW [WHEN Condition]]
DECLARE
< Variable declarations>;
< Constant declarations>;
BEGIN
<PL/SQL subprogram body>;
EXCEPTION
<Exception PL/SQL block>;
END;
Syntax for deleting a trigger:-
DROP TRIGGER<TriggerName>
Where, TriggerName is the name of the trigger to be dropped.
Example: To Create a trigger on the emp table, which shows the old values and new value
of ename after any updation on ename of emp table.
Solution:
CREATE OR REPLACE TRIGGER EMP_UPDATE
AFTER UPDATE OF ENAME ON EMP FOR EACH ROW
BEGIN
DBMS_OUTPUT .PUT_LINE(‘OLD NAME: ’ ||:OLD.ENAME);
DBMS_OUTPUT .PUT_LINE(‘NEW NAME: ’ ||:NEW.ENAME);
END;

Das könnte Ihnen auch gefallen