SQL PLSQL
SQL PLSQL
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).
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).
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.
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.
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.
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.
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.
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).
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;
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;
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.
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.
VARIABLE ATTRIBUTES;-
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.
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.
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).
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.
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.
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.
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.
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.
Method2;-
Begin
Packagename.procedurename(actual parameter);
End;
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.
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 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.
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;
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’;