You are on page 1of 25

SQL DEFINITIONS

 DATABASE;-
DB is the collection of data, i.e. it is a data structure that stores organized information.
Different databases in the market are:-

 MANGO DB
 ORACLE DB
 AMAZON ROS
 NOSQL
Oracle database is commonly used for running online transaction processing (OLTP), data
warehousing, and mixed (OLTP & DW).

 SQL;-
It is a database language, used to communicate with the databases.
It consists set of instructions with commands.

 Datatype;-
Datatype specifies the type of data within a table column.
Some of datatypes are number,char,varchar,varchar2,data etc…

 SQL SUBLANGUAGES;-
 DDL(Create,Alter,Drop,Rename,Truncate) format;- command table tablename
 DML(insert,update,merge)
 DQL(select)
 TCL(commit,rollback,savepoint)
 DCL(grant,revoke).

 OPERATORS USED IN SELECT STATEMENT;


 Arithematic operators(+,-,*,/).
 Relational operators(=,<,>,<=,>=,<>/!=).
 Logical operators(AND,OR,NOT).
 Special operators(in,not in,between,like,nvl(),escape,like).

 FUNCTIONS;-
The function is used to solve a particular task and the function must return value.
 Number Function :- Function operate over number data.
(Abs(), Dual, Mod(m,n),Round(m,n), Trunc(m,n), Ceil &Floor).

 Character Function;- Function which operate over character.


(Upper(),Lower(),Initcap(),Length(),Substr(),Instr(),Lpad(),Rpad(),Ltrim,Rtrim,Translate(),
Replace() & Concat.
 DATE FUNCTIONS;-
 SYSDATE, ADD_MONTHS(), LAST_DAY(), Next_day(), Months_between(),Localtimestamp
etc…..
 Date conversion Functions;-
 To_char() - to convert date time into date string.
 To_date() – convert date string into oracle ‘date’ type.
 Extract- extract date part from date value.
 Trunc Function – date part is adjusted to beginning of month/Quarter/Year.

 GROUP FUNCTIONS;-
The group function returns one result per group.
As it operates over many values within a column and returns a single value.
 Max(),Min(),Avg(),Sum(),Count()
 GROUP BY;-
Group by the statement is used to group the rows that have the same value. (Note;-
while using group by function the columns which are specified after the select statement
must use after group by.)
 Having();-
Having clause is used in Group Functions, it gives the values from the Grouped rows
whereas ‘where’ clause is applied to individual rows.
 Order By;-
Order by is used to arrange data in sorting order(asc /desc).

 CONSTRAINTS;-
Constraints are used to specify rules for data in a table.
It prevents invalid data entry into the table.
 NOT NULL;-
It does not accept null values but it accepts duplicate values.

 UNIQUE;-
It does not accept duplicate values but it accepts a null value. whenever a unique constraint is
created on a column, the oracle automatically creates an index on that column.

 PRIMARY KEY;-
It does not accept null and duplicate values. index created automatically on pk.

 FOREIGN KEY;-
It establishes a relationship between tables, FK is used to reference from one table to another.

 DEFAULT;-
It is used for inserting default values.

 CHECK;-
it is used to limit the value range that can be placed in a column.

 COMPOSITE PRIMARY KEY;-


It is used to create a primary key on multiple columns.
 JOINS;-
Join is an operation that combines records from two or more tables based on the related columns
between those tables.

 INNER JOIN
 LEFT JOIN
 RIGHT JOIN
 FULL OUTER JOIN
 CROSS JOIN
 NATURAL JOIN
 SELF JOIN.

 INNER JOIN;-
This type of join returns those records which have matching values in both tables.

 LEFT JOIN;-
This type of join returns all records (matching record with Right table & unmatching record) from
the left table and also those records which have matching values in the right table.
For the records having no matching values with a left table in the right table will be null.

 RIGHT JOIN;-
This type of join returns all records (matching record with Left table & unmatching record) from
the Right table and also those records which have matching values in Left table.
For the records having no matching values with a right table in the left table will be null.

 FULL OUTER JOIN;-


This type of join returns all records from both tables, rows without matching values will be
placed by null.

 NATURAL JOIN;-
In This Natural join, conditions are formed by matching all pairs of columns in the table that has
the same name and compatible data types. Whereas in inner join the conditions are given
explicitly.

 SELF JOIN;-
A self-join is a join in which a table is joined with itself (which is also called Unary relationships),
especially when the table has a FOREIGN KEY that references its PRIMARY KEY. To join a table
itself means that each row of the table is combined with itself and with every other row of the
table.
 SET OPERATORS;-
SET operators are mainly used to combine the same type of data from two or more tables.
 Union;-
It returns unique values from both tables and sorts automatically when there is another copy of
data in another table and returns it as one.

 Union all;-
It returns unique data and duplicate data from both tables.it won’t remove duplicate entries.

 Intersect;-
It returns a common value from the tables.

 Minus/EXCEPT;-
It returns the values in the first table those values not in the second table.

 Intersect all;-
It returns common values present in both tables including duplicates.

 Minus all/EXCEPT ALL;-


It returns all the records from one table excluding records from the other table. Duplicate entries
won’t be removed.

NOTE;- whenever we are using set operators corresponding expressions must belong
to the same data type only.
Always set operators return first query column name or alias name as column headings.

 SUBQUERIES;-
A subquery is a select query that is enclosed inside another query.
Subquery consists of two Parts
1). Child query.
2). Parent query.

Child query provides values to another query is called child query.


Parent query receives values from another query is called parent query.

 ANALYTICAL FUNCTION;- database servers execute an analytical function for each row with in-the group.
 ROW number();- assigns different rank numbers when values are the same.
 Rank();- assigns same rank numbers when values are same and rank skips to next consecutive
rank numbers.
 Dense_rank();-assigns same rank numbers when values are same but it did not skip to next rank
number.
 CLUSTER;-
 Cluster is a database object which contains a group of tables together, and it will share
the same data block.
 Cluster is used to improve performance.
 Cluster must have one column common at least, that common column called cluster key.
 Cluster is used to improve the performance of joins.
 Cluster is physical memory that is sharing a group of related tables.

Steps in creating cluster;-


 Create cluster
 Create cluster index. (creating an index on a cluster).
 Create cluster tables.

 Partition;-
 Partitioning is a database process where very large tables are divided into multiple
smaller parts.
 At the time of table creation a table can be decomposed into a number of its name
partitions called partition tables.
 Partition tables are used to improve the performance of applications in the backup and
recovery process.
 Partition tables are created on a key column this is called ‘partition key’.

 Partition types ;-
 Range partition ;-
Range partition is based on range of values .
 List partition ;-
List partition is based on a list of values.
 Hash partition;-
Hash partition is based on a hash algorithm i.e. it is created based on equal size.

 SYNONYMS;-
 Synonyms are database objects.
 Synonyms are used to create a permanent alias name for tables.
 Once synonym is created we can perform select/insert/update/delete operations on the
table through synonym.

 Types of synonyms;-
 Private synonym:-
It is the default synonym, it is used by the owner of the synonym only. To create this we
need to create synonym privileges.
 Public synonym;-
It is created by dba, it can be accessed by any authenticated user, to create this we need
to create public synonym privilege.
Note;- We can access data through table name even after deleting of
synonym.
 INDEX;-
 An Index is a database object, it is used to retrieve data fastly from the database.
 Index maintains ordered values.

 Types of indexes;-
 Simple Index:- Index created on a single column of the table.
Create index name on tbl (cool name).

 Composite Index:- Index created on multiple columns of the table.


Create index index name on tbl(col1, col2).

 Function based index:- Index created based on expressions on columns or functions on


columns.
Create index indexname on tbl (col1+val, col2*expression);

 Reverse Index;- This index is preferable to start the search from the highest value, it will
start the search from the highest value to the least value within the tree.
Create index name on table (col) Reverse;

 B-tree index;- In oracle by default indexes are of B-tree index.


Whenever we create a B-tree index, the Oracle server automatically creates a B-tree
structure.
Based on column values. In this structure always leaf block stores actual data with
rowid
Create index indexname on table name (col name);

 Unique index;- Unique index is created on the unique column. By default when
constraints like Primary key, unique are created on a column of the table Oracle
automatically creates an index on that table.
create unique index and name on tbl (col name);
 SEQUENCES;-
 Sequence is a database object.
 It is used to generate sequential integers.
 Generally sequences are used to generate primary key column values.
Syntax;-
Create sequence name
Start with n
Increment by n
Min value n
Max value n
Cycle cache
In sequences, we can change sequence parameter values by using ‘alter command’,
except start with value.
 Select sequence_name from user_sequences; And Drop sequence name;
 VIEWS:-
 View is a database object. The view has logical data whereas the table has physical data.
i.e. view does not store data hence it is called a virtual table.
 Generally views created from the Base table.
 View Provide Authority level of Security.
 TYPES OF VIEWS;-
 Simple view or Updateable View;-
Created based on a single table.
We can also execute insert, update & delete commands.
Syntax;-
Create view name as select ….from table name;

 Simple view with ‘read only' option;-


If View is created with the ‘read only’ option then data manipulations are not allowed on this
view.
Syntax;-
Create view name as select ….from table with reading only;

 Simple view with check option;-


If the view is created with the check option then row insertion is based on some condition.
Syntax;-
Create view name as select ….from table with check option;

 Composite view;-
View created based on more than one table.
Does not allow DML operation.
It is also known as a read-only view or join view.
Syntax;-
Create view view name as select …..from table1,table2….where <join condition>.

 Force view:-
Force view created without a table, by default view created with errors.
Syntax;-
Create force view <view name> as select ….from <non exist table>;
Note;-
If the table is created after force view creation then force view behaves like a normal view.

 Materialised view;-
A view that contains data physically is known as Materialized view.it occupies physical disk
space.
These views are created to maintain local copies from the data center.
By default, MV is not changed with Master table changes.
To accept changes according to the master table we should apply Refresh methods
(Refresh Fast method, Refresh Complete Method, Refresh Force method) While view creation
only.
PLSQL DEFINITIONS

 PLSQL;-
PLSQL is a procedural Language along with SQL. It is an extension to SQL.
PLSQL is a collection of user-defined objects programs, procedures, functions, triggers,
types, packages, and so on.

 PLSQL PROGRAM;-
It is a collection of programming statements and SQL Queries.

 PLSQL programs are divided into 2 categories


 Anonymous block/programs.
 Subprograms.

 Block Structure;-
 Declare;- It contains declaration statements, variables are declared. Variables are used
to store the values and those values are useful to store the values.

 Begin;- it is also known as execution block. We write 3 types of statements (Assignment


statements, Output statements, Data processing statements).

 Exception:- This block is useful to handle runtime errors.

 END;- It indicates the end of the program.

 VARIABLE ATTRIBUTES;-

Variable attributes are used in place of datatype in variable declaration.


Whenever we use attributes oracle automatically allocates memory for the variable.

 Column level attribute (%type);- in this method we are defining attributes for individual
columns. Variablename table name.columnname%type;

 Row-level attribute (%row type);- In this method single variable can represent all
different data types into a single unit.
Variable name table name%rowtype;
 Conditional Statements;-
Decision-making statements are those statements that are in charge of executing a
statement out of multiple given statements based on some condition. The condition will
return either true or false.
 If then statement;- This condition is used to execute a particular section of codes
only when a condition is satisfied (it has only true part condition).

 If then else;- This condition is mainly used to select between two alternatives
(it has both true and false conditions).

 Nested if;- Writing if condition in other if condition. It makes the code complex
and using a lot of statements makes program testing difficult.

 If then else;- In this statement, one alternative should be chosen from a set of
alternatives Each alternative has its condition to be satisfied. If none of the if and
elsif statements are satisfied then else statement will be executed.

 Case ;-It is set of when clauses.


Each when clause has set of statements.
Case value is compared with each when clause.
If case value not matched with any when clause then statements under
else part will executed.

 ITERATIVE CONTROL;-
Iterative control statements are used when we want to repeat the execution of one or
more statements a specified number of times.
 Simple loop ;-
It helps to execute sequence of statements for multiple times.
In simple loop when ‘exit when condition’ is true then loop is completed.
It is also called as infinite loop.
 While loop ;-
While condition is checked at beginning of loop.
If condition is false then it comes out from the loop, it will execute loop till
loop condition is true.
 For loop ;-
In for loop we can specify the range of integer number.
For loop executed up to specified range.
 CURSOR;-
A cursor is a work area used by the oracle engine for its internal processing and storing
information while executing SQL statements.

 Implicit cursor ;-
Implicit cursor is automatically created by oracle engine whenever SQL statement
is executed. Whenever DML operations occur in the Database then an implicit cursor is
created that holds rows affected that memory area is called implicit cursor or SQL area or
context area.
 Explicit cursor ;-
This cursor is also called named cursor. In this explicit cursor, multiple records are
retrieved from SQL statements. An explicit memory area is also called the ‘Active set
area’. This cursor is defined and managed by programmers.
This process consists of
 DECLARE
 OPEN
 FETCH
 CLOSE

 Parameterized cursor ;-
An explicit cursor which accepts a list of parameters is known as Parameterized
cursor. Each time we can open the cursor we may pass a different set of parameters for
which we will get different result sets.

 Ref cursor ;-
PL/SQL datatype using which you can declare a special type of variable called
Cursor Variable. it is a user-defined type that is used to process multiple records and also
this is a record by record process. In the Static cursor, database servers execute only one
select statement at a time for a single active set area.
In Ref cursor database servers execute no of select statements dynamically
for the single set area that’s why it is also called Dynamic Cursor.
Static Cursor is not allowed to pass Cursor as a parameter to use Sub Programs. We
can pass Ref cursor as Parameter to use Sub Programs.
Static Cursor does not return multiple records into the client application, whereas Ref
Cursor is allowed to return multiple records into Client application (Java, .net, Php..).
Ref Cursor is of two types Strong Ref Cursor(return clause is added) and Weak Ref
Cursor.
 EXCEPTION ;-
Exception is a error condition during program execution.
PLSQL supports programmers to catch such conditions using exception block in a
Program.
Types of Exceptions ;-
PRE- DEFINED EXCEPTIONS ;-
Pre-defined exceptions are raised automatically by the runtime system.

 NO_data_found.
 Too_many_rows.
 Zero_divide.
 Invalid_cursor.
 Cursor_already_open.
 Dup_val_on_index.

USER_DEFINED EXCEPTIONS;-
User defined exceptions are defined by User, User defined exceptions must be declared
and then raised explicitly using raise statement, Raise_application_error.
Raise statement :- Exception raised by name.
Raise_application_error :- Exception raised by code.

Handling User-Defined Exception ;-


step1;- Declare
In declare section of plsql block we are creating our own exception name
by using exception
Step2;- Raise
We can raise user-defined exceptions explicitly either in the executable section or the
exception section.
Step3;- Handling Exception
We use an exception handler to handle user-defined exceptions in the exception section.

Unnamed Exception;-
These are the predefined errors that do not have any name associated with them.
These types of exceptions have predefined unique error codes and an error message but
without a name.
In this method, we are creating our exception name and associating that exception name with
the appropriate error number by exception ‘’exception_init()’’ function.
Ex;- pragma exception_init (userdefined exception name, err
num);
used in declare block
Pragma exception_init(a,-1400);

 Raise_application_error() ;-
Raise_application_error is predefined procedure available in dbms_standard
package.
In Oracle, if we want to display user-defined exception messages in the more descriptive
form then we prefer Raise_application_error(in oracle error format).

Raise_application_error(error number, message);


error number ;- we can give between 20000 to 20999, errmsg upto 512
characters.

 Error tapping Functions;-


Oracle has two predefined error tapping functions that are used to return error numbers,
errors with error messages.
These are
1. SQL code
2. SQL errm

These functions are used ‘when others then’ clause is used in an exception handler.
If we want to know the error number at run time then only we are allowed to use SQL code.

Sql code returns value - Meaning


0 - No errors
-ve - Oracle error
100 - No data found
1 - User defined exception
 SUBPROGRAMS ;-
Sub Programs are named PLSQL blocks which is used to solved Particular task. Sub
Programs are of
1. Procedure (Perform Action) may or may not return value.
2. Function (Return Value).
 Procedures & Functions are the Sub Programs that can be created
and saved in the database.
 They can be called or referred inside other blocks also.

 Procedures are automatically stored in databases permanently hence called Stored Procedures.
Procedure specification;- Consists of object type, object name, and argument.
The argument is a variable that is declared in specification part by default
argument is useful to accept input value at runtime.
Procedure Body;- Contains Declarations, Begin block, Exception block, and End block.
Formal Parameter:- Parameter is variable of PLSQL datatype through which PL/SQL
Subprogram exchange values with main code. This parameter allows to give input to a
subprogram and to extract from these Subprograms.
Parameters defined along with Subprograms at creation time.
Parameters included in calling statement of subprograms to interact values with
Subprograms.
The data type of parameter in the subprogram and calling statement should same.
Size of Data type Should not mention at the time of Parameter declaration as size
is dynamic for this type.
Autonomous Transaction ;-
Autonomous Transactions are independent transactions used in autonomous blocks,
procedures and triggers. Generally we are defining autonomous transaction to child
procedure.
Whenever we are calling autonomous procedure in main transaction and main
transaction TCL Commands never affected on Autonomous TCL commands procedure,
because these are independent procedure.
For autonomous transaction we use pragma autonomous_transaction along with
commit.
Accessible by clause;- This clause is used in procedure specification and provides security
of procedure. Accessible by clause is allowed to call within specific procedure specifying
accessible by clause.
Authid current_user;- When the procedure has authid current _user clause then those
procedures are allowed to execute only the owner of the procedure.
Handled or Unhandled Exception in Procedures:-
In Oracle Whenever we are calling inner procedure into outer procedure then we must
handle inner procedure exception within inner procedure only.
 Function ;-
Function is a named PL/SQL block which is used to solve particular task. It returns value.
Functions are of two parts;-
1. Function Specification.
2.Function Body.
In Function Specification we are specifying name of the function and type of parameter.
In Function body we are solving actual task.

Methods of Executing Procedures;-


1. Using Bind variable.
2.Using Anonymous block.
3.Using Call Statement.

Methods of Executing Functions;-


1.Using select statement.
2.Using anonymous block.

Generally, we cannot use select statements for executing DML functions directly.
We can use select statements by using pragma autonomous_transaction.

We can use out mode parameter in the function, but these functions are not allowed to execute
by using a select statement.
If we want to return more values from the function then only we are allowed to use out
parameters.

Difference between Procedures and Functions:-


Procedures;-
1.Procedures are optionally return value using ‘out’ & ‘in out’ parameter.
2.Cannot be called from SQL statement.
3.Procedures can have DML statements.
4.Return Keyword to return out of procedure.

Functions;-
1. Function must always return a value.
2. Function can be called from SQL Statement.
3. Functions having DML Statements cannot be called from select statements, but can call from
select statements using Autonomous transactions.
4. Return keyword is to return value.
 PACKAGES;-
Package is database object and it is logical grouping of related subprogram
(procedure/Function) into Single Element.
A package is compiled and stored as a database object that can be used later.
Generally, Packages are used to improve the performance of applications because
whenever we are calling packages (Subprograms) for the first time then automatically total
package load into the memory area. Whenever we are calling subsequent procedures and
functions then the oracle server calls those subprograms from the memory area.

 PLSQL Package has two components :


1)Package Specification.
2)Package Body.
 Package Specification :
Package Specification consists of declaration of all public variables, cursors, objects, procedures
functions and exceptions.
The elements which are all declared in specification can be accessed from outside of package
Such elements known as Public element.
Package specification can exist without package body.

 Package Body :
It consists of the definition of all elements that are present in the package specification.it is a
dependable object, it depends on package specification.
It can also have definitions of elements that are not declared in the specification,
these elements are called private elements and can be called only from the inside package.

Executing Package sub programs :-


1.Calling package procedure;-
Method1;-
Exec packagename.procedurename(actual parameter);

Method2;-
Begin
Packagename.procedurename(actual parameter);
End;

2.Calling Package Functions;-


Method1;- (using select statement)
Packagename.functionname(actual parameter);
 Overloading ;
Overloading is having many subprograms with the same name.
These subprograms will be differing from each other by some parameters or types of
parameters or return i.e. Subprogram with the same name but with a different number of
parameters and different types of parameters are considered as overloading.
This is useful when many sub Programs need to do the same task, but the way of calling
each of them should be different. In this case, the subprogram name will be kept the same for
all and parameters will be changed as per the calling statement.

Dependency in packages ;
A Specification is a standalone object.
A package body is dependent on specification.
The package body can be compiled separately, whenever specification is compiled, the package
body needs to be recompiled as it will become invalid.
The Subprogram in the Package body is dependent on the private element and should be
defined only after the private element declaration.

 COLLECTIONS;-
The collection is an ordered group of elements of particular data types.
It can be a collection of simple data types or complex data types (user-defined or record types).
Collection means the group of values with the same datatype or group of records with the same
structure. If any variable can store a group of values at a time then it is known as
‘collection type variable’,
Array;- Set of Location. Each location is identified with an Index Value. In Oracle array index
value begins with 1.
Arrays are of two types, single-dimensional array, and multi-dimensional array. In a single
dimensional array – under each location, we can store a value, but in a multidimensional array
stores group of locations, and each location stores one record. In 1 dimensional array, array
location data type is declared by column type. But, in a multidimensional array, array location
datatype is declared by row type.
We can also create our own user-defined data types by using ‘type’ keyword’.
Generally, user-defined data types are created in two steps :
1. We create user-defined types from appropriate syntax.
2. Then we create variables from that type.

PL/SQL has the following user-defined types


1. PL/SQL record
2. Index by table
3. Nested table
4. Varray
5. Ref Cursor
 Index by table (Associative array);-
Index by the table is a user-defined type that is used to store several numbers of data
items in a single image. Index by the table is an unbound table.
Index by a table having ‘key-valve’ pairs’ i.e. here value field stores actual data whereas
key field stores Indexes. These indexes are either integers or characters and also indexes are
positive, negative key field behaves like a primary key that why the field doesn’t accept
duplicate values.
Index by tables is used to improve the performance of the application because by default
these tables are stored in RAM.so it is called Memory tables.
To improve the performance of the application Oracle provides a special datatype
‘BINARY_INTEGER’ for key fields within ‘index by table’.
As this is a user-defined type so we are creating in a two-step process:-
1. Create Type
2. Create a variable of that type.
Syntax;-
Type typename is table of data type(size) index by binary_integer;
Variablename typename ;
When the resource table has a large amount of data and also when we are trying to transfer
data by using ‘Cursors’ then this will degrade performance because the cursor internally uses
record by record process. To overcome this ‘BULK COLLECT’ clause is introduced.
When using the ‘The Bulk Collect’ clause oracle server selects column data at a time and store
that data into collections.
Select *bulk collect into collection variable name from table name where condition.
 Nested table;-
This collection is also known as user-defined types which are used to store several data items
into a single unit.
Before storing data into the collection we must initialize through the constructor. Here
constructor name is as same as the type name.
This is an unbound table.
The nested table does not have key_value pairs.
As index by table cant store data into database permanently, to overcome this oracle
8.0 introduced an extension to index by a table which is used to store data permanently to the
database by using SQL.
In the Nested table, we can also store data directly without using the extended collection
method, in that case, we must specify actual data within the constructor itself.
In Index by the table, we cannot add or remove indexes whereas in the nested table we
can add or remove indexes by using extend, trim, collection methods.
In Index by the table are not allowed to allocate memory. Oracle server itself allocates
automatically up to those indexes. Whereas in the Nested table we must reserve memory
explicitly by using extended collection method up to that Indexes.
This is a user-defined type so we are creating it in a two-step process, we are creating
type first then variable from that type.
 Type Type-name is a table of data types (size)
Variable type-name := type-name();
 VARRAY’S;-
Varray is a collection method in which the size of the memory area is fixed. The array size
cannot be exceeded its fixed value.
In Varrays we are not allowed to delete particular elements or range of indexes by using
the delete collection method, but we can delete all elements by using the delete
collection method. That’s, why Varray does not have gaps.
Syntax;-
Type <type_name> is varray(<size>) of <data_type>;

 BULK BIND;-
 Bulk bind is PL/SQL Technique where instead of multiple individual select, insert,
update or delete statements are executed to retrieve or store data at table, all
operations are carried at once in bulk.
 In the bulk bind process, we can execute multiple DML statements at a time, bulk
bind improves the performance of the application.
 As it reduces the number of context switches.

Bulk bind is of two-step process;-


Step1;- Fetch data from the table into the collection by using the Bulk collect clause.
Step2;- Process all data in collection at a time by using in SQL engine through For all statement.

 Bulk collect;-
Bulk collection is a method of fetching data where the PL/SQL engine tells the SQL engine
to collect many rows at once and place them in the collection.
The SQL engine retrieves all rows and loads them into collection and switches back to
PL/SQL engine.
Select* bulk collect into collection varname from table name where condition;

CONTEXT SWITCHING;-
While Executing code in PL/SQL, if there is any SQL Statement comes, then PL/SQL
The engine needs to pass SQL statement to SQL engine, SQL statement fetches record
(result) and passes back to the PLSQL engine.

 DYNAMIC SQL;-
It is a combination of SQL and PL/SQL i.e. SQL statements are executed dynamically with
PL/SQL Block using Execute Immediate clause.
Generally in PL/SQL block, we are not allowed to use DDL, DCL statements are allowed to
use within PL/SQL block.

Syntax;-
Begin
Execute immediate SQL statement;
End;
 TRIGGERS ;-
Trigger is same as stored programs and also it will automatically invoked or fired
whenever certain event occur. We are creating a trigger on some condition whenever that
condition arises the trigger will fire.

Classification based on level;-


1. Statement level trigger;- It fires one time for the specified event statement.
2. Row level trigger;- It fires for each record that got affected in the specified event.
(only for DML).

Classification based on the event ;-


1.DML Trigger ;- It fires when DML event is specified (INSERT/UPDATE/DELETE).
2.DDL Trigger ;- It fires when the DDL event is specified (CREATE/ALTER).
3.DATABASE Trigger ;- it fires when database event is specified
(logon/logoff/ start up/shut down).

Other than the above triggers


Instead of trigger (Trigger on views)
Compound Trigger (combines DML trigger in a single block).

Syntax ;-
Create or replace trigger trigger-name
Before/after insert/update/delete on table-name
FOR each row
When condition
Declare
Variable declaration, cursors, user defined exceptions;
Begin
Exception
End;

The trigger has two parts;-


Trigger Specification and Trigger Body.
Purpose of Triggers ;
1.Auditing.
2.Logging.
3.Enforcing Security for transactions.
4.Prevent Invalid data or Transactions.
5.Automatic trigger of other events like sending email upon data change or job
completion status.
 SQL LOADER;-
 SQL loader is used to transfer flat-file (data from external files) into Oracle database.
 SQL loader is also called ‘Bulk Loader’.
 Flat files are of two types variable record(which have delimiters) and fixed record
(which do not have de Limiters).
 SQL loader cannot transfer directly, but it transfers with the help of the Control file.
 We pass the control file path into the SQL loader tool.
 During this process, the SQL Loader tool automatically creates a ‘Log file’ with the
same name as ‘Control file’.
 Logfile consists of Loaded & Rejected number of records and also stores Oracle
error numbers and error messages.
 Due to some issues, while transferring data from flat file to Oracle Database some
records are not loaded into the database and got rejected.
 Those records are Rejected records or Discarded records, Rejected records stored in
Bad files and Discard files.
 Bad files (.bad) store those records which are rejected due to data-type Mismatch and
business Violation. The bad file is automatically created as the same name as the
flat file name.
 We can also create a bad file explicitly by using the Bad file Clause within Control file.
 Discard files (.dsc) stores those records which are rejected records based on when
condition within ‘Control file’.

 UTL_FILE Package;-
 This package is used to write data into an O.S file and also read from the O.S file.
 To write data into an O.S file then we use the putf() procedure from the Utl_File
package.
 To read data from the O.S file then we use get_line() Procedure from Utl_file
package.
 In Oracle Before we are using the Utl_file package, we must create an alias directory
related to the physical directory.
Create or replace directory directory-name as ‘path’;

 Writing data into an O.S file;-


 STEP1 ;-
Before we are Opening file we must create file pointer variable by using file_type
from UTL_FILE package in declare section of PL/SQL block.
Filepointer var-name utlfile.file_type;
 STEP2 ;-
Before writing data into file we must open file by fopen() function from
Utl_file package. This Function is used in executable section of PL/SQL block.
Fopen accepts 3 parameters.
Filepointer var-name := utl_file.fopen (alias directory,filename,mode).
 STEP3 ;- utl_file.putf(varname, ‘context’); (writing data into file).

 STEP4;- utl_file.fclose (Filepointer varname);

You might also like