SlideShare a Scribd company logo
1 of 74
Download to read offline
1
1
CONTENTS
INTRODUCTION: DML, DDL,DCL&TCL.................................................................................................2
JOINS:.............................................................................................................................................................13
AGGREGATE: ..............................................................................................................................................17
ANALTICAL: ................................................................................................................................................19
SET OPERATORS:.......................................................................................................................................20
STRING:.........................................................................................................................................................23
CASE & DECODE: .......................................................................................................................................24
NULL HANDLING: ......................................................................................................................................25
SYSNONMYS: ...............................................................................................................................................26
SEQUENCE: ..................................................................................................................................................27
CONSTRAIN: ................................................................................................................................................28
VIEWS & MATERIALIZED VIEW:..........................................................................................................31
INDEX: ...........................................................................................................................................................34
GTT:................................................................................................................................................................38
SUB QUERYS & PIVOT:.............................................................................................................................39
PL/SQL: ..........................................................................................................................................................41
PERFORMANCE TUNING:........................................................................................................................41
ANONYMOUS & CURSOR BLOCK:........................................................................................................43
COLLECTIONS:...........................................................................................................................................44
PROCEDURES:.............................................................................................................................................47
REF CURSOR: ..............................................................................................................................................48
EXCEPTIONS: ..............................................................................................................................................49
FUNCTIONS:.................................................................................................................................................50
PACKAGES: ..................................................................................................................................................51
PARTITION AND INDEX (ORACLE INDEX):: ......................................................................................53
TRIGGER: .....................................................................................................................................................56
HINTS AND TABLE REGONIZATION:...................................................................................................58
NORMALIZATION:.....................................................................................................................................60
OTHER QUESTIONS:..................................................................................................................................61
UNIX: ..............................................................................................................................................................61
2
2
INTRODUCTION: DML, DDL,DCL&TCL
In which language Oracle has been developed?
Oracle has been developed forton and redone by C Language.
What are the components of logical database structure in Oracle database?
Components of logical database structure.
Tablespaces
Database's schema object
What is a tablespace?
A database contains Logical Storage Unit called tablespaces. A tablespace is a set of related
logical structures. Actually a tablespace groups related logical structures together
What is SQL?
SQL stands for the Structured Query Language. SQL is a standard query language used for
maintaining the relational database and perform many different operations of data
manipulation on the data. SQL initially was invented in 1970. It is a database language used
for database creation, deletion, fetching rows and modifying rows, etc. sometimes it is
pronounced as 'sequel.
What are the subsets of SQL?
Data definition language (DDL):DDL is used to define the data structure it consists of the
commands like CREATE, ALTER, DROP, etc.
Data manipulation language (DML):DML is used to manipulate already existing data in the
database. The commands in this category are SELECT, UPDATE, INSERT, etc.
Data control language (DCL):DCL is used to control access to data in the database and
includes commands such as GRANT, REVOKE.
Transaction Control Language(TCL): it is used to validate tha transaction such as commit,
rollback
What is a Data Definition Language?
Data definition language (DDL) is the subset of the database which defines the data structure
of the database in the initial stage when the database is about to be created. It consists of the
following commands: CREATE, ALTER and DELETE database objects such as schema,
tables, view, sequence, etc.
3
3
What is a Data Manipulation Language?
Data manipulation language makes the user able to retrieve and manipulate data. It is used to
perform the following operations.
Insert data into database through INSERT command.
Retrieve data from the database through SELECT command.
Update data in the database through UPDATE command.
Delete data from the database through DELETE command.
What is Data Control Language?
Data control language allows you to control access to the database. DCL is the only subset of
the database which decides that what part of the database should be accessed by which user
at what point of time. It includes two commands GRANT and REVOKE.
GRANT: to grant the specific user to perform a particular task
REVOKE: to cancel previously denied or granted permissions.
What are privileges and Grants?
Privileges are the rights to execute SQL statements – means Right to connect and connect.
Grants are given to the object so that objects can be accessed accordingly. Grants can be
provided by the owner or creator of an object.
SET TRANSACTION?
→ It is used to set current transaction to read only and read write.
→ This doesn't affects other transaction by other users.
→ To end this transaction use ‘COMMIT’ or ‘ROLLBACK’.
→ Name is the transaction name given by user.
Example 1 :-
SET TRANSACTION READ ONLY NAME 'TORENTO';
Example 2 :-
SET TRANSACTION READ WRITE NAME 'TORENTO';
Difference between varchar and varchar2 data types?
Varchar can store upto 2000 bytes and varchar2 can store upto 4000 bytes. Varchar will
occupy space for NULL values and Varchar2 will not occupy any space. Both are differed
with respect to space.
What is BLOB datatype?
A BLOB data type is a varying length binary string which is used to store two gigabytes
memory. Length should be specified in Bytes for BLOB.
What is RAW datatype?
RAW datatype is used to store values in binary data format. The maximum size for a raw in
a table in 32767 bytes.
4
4
What are the components of database structure in oracle?
ANS: There are two type of database component physical database structure & logical
database structure.
What are the components of physical database structure of Oracle database?
Oracle database is comprised of three types of files. One or more data files, two are
more redo log files, and one or more control files.
What is Physical database structure?
ANS: Physical database structure of oracle database are control files, redo log files and
datafiles.
Datafile: This component stores the actual data. Each datafile is associated with only one
database and tablespace.
Redo Log files: These are more or less like backup files which are written before any
changes to data files are written.
Control files: These files contain the database structure information. Information like
database creation date, name, redo threads, archive log history etc is stored.
What is Logical database structure?
ANS: Logical database structure includes tablespaces, schema objects, data blocks, extents
and segments.
Tablespaces
Database is logically divided into one or more tablespaces. Each tablespace creates one or
more datafiles to physically store data.
Schema objects
Schema objects are the structure that represents database's data. Schema objects include
structures such as tables, views, sequences, stored procedures, indexes, synonyms, clusters
and database links.
Data Blocks
Data block represents specific number of bytes of physical database space on disk.
Extents
An extent represents continuous data blocks that are used to store specific data information.
Segments
A segment is a set of extents allocated for a certain logical structure.
5
5
What is table lock?
ANS: Table lock prevents conflicting DDL operations that would override data changes in a
current transaction. Table Locks (TM) A transaction automatically acquires a table
lock (TM lock) when a table is modified with the following statements: INSERT , UPDATE
, DELETE , MERGE , and SELECT ... FOR UPDATE . These DML operations require table
locks to reserve DML access to the table on behalf of a transaction and to prevent DDL
operations that would conflict with the transaction.
Types of Table Lock?
ANS: There are five different types of locks in Oracle, and they are: exclusive, shared,
shared row exclusive, row shared, and row exclusive.
How to remove Table Lock?
ANS: You can release the lock using ROLLBACK or COMMIT.
The DISABLE TABLE LOCK only prevents DDL operations to be performed (like ALTER
TABLE, DROP TABLE, a.s.o. ), and PARALLEL DML, it DOES NOT prevent normal
(serial) DML statements.
What is meant by Deadlock Situation?
ANS: It is a situation in which two or more transaction are waiting for data locked by each
other, resulting in all sessions being blocked. Oracle automatically detects & resolves
deadlock by rolling back the statement associated with transaction that detects deadlock.
What is table Re-org?
ANS: The main goal of table reorganization is to reduce IO when accessing the big database
tables.
1. Reorders the table data according to the primary key index.
2. Column reordering to push columns that have no data, nulls, to the end of the table row
The column reordering can be very useful for tables that have 300+ columns many of the
columns are null. When the null columns are pushed to the end of the row, the read operation
becomes streamlined thus increasing performance.
What is Save point?
ANS: It is a marker. It is used to identify a point to which you can roll back later. If two save
point have same name then when you rollback will done until the last occurrence of the save
point. OR Use the SAVEPOINT statement to identify a point in a transaction to which you
can later roll back.
6
6
How can we save images in database ?
ANS: we can save image in D.B by using BLOB datatype. D.B. images are converted into
BLOB, inserted in D.B then stored.
What is database Dictionary? How it can be created?
ANS: Data dictionary is a set of database tables used to store information about D.B.
definition. It contains information about D.B. object such as Tables, Views, Indexes,
Column, datatypes.
To create data dictionary create connection to your D.B, then select connection, right click &
choose generate DB Doc.
How to edit VARCHAR2 Limit?
ANS: Step1. ADD a column with any name/ dummy name with desired varchar limit
Step2. Update all data from existing column to new dummy column
Step3. Drop old Column
Step4. Rename new column with old column name.
What is Oracle table?
A table is the basic unit of data storage in an Oracle database. The tables of a database
hold all of the user accessible data. Table data is stored in rows and columns.
What are Clusters?
Clusters are groups of one or more tables physically stores together to share common
columns and are often used together.
What does ROLLBACK do?
ROLLBACK retracts any of the changes resulting from the SQL statements in the
transaction.
What is the usage of SAVEPOINTS?
SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling
back part of a transaction. Maximum of five save points are allowed.
Define transaction?
A transaction is a sequence of SQL statements that Oracle Database treats as a single
unit.
7
7
What is the difference between sql & oracle?
SQL is Stuctured Query Language.Oracle is a Database.SQL is used to write queries
against Oracle DB.
What are different Oracle database objects?
TABLES
VIEWS
INDEXES
SYNONYMS
SEQUENCES
TABLESPACES
What is schema?
A schema is collection of database objects of a user.
What are Roles?
Roles are named groups of related privileges that are granted to users or other roles.
What are the dictionary tables used to monitor a database spaces ?
DBA_FREE_SPACE
DBA_SEGMENTS
DBA_DATA_FILES
What is a database instance?
A database instance is a set of memory structure and background processes that access
a set of database files. The processes can be shared by all of the users.
What are parameters?
Parameters provide a simple mechanism for defining and setting the valuesof inputs
that are required by a form at startup.Form parameters are variables of type char,number,date
that you define at design time.
What are the different file extensions that are created by oracle reports?
Rep file and Rdf file.
Explain the difference between a data block, an extent and a segment?
A data block is the smallest unit of logical storage for a database object. As objects
grow they take chunks of additional storage that are composed of contiguous data blocks.
These groupings of contiguous data blocks are called extents. All the extents that an object
takes when grouped together are considered the segment of the database object.
8
8
What is bind reference and how can it be created?
Bind reference are used to replace the single value in sql, pl/sql statements a bind
reference can be created using a (:) before a column or a parameter name.
How many LONG columns are allowed in a table? Is it possible to use LONG columns
in WHERE clause or ORDER BY?
Only one LONG column is allowed. It is not possible to use LONG column in
WHERE or ORDER BY clause.
What is BCP? When does it used?
BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does
not copy the structures same as source to destination.
What is SYSTEM tablespace and when is it created?
Every Oracle database contains a tablespace named SYSTEM, which is automatically
created when the database is created. The SYSTEM tablespace always contains the data
dictionary tables for the entire database.
Which date function returns number value?
months_between
What is the default return value of a function?
The default return value from a function is int. In other words, unless explicitly
specified the default return value by compiler would be integer value from function.
What is the difference between oracle, sql and sql server?
Oracle is based on RDBMS.
SQL is Structured Query Language.
SQL Server is another tool for RDBMS provided by MicroSoft.
What is SGA?
The System Global Area in an Oracle database is the area in memory to facilitate the transfer
of information between users. It holds the most recently requested structural information
between users. It holds the most recently requested structural information about the database.
The structure is database buffers, dictionary cache, redo log buffer and shared pool area.
What is a data segment?
Data segment are the physical areas within a database block in which the data associated
with tables and clusters are stored.
9
9
What is dual?
Dual is a dummy table and it contains only one columns.
What is the data type of DUAL table?
The DUAL table is a one-column table present in oracle database. The table has a single
VARCHAR2(1) column called DUMMY which has a value of 'X'.
How do we display rows from the table without duplicates?
Duplicate rows can be removed by using the keyword DISTINCT in the select statement.
What is the fastest query method to fetch data from the table?
Row can be fetched from table by using ROWID. Using ROW ID is the fastest query method
to fetch data from the table.
What is Data Dictionary Table?
It is a Meta data about the data base
Difference between Delete and Truncate?
DELETE TRUNCATE
• We can Rollback after delete.
• No tablespace is reduced
We can't Rollback after performing
Truncate.
Tablespace is reduced
(ii) Delete does not reset identity of table. (ii). Truncate reset identity of table.
Data stored in low level watermark Data stored in high level watermark
Implicit commit Auto commit
(iii) It locks the table row (Row Level
Lock).
(iii). It locks the entire table (Table Level
Lock)
(iv) Its DML(Data Manipulation Language)
command.
(iv) Its DDL(Data Definition Language)
command.
(v) We can use WHERE to filter data to
delete.
(v) We can't use WHERE clause with it.
(vi) Trigger is fired. (vi) Trigger is not fired while truncate.
(vii) Syntax :
DELETE FROM table_name ;
DELETE FROM table_name WHERE
example_column_id IN (1,2,3) ;
(vii) Syntax :
1) TRUNCATE TABLE table_name;
10
10
Blob Clob
The full form of Blob is Binary Large
Object.
The full form of Clob is Character Large
Object.
This is used to store large binary data. This is used to store large textual data.
This stores values in the form of binary
streams.
This stores values in the form of character
streams.
Using this you can store files like text files,
PDF documents, word documents etc.
Using this you can stores files like videos,
images, gifs, and audio files.
COMMIT ROLLBACK
(i) COMMIT validates the modifications
made by the current transaction.
(i) ROLLBACK erases the modifications
made by the current transaction.
(ii) After execution of COMMIT statement,
the transaction can not be ROLLBACK.
(ii) Once ROLLBACK is executed database
reaches its previous state, I.e. before the
execution of the first statement of the
transaction.
(iii) COMMIT occurs when the transaction
gets executed successfully.
(iii) ROLLBACK occurs when the
transaction is aborted in middle of the
execution.
(iv) Syntax :- COMMIT; (iv) Syntax :- ROLLBACK;
ROWID ROWNUM
(i) ROWID is nothing but Physical memory
allocation.
(i) ROWNUM is nothing but the sequence
which is allocated to that data retrieval
bunch.
(ii) ROWID is permanent to that row which
identifies the address of that row.
(ii) ROWNUM is temporarily allocated
sequence to the rows.
(iii) ROWID is 16 digit Hexadecimal
number which is uniquely identifies the
rows.
(iii) ROWNUM is numeric sequence
number allocated to that row temporarily.
(iv) ROWID returns PHYSICAL
ADDRESS of that row.
(iv) ROWNUM returns the sequence
number to that row.
(v) ROWID is automatically generated
unique id of a row and it is generated at the
time of insertion of row.
(v) ROWNUM is an dynamic value
automatically retrieved along with select
statement output.
(vi) ROWID is the fastest means of
accessing data.
(vi) ROWNUM is not related to access of
data.
11
11
Difference between Delete Truncate and Drop?
DELETE TRUNCATE DROP
Deletes some or all
rows of a table
Deletes all rows of a table Removes all rows and also
the table definition,
including indexes, triggers,
grants, parameters
DML DDL DDL
Commit required Commit not required Commit not required
Uncommitted deletes
can be rolled back
Cannot be rolled back –
once truncated, gone
forever
A dropped table can be
reinstated from the recycle
bin
Filter criteria be
specified via WHERE
clause
No filter criteria allowed,
removes all rows
No filter criteria allowed,
removes all rows
DELETE triggers fired No triggers fired No triggers fired
DELETE can be slow
especially if the table
has many triggers,
indexes, and other
dependencies
TRUNCATE is fast for
deleting all rows, even
more than dropping and
recreating the table using
DROP
DROP may not be as fast as
TRUNCATE, as dropping
and re-creating the table
requires you to re-grant
object privileges, re-create
indexes, constraints, etc.
DELETE ANY TABLE
allows you to delete
rows from any table of
any schema.
DROP ANY TABLE system
privilege.
DROP ANY TABLE system
privilege.
DELETE privilege on a
specific table can be
granted to another user
or role.
TRUNCATE privilege on a
specific table cannot be
granted to another user or
role.
DROP ANY privilege on a
specific table cannot be
granted to another user or
role.
CHAR VARCHAR
CHAR stores fixed length character string VARCHAR stores variable length character
strings
String length is between 1-2000 String length is between 1-4000
It can hold max 256 character It can hold max 65,535 character
It uses static memory allocations It uses dynamic memory allocations
It is 50% faster than VARCHAR It is slower than CHAR
VARCHAR VARCHAR2
VARCHAR can store up to 2000 bytes. VARCHAR2 can store up to 4000 bytes of
characters.
If we declare datatype as VARCHAR then
it will occupy space for NULL values.
In the case of VARCHAR2 datatype, it will
not occupy any space for NULL values.
12
12
What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 characters long,
blockno, row number are the components of ROWID.
What is an alias in SQL statements?
Alias is a user-defined alternative name given to the column or table. By default column,
alias headings appear in upper case. Enclose the alias in double quotation marks (“ “) to
make it case-sensitive. “AS” Keyword before the alias name makes the SELECT clause
easier to read.
For example Select emp_name AS name from employee; (Here AS is a keyword and
“name” is an alias).
How a SQL Query run?
FROM
WHERE
JOINS
GROUP BY
HAVING
SELECT
ORDER BY
LIMIT
Difference between OLTP & OLAP?
OLTP OLAP
It is an online transactional system and
manages database modification.
It is an online data retrieving and data
analysis system.
Insert, Update, Delete information from the
database.
Extract data for analyzing that helps in
decision making.
OLTP and its transactions are the original
source of data.
Different OLTPs database becomes the
source of data for OLAP.
OLTP has short transactions. OLAP has long transactions.
The processing time of a transaction is
comparatively less in OLTP.
The processing time of a transaction is
comparatively more in OLAP.
Simpler queries. Complex queries.
Tables in OLTP database are normalized
(3NF).
Tables in OLAP database are not
normalized.
OLTP database must maintain data integrity
constraint.
OLAP database does not get frequently
modified. Hence, data integrity is not
affected.
13
13
JOINS:
What is the usage of Merge Statement?
Merge statement is used to select rows from one or more data source for updating and
insertion into a table or a view. It is used to combine multiple operations.
Equi join will omit null values, Outer Join will not omit null values.
Equi Join
T1 T2 1 1 T1 T2 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 3 X 2 = 6 RECORDS
1 1 1 NULL 1 1 1 1 1 1
1 1 1 1 1 1 NULL NULL
1 1 1 1 1 1 NULL ONLY TABLE
STRUCTURE
On & And The Filtered Records Will Be Displayed As Null
On & Where The Filtered Records Will Be Flushed Out
Which are the most commonly used SQL joins?
Most commonly used SQL joins are INNER JOIN and LEFT OUTER JOIN and RIGHT
OUTER JOIN.
What are the different types of joins in SQL?
Joins are used to merge two tables or retrieve data from tables. It depends on the relationship
between tables.
Following are the most commonly used joins in SQL:
Inner Join: inner joins
Outer Join: outer joins are of three type:
right outer join
Left outer join
Full outer join
14
14
What is Inner Join in SQL?
Inner join:
INNER JOIN OR EQUI JOIN
• To select matched rows from two or more table is called equi join.
• It can be called as inner join or natural join (natural join find common columns
from both the table).
INNER JOIN
What is Right Join in SQL?
Right Join:
RIGHT OUTER JOIN
To get matched record from both the table and unmatched record from right table.
RIGHT JOIN
What is Left Join in SQL?
Left Outer Join
To get matched record from both the table and unmatched record from left table.
LEFT JOIN
What is Full Join in SQL?
15
15
Full Join:
FULL OUTER JOIN
To get both matched and unmatched record from both the table.
FULL OUTER JOIN
What is self-join and what is the requirement of self-join?
A self-join is often very useful to convert a hierarchical structure to a flat structure. It is used
to join a table to itself as like if that is the second table
How to fetch the unmatched records?
Use FULL OUTER JOIN
Then, use WHERE clause to filter only null values.
How to fetch common records?
Use INTERSECT – Fetch Common records from two columns
Use INNER JOIN – Fetch Common records from two tables
What is Cartesian product or cross-join?
ANS: The Cartesian product, also referred to as a cross-join, returns all the rows in all the
tables listed in the query. Each row in the first table is paired with all the rows in the second
table.
CROSS JOIN
It is a Cartesian product.
Number of rows in first table is joined with number of rows in the second table.
Cartesian product is formed when user ignores ‘WHERE’ clause.
Cross join is used by developers to perform performance testing.
16
16
SEMI JOIN?
→ It returns row from first table when one or more row matched found in second table. →
→ Difference between semi-join and inner join is that row in first table will be returned only
once even if the second table contains two matches from a row in the first table, only one
copy of the row will be returned.
→ Semi-joins are written by using ‘IN’ & ‘EXISTS’ constructs.
ANTI JOIN?
→ It returns row from first table when no matches found in second table.
→ Anti-joins are written by using ‘NOT IN’ & ‘NOT EXISTS’ constructs.
Difference between Inner, Left outer, Right outer and Full outer joins?
Inner Join
Or Simple Join
Left Outer Join Right Outer Join Full Outer Join
Inner joins join the
multiple tables and
return those rows for
which the join
condition is true.
The inner join is the
most common join
among the types of
join.
The Left Outer Join
returns contain all
rows from the LEFT
table ( according to
the specified in ON
condition) and from
the other table
only those rows
where the joined
condition is true.
The RIGHT
OUTER JOIN
returns contain all
rows from the
RIGHT table
(according to the
specified in ON
condition) and from
the other table
only those rows
where the joined
condition is true.
The Full Outer Join
returns contain all
rows from the LEFT
table and RIGHT
table with null in
fields where the join
condition is not true.
SELECT column [ ,
column ] FROM t1
INNER JOIN t2
ON t1.column =
t2.column;
SELECT column [ ,
column ] FROM t1
LEFT [OUTER]
JOIN t2
ON t1.column =
t2.column;
SELECT column [ ,
column ] FROM t1
RIGHT [OUTER]
JOIN t2
ON t1.column =
t2.column;
SELECT column [ ,
column ] FROM t1
FULL [OUTER]
JOIN t2
ON t1.column =
t2.column;
The Oracle INNER
JOIN returns the
intersect records
of t1 and t2 as a
result.
The Oracle LEFT
OUTER JOIN
returns all the
records from t1 and
the intersect records
of t1 and t2 as a
result.
The Oracle RIGHT
OUTER JOIN
returns all the
records from t2 and
the intersect records
of t1 and t2 as a
result.
The Oracle FULL
OUTER JOIN
returns all the
records from t1 and
t2 tables as a result.
17
17
How can you fetch common data from 2 column?
ANS: we can fetch common data from two column by using Intersect or inner join
depending upon what actually you mean by common data.
Difference between Equi join & Outer join?
Equi Joins Outer Joins
Oracle Equi Joins retrieves the matching
column values of the multiple tables. The
join condition or the comparison operator
present in the WHERE clause of the select
statement.
Another type of joins is an outer
join which returns a result of an inner join
plus all the rows from one table for which
the join condition is not true.
SELECT column [ , column ] FROM t1 , t2
where t1.column = t2.column;
SELECT column [ , column ] FROM t1
LEFT | RIGHT | FULL [OUTER] JOIN
t2
ON t1.column = t2.column;
The Oracle Equijoin returns the intersect
records of t1 and t2 as a result.
There are three types of outer join as
given below:
Left Outer Joins (also called as Left Joins)
Right Outer Joins (also called as Right
Joins)
Full Outer Joins (also called as Full Joins)
AGGREGATE:
Count(*),Count(Coulmn) Will Be 0 If No Records But Max , Min Values Is Null
COUNT(COLUMN_NAME) COUNT(*)
Counts the entries in a column -
ignoring null values.
Counts the rows in table - including
null values.
Both are aggregate function or group
function.
Both are aggregate function or group
function.
Count(1) Count(*)
Counts The Rows In Table - Including
Null Values.
Counts The Rows In Table - Including
Null Values.
Counts Row By accessing An Index Counts Row Produced By Query
Fast, because it access index SLOW
Oracle Property ANSII standard
18
18
GROUP BY ORDER BY
Performs Grouping function Performs sorting function
Order of Column make no differences Order of Column make differences
Group by clause is always placed before
order by clause
order by clause is always placed after
group by clause
Attribute under Aggregate function
cannot be in Group By clause.
Attribute under aggregate can be in
Order By Clause.
WHERE HAVING
Used to filter records from tables Used to filter records from groups
Act as a Pre-filter Act as a Post-filter
Used without group by clause Must use group by clause
SELECT and other statements such as
UPDATE, DELETE or either one of
them.
Can't be used without a SELECT
statement.
GROUP BY comes after WHERE GROUP BY comes before HAVING.
(i) Implemented in row operations. (i) Implemented in column operations.
(ii) Applied to Single row. (ii) Applied to summarized row or
groups.
When do you use WHERE clause and when do you use HAVING clause?
The WHERE condition lets you restrict the rows selected to those that satisfy one or
more conditions. Use the HAVING clause to restrict the groups of returned rows to those
groups for which the specified condition is TRUE.
WHAT IS LISTTAGG() AGGREGATE?SEQ
It is used to display records in a single array format by specific delimiter. STAGG() function
is an aggregation function that transforms data from multiple rows into a single list of values
separated by a specified delimiter.
AGGREGATE FUNCTION ANALYTICAL FUNCTION
It is used to give cumulative set of data It is used to give analysis set of data
Column present in select should be
present in group by clause
Column present in select may or may
not be present in group by clause
We can group data by group by clause
& filter by having clause
We can group data by using partition
keyword
Single row output Multiple row output
It will return single value It will return more than one value
slower than analytical function faster comparing aggregate function
Here we use Sum, Avg, Count, Min,
Max
Here we use Rank, Dense_rank, Lead,
Lag, Row_number, First_value
19
19
RULES FOR AGGREGATE:
• Group functions accept only one argument.
• Group functions ignore null values including COUNT (*).
• Whenever column is followed by group function or group function followed by
column should have ‘group by’.
• The group functions SUM & AVG only work in number and not in date and
character.
• The ‘*’ cannot be used except COUNT.
• When you are restricting with group functions use ‘HAVING’ clause.
ANALTICAL:
What is Analytical Function?
ANS: Analytic functions are the last set of operations performed in a query except for the
final ORDER BY clause. Analytical function is Multi rows output. Here we use partition by
keyword for grouping. It will return more than one value. All columns is specified by using
partition clause. No row collapse and number of input is equal to the number of output.
Oracle Analytic Functions
RANK
DENSE_RANK.
LEAD.
LAG.
FIRST_VALUE.
LAST_VALUE.
NTH_VALUE.
NTILE.
Difference between RANK and DENSE_RANK?
RANK DENSE RANK
Both are analytical function Both are analytical function
(i) Both are analytical function. Skip
sequence
(i) Both are analytical function. Doesn’t
skip sequence
If there is any repeated rank it will skip
the next rank
If there is any repeated rank it will not
skip the next rank
Example :- Rank 1
1
3
1 is repeated 2 times so It will skip the
2nd rank and it will print 3 as next rank
Example :- Dense_Rank 1
1
2
It will not skip any values, It will print
in the same order
20
20
Difference between LEAD and LAG?
LEAD LAG
Both are analytical function Both are analytical function
It will fetch the next value of current
row
It will fetch the previous value of
current row
Example :-
Lead
10000 , 20000
20000 , 30000
30000 , null
Example :-
Lag
10000 , null
20000 , 10000
30000 , 20000
SET OPERATORS:
What are the set operators in SQL?
It is used to merge two or more queries
Union, Union All, Intersect or Minus operators are the set operators used in the SQL.
Difference b/w union and union all
Union Union all
Join 2 query by eliminate duplicates Only Merge 2 query
Its sorting manner based on 1st
column No sorting
Slower compare to union all Faster compare to union
Difference between Union And Union All
Union Union All
UNION: only keeps unique records UNION ALL: keeps all records,
including duplicates
It combines the result set from multiple
tables and returns distinct records into a
single result set.
It combines the result set from multiple
tables and returns all records into a single
result set.
Following is the basic syntax of UNION
operator:
SELECT column_list FROM table1
UNION
SELECT column_list FROM table2;
Following is the basic syntax of UNION
ALL operator:
SELECT column_list FROM table1
UNION ALL
SELECT column_list FROM table2;
It has a default feature to eliminate the
duplicate rows from the output.
It has no feature to eliminate the duplicate
rows from the output.
Its performance is slow because it takes time
to find and then remove duplicate records.
Its performance is fast because it does not
eliminate the duplicate rows.
Most database users prefer to use this
operator.
Most database users do not prefer to use
this operator.
21
21
Union All Full Outer Join
Union is vertical - rows from table1
followed by rows from table2 (distinct for
union, all for union all) & both table must
have same number of columns with
compatible datatypes.
Full outer join is horizontal. Number of
rows in full outer join is max of table1 and
table 2 rows and number of columns =
table1 columns + table2 columns.
It is faster It is slower compared to Union all
Intersect Minus
Intersect Set operator is used to fetch the
common records from 2 different tables .
Minus Operator is used to fetch the records
from first table which eliminates common
records.
It returns only the rows returned from both
queries
It returns unique rows selected by first
query but not the rows selected from second
query
SELECT city_name FROM CUST_DATA
INTERSECT
SELECT city_name FROM SUPP_DATA;
SELECT city_name FROM CUST_DATA
MINUS
SELECT city_name FROM SUPP_DATA;
For Performance tuning Intersect operator is
not preferable as it takes time to fetch
duplicate records
Minus operator is preferable operator in
Performance tuning.
What are the types of operators available in SQL?
Operators are the special keywords or special characters reserved for performing particular
operations and are used in the SQL queries. There is three type of operators used in SQL:
Arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), etc.
Logical operators: ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT,
OR, UNIQUE.
Comparison operator: =, !=, <>, <, >, <=, >=, !<, !>
Rules of Set Operators?
ANS: NUMBER OF COLUMNS IN SELECT CLAUSE SHOULD BE SAME.
CORRESPONDING DATA TYPES SHOULD BE SAME.
What are Wild card Operators?
% and _ are wildcard operators
% = Any number of Character
_ = Escape Character
It uses conjunction with ‘LIKE’ Operators.
22
22
What is Wildcard Operator?
ANS: The wildcard is an advanced search technique that can be used to maximize your
search results in library databases. Wildcards are used in search terms to represent one or
more other characters.
What is Wildcard LIKE operator?
ANS: The Oracle LIKE condition allows wildcards to be used in the WHERE clause of a
SELECT, INSERT, UPDATE, or DELETE statement. This allows you to perform pattern
matching.
IN EXISTS
The answer of IN can be TRUE or FALSE
or NULL
The answer of EXISTS can be TRUE or
FALSE
IN compares values between parent query
and sub-query
EXISTS cannot compare values between
parent query and sub-query
IN is used as multiple OR operator
It can be used to determine if any values are
returned or not
IN is faster than EXISTS if sub-query result
is less
EXISTS is faster than IN if sub-query result
is large
NULL cannot be compared using IN
condition
NULL can be compared using EXISTS
condition
In operator test for the particular value in
the sub query.
Exist operator is a Boolean operator.so it
works more efficient and faster than IN
operator as it will be faster to process
Boolean value rather than processing
values itself.
In operator scan all the values inside the IN
block.
EXISTS quit after 1st occurrence.
In case of a big number of list from the
select list IN operator should not be used.
The exists shall be used with the proper
condition this will definitely make the
query optimal query.
'IN' can be used on sub-queries as well as
with values.
Whereas 'EXISTS' can only be used on
sub-queries.
IN picks the list of matching values. EXISTS returns the Boolean values like
true or false. Exists is faster than in.
23
23
The two most commonly used wildcards are:
An asterisk (*) may be used to specify any number of characters. It is typically used at the
end of a root word, when it is referred to as "truncation." This is great when you want to
search for variable endings of a root word.
For example: searching for educat* would tell the database to look for all possible endings
to that root. Results will include educate, educated, education, educational or educator.
A question mark (?) may be used to represent a single character, anywhere in the word. It is
most useful when there are variable spellings for a word, and you want to search for all
variants at once.
For example, searching for colo?r would return both color and colour.
STRING:
Difference between Replace and Translate?
REPLACE TRANSALATE
it will replace set of string with another set
of string
It will replace set of string with another set
of string by individual character.
(i) Replaces entire string at a time. (i) Replaces character one-to-one basis.
(ii) Returns string if no match found. (ii) Returns null if no match found.
(iii) Syntax :- Replace ('Oracle','Ora',123 ) (iii) Syntax:- Translate ('Oracle','Oae',123 )
India Will Replace 123 Will Then Check
Exact Match Of Ind
Translate Replace 123 Will Then It Will
Check By With Individual Character
I Will Be Replaced By 1
N Will Be Replaced By 2
D Will Be Replaced By 3
What is difference between SUBSTR and INSTR?
INSTR function search string for sub-string and returns an integer indicating the
position of the character in string that is the first character of this
occurrence.SUBSTR function return a portion of string, beginning at character position,
substring_length characters long.SUBSTR calculates lengths using characters as defined by
the input character set.
24
24
Difference between INSTR and SUBSTR?
INSTR SUBSTR
(i) The INSTR function provides character
position in a pattern of string.
(i) The SUBSTR function returns a specific
portion of a string.
ii) INSTR is used to find the position of any
particular character in a word which returns
numeric value.
(ii) SUBSTR is used to extract a set of
characters from a string by specifying the
character starting position and end position
and length of characters to be fetched.
(iii) INSTR returns numeric. (iii) SUBSTR returns string.
WE USE 4 ARGUMENTS WE USE 3 ARGUMENTS
(iv) Syntax :- INSTR('HELLO','E',1,2) (iv) Syntax :- SUBSTR('HELLO',2,3)
CASE & DECODE:
CASE DECODE
Case will handle all type of relational
operators like =,<=,>=,<>
Decode will handle only equality check
Case is a statement Decode is a function
Null handling capability of case & decode
is different
Ex: null = null then 1 else 0 case will return
0. Because null is not equal to another null
Ex: null = null then 1 else 0 decode will
return 1. Because null is equal to another
null
(i) Complies with ANSII SQL (i) Oracle proprietary.
(iv) Needs data consistency. (iv) Data consistency no needed.
(v) NULL = NULL, returns FALSE (v) NULL = NULL, returns TRUE
(vi) Can be used in PL/SQL block and SQL
statements.
(vi) Can be used in SQL Statements.
(vii) Can be Used in parameters while
calling a procedure.
(vii) Cannot be Used in parameters while
calling a procedure.
What is DECODE function used for?
DECODE is used to decode a CHAR or VARCHAR2 or NUMBER into any of
several different character strings or numbers based on value. That is DECODE does a
value-by-value substitution.
25
25
NULL HANDLING:
What is null value?
Null Value is neither zero nor it is a blank space. It is some unknown value which
occupies 4 bytes of space of memory in SQL.
NULL:-???
• Null is a unassigned value or unknown value or undefined value.
• Null is not equal to zero.
• Null is not equal to space.
• Null is not equal to underscore.
• Null is not equal to Null.
• Null is not equal to ‘’
Null is always greater than any number because in ascending order Null comes last and in
descending order it comes first or it is maximum in ascending order & minimum in
descending order.
Describe different types of null handling Function used in SQL?
NVL: Converts a null value to an actual value. NVL (exp1, exp2) .If exp1 is null then the
NVL function returns the value of exp2.
Replace null value
NVL2: If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2 returns exp3. The
argument exp1 can have any data type. NVL2 (exp1, exp2, exp3)
Replace both null value and not null value
NULLIF: Compares two expressions and returns null if they are equal or the first expression
if they are not equal. NULLIF (exp1, exp2)
Null null – null
10 10 – null
10 null -10
Null 10- null
COALESCE: Returns the first non-null expression in the expression list. COALESCE
(exp1, exp2… expn). The advantage of the COALESCE function over the NVL function is
that the COALESCE function can take multiple alternative values.
Return the first not null value
Define NULL?
ANS: Null is an Unknown Undefined values. Null is not equal to zero(space/empty
character). Null is not equal to another null.
26
26
What is difference b/w nvl and nvl2 and coalesce?
NVL NVL2 COALESCE
(i) 2 arguments. (i) 3 arguments. (I) 2 or more arguments.
(ii) If the first argument is
null then display the second
argument else display the
first argument.
(ii) If the first argument is
null then display the third
argument else display the
second argument.
(ii) It returns the first not null
able column from the
arguments list.
(iii) Syntax :- NVL(1,2) (iii) Syntax :- NVL2(1,2,3) (iii) Syntax :-
COALESCE(1,2)
SYSNONMYS:
What is synonym?
A synonym is an alternative name for DATABASE or oracle object such as tables, view,
sequences, stored procedures and other database objects.
You can create synonym for synonym. Because it is a object of database.
TYPES :-
Private Synonym. (WITHIN SCHEMA)
This synonym is accessed within the schema. The default one is private
Public Synonym. (ACCESSED ACROSS or between THE SCHEMA)
This synonym is accessed across or between the schema.
Difference between a view and a synonym
Synonym View
Synonym is just a second name of table
used for multiple link of database. synonym
can be on view.
View can be created with many tables, and
with virtual columns and with conditions.
What is the difference between a view and a synonym?
Synonym is just a second name of table used for multiple link of database. View can
be created with many tables, and with virtual columns and with conditions. But synonym can
be on view.
27
27
SEQUENCE:
WHAT IS SQUENCE?
• It unique auto generated number.
• It has start with, increment by, min value, max value, cycle, cache.
• Commit, save point or rollback doesn't work.
• It is mainly used for generating primary key column values.
• We cannot change start with in sequence.
• Sequence can be shared with multiple tables.
• Sequence sometimes act as primary key
• It is a schema object.
A sequence is an object in Oracle that is used to generate a number sequence. This can be
useful when you need to create a unique number to act as a primary key.
NUMBER GENERATOR AND SEQUENCE CAN NOT BE ROLLED BACK
SEQUENCE CAN BE SHARED WITH MULTIPLE TABLES;
CREATE SEQUENCE SEQ1
START WITH 1
INCREMENT BY 1
MINVALUE 1
MAXVALUE 10
NOCACHE
NOCYCLE;
Increment by:
• Interval between sequence number
• Either + or - value but not zero
• (+)- ASC/(-)DESC
• If you omit, then default (one)
Max value:
• It must be greater than equal to start with
• Must be greater than min value
Min value:
• Must be lesser than equal to start with.
• Must be lesser than Max value
Start with:
• Specify first sequence number to be generated.
28
28
Cycle No cycle Cache No cache
It specifies when
sequence contain to
generate when it is
reached max / min
well
Default one this
cycle not mentioned
• Faster
retrieval
• Min=2
• Value of sea
is pre-
allocated
Max= maxvalue-
minvalue
Default: cache 20.
Value of sea is not
pre-allocated
Disadvantage of cache:
Lost of sequence value if the system sudden a crash occurs.
CONSTRAIN:
Constraints are of two types. They are
1. Table Level Constraints :-
The constraints can be specified after all the columns are defined. This is called table-level
definition.
2. Column Level Constraints :-
The constraints can be specified immediately after the column definition. This is called
column-level definition.
What is a primary key?
• It is a unique identifier.
• Ignores null values.
• It is entity integrity.
• It will not accept duplicate values.
• It is a cluster index.
• Only one primary key is allowed in a table.
• If need more than one primary key its possible in composite primary key.
• It automatically generates unique index.
A primary key is a field or the combination of fields which uniquely specify a row. The
Primary key is a special kind of unique key. Primary key values cannot be NULL. For
example, the Social Security Number can be treated as the primary key for any individual.
COMPOSITE PRIMARY KEY (P)?
Usually table have only one primary key but if we want to set more than one primary key
then we go for composite primary key.
29
29
What is a foreign key?
Foreign key is a key used to link two tables together.
foreign key is field or a collection of field in one table that refers to the primary key in
another table. Table containing foreign key is called child table. Table containing candidate
key is called the reference or parent table.
• It is Referential Integrity (RI).
• It refers a primary (or) unique constraint of another table.
• It accepts null values in child records.
• It accepts duplicate values in child records.
• It is like a parent and child relationship.
A foreign key is specified as a key which is related to the primary key of another table. A
relationship needs to be created between two tables by referencing foreign key with the
primary key of another table. Foreign key acts like a cross-reference between tables as it
refers to the primary key of other table and the primary key-foreign key relationship is a very
crucial relationship as it maintains the ACID properties of database sometimes.
Integrity constraint violation :
child record found- delete.
parent record not found -insert.
On delete cascade:
It will delete parent record and corresponding child records also
On delete set null:
It will delete parent record and corresponding child record it’ll set null
What is a unique key?
• It is unique identifier.
• It accepts null values and can accept more than 1 null value.
• It is entity integrity.
• It is non – cluster index.
• It automatically generates unique index.
Unique key constraint uniquely identifies each record in the database. This key provides
uniqueness for the column or set of columns.
The Unique key cannot accept a duplicate value.
The unique key can accept only on Null value.
Not null key(C):
It ignores null value.
It is a domain integrity condition.
Check [C]:
It is a domain integrity
It should satisfy your condition.
30
30
Different between Primary key and Foreign key?
Primary key Foreign key
It is used to uniquely identify data in the
table
It is used to maintain relationship
between tables
It can’t be null It can accept the null values
Two or more rows can’t have same primary
key
It can carry duplicate value for a foreign
key attribute
Primary has clustered index By default, It is not clustered index
Primary key constraint can be defined on
temporary table
It can’t be defined on temporary tables
Primary Key Unique key
Used to serve as a unique identifier
for each row in a table.
Uniquely determines a row
which isn’t primary key.
Cannot accept NULL values. Can accept one NULL value.
Only one primary key More than one unique key
Creates clustered index Creates non-clustered index
What is the difference between primary key and unique key?
Primary key and unique key both are the essential constraints of the SQL, but there is a small
difference between them
Primary key carries unique value but the field of the primary key cannot be Null on the other
hand unique key also carry unique value but it can have a single Null value field
What is difference between UNIQUE constraint and PRIMARY KEY constraint?
A column defined as UNIQUE can contain Nulls while a column defined as
PRIMARY KEY can't contain Nulls. A table can have only one primary keys.
31
31
VIEWS & MATERIALIZED VIEW:
What is view in SQL ?
1 view is a virtual table.
2. It does not contain any physical data.
3. We can create view from another view.
4. Only queries stores in data dictionary table.
Advantages of views?
• To make more complex query look simple.
Views Can Be Used To Reduce The Complexity Of The Database Schema
Views Can Be Used As Mechanism To Implement Row And Column Level Security
Views Can Be Used To Present Aggregated Data And Hide Detailed Data.
• To restrict data access of views.
What are the advantages of views?
Provide an additional level of table security, by restricting access to a predetermined set of
rows and columns of a table.
Hide data complexity.
Simplify commands for the user.
Present the data in a different perspective from that of the base table Store complex queries
What is materialized views
Materialized view is a database objects that store the result of a query.
It is a schema object.
It can be called as snapshots.
Materialized view occupies space in database.
It will save the result set of the query in data dictionary table.
We will not get updated data from Materialized view until we go for REFRESH
Why use materialized view instead of a table?
Materialized views are basically used to increase query performance since it contains
results of a query. They should be used for reporting instead of a table for a faster execution.
Advantages of materialized views:
You can create materialized view on another materialized view. So that it reduces more
network traffic.
It can be either read only, writable or updatable.
You can create materialized view for join queries and quires that contain aggregate functions.
It reduces network traffic.
32
32
Types of views
1. SIMPLE VIEW
2. COMPLEX VIEW
3. FORCE VIEW
Difference between Simple view and Complex View?
SIMPLE VIEW COMPLEX VIEW
(i) Contains only one single base table or is
created from only one table.
(i) Contains more than one base tables or is
created from more than one tables.
(ii) We cannot use group functions like
MAX(), COUNT(), etc.
(ii) We can use group functions.
(iii) Does not contain groups of data. (iii) It can contain groups of data.
(iv) DML operations could be performed
through a simple view.
(iv) DML operations could not
always be performed through a
complex view.
(v) INSERT, DELETE and UPDATE are
directly possible on a simple view.
(v) We cannot apply INSERT, DELETE
and UPDATE on complex view directly.
(vi) Simple view does not contain group by,
distinct, pseudo column like ROWNUM,
columns defined by expressions.
(vi) It can contain group by, distinct, pseudo
column like ROWNUM, columns defined
by expressions.
• It truncate & reload new data.
• It is fast
• Compare log file & fetch remaining
data
• It is slower
Difference Complete, Fast and Force Refresh?
Complete Refresh means you truncate entire materialized view and insert new data.
Fast Refresh means you update (or insert/delete) only the rows which have been changed on
master tables.
And just as information Force Refresh mean, Oracle tries to make a Fast Refresh and if this
is not possible then do Complete Refresh.
Usually Fast Refresh is much faster than Complete Refresh but it has restrictions. You have
to define MATERIALIZED VIEW LOG on master tables
33
33
VIEW MATERIALIZED VIEW
(i) A View is never stored it is only
displayed.
(i) A Materialized View is stored on the
disk.
(ii) View is the virtual table formed from
one or more base tables or views.
(ii) Materialized view is a SNAPSHOT
physical copy of the base table.
(iii) View is updated each time the virtual
table (View) is used.
(iii) Materialized View has to be updated
manually or using triggers.
(iv) Slow processing. (iv) Fast processing.
(v) View do not require memory space. (v) Materialized View utilizes memory
space.
(vi) No need log file. (vi) It will maintain log files.
(vii) Only select query has saved in data
dictionary table.
(vii) It will saves the output of the select
query in data dictionary table.
Types: simple, complex & force view Complete refresh , fast and force refresh
(viii) Syntax :-
Create View V As
(viii) Syntax:-
Create Materialized View V Build [clause]
Refresh [clause] On [Trigger] As
Without base table we can create table
using force view
Without base table we can not create MV
Index can not be created in views Index can be created in MV
Complete refresh Fast and force refresh
It truncate and reload new data Compare log file fetch remaining data
It is fast It is slow
DBMS_MVIEWS.REFRESH(‘MV_1,’C’); DBMS_MVIEWS.REFRESH(‘MV_1,’F’);
Force view:
• Not an existent table.
• No base table is necessary
• We can create a view with the dummy based table which does not exist in the
database.
• This view will be having errors.
• May be used for application code test.
34
34
Manipulate data in view:
Read only:
This can be used where you don’t want to manipulate data in a view.
Check option:
This is used where you want to insert data in views by checking condition from where
clause.
Updateable:
You can’t use order by and group by
You can’t use analytical and aggregate function.
How to Refresh View?
ANS: To refresh the Oracle materialized view, call one of the procedures in
DBMS_MVIEW. The DBMS_MVIEW package provides three types of refresh operations:
DBMS_MVIEW. REFRESH: Refreshes one or more Oracle materialized views.
MATERIALIZED VIEW LOG???
• Materialized view logs are used to track changes (insert, update and delete) to a table.
• Purging materialized view logs.
• It show no of changes made to a table.
• If you refresh materialized view then this gets to zero.
INDEX:
INDEX is a database object. It plays key role in performance tuning.
It is prefereable to create index on all varchar clause column in a query.
It is used by the oracle server.
It is based on rowid.
Should be created when less of rows to be retrieved in a large table.
It will effective if we Want to retrieve 4% of rows from the table.
TYPES OF INDEX?
B-TREE INDEX Balance tree index
When We Have high cardinality(low duplicates it is preferable to create B-Tree index.
Column that contains more than 100 unique records
BITMAP INDEX
When We Have low cardinality(high duplicates) it is preferable to create B-Tree index
Column that contains less than 100 unique records
FUNCTION BASED INDEX
When We create index on functional based column it is functional index.
It is not guaranteed that create functional index will be used all the time.
Oracle optimizer will decide whether it should be used or not based on the cost effect.
35
35
Trunc() column name
Upper() column name
What is an Index?
An Index is an optional structure associated with a table to have direct access to rows,
which can be created to increase the performance of data retrieval. Index can be created on
one or more columns of a table.
How you will avoid your query from using indexes?
By changing the order of the columns that are used in the index, in the Where
condition, or by concatenating the columns with some constant values.
INDEX:-
• It is used to improve the performance of query retrieval.
• Index can be either Unique or Non-Unique index
1. UNIQUE INDEX :
• It is created automatically when a user defines a primary/unique constraint for a
column.
2. NON – UNIQUE INDEX :
• Created by the user to speed up the retrieval of rows.
• Maintained by oracle server
WHEN TO CREATE INDEX :-
• When a table is large.
• When most of the queries are expected to retrieve less than 4% of rows from the table.
• When a column contains a wide range of values.
• When column is most often used as a condition in a query.
• When a column contains large number of null values.
WHEN NOT TO CREATE INDEX :-
• When a table is small.
• When most of the queries are excepted retrieve more than 4% of rows from the table.
• When column contains a large number of duplicates.
• When column is not most often used as condition in a query.
• When a table is updated frequently.
36
36
What is the unique Index?
Unique Index:
For creating a unique index, the user has to check the data in the column because the unique
indexes are used when any column of the table has unique values. This indexing does not
allow the field to have duplicate values if the column is unique indexed. A unique index can
be applied automatically when a primary key is defined.
What is Clustered Index in SQL?
Clustered Index:
The clustered index is used to reorder the physical order of the table and search based on the
key values. Each table can have only one clustered index. The Clustered index is the only
index which has been automatically created when the primary key is generated. If moderate
data modification needed to be done in the table then clustered indexes are preferred.
What is the Non-Clustered Index in SQL?
Non-Clustered Index:
The reason to create non-clustered index is searching the data. We well know that clustered
indexes are created automatically primary keys are generated, but non-clustered indexes are
created when multiple joins conditions and various filters are used in the query. Non-
Clustered Index does not alter the physical order of the table and maintains logical order of
data. Each table can have 999 non-clustered indexes.
What is the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table
are physically stored. Therefore table can have only one clustered index. The leaf nodes of a
clustered index contain the data pages.
A Nonclustered index is a special type of index in which the logical order of the index
does not match the physical stored order of the rows on disk.
What is Index
• It is used to improve the performance of query retrieval.
• Index can be either Unique or Non-Unique index
What is UNIQUE INDEX :
• It is created automatically when a user defines a primary/unique constraint for a
column.
What is NON – UNIQUE INDEX :
• Created by the user to speed up the retrieval of rows.
• Maintained by oracle server
37
37
WHEN TO CREATE INDEX?
• When a table is large.
• When most of the queries are expected to retrieve less than 4% of rows from the table.
• When a column contains a wide range of values.
• When column is most often used as a condition in a query.
• When a column contains large number of null values.
WHEN NOT TO CREATE INDEX?
• When a table is small.
• When most of the queries are excepted retrieve more than 4% of rows from the table.
• When column contains a large number of duplicates.
• When column is not most often used as condition in a query.
• When a table is updated frequently.
Clustered Index Non-Clustered Index
A clustered index is a special type of index
that reorders the way records in the table are
physically stored. Therefore table can have
only one clustered index. The leaf nodes of
a clustered index contain the data pages.
A Non-clustered index is a special type of
index in which the logical order of the index
does not match the physical stored order of
the rows on disk.
B-Tree Index Bitmap Index Functional Index
B-Tree index is an
index that is created on
columns that contain
very unique values
Bitmap is a method of
indexing, offering
performance benefits
and storage savings
Function-based indexes allow you to
create an index based on a function or
expression.
B-Tree works best with
many distinct indexed
values
Bitmap works best with
many distinct indexed
values
CREATE INDEX
idx_emp_id
ON employee (id);
CREATE BITMAP
INDEX
idx_emp_gender
ON employee(gender);
CREATE INDEX index_name
ON
table_name(function(column_name));
High Cardinality,Less
Duplicates
Low Cardinality, More
Duplicates
What is an Oracle index?
An index is an optional structure associated with a table to have direct access to rows,
which can be created to increase the performance of data retrieval. Index can be created on
one or more columns of a table.
38
38
What are the different index configurations a table can have?
A table can have one of the following index configurations
No indexes
A clustered index
A clustered index and many nonclustered indexes
A nonclustered index
Many nonclustered indexes.
How to know which index a table is using?
SELECT table_name,index_name FROM user_constraints.
GTT:
GLOBAL TEMPOARY TABLE:-
• It is session level table.
• It stores data only in session level once the session is close, all the data will be
truncated or flushed out and only structure remains
• It is used to store parameters values for the procedures
• It is used to session level testing.
• Data in temporary table is stored in temp segments in the temp table space.
• Data in temporary tables is automatically deleted at the end of the database
session, even if it ends abnormally.
• Views can be created against temporary tables and combinations of temporary
and permanent tables.
• Temporary tables can have triggers associated with them.
• Indexes can be created on temporary tables. The content of the index and the
scope of the index is the same as the database session.
TYPES :-
→ ON COMMIT PRESERVE ROWS
This indicates that data should be present till the session ends.
→ ON COMMIT DELETE ROWS
• This indicates that data should be deleted at the end of this transaction.
• It is the default one.
GTT WITH Clause
(i) The main difference is that the
temporary table is a stored table.
(i) It will not saves in database.
(ii) Views can create in GTT (ii) Views cannot create in WITH Clause.
(iii) Index can be create in GTT (iii) Index cannot create in WITH Clause.
39
39
Global temporary tables GTT Views
Global temporary tables in Oracle are
permanent database objects that store data
on disk and visible to all sessions.
An Oracle VIEW, in essence, is a virtual
table that does not physically exist. Rather,
it is created by a query joining one or more
tables.
PARSING :-
Oracle needs to execute some task before executing SQL query (which is received from
user).
This process is called Parsing.
1. SYNTACTIC CHECK :-
→ Oracle parses the syntax to check for misspelled SQL keywords.
2. SEMANTIC CHECK :-
→ Oracle verifies all table names & column name from the data dictionary table and check
to see if user is authorized to view data.
3. OPTIMIZATION :-
→ Oracle creates an execution plan on schema statistics.
→ If the entire above task performs then it is called hard parsing.
→ If only syntactic check & semantic check perform then it is called soft parsing.
→ Soft parsing occurs when you use ‘cursors’.
SUB QUERYS & PIVOT:
A query embedded within another query is called sub query.
There are two types of sub query they are
SINGLE ROW SUB QUERY
When a sub query returns one row then it is called single row sub query.
MULTI ROW SUB QUERY
When a sub query returns more than one row is called multi row sub query.
TYPES :-
SCALAR SUB QUERY
Whenever a ‘Select’ clause followed by sub query is called scalar sub query
INLINE VIEW
Whenever a ‘From’ clause followed by sub query is called Inline view or named sub query in
a from clause is called Inline view.
40
40
NESTED SUB QUERY
Whenever a ‘Where’ clause followed by sub query is called nested sub query. Here first
inner query is executed then outer query will be executed.
It doesn’t have any reference between inner query and outer query. Inner query runs only
once for outer query.
CO-RELATED SUB QUERY
When the inner query has reference to outer query is called correlated sub query.
Here outer query runs first and then inner query is executed.
It is user row by row processing.
The inner query is executed once for every row of the outer query.
It is faster.
What are the various types of queries? The types of queries are :
Normal Queries
Sub Queries
Co-related queries
Nested queries
Compound queries
Nested Query Sub Query Correlated Query Sub Query
In Nested Query, Inner query runs first, and
only once. Outer query is executed with
result from Inner query.Hence, Inner query
is used in execution of Outer query.
In Correlated Query, Outer query executes
first and for every Outer query row Inner
query is executed. Hence, Inner query uses
values from Outer query.
Bottom up approach i.e. Inner query runs
first, and only once. Outer query is executed
with result from Inner query.
Top to Down Approach i.e. Outer query
executes first and for every Outer query row
Inner query is executed.
Inner query execution is not dependent on
Outer query.
Inner query is dependent on Outer query.
Performs better than Correlated Query but is
slower than Join Operation.
Performs slower than both Nested Query
and Join operations as for every outer query
inner query is executed.
Difference between PIVOT and UNPIVOT and Reverse PIVOT
PIVOT UNPIVOT Reverse PIVOT
The PIVOT statement is
used to convert table rows
into columns
The UNPIVOT operator
converts columns back to
rows.
Reversing a PIVOT
statement refers to the
process of applying
the UNPIVOT operator to
the already PIVOTED
dataset in order to retrieve
the original dataset.
41
41
PL/SQL:
• Procedural language structured query language
• It is a procedural language extension to SQL
• SQL statement puts together in one single block and sends the entire block to the
server in one single cell.
• Thereby reducing network traffic.
Benefits:
• Performance benefit
• Modularization→(large block of codes into smaller piece)
• Portable
• Exception handling
• Programming features.
SQL PLSQL
It is a single query that is used to perform
DML from DDL
It is a block of codes used to write the entire
program blocks
Execute one statement at the time Executed as a block of code
You can’t embed PLSQL in sql You can embed SQL in plsql
It tells the database what to do It tells the database how to do things
Interaction with database server No interaction with database server
Used to manipulate data used to create an application
C1%rowcount SQL%rowcount
gives how many rows which will run Gives how many those affected in SQL
query
c-5 ex: 5rows table Sql-50
PERFORMANCE TUNING:
• First we have to count all the dates
Select count(1) from employees;
• If increases in datacount, then we go for the “table stats”
Select last_analyzed, T * from all_tables T
Where Table_name = ‘emp_perF’
• Check for last analyzed will be in todays date otherwise
Begin
Dbms_statts.gather_table_stats(‘HR’,’emp_perF’)
• Then we go for ‘explain plan’
Explain plan for
Select E.ID, P_first_name from Employee E, Emp_perF P
Where E.ID= P.employee_id;
• Explained, then
Select * from table(DBMS_XPLAN.DISPLAY());
42
42
Explain Plan:
• Always read from last /reverse
• If the table contain number of bytes high and cost high go for that table.
Operation in explain plan:
Types of join :
Hash Join(check =):
• When we join large table with small table
• Optimizer will create hash memory
• Then, values of small tables stored in a hash memory
• Hash memory created in large table only
• Then go for equality check
Nested loop Join:
• Co-related query
• When we have less no of results set
• when join two large table
Merge join:
Other than equality check
Oracle Optimizer:
RBC-Rule based optimizer →(before 11g only RBC)
CBC-Cost based optimizer
BMC Remedy:
• it is ticketing tool
• for any issues we can raise and clear it
• way to ticket track
i. request(configuration)
ii. incident (severity issue)
iii. problem management (code change, too built)
iv. change management
SVN Tool: (sub version tool):
• it is a centralized version control system
• open source tool for version control
• it used to manage the current and previous version of files like source code,
documentation & file.
• (SVN tortoise) our version (Apache made)
43
43
ANONYMOUS & CURSOR BLOCK:
ANONYMOUS BLOCK
• PL/SQL block which can be created & used in same session but they will not be stored
in server as database object.
• It does not have any name assigned to them.
Declare
Begin
Exception(optional)
End
%type:
Used to retrieve datatype of single column form a table
%rowtype:
Used to retrieve datatype of entire column form a table
CURSOR BLOCK
• Cursor Stores the result of SQL query and manipulates in temporary work area.
• Cursor can hold more than one row but it process row by row (loop).
• Cursor holds set of rows called active rows.
• We can perform DML operation in cursor by IF statement.
• The cursor is a pointer to this context area
• Oracle creates context area for processing an SQL statement through the cursor.
There are two type of cursor
1. Implicit cursor
2. Explicit cursor
3.
Implicit cursor:
It is automatically generated by oracle while SQL statement is executed.
Explicit cursor:
It is defined by user or programmer to gain more control over the context area.
SYNTAX: Cursor <cursor name> is Select_statement.
Implicit cursor Explicit cursor
No need cursor keyword for declare Requires declaration of cursor keyboard
returns one row Returns one or more rows
Automatically created by Oracle whenever
SQL statement is executed
Programmer defined cursor for control over
context area
Simple select query Row by row fetch
Default cursor Defined cursor
44
44
ATTRIBUTES OF CURSOR:
%NOTFOUND, %FOUND, %ISOPEN, %ROWCOUNT.
%NOTFOUND:
Loop Runs For Multiple Value Output Until Condition Is True
Loop runs for all values
Returns Boolean result
• True→ not fetch record else fetch record
%FOUND:
Loop Runs For Only One Value Output Until Condition Is False
Loop runs for only one value
If it is true then fetch records false then not fetch records
%ROWCOUNT:
To Fetch The No Of Rows Affected Rows In Complete Cursor Record
Return numeric value
Gives actual count of records that are affected by DML activity
%ISOPEN:
Returns True If The Cursor Is Open, Else False.
Boolean result true/ else falls cursor already opened
Difference between Cursor and Ref Cursor
Cursor Ref Cursor
A cursor is really any SQL statement that
runs DML (select, insert, update, delete) on
your database.
A ref cursor is a pointer to a result set. This
is normally used to open a query on the
database server, then leave it up to the client
to fetch the result it needs.
What is the difference between Explicit and Implicit Cursors?
An Implicit cursor is one created "automatically" for you by Oracle when you execute
a query. It is simpler to code
An Explicit cursor is one you create yourself. It takes more code, but gives more control - for
example, you can just open-fetch-close if you only want the first record and don't care if
there are others DBA_DATA_FILES.
COLLECTIONS:
• it is an ordered group of elements having the same data type
• Each element has a unique subscript that represent its position in the collection
• It is one dimension
45
45
VARRAY:
• It is dense and bounded
• Varray variable size array
• When you create a varray you must declare a maximum number of columns
• They use sequence number as subscript
• We can’t delete in VR
• We can’t rent only last to first
• Stored in a database
10 33 45 51 67
1 2 3 4 5
X(1)=10 , X(4)=51 Index value(above table 1,2,3,4,5) is created by oracle DBMS
Collection method:
• First/last
• Next/prior
• Count
• Extends
• Trim
• Delete
• Exits
Datas.csv(hat file)→server layer path root/script/a,g/ss/file/data→ staying table/delta
table Emp_stg)→Target table(query→select→all files)
Nested Table: (table of )
• nested table is the column type that hold a set of values
• It is prased and unbounded
• Main advantage is no limits
• It will create new value add boxes
• We can delete in nested table
• It can be stored in a database
Associative array: (table of ( ) index by PLS_integer/ binary_integer):
• Set off key values pair
• Each key is unique and the key can be either string or integer
• Stored in ram level only
• It is capable of holding an unspecified number
Limit 10:
For reduce memory use:
Fetch C1 bulk collect into V_RC limit 100;
46
46
PLS INTEGER BINARY INTEGER
When a PSL-Integer calculation overflow
an exception is raised
When a binary-Integer calculation overflow
no exception is raised
It is Subset of binary integer It is Subset of integer
Stores data in arithmetic format
(requires less storage)
Stores data in binary format
It is faster than number and binary integer
(better performance)
It is also faster, but slower than pls_integer
It uses machine arithmetic It uses library arithmetic
For All For
Fetch and insert/ update / delete in one shot Fetch and insert/ update / delete in loop
format
One for all, only one DML operation We can use multiple DML operation inside
for in Loop
Bulk binding operation
Bulk Binding:
Combination of Bulk collect and for all
Bulk collect → fetch the data → using ‘select’
For all→ process the data→using ‘insert’,’update’,’delete’.
Advantage of bulk collect:
• Only one context switch (collect data from PLSQL engine to SQL engine in one loop)
• Increases the performance by reducing the interaction between database and PL/SQL
engine
• Limit clause→ for reduce memory use
Disadvantage:
• Issues in memory allocation
Nested table array V array
Nested tables are unbounded. VARRAYs are always bounded (varying
arrays have a limited number of entries)
Initially dense but can become sparse
through deletions.
Never sparse.
Order is not preserved When you store and retrieve a VARRAY,
its element order is preserved
Can be indexed Cannot be indexed
47
47
Associate array or Index
by table
Nested table array V array
Unbounded i.e. the number
of elements it can hold is not
pre-defined
Unbounded i.e. the number
of elements it can hold is not
pre-defined
Bounded i.e. holds a
declared number of
elements, though this
number can be changed at
runtime
Can be arbitrary numbers or
strings. Need not be
sequential.
Sequential numbers, starting
from one
Sequential numbers, starting
from one
Index by tables can be used
in PL/SQL programs only,
cannot be stored in the
database.
Can be stored in the
database using equivalent
SQL types, and manipulated
through SQL.
Can be stored in the
database using equivalent
SQL types, and manipulated
through SQL (but with less
ease than nested tables)
Works as key-value pairs.
e.g. Salaries of employees
can be stored with unique
employee numbers used as
subscripts
sal(102) := 2000;
Similar to one-column
database tables.
Oracle stores the nested
table data in no particular
order. But when you retrieve
the nested table into a
PL/SQL variable, the rows
are given consecutive
subscripts starting at 1.
Standard subscripting syntax
e.g.
color(3) is the 3rd color in
varray color
Most flexible. Size can
increase/ decrease
dynamically.
Elements can be added to
any position in the list and
deleted from any position.
Almost like index-by tables,
except that subscript values
are not as flexible. Deletions
are possible from non-
contiguous positions.
Not very flexible. You must
retrieve and update all the
elements of the varray at the
same time.
Hash tables Sets and bags Arrays
PROCEDURES:
Stored procedure:
• It is named P L SQL subprograms
• It is compiled and stored in database for repeated execution
• It can accept an argument and can return a value
• It is a schema object
• It improves the performance of an application by reducing network trafficking
• It can accept parameter
• If procedure is created outside the package then it is called as stored subprogram or
standalone subprogram
• If procedure is created in package then it is called as packaged subprogram.
48
48
Note:
• We can create a procedure inside anonymous block
• We can create procedure inside package
• We can create procedure inside procedure
• Used to business logic development
• May or may not have return value
Local procedure [private procedure]:
• Whenever you create a procedure inside the anonymous block it is called local
procedure
• This procedure doesn’t store in database and cannot be called outside anonymous
block
Parameters:
• This indicates that value must be supplied when you execute the procedure
• in , out , in/out
To view entire query of a procedure:
select * from user_source where name = ’P_first’;
Create Or Replace:
it would not affect grants which is given to objects and not affect the dependencies
select * from user_dependencies
create: completely clears the grams and dependencies
REF CURSOR:
Cursor→static
Ref cursor→ dynamic
• It is a data type
• It will close implicit
• entire table result output
• mostly give ref cursor to front end user
strong ref cursor:
• we know structure at compilation time
• it returns a value which can be of any data type
weak ref cursor:
• doesn’t know structure at compilation time
• query result will be stored
49
49
bind variable: (:Y)
• it is a placeholder in SQL statement
• by using this you can write a SQL statement that accept inputs or parameter at runtime
• it can improve SQL query performance also
Hard phrase Soft phrase
Query→buffer cache→data block Query→buffer cache
Select * from V$SQL order by first_load_time DESC.
Each query has unique ID 13 digit
EXCEPTIONS:
• Exceptions are used to handle error in PLSQL block
• The action to be performed when error occurs
Rules:
• Exception must be declared the declaration section
• Exception must be raised in exception section
• Exception should be handled exception section
SQLERRM→SQL ERROR MESSAGE
SQL CODE→ SQL ERROR CODE
Type of exceptions:
• Pre-defined (oracle error no→error message)
• Non-predefined(oracle error no→own message)
• User defined(own error no→own message)
Pre-defined:
• This can be called as system defined exception or unnamed system exception
• PLSQL predefined some common Oracle error as exception
• 20 predefined exception (SYS_INVALID_ROWID,
CURSOR_ALREADY_OPENED, NO_DATA_FOUND, TOO_MANY_ROWS,
ZERO_DIVIDE, INVALID_NUMBER, VALUE_ERROR, OTHERS,
INVALID_CURSOR)
Non-predefined:
• The system exception for which oracle doesn’t have name is called non-predefined
(or) unnamed system exception.
• Hear, we use ‘PRAGMAEXCEPTION_INIT’ is used to bind defined exception to a
particular error number of others
50
50
Rules for writing exception:
• If you use more than one exception in a block then only one exception fires that will
be based on first error occurrence.
• If you use ‘other’ exception another exception then ‘other’ it must be lost in exception
section.
User Defined:
• Apart from system exception you could explicitly define and raise exception.
• In user defined we use ‘RAISE’ keyword to forcibly raise an exception
• Error range(-20000 to -20999).
Save exception:
The save exceptions clause allows the bulk operation to continue past any exceptions, but if
any exceptions where raised in the whole operation, then it will jump to the exception
handler once the operation is complete.
FUNCTIONS:
• it is a PLSQL program which can be called as stored function
• It must always return a value
• It is a compiled and stored in database for repeated execution
• It can accept arguments
• We can also call to function in select statement
• Return only one value for multiple we use out parameter function
• Functions compute a value
• Function also can be called as part of execution
• Function cannot perform DML
• Function can use only parameter IN
• It is a schema object
Note:
• We can create function inside the package
• We can create function inside anonymous block
• We can create function inside the procedure
• If a function is created outside the package then it is called stored subprogram
• If it is created inside the package then it is called package subprogram
What are functions and their usage in SQL?
SQL functions are simple code snippets that are frequently used and re-used in database
systems for data processing and manipulation. Functions are the measured values. It always
performs a specific task. The following rules should be remembered while creating
functions:
51
51
o A function should have a name, and the name cannot begin with a special character
such as @, $, #, or other similar characters.
o Functions can only work with the SELECT statements.
o Every time a function is called, it compiles.
o Functions must return value or result.
o Functions are always used with input parameters.
SQL categories the functions into two types:
o User-Defined Function: Functions created by a user based on their needs are termed
user-defined functions.
o System Defined Function: Functions whose definition is defined by the system are
termed system-defined functions. They are built-in database functions.
SQL functions are used for the following purposes:
o To perform calculations on data
o To modify individual data items
o To manipulate the output
o To format dates and numbers
o To convert data types
Procedure Function
Procedure perform an action Function performs complete value
It can accept and may or may not return a
value
It can accept the value and must return a
value
It cannot be called from select statement It can be called from select statement
Procedures can have multiple out
parameters
Function are generally restricted to return a
single value
Not useful in queries More useful in queries
It is slightly easier to call It is not easier to call compared to function
PACKAGES:
It is group of logically related sub-programs. It is schema object.
It has 2 parts 1.)specification and 2.)Body
Local or Private Procedure:
The subprogram defined in specification should be defined in body.
The subprogram defined in body may or may not be defined in specification.
Over Loading Concept:
When we have some sub program in packages difference in no of parameters, name of
parameter, , datatype of parameter.
Package Specification:
• It contain a declaration
• You can decide cursor, type, variable, sub-program, exception and constant
• You can create a package specification without package body
52
52
• Whatever declared in package specification is global.
• Subprogram which is defined in specification should be declared in body.
• we can compile only specification
Package body:
• it contains definitions
• it contained definition of subprogram that is listed in package specification
• it also contain the definition of subprogram that is listed in the package specification.
• It also contains local procedure it will be one time procedure it is also called as
private procedure.
• You can delete the package body without deleting the package specification.
Note:
• Subprogram which is defended package may or may not be present in specification.
• You can compile specification body by using 
• We can compile body also.
Advantages:
• When package subprogram are executed for first time it is loaded to memory, further
execution of subprogram doesn’t require disk I/O.
• Packages supports Overloading concepts.
• Subprogram defend in package specification are global subprogram or global variable
in specification.
Overloading: [by using assign parameters]:
• P1 (difference in number of arguments)
• P2 (difference in parameter data type)
• P3(difference in their parameter name)
Grant execute on (pkg132 systems);
SQL query tuning:
• Select field instead of select *
• Avoid using select distinct
• Create join using with inner join [not using word]
• Use where instead of having for filter purpose
• use wild card operator at the end of phrase only (%)
• use limit to sample query result
• run your query during off peak hours
Pragma serially reusable:
• Memory allocation of constant
• Declaration in specification
53
53
Bodiless packages:
• You can use the bodiless packages for execution
• Here this variable exists only in this session
Performance tuning:
• First we will check for the date counts
• We will go For the table statistics which place primary role in performance tuning ( no
of rows in explain plan is based on status gathered]
• If not we use gathered status for all the table
• Then we will check for the index and make sure index are in valid state or not
• If not we will rebuild the index
Block level:
• for any block level tuning we will go for DBMS profiler (it’s getting ROWID and long
running SQLID then process goes for explain plan
• we also get AWR report from DBA Team getting SQL statistics information that is
(automated workload repository) from there we get long running SQL ID)
• then we take explain plan for the query
• From explain plan we get what type of scan it goes for
o Table full scan
o Index scan
o Index unique scan
o Index range scan
o Index full scan
o Index fast full scan
• Then we use the hints to change the optimizer plan
• We check up on the cardinality, costs and bytes like this performance tuning goes on.
PARTITION AND INDEX (ORACLE INDEX)::
TABLE PATITIONING:-
• Table partition is a method of splitting an object (table or index) into separate
partitions based on some criteria. The criteria can be date, number or character.
• If table contains more number of rows then queries takes more time to execute a query
and table becomes harder to manager. So in that case we use table partitioning to
overcome those issues. We can partition Table, Index & Materialized View.
• Partition allows table, index and index organized a table to be subdivided into smaller
pieces
• It is used to reduce the cost and improving performance of application.
54
54
Advantages:
• Increase performance
• Increase availability
• Enable storage cost optimization
• Enable simple management
Where we use:
• Tables greater than 2GB
• Tables contain historical old data
• When content needs to be distributed
• when table performance this week
What is Partition key?
ANS: The partition key is a set of one or more columns that determines
the partition for each row. Oracle automatically directs insert, update, and delete operations
to the appropriate partition through the use of the partition key.
What is use of Partition?
ANS: The PARTITION BY clause sets the range of records that will be used for each
"GROUP" within the OVER clause. In your example SQL, DEPT_COUNT will return the
number of employees within that department for every employee record.
What are the types of Partition?
ANS: Oracle provides the following partitioning methods:
Range Partitioning.
List Partitioning.
Hash Partitioning.
Composite Partitioning
Table Partition:
• Segmenting the data
• Partition allows table, index are sub divided into small pieces
• It reduces cost and improves performance of the application
When we go for:
• In master table
• Table greater than 2 GB
• Tables contain historically old records
• When table performance is weak
55
55
Advantages:
• Increases performance
• Increases availability
• Optimize the storage cost
• Simpler management
Types:
• Range partition
• List partition
• Hash partition
• Composite partition
Range Partition:
CREATE TABLE sales_range
(salesman_id NUMBER(5), salesman_name VARCHAR2(30),
sales_amount NUMBER(10), sales_date DATE)
PARTITION BY RANGE(sales_date)
INTERVAL(NUMTOYMINTERVAL(1,'MONTH'))
(PARTITION sales_jan2000 VALUES LESS
THAN(TO_DATE('02/01/2000','MM/DD/YYYY')));
Interval partition:
• Available only after oracle 11g version
• When we adding new data, there must be error (not in range)
• This overcome by using interval partition
• When max limit reaches oracle itself create a partition called interval partition
• When we drop the table partition then data also trauncated
List partition: (region wise partition):
CREATE TABLE sales_list
(salesman_id NUMBER(5), salesman_name VARCHAR2(30),
sales_state VARCHAR2(20), sales_amount NUMBER(10),
sales_date DATE) PARTITION BY LIST(sales_state)
(PARTITION sales_west VALUES('CHENNAI', 'MADURAI'),
PARTITION sales_east VALUES ('New York', 'VADODRA', 'DELHI'),
PARTITION sales_central VALUES('BANG', 'COCHIN'),
PARTITION SYS_PART VALUES('COIM'),
PARTITION SYS_PAR1 VALUES('TRICHY'),
PARTITION sales_other VALUES(DEFAULT));
56
56
Automatic:
• Only after 12c version
• When we insert ‘AAA’,’BBB’ it automatically inserts their loation
• Otherwise it create sales_others by own name.
Hash Partition:
• It is partitioned by datablocks
• Most not used
• When we don’t know to do partition on which column in that case we go for hash
partition
Composite Partition:
• Combination of any two partition
Global index:
Create on the table
Local index:
• Create on each partition
• Effective once
Prefixed local index:
• Create index year_idx
On all_fact(sale_date)→ partition key
Local (partition sales_jan 2021);
Sub-prefixed local index:
Create index year_idx on all_fac(sale_amount)→partition key
Local(partition sale_jan2021);
How to create a partition in already created table?
• We go for “exchange partition”
• Method:
a. New table with all partition
b. Load data from old to new
c. Rename new table
d. Drop a old table
TRIGGER:
• Trigger is a database object which automatically occurs when a triggering event
occurs.
• Event fires another event
• You can enable & disable trigger
57
57
Event option:
• DML (insert,delete,update)
• DDL (create,alter)
• User logon/logoff
• System (startup/Shutdown)
Used for:
• Prevent invalid transaction
• Generating values for any derived column
• Auditing purpose
• To maintain having historic data of core table
Restriction:
• We cant use DDL in trigger because they have implicit cursor
• We cant use commit, savepoint or rollback
• We cant call trigger inside any function/procedure
• We can call others inside the trigger
SELECT * FROM USER_TRIGGER
ALTER TRIGGER TRG1 DISABLE
Projectin Trigger:
We use to capture the history data/table in core schema, it will be capture in the trigger table
with userid.
Row level trigger Statement level trigger
When triggering event takes place many
times, that much time trigger is fired
When triggering event takes place many
times it fires only once to target table
For each row clause is present That clause not present
Used for data auditing purpose
:old word only in row level trigger
Used for additional security on the
transaction performed in the table
Ex: if 1500 rows are to be inserted then
1500 times trigger fires
If 1500 rows are to be inserted then only
one trigger fires
Mutating table / Mutating errors: (ORA-04091) Recursive SQL
• If any DML operation is taking place in a table and your trying to make another
change in middle of first change.
• When we do DML operation on a table, trigger associated with the table automatically
fire and make another change (DML) to the same table
• This is overcome by using compound trigger
• It is 11G new feature
58
58
Compound Trigger:
More than one trigger in same table in called compound trigger.
It fires as:
Before statement level follows by
Before row level follows by
After row level follows by
After statement level
Pragma autonomous transaction:
• Pragma→complier directive
• Provide information to the computer
• Performs independent transaction
• You must use commit or rollback, otherwise we get error ‘ORA-06519’
• Independent transaction between begin & end without affecting entire transaction or
other transaction
• We can do DDl,,DML in function & procedure using Pragma autonomous transaction.
HINTS AND TABLE REGONIZATION:
• Optimizer directive
• Used to change the optimizer directive plan
Hints of Joining Order:
• Leading
• Ordered
• Used to determine in which order to join the table
• Optime will go to RBC
Select/*+ordered*/from employees;
Hints of access path:
• Index /* index(emp_dep_x)*/
• No_index /*+no_index(emp_department_lX)*/
• Append
• Full
Append:
• Direct load datablock
• Faster
• Not stored in buffer/redo logs
Hints for parallel execution:
/*+parallel(2)*/ → depend upon space
59
59
Technique is multithreading:
• Use multiple I/O to run fast
• We need DBA confirmation & proper server space, then only we use the parallel hint
• For this DBA team generate certain formula
Hints for Join condition:
USE_HASH
NO_USE_HASH
USE_NL
NO_USE_NL
USE_MERGE
NO_USE_MERGE
Example: select/* + no_use_hash*/ from employees;
Select * from table (DBMS_xplan.Display());
Types of Scan:
1. Table full scan:
• Analyse all records in the table.
• For look up table , we go for table full scan
2. Index scan:
• When we use primary or unique key column in a where clause
• It automatically goes for index unique scan.
3. Index range scan:
• When we use range between or limits in a where clause
4. Index fast scan:
• When a column used in where clause contains index
• All column must contain index
5. Index fast full scan:
• When a column used in select clause contain index and also columns used in where
clause contain index.
6. Index skip scan:
• When we create a composite index (A,B) we call only one composite index column
where as skip another column using filters
Table recognition:
By using this we can remove empty blocks in the table
Tablespace→multiple space→multiple extend→datablocks
Create table ‘HR’,’Prawin’
(Id number
name varchar2(50)) Tablespace A;
alter table prawin move to buffer_TB;
alter table prawin move to A;
(by using this, we can shrink the empty blocks)
60
60
NORMALIZATION:
What is Normalization?
ANS: Normalization is a systematic approach of decomposing tables to eliminate data
redundancy and undesirable characteristics like Insertion, Update and Deletion Anomalies. It
is a multi-step process that puts data into tabular form by removing duplicated data from the
relation tables.
What is Normalization in a Database?
Normalization is used to minimize redundancy and dependency by organizing fields and
table of a database.
There are some rules of database normalization which commonly known as Normal From
and they are:
First normal form(1NF)
Second normal form(2NF)
Third normal form(3NF)
Boyce-Codd normal form(BCNF)
Using these steps, the redundancy, anomalies, inconsistency of the data in the database can
be removed.
What is the primary use of Normalization?
Normalization is mainly used to add, delete or modify a field that can be made in a single
table. The primary use of Normalization is to remove redundancy and to remove the insert,
delete and update distractions. Normalization breaks the table into small partitions and then
link them using different relationships so that it will avoid the chances of redundancy.
What is Denormalization in a Database?
Denormalization is used to access the data from higher or lower normal form of database. It
also processes redundancy into a table by incorporating data from the related tables.
Denormalization adds required redundant term into the tables so that we can avoid using
complex joins and many other complex operations. Denormalization doesn?t mean that
normalization will not be done, but the denormalization process takes place after the
normalization process.
What are the disadvantages of not performing Database Normalization?
The major disadvantages are:
The occurrence of redundant terms in the database which causes the waste of the space in the
disk.
Due to redundant terms inconsistency may also occur id any change will be made in the data
of one table but not made in the same data of another table then inconsistency will take
place, which will lead to the maintenance problem and effects the ACID properties as well.
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL
Paper Presentation of SQL and PL/SQL

More Related Content

What's hot

Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
Anurag
 

What's hot (20)

Mysql
MysqlMysql
Mysql
 
Constraints In Sql
Constraints In SqlConstraints In Sql
Constraints In Sql
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Sql commands
Sql commandsSql commands
Sql commands
 
Structured Query Language (SQL)
Structured Query Language (SQL)Structured Query Language (SQL)
Structured Query Language (SQL)
 
Sql commands
Sql commandsSql commands
Sql commands
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
MySql slides (ppt)
MySql slides (ppt)MySql slides (ppt)
MySql slides (ppt)
 
Basic SQL and History
 Basic SQL and History Basic SQL and History
Basic SQL and History
 
Introduction to structured query language (sql)
Introduction to structured query language (sql)Introduction to structured query language (sql)
Introduction to structured query language (sql)
 
Oracle Tablespace - Basic
Oracle Tablespace - BasicOracle Tablespace - Basic
Oracle Tablespace - Basic
 
Sql commands
Sql commandsSql commands
Sql commands
 
Oracle User Management
Oracle User ManagementOracle User Management
Oracle User Management
 
Sql Server Basics
Sql Server BasicsSql Server Basics
Sql Server Basics
 
Sql(structured query language)
Sql(structured query language)Sql(structured query language)
Sql(structured query language)
 
Cursors
CursorsCursors
Cursors
 
SQL(DDL & DML)
SQL(DDL & DML)SQL(DDL & DML)
SQL(DDL & DML)
 
Structured Query Language
Structured Query LanguageStructured Query Language
Structured Query Language
 

Similar to Paper Presentation of SQL and PL/SQL

Introduction to Database Management System
Introduction to Database Management SystemIntroduction to Database Management System
Introduction to Database Management System
Hitesh Mohapatra
 
SQL, Oracle, Joins
SQL, Oracle, JoinsSQL, Oracle, Joins
SQL, Oracle, Joins
Gaurish Goel
 
Active directory interview_questions
Active directory interview_questionsActive directory interview_questions
Active directory interview_questions
subhashmr
 

Similar to Paper Presentation of SQL and PL/SQL (20)

Oracle tutorial
Oracle tutorialOracle tutorial
Oracle tutorial
 
Introduction to Database Management System
Introduction to Database Management SystemIntroduction to Database Management System
Introduction to Database Management System
 
Bt0066 database management system1
Bt0066 database management system1Bt0066 database management system1
Bt0066 database management system1
 
Sql introduction
Sql introductionSql introduction
Sql introduction
 
Sql server
Sql serverSql server
Sql server
 
Discover Database
Discover DatabaseDiscover Database
Discover Database
 
Database Languages
Database LanguagesDatabase Languages
Database Languages
 
Dbms notes
Dbms notesDbms notes
Dbms notes
 
Introduction to Oracle Database
Introduction to Oracle DatabaseIntroduction to Oracle Database
Introduction to Oracle Database
 
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangaloreOracle DBA Tutorial for Beginners -Oracle training institute in bangalore
Oracle DBA Tutorial for Beginners -Oracle training institute in bangalore
 
PostgreSQL Terminology
PostgreSQL TerminologyPostgreSQL Terminology
PostgreSQL Terminology
 
SQL, Oracle, Joins
SQL, Oracle, JoinsSQL, Oracle, Joins
SQL, Oracle, Joins
 
Active directory interview_questions
Active directory interview_questionsActive directory interview_questions
Active directory interview_questions
 
Active directory interview_questions
Active directory interview_questionsActive directory interview_questions
Active directory interview_questions
 
Database-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptxDatabase-management-system-dbms-ppt.pptx
Database-management-system-dbms-ppt.pptx
 
Overview of databases
Overview of databasesOverview of databases
Overview of databases
 
Dbms Basics
Dbms BasicsDbms Basics
Dbms Basics
 
Oracle archi ppt
Oracle archi pptOracle archi ppt
Oracle archi ppt
 
Oracle 11g SQL Overview
Oracle 11g SQL OverviewOracle 11g SQL Overview
Oracle 11g SQL Overview
 
Sql server
Sql serverSql server
Sql server
 

Recently uploaded

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

Paper Presentation of SQL and PL/SQL

  • 1. 1 1 CONTENTS INTRODUCTION: DML, DDL,DCL&TCL.................................................................................................2 JOINS:.............................................................................................................................................................13 AGGREGATE: ..............................................................................................................................................17 ANALTICAL: ................................................................................................................................................19 SET OPERATORS:.......................................................................................................................................20 STRING:.........................................................................................................................................................23 CASE & DECODE: .......................................................................................................................................24 NULL HANDLING: ......................................................................................................................................25 SYSNONMYS: ...............................................................................................................................................26 SEQUENCE: ..................................................................................................................................................27 CONSTRAIN: ................................................................................................................................................28 VIEWS & MATERIALIZED VIEW:..........................................................................................................31 INDEX: ...........................................................................................................................................................34 GTT:................................................................................................................................................................38 SUB QUERYS & PIVOT:.............................................................................................................................39 PL/SQL: ..........................................................................................................................................................41 PERFORMANCE TUNING:........................................................................................................................41 ANONYMOUS & CURSOR BLOCK:........................................................................................................43 COLLECTIONS:...........................................................................................................................................44 PROCEDURES:.............................................................................................................................................47 REF CURSOR: ..............................................................................................................................................48 EXCEPTIONS: ..............................................................................................................................................49 FUNCTIONS:.................................................................................................................................................50 PACKAGES: ..................................................................................................................................................51 PARTITION AND INDEX (ORACLE INDEX):: ......................................................................................53 TRIGGER: .....................................................................................................................................................56 HINTS AND TABLE REGONIZATION:...................................................................................................58 NORMALIZATION:.....................................................................................................................................60 OTHER QUESTIONS:..................................................................................................................................61 UNIX: ..............................................................................................................................................................61
  • 2. 2 2 INTRODUCTION: DML, DDL,DCL&TCL In which language Oracle has been developed? Oracle has been developed forton and redone by C Language. What are the components of logical database structure in Oracle database? Components of logical database structure. Tablespaces Database's schema object What is a tablespace? A database contains Logical Storage Unit called tablespaces. A tablespace is a set of related logical structures. Actually a tablespace groups related logical structures together What is SQL? SQL stands for the Structured Query Language. SQL is a standard query language used for maintaining the relational database and perform many different operations of data manipulation on the data. SQL initially was invented in 1970. It is a database language used for database creation, deletion, fetching rows and modifying rows, etc. sometimes it is pronounced as 'sequel. What are the subsets of SQL? Data definition language (DDL):DDL is used to define the data structure it consists of the commands like CREATE, ALTER, DROP, etc. Data manipulation language (DML):DML is used to manipulate already existing data in the database. The commands in this category are SELECT, UPDATE, INSERT, etc. Data control language (DCL):DCL is used to control access to data in the database and includes commands such as GRANT, REVOKE. Transaction Control Language(TCL): it is used to validate tha transaction such as commit, rollback What is a Data Definition Language? Data definition language (DDL) is the subset of the database which defines the data structure of the database in the initial stage when the database is about to be created. It consists of the following commands: CREATE, ALTER and DELETE database objects such as schema, tables, view, sequence, etc.
  • 3. 3 3 What is a Data Manipulation Language? Data manipulation language makes the user able to retrieve and manipulate data. It is used to perform the following operations. Insert data into database through INSERT command. Retrieve data from the database through SELECT command. Update data in the database through UPDATE command. Delete data from the database through DELETE command. What is Data Control Language? Data control language allows you to control access to the database. DCL is the only subset of the database which decides that what part of the database should be accessed by which user at what point of time. It includes two commands GRANT and REVOKE. GRANT: to grant the specific user to perform a particular task REVOKE: to cancel previously denied or granted permissions. What are privileges and Grants? Privileges are the rights to execute SQL statements – means Right to connect and connect. Grants are given to the object so that objects can be accessed accordingly. Grants can be provided by the owner or creator of an object. SET TRANSACTION? → It is used to set current transaction to read only and read write. → This doesn't affects other transaction by other users. → To end this transaction use ‘COMMIT’ or ‘ROLLBACK’. → Name is the transaction name given by user. Example 1 :- SET TRANSACTION READ ONLY NAME 'TORENTO'; Example 2 :- SET TRANSACTION READ WRITE NAME 'TORENTO'; Difference between varchar and varchar2 data types? Varchar can store upto 2000 bytes and varchar2 can store upto 4000 bytes. Varchar will occupy space for NULL values and Varchar2 will not occupy any space. Both are differed with respect to space. What is BLOB datatype? A BLOB data type is a varying length binary string which is used to store two gigabytes memory. Length should be specified in Bytes for BLOB. What is RAW datatype? RAW datatype is used to store values in binary data format. The maximum size for a raw in a table in 32767 bytes.
  • 4. 4 4 What are the components of database structure in oracle? ANS: There are two type of database component physical database structure & logical database structure. What are the components of physical database structure of Oracle database? Oracle database is comprised of three types of files. One or more data files, two are more redo log files, and one or more control files. What is Physical database structure? ANS: Physical database structure of oracle database are control files, redo log files and datafiles. Datafile: This component stores the actual data. Each datafile is associated with only one database and tablespace. Redo Log files: These are more or less like backup files which are written before any changes to data files are written. Control files: These files contain the database structure information. Information like database creation date, name, redo threads, archive log history etc is stored. What is Logical database structure? ANS: Logical database structure includes tablespaces, schema objects, data blocks, extents and segments. Tablespaces Database is logically divided into one or more tablespaces. Each tablespace creates one or more datafiles to physically store data. Schema objects Schema objects are the structure that represents database's data. Schema objects include structures such as tables, views, sequences, stored procedures, indexes, synonyms, clusters and database links. Data Blocks Data block represents specific number of bytes of physical database space on disk. Extents An extent represents continuous data blocks that are used to store specific data information. Segments A segment is a set of extents allocated for a certain logical structure.
  • 5. 5 5 What is table lock? ANS: Table lock prevents conflicting DDL operations that would override data changes in a current transaction. Table Locks (TM) A transaction automatically acquires a table lock (TM lock) when a table is modified with the following statements: INSERT , UPDATE , DELETE , MERGE , and SELECT ... FOR UPDATE . These DML operations require table locks to reserve DML access to the table on behalf of a transaction and to prevent DDL operations that would conflict with the transaction. Types of Table Lock? ANS: There are five different types of locks in Oracle, and they are: exclusive, shared, shared row exclusive, row shared, and row exclusive. How to remove Table Lock? ANS: You can release the lock using ROLLBACK or COMMIT. The DISABLE TABLE LOCK only prevents DDL operations to be performed (like ALTER TABLE, DROP TABLE, a.s.o. ), and PARALLEL DML, it DOES NOT prevent normal (serial) DML statements. What is meant by Deadlock Situation? ANS: It is a situation in which two or more transaction are waiting for data locked by each other, resulting in all sessions being blocked. Oracle automatically detects & resolves deadlock by rolling back the statement associated with transaction that detects deadlock. What is table Re-org? ANS: The main goal of table reorganization is to reduce IO when accessing the big database tables. 1. Reorders the table data according to the primary key index. 2. Column reordering to push columns that have no data, nulls, to the end of the table row The column reordering can be very useful for tables that have 300+ columns many of the columns are null. When the null columns are pushed to the end of the row, the read operation becomes streamlined thus increasing performance. What is Save point? ANS: It is a marker. It is used to identify a point to which you can roll back later. If two save point have same name then when you rollback will done until the last occurrence of the save point. OR Use the SAVEPOINT statement to identify a point in a transaction to which you can later roll back.
  • 6. 6 6 How can we save images in database ? ANS: we can save image in D.B by using BLOB datatype. D.B. images are converted into BLOB, inserted in D.B then stored. What is database Dictionary? How it can be created? ANS: Data dictionary is a set of database tables used to store information about D.B. definition. It contains information about D.B. object such as Tables, Views, Indexes, Column, datatypes. To create data dictionary create connection to your D.B, then select connection, right click & choose generate DB Doc. How to edit VARCHAR2 Limit? ANS: Step1. ADD a column with any name/ dummy name with desired varchar limit Step2. Update all data from existing column to new dummy column Step3. Drop old Column Step4. Rename new column with old column name. What is Oracle table? A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns. What are Clusters? Clusters are groups of one or more tables physically stores together to share common columns and are often used together. What does ROLLBACK do? ROLLBACK retracts any of the changes resulting from the SQL statements in the transaction. What is the usage of SAVEPOINTS? SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed. Define transaction? A transaction is a sequence of SQL statements that Oracle Database treats as a single unit.
  • 7. 7 7 What is the difference between sql & oracle? SQL is Stuctured Query Language.Oracle is a Database.SQL is used to write queries against Oracle DB. What are different Oracle database objects? TABLES VIEWS INDEXES SYNONYMS SEQUENCES TABLESPACES What is schema? A schema is collection of database objects of a user. What are Roles? Roles are named groups of related privileges that are granted to users or other roles. What are the dictionary tables used to monitor a database spaces ? DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES What is a database instance? A database instance is a set of memory structure and background processes that access a set of database files. The processes can be shared by all of the users. What are parameters? Parameters provide a simple mechanism for defining and setting the valuesof inputs that are required by a form at startup.Form parameters are variables of type char,number,date that you define at design time. What are the different file extensions that are created by oracle reports? Rep file and Rdf file. Explain the difference between a data block, an extent and a segment? A data block is the smallest unit of logical storage for a database object. As objects grow they take chunks of additional storage that are composed of contiguous data blocks. These groupings of contiguous data blocks are called extents. All the extents that an object takes when grouped together are considered the segment of the database object.
  • 8. 8 8 What is bind reference and how can it be created? Bind reference are used to replace the single value in sql, pl/sql statements a bind reference can be created using a (:) before a column or a parameter name. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY? Only one LONG column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause. What is BCP? When does it used? BulkCopy is a tool used to copy huge amount of data from tables and views. BCP does not copy the structures same as source to destination. What is SYSTEM tablespace and when is it created? Every Oracle database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. Which date function returns number value? months_between What is the default return value of a function? The default return value from a function is int. In other words, unless explicitly specified the default return value by compiler would be integer value from function. What is the difference between oracle, sql and sql server? Oracle is based on RDBMS. SQL is Structured Query Language. SQL Server is another tool for RDBMS provided by MicroSoft. What is SGA? The System Global Area in an Oracle database is the area in memory to facilitate the transfer of information between users. It holds the most recently requested structural information between users. It holds the most recently requested structural information about the database. The structure is database buffers, dictionary cache, redo log buffer and shared pool area. What is a data segment? Data segment are the physical areas within a database block in which the data associated with tables and clusters are stored.
  • 9. 9 9 What is dual? Dual is a dummy table and it contains only one columns. What is the data type of DUAL table? The DUAL table is a one-column table present in oracle database. The table has a single VARCHAR2(1) column called DUMMY which has a value of 'X'. How do we display rows from the table without duplicates? Duplicate rows can be removed by using the keyword DISTINCT in the select statement. What is the fastest query method to fetch data from the table? Row can be fetched from table by using ROWID. Using ROW ID is the fastest query method to fetch data from the table. What is Data Dictionary Table? It is a Meta data about the data base Difference between Delete and Truncate? DELETE TRUNCATE • We can Rollback after delete. • No tablespace is reduced We can't Rollback after performing Truncate. Tablespace is reduced (ii) Delete does not reset identity of table. (ii). Truncate reset identity of table. Data stored in low level watermark Data stored in high level watermark Implicit commit Auto commit (iii) It locks the table row (Row Level Lock). (iii). It locks the entire table (Table Level Lock) (iv) Its DML(Data Manipulation Language) command. (iv) Its DDL(Data Definition Language) command. (v) We can use WHERE to filter data to delete. (v) We can't use WHERE clause with it. (vi) Trigger is fired. (vi) Trigger is not fired while truncate. (vii) Syntax : DELETE FROM table_name ; DELETE FROM table_name WHERE example_column_id IN (1,2,3) ; (vii) Syntax : 1) TRUNCATE TABLE table_name;
  • 10. 10 10 Blob Clob The full form of Blob is Binary Large Object. The full form of Clob is Character Large Object. This is used to store large binary data. This is used to store large textual data. This stores values in the form of binary streams. This stores values in the form of character streams. Using this you can store files like text files, PDF documents, word documents etc. Using this you can stores files like videos, images, gifs, and audio files. COMMIT ROLLBACK (i) COMMIT validates the modifications made by the current transaction. (i) ROLLBACK erases the modifications made by the current transaction. (ii) After execution of COMMIT statement, the transaction can not be ROLLBACK. (ii) Once ROLLBACK is executed database reaches its previous state, I.e. before the execution of the first statement of the transaction. (iii) COMMIT occurs when the transaction gets executed successfully. (iii) ROLLBACK occurs when the transaction is aborted in middle of the execution. (iv) Syntax :- COMMIT; (iv) Syntax :- ROLLBACK; ROWID ROWNUM (i) ROWID is nothing but Physical memory allocation. (i) ROWNUM is nothing but the sequence which is allocated to that data retrieval bunch. (ii) ROWID is permanent to that row which identifies the address of that row. (ii) ROWNUM is temporarily allocated sequence to the rows. (iii) ROWID is 16 digit Hexadecimal number which is uniquely identifies the rows. (iii) ROWNUM is numeric sequence number allocated to that row temporarily. (iv) ROWID returns PHYSICAL ADDRESS of that row. (iv) ROWNUM returns the sequence number to that row. (v) ROWID is automatically generated unique id of a row and it is generated at the time of insertion of row. (v) ROWNUM is an dynamic value automatically retrieved along with select statement output. (vi) ROWID is the fastest means of accessing data. (vi) ROWNUM is not related to access of data.
  • 11. 11 11 Difference between Delete Truncate and Drop? DELETE TRUNCATE DROP Deletes some or all rows of a table Deletes all rows of a table Removes all rows and also the table definition, including indexes, triggers, grants, parameters DML DDL DDL Commit required Commit not required Commit not required Uncommitted deletes can be rolled back Cannot be rolled back – once truncated, gone forever A dropped table can be reinstated from the recycle bin Filter criteria be specified via WHERE clause No filter criteria allowed, removes all rows No filter criteria allowed, removes all rows DELETE triggers fired No triggers fired No triggers fired DELETE can be slow especially if the table has many triggers, indexes, and other dependencies TRUNCATE is fast for deleting all rows, even more than dropping and recreating the table using DROP DROP may not be as fast as TRUNCATE, as dropping and re-creating the table requires you to re-grant object privileges, re-create indexes, constraints, etc. DELETE ANY TABLE allows you to delete rows from any table of any schema. DROP ANY TABLE system privilege. DROP ANY TABLE system privilege. DELETE privilege on a specific table can be granted to another user or role. TRUNCATE privilege on a specific table cannot be granted to another user or role. DROP ANY privilege on a specific table cannot be granted to another user or role. CHAR VARCHAR CHAR stores fixed length character string VARCHAR stores variable length character strings String length is between 1-2000 String length is between 1-4000 It can hold max 256 character It can hold max 65,535 character It uses static memory allocations It uses dynamic memory allocations It is 50% faster than VARCHAR It is slower than CHAR VARCHAR VARCHAR2 VARCHAR can store up to 2000 bytes. VARCHAR2 can store up to 4000 bytes of characters. If we declare datatype as VARCHAR then it will occupy space for NULL values. In the case of VARCHAR2 datatype, it will not occupy any space for NULL values.
  • 12. 12 12 What is ROWID? ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, row number are the components of ROWID. What is an alias in SQL statements? Alias is a user-defined alternative name given to the column or table. By default column, alias headings appear in upper case. Enclose the alias in double quotation marks (“ “) to make it case-sensitive. “AS” Keyword before the alias name makes the SELECT clause easier to read. For example Select emp_name AS name from employee; (Here AS is a keyword and “name” is an alias). How a SQL Query run? FROM WHERE JOINS GROUP BY HAVING SELECT ORDER BY LIMIT Difference between OLTP & OLAP? OLTP OLAP It is an online transactional system and manages database modification. It is an online data retrieving and data analysis system. Insert, Update, Delete information from the database. Extract data for analyzing that helps in decision making. OLTP and its transactions are the original source of data. Different OLTPs database becomes the source of data for OLAP. OLTP has short transactions. OLAP has long transactions. The processing time of a transaction is comparatively less in OLTP. The processing time of a transaction is comparatively more in OLAP. Simpler queries. Complex queries. Tables in OLTP database are normalized (3NF). Tables in OLAP database are not normalized. OLTP database must maintain data integrity constraint. OLAP database does not get frequently modified. Hence, data integrity is not affected.
  • 13. 13 13 JOINS: What is the usage of Merge Statement? Merge statement is used to select rows from one or more data source for updating and insertion into a table or a view. It is used to combine multiple operations. Equi join will omit null values, Outer Join will not omit null values. Equi Join T1 T2 1 1 T1 T2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 3 X 2 = 6 RECORDS 1 1 1 NULL 1 1 1 1 1 1 1 1 1 1 1 1 NULL NULL 1 1 1 1 1 1 NULL ONLY TABLE STRUCTURE On & And The Filtered Records Will Be Displayed As Null On & Where The Filtered Records Will Be Flushed Out Which are the most commonly used SQL joins? Most commonly used SQL joins are INNER JOIN and LEFT OUTER JOIN and RIGHT OUTER JOIN. What are the different types of joins in SQL? Joins are used to merge two tables or retrieve data from tables. It depends on the relationship between tables. Following are the most commonly used joins in SQL: Inner Join: inner joins Outer Join: outer joins are of three type: right outer join Left outer join Full outer join
  • 14. 14 14 What is Inner Join in SQL? Inner join: INNER JOIN OR EQUI JOIN • To select matched rows from two or more table is called equi join. • It can be called as inner join or natural join (natural join find common columns from both the table). INNER JOIN What is Right Join in SQL? Right Join: RIGHT OUTER JOIN To get matched record from both the table and unmatched record from right table. RIGHT JOIN What is Left Join in SQL? Left Outer Join To get matched record from both the table and unmatched record from left table. LEFT JOIN What is Full Join in SQL?
  • 15. 15 15 Full Join: FULL OUTER JOIN To get both matched and unmatched record from both the table. FULL OUTER JOIN What is self-join and what is the requirement of self-join? A self-join is often very useful to convert a hierarchical structure to a flat structure. It is used to join a table to itself as like if that is the second table How to fetch the unmatched records? Use FULL OUTER JOIN Then, use WHERE clause to filter only null values. How to fetch common records? Use INTERSECT – Fetch Common records from two columns Use INNER JOIN – Fetch Common records from two tables What is Cartesian product or cross-join? ANS: The Cartesian product, also referred to as a cross-join, returns all the rows in all the tables listed in the query. Each row in the first table is paired with all the rows in the second table. CROSS JOIN It is a Cartesian product. Number of rows in first table is joined with number of rows in the second table. Cartesian product is formed when user ignores ‘WHERE’ clause. Cross join is used by developers to perform performance testing.
  • 16. 16 16 SEMI JOIN? → It returns row from first table when one or more row matched found in second table. → → Difference between semi-join and inner join is that row in first table will be returned only once even if the second table contains two matches from a row in the first table, only one copy of the row will be returned. → Semi-joins are written by using ‘IN’ & ‘EXISTS’ constructs. ANTI JOIN? → It returns row from first table when no matches found in second table. → Anti-joins are written by using ‘NOT IN’ & ‘NOT EXISTS’ constructs. Difference between Inner, Left outer, Right outer and Full outer joins? Inner Join Or Simple Join Left Outer Join Right Outer Join Full Outer Join Inner joins join the multiple tables and return those rows for which the join condition is true. The inner join is the most common join among the types of join. The Left Outer Join returns contain all rows from the LEFT table ( according to the specified in ON condition) and from the other table only those rows where the joined condition is true. The RIGHT OUTER JOIN returns contain all rows from the RIGHT table (according to the specified in ON condition) and from the other table only those rows where the joined condition is true. The Full Outer Join returns contain all rows from the LEFT table and RIGHT table with null in fields where the join condition is not true. SELECT column [ , column ] FROM t1 INNER JOIN t2 ON t1.column = t2.column; SELECT column [ , column ] FROM t1 LEFT [OUTER] JOIN t2 ON t1.column = t2.column; SELECT column [ , column ] FROM t1 RIGHT [OUTER] JOIN t2 ON t1.column = t2.column; SELECT column [ , column ] FROM t1 FULL [OUTER] JOIN t2 ON t1.column = t2.column; The Oracle INNER JOIN returns the intersect records of t1 and t2 as a result. The Oracle LEFT OUTER JOIN returns all the records from t1 and the intersect records of t1 and t2 as a result. The Oracle RIGHT OUTER JOIN returns all the records from t2 and the intersect records of t1 and t2 as a result. The Oracle FULL OUTER JOIN returns all the records from t1 and t2 tables as a result.
  • 17. 17 17 How can you fetch common data from 2 column? ANS: we can fetch common data from two column by using Intersect or inner join depending upon what actually you mean by common data. Difference between Equi join & Outer join? Equi Joins Outer Joins Oracle Equi Joins retrieves the matching column values of the multiple tables. The join condition or the comparison operator present in the WHERE clause of the select statement. Another type of joins is an outer join which returns a result of an inner join plus all the rows from one table for which the join condition is not true. SELECT column [ , column ] FROM t1 , t2 where t1.column = t2.column; SELECT column [ , column ] FROM t1 LEFT | RIGHT | FULL [OUTER] JOIN t2 ON t1.column = t2.column; The Oracle Equijoin returns the intersect records of t1 and t2 as a result. There are three types of outer join as given below: Left Outer Joins (also called as Left Joins) Right Outer Joins (also called as Right Joins) Full Outer Joins (also called as Full Joins) AGGREGATE: Count(*),Count(Coulmn) Will Be 0 If No Records But Max , Min Values Is Null COUNT(COLUMN_NAME) COUNT(*) Counts the entries in a column - ignoring null values. Counts the rows in table - including null values. Both are aggregate function or group function. Both are aggregate function or group function. Count(1) Count(*) Counts The Rows In Table - Including Null Values. Counts The Rows In Table - Including Null Values. Counts Row By accessing An Index Counts Row Produced By Query Fast, because it access index SLOW Oracle Property ANSII standard
  • 18. 18 18 GROUP BY ORDER BY Performs Grouping function Performs sorting function Order of Column make no differences Order of Column make differences Group by clause is always placed before order by clause order by clause is always placed after group by clause Attribute under Aggregate function cannot be in Group By clause. Attribute under aggregate can be in Order By Clause. WHERE HAVING Used to filter records from tables Used to filter records from groups Act as a Pre-filter Act as a Post-filter Used without group by clause Must use group by clause SELECT and other statements such as UPDATE, DELETE or either one of them. Can't be used without a SELECT statement. GROUP BY comes after WHERE GROUP BY comes before HAVING. (i) Implemented in row operations. (i) Implemented in column operations. (ii) Applied to Single row. (ii) Applied to summarized row or groups. When do you use WHERE clause and when do you use HAVING clause? The WHERE condition lets you restrict the rows selected to those that satisfy one or more conditions. Use the HAVING clause to restrict the groups of returned rows to those groups for which the specified condition is TRUE. WHAT IS LISTTAGG() AGGREGATE?SEQ It is used to display records in a single array format by specific delimiter. STAGG() function is an aggregation function that transforms data from multiple rows into a single list of values separated by a specified delimiter. AGGREGATE FUNCTION ANALYTICAL FUNCTION It is used to give cumulative set of data It is used to give analysis set of data Column present in select should be present in group by clause Column present in select may or may not be present in group by clause We can group data by group by clause & filter by having clause We can group data by using partition keyword Single row output Multiple row output It will return single value It will return more than one value slower than analytical function faster comparing aggregate function Here we use Sum, Avg, Count, Min, Max Here we use Rank, Dense_rank, Lead, Lag, Row_number, First_value
  • 19. 19 19 RULES FOR AGGREGATE: • Group functions accept only one argument. • Group functions ignore null values including COUNT (*). • Whenever column is followed by group function or group function followed by column should have ‘group by’. • The group functions SUM & AVG only work in number and not in date and character. • The ‘*’ cannot be used except COUNT. • When you are restricting with group functions use ‘HAVING’ clause. ANALTICAL: What is Analytical Function? ANS: Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. Analytical function is Multi rows output. Here we use partition by keyword for grouping. It will return more than one value. All columns is specified by using partition clause. No row collapse and number of input is equal to the number of output. Oracle Analytic Functions RANK DENSE_RANK. LEAD. LAG. FIRST_VALUE. LAST_VALUE. NTH_VALUE. NTILE. Difference between RANK and DENSE_RANK? RANK DENSE RANK Both are analytical function Both are analytical function (i) Both are analytical function. Skip sequence (i) Both are analytical function. Doesn’t skip sequence If there is any repeated rank it will skip the next rank If there is any repeated rank it will not skip the next rank Example :- Rank 1 1 3 1 is repeated 2 times so It will skip the 2nd rank and it will print 3 as next rank Example :- Dense_Rank 1 1 2 It will not skip any values, It will print in the same order
  • 20. 20 20 Difference between LEAD and LAG? LEAD LAG Both are analytical function Both are analytical function It will fetch the next value of current row It will fetch the previous value of current row Example :- Lead 10000 , 20000 20000 , 30000 30000 , null Example :- Lag 10000 , null 20000 , 10000 30000 , 20000 SET OPERATORS: What are the set operators in SQL? It is used to merge two or more queries Union, Union All, Intersect or Minus operators are the set operators used in the SQL. Difference b/w union and union all Union Union all Join 2 query by eliminate duplicates Only Merge 2 query Its sorting manner based on 1st column No sorting Slower compare to union all Faster compare to union Difference between Union And Union All Union Union All UNION: only keeps unique records UNION ALL: keeps all records, including duplicates It combines the result set from multiple tables and returns distinct records into a single result set. It combines the result set from multiple tables and returns all records into a single result set. Following is the basic syntax of UNION operator: SELECT column_list FROM table1 UNION SELECT column_list FROM table2; Following is the basic syntax of UNION ALL operator: SELECT column_list FROM table1 UNION ALL SELECT column_list FROM table2; It has a default feature to eliminate the duplicate rows from the output. It has no feature to eliminate the duplicate rows from the output. Its performance is slow because it takes time to find and then remove duplicate records. Its performance is fast because it does not eliminate the duplicate rows. Most database users prefer to use this operator. Most database users do not prefer to use this operator.
  • 21. 21 21 Union All Full Outer Join Union is vertical - rows from table1 followed by rows from table2 (distinct for union, all for union all) & both table must have same number of columns with compatible datatypes. Full outer join is horizontal. Number of rows in full outer join is max of table1 and table 2 rows and number of columns = table1 columns + table2 columns. It is faster It is slower compared to Union all Intersect Minus Intersect Set operator is used to fetch the common records from 2 different tables . Minus Operator is used to fetch the records from first table which eliminates common records. It returns only the rows returned from both queries It returns unique rows selected by first query but not the rows selected from second query SELECT city_name FROM CUST_DATA INTERSECT SELECT city_name FROM SUPP_DATA; SELECT city_name FROM CUST_DATA MINUS SELECT city_name FROM SUPP_DATA; For Performance tuning Intersect operator is not preferable as it takes time to fetch duplicate records Minus operator is preferable operator in Performance tuning. What are the types of operators available in SQL? Operators are the special keywords or special characters reserved for performing particular operations and are used in the SQL queries. There is three type of operators used in SQL: Arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), etc. Logical operators: ALL, AND, ANY, ISNULL, EXISTS, BETWEEN, IN, LIKE, NOT, OR, UNIQUE. Comparison operator: =, !=, <>, <, >, <=, >=, !<, !> Rules of Set Operators? ANS: NUMBER OF COLUMNS IN SELECT CLAUSE SHOULD BE SAME. CORRESPONDING DATA TYPES SHOULD BE SAME. What are Wild card Operators? % and _ are wildcard operators % = Any number of Character _ = Escape Character It uses conjunction with ‘LIKE’ Operators.
  • 22. 22 22 What is Wildcard Operator? ANS: The wildcard is an advanced search technique that can be used to maximize your search results in library databases. Wildcards are used in search terms to represent one or more other characters. What is Wildcard LIKE operator? ANS: The Oracle LIKE condition allows wildcards to be used in the WHERE clause of a SELECT, INSERT, UPDATE, or DELETE statement. This allows you to perform pattern matching. IN EXISTS The answer of IN can be TRUE or FALSE or NULL The answer of EXISTS can be TRUE or FALSE IN compares values between parent query and sub-query EXISTS cannot compare values between parent query and sub-query IN is used as multiple OR operator It can be used to determine if any values are returned or not IN is faster than EXISTS if sub-query result is less EXISTS is faster than IN if sub-query result is large NULL cannot be compared using IN condition NULL can be compared using EXISTS condition In operator test for the particular value in the sub query. Exist operator is a Boolean operator.so it works more efficient and faster than IN operator as it will be faster to process Boolean value rather than processing values itself. In operator scan all the values inside the IN block. EXISTS quit after 1st occurrence. In case of a big number of list from the select list IN operator should not be used. The exists shall be used with the proper condition this will definitely make the query optimal query. 'IN' can be used on sub-queries as well as with values. Whereas 'EXISTS' can only be used on sub-queries. IN picks the list of matching values. EXISTS returns the Boolean values like true or false. Exists is faster than in.
  • 23. 23 23 The two most commonly used wildcards are: An asterisk (*) may be used to specify any number of characters. It is typically used at the end of a root word, when it is referred to as "truncation." This is great when you want to search for variable endings of a root word. For example: searching for educat* would tell the database to look for all possible endings to that root. Results will include educate, educated, education, educational or educator. A question mark (?) may be used to represent a single character, anywhere in the word. It is most useful when there are variable spellings for a word, and you want to search for all variants at once. For example, searching for colo?r would return both color and colour. STRING: Difference between Replace and Translate? REPLACE TRANSALATE it will replace set of string with another set of string It will replace set of string with another set of string by individual character. (i) Replaces entire string at a time. (i) Replaces character one-to-one basis. (ii) Returns string if no match found. (ii) Returns null if no match found. (iii) Syntax :- Replace ('Oracle','Ora',123 ) (iii) Syntax:- Translate ('Oracle','Oae',123 ) India Will Replace 123 Will Then Check Exact Match Of Ind Translate Replace 123 Will Then It Will Check By With Individual Character I Will Be Replaced By 1 N Will Be Replaced By 2 D Will Be Replaced By 3 What is difference between SUBSTR and INSTR? INSTR function search string for sub-string and returns an integer indicating the position of the character in string that is the first character of this occurrence.SUBSTR function return a portion of string, beginning at character position, substring_length characters long.SUBSTR calculates lengths using characters as defined by the input character set.
  • 24. 24 24 Difference between INSTR and SUBSTR? INSTR SUBSTR (i) The INSTR function provides character position in a pattern of string. (i) The SUBSTR function returns a specific portion of a string. ii) INSTR is used to find the position of any particular character in a word which returns numeric value. (ii) SUBSTR is used to extract a set of characters from a string by specifying the character starting position and end position and length of characters to be fetched. (iii) INSTR returns numeric. (iii) SUBSTR returns string. WE USE 4 ARGUMENTS WE USE 3 ARGUMENTS (iv) Syntax :- INSTR('HELLO','E',1,2) (iv) Syntax :- SUBSTR('HELLO',2,3) CASE & DECODE: CASE DECODE Case will handle all type of relational operators like =,<=,>=,<> Decode will handle only equality check Case is a statement Decode is a function Null handling capability of case & decode is different Ex: null = null then 1 else 0 case will return 0. Because null is not equal to another null Ex: null = null then 1 else 0 decode will return 1. Because null is equal to another null (i) Complies with ANSII SQL (i) Oracle proprietary. (iv) Needs data consistency. (iv) Data consistency no needed. (v) NULL = NULL, returns FALSE (v) NULL = NULL, returns TRUE (vi) Can be used in PL/SQL block and SQL statements. (vi) Can be used in SQL Statements. (vii) Can be Used in parameters while calling a procedure. (vii) Cannot be Used in parameters while calling a procedure. What is DECODE function used for? DECODE is used to decode a CHAR or VARCHAR2 or NUMBER into any of several different character strings or numbers based on value. That is DECODE does a value-by-value substitution.
  • 25. 25 25 NULL HANDLING: What is null value? Null Value is neither zero nor it is a blank space. It is some unknown value which occupies 4 bytes of space of memory in SQL. NULL:-??? • Null is a unassigned value or unknown value or undefined value. • Null is not equal to zero. • Null is not equal to space. • Null is not equal to underscore. • Null is not equal to Null. • Null is not equal to ‘’ Null is always greater than any number because in ascending order Null comes last and in descending order it comes first or it is maximum in ascending order & minimum in descending order. Describe different types of null handling Function used in SQL? NVL: Converts a null value to an actual value. NVL (exp1, exp2) .If exp1 is null then the NVL function returns the value of exp2. Replace null value NVL2: If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2 returns exp3. The argument exp1 can have any data type. NVL2 (exp1, exp2, exp3) Replace both null value and not null value NULLIF: Compares two expressions and returns null if they are equal or the first expression if they are not equal. NULLIF (exp1, exp2) Null null – null 10 10 – null 10 null -10 Null 10- null COALESCE: Returns the first non-null expression in the expression list. COALESCE (exp1, exp2… expn). The advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternative values. Return the first not null value Define NULL? ANS: Null is an Unknown Undefined values. Null is not equal to zero(space/empty character). Null is not equal to another null.
  • 26. 26 26 What is difference b/w nvl and nvl2 and coalesce? NVL NVL2 COALESCE (i) 2 arguments. (i) 3 arguments. (I) 2 or more arguments. (ii) If the first argument is null then display the second argument else display the first argument. (ii) If the first argument is null then display the third argument else display the second argument. (ii) It returns the first not null able column from the arguments list. (iii) Syntax :- NVL(1,2) (iii) Syntax :- NVL2(1,2,3) (iii) Syntax :- COALESCE(1,2) SYSNONMYS: What is synonym? A synonym is an alternative name for DATABASE or oracle object such as tables, view, sequences, stored procedures and other database objects. You can create synonym for synonym. Because it is a object of database. TYPES :- Private Synonym. (WITHIN SCHEMA) This synonym is accessed within the schema. The default one is private Public Synonym. (ACCESSED ACROSS or between THE SCHEMA) This synonym is accessed across or between the schema. Difference between a view and a synonym Synonym View Synonym is just a second name of table used for multiple link of database. synonym can be on view. View can be created with many tables, and with virtual columns and with conditions. What is the difference between a view and a synonym? Synonym is just a second name of table used for multiple link of database. View can be created with many tables, and with virtual columns and with conditions. But synonym can be on view.
  • 27. 27 27 SEQUENCE: WHAT IS SQUENCE? • It unique auto generated number. • It has start with, increment by, min value, max value, cycle, cache. • Commit, save point or rollback doesn't work. • It is mainly used for generating primary key column values. • We cannot change start with in sequence. • Sequence can be shared with multiple tables. • Sequence sometimes act as primary key • It is a schema object. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key. NUMBER GENERATOR AND SEQUENCE CAN NOT BE ROLLED BACK SEQUENCE CAN BE SHARED WITH MULTIPLE TABLES; CREATE SEQUENCE SEQ1 START WITH 1 INCREMENT BY 1 MINVALUE 1 MAXVALUE 10 NOCACHE NOCYCLE; Increment by: • Interval between sequence number • Either + or - value but not zero • (+)- ASC/(-)DESC • If you omit, then default (one) Max value: • It must be greater than equal to start with • Must be greater than min value Min value: • Must be lesser than equal to start with. • Must be lesser than Max value Start with: • Specify first sequence number to be generated.
  • 28. 28 28 Cycle No cycle Cache No cache It specifies when sequence contain to generate when it is reached max / min well Default one this cycle not mentioned • Faster retrieval • Min=2 • Value of sea is pre- allocated Max= maxvalue- minvalue Default: cache 20. Value of sea is not pre-allocated Disadvantage of cache: Lost of sequence value if the system sudden a crash occurs. CONSTRAIN: Constraints are of two types. They are 1. Table Level Constraints :- The constraints can be specified after all the columns are defined. This is called table-level definition. 2. Column Level Constraints :- The constraints can be specified immediately after the column definition. This is called column-level definition. What is a primary key? • It is a unique identifier. • Ignores null values. • It is entity integrity. • It will not accept duplicate values. • It is a cluster index. • Only one primary key is allowed in a table. • If need more than one primary key its possible in composite primary key. • It automatically generates unique index. A primary key is a field or the combination of fields which uniquely specify a row. The Primary key is a special kind of unique key. Primary key values cannot be NULL. For example, the Social Security Number can be treated as the primary key for any individual. COMPOSITE PRIMARY KEY (P)? Usually table have only one primary key but if we want to set more than one primary key then we go for composite primary key.
  • 29. 29 29 What is a foreign key? Foreign key is a key used to link two tables together. foreign key is field or a collection of field in one table that refers to the primary key in another table. Table containing foreign key is called child table. Table containing candidate key is called the reference or parent table. • It is Referential Integrity (RI). • It refers a primary (or) unique constraint of another table. • It accepts null values in child records. • It accepts duplicate values in child records. • It is like a parent and child relationship. A foreign key is specified as a key which is related to the primary key of another table. A relationship needs to be created between two tables by referencing foreign key with the primary key of another table. Foreign key acts like a cross-reference between tables as it refers to the primary key of other table and the primary key-foreign key relationship is a very crucial relationship as it maintains the ACID properties of database sometimes. Integrity constraint violation : child record found- delete. parent record not found -insert. On delete cascade: It will delete parent record and corresponding child records also On delete set null: It will delete parent record and corresponding child record it’ll set null What is a unique key? • It is unique identifier. • It accepts null values and can accept more than 1 null value. • It is entity integrity. • It is non – cluster index. • It automatically generates unique index. Unique key constraint uniquely identifies each record in the database. This key provides uniqueness for the column or set of columns. The Unique key cannot accept a duplicate value. The unique key can accept only on Null value. Not null key(C): It ignores null value. It is a domain integrity condition. Check [C]: It is a domain integrity It should satisfy your condition.
  • 30. 30 30 Different between Primary key and Foreign key? Primary key Foreign key It is used to uniquely identify data in the table It is used to maintain relationship between tables It can’t be null It can accept the null values Two or more rows can’t have same primary key It can carry duplicate value for a foreign key attribute Primary has clustered index By default, It is not clustered index Primary key constraint can be defined on temporary table It can’t be defined on temporary tables Primary Key Unique key Used to serve as a unique identifier for each row in a table. Uniquely determines a row which isn’t primary key. Cannot accept NULL values. Can accept one NULL value. Only one primary key More than one unique key Creates clustered index Creates non-clustered index What is the difference between primary key and unique key? Primary key and unique key both are the essential constraints of the SQL, but there is a small difference between them Primary key carries unique value but the field of the primary key cannot be Null on the other hand unique key also carry unique value but it can have a single Null value field What is difference between UNIQUE constraint and PRIMARY KEY constraint? A column defined as UNIQUE can contain Nulls while a column defined as PRIMARY KEY can't contain Nulls. A table can have only one primary keys.
  • 31. 31 31 VIEWS & MATERIALIZED VIEW: What is view in SQL ? 1 view is a virtual table. 2. It does not contain any physical data. 3. We can create view from another view. 4. Only queries stores in data dictionary table. Advantages of views? • To make more complex query look simple. Views Can Be Used To Reduce The Complexity Of The Database Schema Views Can Be Used As Mechanism To Implement Row And Column Level Security Views Can Be Used To Present Aggregated Data And Hide Detailed Data. • To restrict data access of views. What are the advantages of views? Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table. Hide data complexity. Simplify commands for the user. Present the data in a different perspective from that of the base table Store complex queries What is materialized views Materialized view is a database objects that store the result of a query. It is a schema object. It can be called as snapshots. Materialized view occupies space in database. It will save the result set of the query in data dictionary table. We will not get updated data from Materialized view until we go for REFRESH Why use materialized view instead of a table? Materialized views are basically used to increase query performance since it contains results of a query. They should be used for reporting instead of a table for a faster execution. Advantages of materialized views: You can create materialized view on another materialized view. So that it reduces more network traffic. It can be either read only, writable or updatable. You can create materialized view for join queries and quires that contain aggregate functions. It reduces network traffic.
  • 32. 32 32 Types of views 1. SIMPLE VIEW 2. COMPLEX VIEW 3. FORCE VIEW Difference between Simple view and Complex View? SIMPLE VIEW COMPLEX VIEW (i) Contains only one single base table or is created from only one table. (i) Contains more than one base tables or is created from more than one tables. (ii) We cannot use group functions like MAX(), COUNT(), etc. (ii) We can use group functions. (iii) Does not contain groups of data. (iii) It can contain groups of data. (iv) DML operations could be performed through a simple view. (iv) DML operations could not always be performed through a complex view. (v) INSERT, DELETE and UPDATE are directly possible on a simple view. (v) We cannot apply INSERT, DELETE and UPDATE on complex view directly. (vi) Simple view does not contain group by, distinct, pseudo column like ROWNUM, columns defined by expressions. (vi) It can contain group by, distinct, pseudo column like ROWNUM, columns defined by expressions. • It truncate & reload new data. • It is fast • Compare log file & fetch remaining data • It is slower Difference Complete, Fast and Force Refresh? Complete Refresh means you truncate entire materialized view and insert new data. Fast Refresh means you update (or insert/delete) only the rows which have been changed on master tables. And just as information Force Refresh mean, Oracle tries to make a Fast Refresh and if this is not possible then do Complete Refresh. Usually Fast Refresh is much faster than Complete Refresh but it has restrictions. You have to define MATERIALIZED VIEW LOG on master tables
  • 33. 33 33 VIEW MATERIALIZED VIEW (i) A View is never stored it is only displayed. (i) A Materialized View is stored on the disk. (ii) View is the virtual table formed from one or more base tables or views. (ii) Materialized view is a SNAPSHOT physical copy of the base table. (iii) View is updated each time the virtual table (View) is used. (iii) Materialized View has to be updated manually or using triggers. (iv) Slow processing. (iv) Fast processing. (v) View do not require memory space. (v) Materialized View utilizes memory space. (vi) No need log file. (vi) It will maintain log files. (vii) Only select query has saved in data dictionary table. (vii) It will saves the output of the select query in data dictionary table. Types: simple, complex & force view Complete refresh , fast and force refresh (viii) Syntax :- Create View V As (viii) Syntax:- Create Materialized View V Build [clause] Refresh [clause] On [Trigger] As Without base table we can create table using force view Without base table we can not create MV Index can not be created in views Index can be created in MV Complete refresh Fast and force refresh It truncate and reload new data Compare log file fetch remaining data It is fast It is slow DBMS_MVIEWS.REFRESH(‘MV_1,’C’); DBMS_MVIEWS.REFRESH(‘MV_1,’F’); Force view: • Not an existent table. • No base table is necessary • We can create a view with the dummy based table which does not exist in the database. • This view will be having errors. • May be used for application code test.
  • 34. 34 34 Manipulate data in view: Read only: This can be used where you don’t want to manipulate data in a view. Check option: This is used where you want to insert data in views by checking condition from where clause. Updateable: You can’t use order by and group by You can’t use analytical and aggregate function. How to Refresh View? ANS: To refresh the Oracle materialized view, call one of the procedures in DBMS_MVIEW. The DBMS_MVIEW package provides three types of refresh operations: DBMS_MVIEW. REFRESH: Refreshes one or more Oracle materialized views. MATERIALIZED VIEW LOG??? • Materialized view logs are used to track changes (insert, update and delete) to a table. • Purging materialized view logs. • It show no of changes made to a table. • If you refresh materialized view then this gets to zero. INDEX: INDEX is a database object. It plays key role in performance tuning. It is prefereable to create index on all varchar clause column in a query. It is used by the oracle server. It is based on rowid. Should be created when less of rows to be retrieved in a large table. It will effective if we Want to retrieve 4% of rows from the table. TYPES OF INDEX? B-TREE INDEX Balance tree index When We Have high cardinality(low duplicates it is preferable to create B-Tree index. Column that contains more than 100 unique records BITMAP INDEX When We Have low cardinality(high duplicates) it is preferable to create B-Tree index Column that contains less than 100 unique records FUNCTION BASED INDEX When We create index on functional based column it is functional index. It is not guaranteed that create functional index will be used all the time. Oracle optimizer will decide whether it should be used or not based on the cost effect.
  • 35. 35 35 Trunc() column name Upper() column name What is an Index? An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table. How you will avoid your query from using indexes? By changing the order of the columns that are used in the index, in the Where condition, or by concatenating the columns with some constant values. INDEX:- • It is used to improve the performance of query retrieval. • Index can be either Unique or Non-Unique index 1. UNIQUE INDEX : • It is created automatically when a user defines a primary/unique constraint for a column. 2. NON – UNIQUE INDEX : • Created by the user to speed up the retrieval of rows. • Maintained by oracle server WHEN TO CREATE INDEX :- • When a table is large. • When most of the queries are expected to retrieve less than 4% of rows from the table. • When a column contains a wide range of values. • When column is most often used as a condition in a query. • When a column contains large number of null values. WHEN NOT TO CREATE INDEX :- • When a table is small. • When most of the queries are excepted retrieve more than 4% of rows from the table. • When column contains a large number of duplicates. • When column is not most often used as condition in a query. • When a table is updated frequently.
  • 36. 36 36 What is the unique Index? Unique Index: For creating a unique index, the user has to check the data in the column because the unique indexes are used when any column of the table has unique values. This indexing does not allow the field to have duplicate values if the column is unique indexed. A unique index can be applied automatically when a primary key is defined. What is Clustered Index in SQL? Clustered Index: The clustered index is used to reorder the physical order of the table and search based on the key values. Each table can have only one clustered index. The Clustered index is the only index which has been automatically created when the primary key is generated. If moderate data modification needed to be done in the table then clustered indexes are preferred. What is the Non-Clustered Index in SQL? Non-Clustered Index: The reason to create non-clustered index is searching the data. We well know that clustered indexes are created automatically primary keys are generated, but non-clustered indexes are created when multiple joins conditions and various filters are used in the query. Non- Clustered Index does not alter the physical order of the table and maintains logical order of data. Each table can have 999 non-clustered indexes. What is the difference between clustered and a non-clustered index? A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A Nonclustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. What is Index • It is used to improve the performance of query retrieval. • Index can be either Unique or Non-Unique index What is UNIQUE INDEX : • It is created automatically when a user defines a primary/unique constraint for a column. What is NON – UNIQUE INDEX : • Created by the user to speed up the retrieval of rows. • Maintained by oracle server
  • 37. 37 37 WHEN TO CREATE INDEX? • When a table is large. • When most of the queries are expected to retrieve less than 4% of rows from the table. • When a column contains a wide range of values. • When column is most often used as a condition in a query. • When a column contains large number of null values. WHEN NOT TO CREATE INDEX? • When a table is small. • When most of the queries are excepted retrieve more than 4% of rows from the table. • When column contains a large number of duplicates. • When column is not most often used as condition in a query. • When a table is updated frequently. Clustered Index Non-Clustered Index A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A Non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. B-Tree Index Bitmap Index Functional Index B-Tree index is an index that is created on columns that contain very unique values Bitmap is a method of indexing, offering performance benefits and storage savings Function-based indexes allow you to create an index based on a function or expression. B-Tree works best with many distinct indexed values Bitmap works best with many distinct indexed values CREATE INDEX idx_emp_id ON employee (id); CREATE BITMAP INDEX idx_emp_gender ON employee(gender); CREATE INDEX index_name ON table_name(function(column_name)); High Cardinality,Less Duplicates Low Cardinality, More Duplicates What is an Oracle index? An index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.
  • 38. 38 38 What are the different index configurations a table can have? A table can have one of the following index configurations No indexes A clustered index A clustered index and many nonclustered indexes A nonclustered index Many nonclustered indexes. How to know which index a table is using? SELECT table_name,index_name FROM user_constraints. GTT: GLOBAL TEMPOARY TABLE:- • It is session level table. • It stores data only in session level once the session is close, all the data will be truncated or flushed out and only structure remains • It is used to store parameters values for the procedures • It is used to session level testing. • Data in temporary table is stored in temp segments in the temp table space. • Data in temporary tables is automatically deleted at the end of the database session, even if it ends abnormally. • Views can be created against temporary tables and combinations of temporary and permanent tables. • Temporary tables can have triggers associated with them. • Indexes can be created on temporary tables. The content of the index and the scope of the index is the same as the database session. TYPES :- → ON COMMIT PRESERVE ROWS This indicates that data should be present till the session ends. → ON COMMIT DELETE ROWS • This indicates that data should be deleted at the end of this transaction. • It is the default one. GTT WITH Clause (i) The main difference is that the temporary table is a stored table. (i) It will not saves in database. (ii) Views can create in GTT (ii) Views cannot create in WITH Clause. (iii) Index can be create in GTT (iii) Index cannot create in WITH Clause.
  • 39. 39 39 Global temporary tables GTT Views Global temporary tables in Oracle are permanent database objects that store data on disk and visible to all sessions. An Oracle VIEW, in essence, is a virtual table that does not physically exist. Rather, it is created by a query joining one or more tables. PARSING :- Oracle needs to execute some task before executing SQL query (which is received from user). This process is called Parsing. 1. SYNTACTIC CHECK :- → Oracle parses the syntax to check for misspelled SQL keywords. 2. SEMANTIC CHECK :- → Oracle verifies all table names & column name from the data dictionary table and check to see if user is authorized to view data. 3. OPTIMIZATION :- → Oracle creates an execution plan on schema statistics. → If the entire above task performs then it is called hard parsing. → If only syntactic check & semantic check perform then it is called soft parsing. → Soft parsing occurs when you use ‘cursors’. SUB QUERYS & PIVOT: A query embedded within another query is called sub query. There are two types of sub query they are SINGLE ROW SUB QUERY When a sub query returns one row then it is called single row sub query. MULTI ROW SUB QUERY When a sub query returns more than one row is called multi row sub query. TYPES :- SCALAR SUB QUERY Whenever a ‘Select’ clause followed by sub query is called scalar sub query INLINE VIEW Whenever a ‘From’ clause followed by sub query is called Inline view or named sub query in a from clause is called Inline view.
  • 40. 40 40 NESTED SUB QUERY Whenever a ‘Where’ clause followed by sub query is called nested sub query. Here first inner query is executed then outer query will be executed. It doesn’t have any reference between inner query and outer query. Inner query runs only once for outer query. CO-RELATED SUB QUERY When the inner query has reference to outer query is called correlated sub query. Here outer query runs first and then inner query is executed. It is user row by row processing. The inner query is executed once for every row of the outer query. It is faster. What are the various types of queries? The types of queries are : Normal Queries Sub Queries Co-related queries Nested queries Compound queries Nested Query Sub Query Correlated Query Sub Query In Nested Query, Inner query runs first, and only once. Outer query is executed with result from Inner query.Hence, Inner query is used in execution of Outer query. In Correlated Query, Outer query executes first and for every Outer query row Inner query is executed. Hence, Inner query uses values from Outer query. Bottom up approach i.e. Inner query runs first, and only once. Outer query is executed with result from Inner query. Top to Down Approach i.e. Outer query executes first and for every Outer query row Inner query is executed. Inner query execution is not dependent on Outer query. Inner query is dependent on Outer query. Performs better than Correlated Query but is slower than Join Operation. Performs slower than both Nested Query and Join operations as for every outer query inner query is executed. Difference between PIVOT and UNPIVOT and Reverse PIVOT PIVOT UNPIVOT Reverse PIVOT The PIVOT statement is used to convert table rows into columns The UNPIVOT operator converts columns back to rows. Reversing a PIVOT statement refers to the process of applying the UNPIVOT operator to the already PIVOTED dataset in order to retrieve the original dataset.
  • 41. 41 41 PL/SQL: • Procedural language structured query language • It is a procedural language extension to SQL • SQL statement puts together in one single block and sends the entire block to the server in one single cell. • Thereby reducing network traffic. Benefits: • Performance benefit • Modularization→(large block of codes into smaller piece) • Portable • Exception handling • Programming features. SQL PLSQL It is a single query that is used to perform DML from DDL It is a block of codes used to write the entire program blocks Execute one statement at the time Executed as a block of code You can’t embed PLSQL in sql You can embed SQL in plsql It tells the database what to do It tells the database how to do things Interaction with database server No interaction with database server Used to manipulate data used to create an application C1%rowcount SQL%rowcount gives how many rows which will run Gives how many those affected in SQL query c-5 ex: 5rows table Sql-50 PERFORMANCE TUNING: • First we have to count all the dates Select count(1) from employees; • If increases in datacount, then we go for the “table stats” Select last_analyzed, T * from all_tables T Where Table_name = ‘emp_perF’ • Check for last analyzed will be in todays date otherwise Begin Dbms_statts.gather_table_stats(‘HR’,’emp_perF’) • Then we go for ‘explain plan’ Explain plan for Select E.ID, P_first_name from Employee E, Emp_perF P Where E.ID= P.employee_id; • Explained, then Select * from table(DBMS_XPLAN.DISPLAY());
  • 42. 42 42 Explain Plan: • Always read from last /reverse • If the table contain number of bytes high and cost high go for that table. Operation in explain plan: Types of join : Hash Join(check =): • When we join large table with small table • Optimizer will create hash memory • Then, values of small tables stored in a hash memory • Hash memory created in large table only • Then go for equality check Nested loop Join: • Co-related query • When we have less no of results set • when join two large table Merge join: Other than equality check Oracle Optimizer: RBC-Rule based optimizer →(before 11g only RBC) CBC-Cost based optimizer BMC Remedy: • it is ticketing tool • for any issues we can raise and clear it • way to ticket track i. request(configuration) ii. incident (severity issue) iii. problem management (code change, too built) iv. change management SVN Tool: (sub version tool): • it is a centralized version control system • open source tool for version control • it used to manage the current and previous version of files like source code, documentation & file. • (SVN tortoise) our version (Apache made)
  • 43. 43 43 ANONYMOUS & CURSOR BLOCK: ANONYMOUS BLOCK • PL/SQL block which can be created & used in same session but they will not be stored in server as database object. • It does not have any name assigned to them. Declare Begin Exception(optional) End %type: Used to retrieve datatype of single column form a table %rowtype: Used to retrieve datatype of entire column form a table CURSOR BLOCK • Cursor Stores the result of SQL query and manipulates in temporary work area. • Cursor can hold more than one row but it process row by row (loop). • Cursor holds set of rows called active rows. • We can perform DML operation in cursor by IF statement. • The cursor is a pointer to this context area • Oracle creates context area for processing an SQL statement through the cursor. There are two type of cursor 1. Implicit cursor 2. Explicit cursor 3. Implicit cursor: It is automatically generated by oracle while SQL statement is executed. Explicit cursor: It is defined by user or programmer to gain more control over the context area. SYNTAX: Cursor <cursor name> is Select_statement. Implicit cursor Explicit cursor No need cursor keyword for declare Requires declaration of cursor keyboard returns one row Returns one or more rows Automatically created by Oracle whenever SQL statement is executed Programmer defined cursor for control over context area Simple select query Row by row fetch Default cursor Defined cursor
  • 44. 44 44 ATTRIBUTES OF CURSOR: %NOTFOUND, %FOUND, %ISOPEN, %ROWCOUNT. %NOTFOUND: Loop Runs For Multiple Value Output Until Condition Is True Loop runs for all values Returns Boolean result • True→ not fetch record else fetch record %FOUND: Loop Runs For Only One Value Output Until Condition Is False Loop runs for only one value If it is true then fetch records false then not fetch records %ROWCOUNT: To Fetch The No Of Rows Affected Rows In Complete Cursor Record Return numeric value Gives actual count of records that are affected by DML activity %ISOPEN: Returns True If The Cursor Is Open, Else False. Boolean result true/ else falls cursor already opened Difference between Cursor and Ref Cursor Cursor Ref Cursor A cursor is really any SQL statement that runs DML (select, insert, update, delete) on your database. A ref cursor is a pointer to a result set. This is normally used to open a query on the database server, then leave it up to the client to fetch the result it needs. What is the difference between Explicit and Implicit Cursors? An Implicit cursor is one created "automatically" for you by Oracle when you execute a query. It is simpler to code An Explicit cursor is one you create yourself. It takes more code, but gives more control - for example, you can just open-fetch-close if you only want the first record and don't care if there are others DBA_DATA_FILES. COLLECTIONS: • it is an ordered group of elements having the same data type • Each element has a unique subscript that represent its position in the collection • It is one dimension
  • 45. 45 45 VARRAY: • It is dense and bounded • Varray variable size array • When you create a varray you must declare a maximum number of columns • They use sequence number as subscript • We can’t delete in VR • We can’t rent only last to first • Stored in a database 10 33 45 51 67 1 2 3 4 5 X(1)=10 , X(4)=51 Index value(above table 1,2,3,4,5) is created by oracle DBMS Collection method: • First/last • Next/prior • Count • Extends • Trim • Delete • Exits Datas.csv(hat file)→server layer path root/script/a,g/ss/file/data→ staying table/delta table Emp_stg)→Target table(query→select→all files) Nested Table: (table of ) • nested table is the column type that hold a set of values • It is prased and unbounded • Main advantage is no limits • It will create new value add boxes • We can delete in nested table • It can be stored in a database Associative array: (table of ( ) index by PLS_integer/ binary_integer): • Set off key values pair • Each key is unique and the key can be either string or integer • Stored in ram level only • It is capable of holding an unspecified number Limit 10: For reduce memory use: Fetch C1 bulk collect into V_RC limit 100;
  • 46. 46 46 PLS INTEGER BINARY INTEGER When a PSL-Integer calculation overflow an exception is raised When a binary-Integer calculation overflow no exception is raised It is Subset of binary integer It is Subset of integer Stores data in arithmetic format (requires less storage) Stores data in binary format It is faster than number and binary integer (better performance) It is also faster, but slower than pls_integer It uses machine arithmetic It uses library arithmetic For All For Fetch and insert/ update / delete in one shot Fetch and insert/ update / delete in loop format One for all, only one DML operation We can use multiple DML operation inside for in Loop Bulk binding operation Bulk Binding: Combination of Bulk collect and for all Bulk collect → fetch the data → using ‘select’ For all→ process the data→using ‘insert’,’update’,’delete’. Advantage of bulk collect: • Only one context switch (collect data from PLSQL engine to SQL engine in one loop) • Increases the performance by reducing the interaction between database and PL/SQL engine • Limit clause→ for reduce memory use Disadvantage: • Issues in memory allocation Nested table array V array Nested tables are unbounded. VARRAYs are always bounded (varying arrays have a limited number of entries) Initially dense but can become sparse through deletions. Never sparse. Order is not preserved When you store and retrieve a VARRAY, its element order is preserved Can be indexed Cannot be indexed
  • 47. 47 47 Associate array or Index by table Nested table array V array Unbounded i.e. the number of elements it can hold is not pre-defined Unbounded i.e. the number of elements it can hold is not pre-defined Bounded i.e. holds a declared number of elements, though this number can be changed at runtime Can be arbitrary numbers or strings. Need not be sequential. Sequential numbers, starting from one Sequential numbers, starting from one Index by tables can be used in PL/SQL programs only, cannot be stored in the database. Can be stored in the database using equivalent SQL types, and manipulated through SQL. Can be stored in the database using equivalent SQL types, and manipulated through SQL (but with less ease than nested tables) Works as key-value pairs. e.g. Salaries of employees can be stored with unique employee numbers used as subscripts sal(102) := 2000; Similar to one-column database tables. Oracle stores the nested table data in no particular order. But when you retrieve the nested table into a PL/SQL variable, the rows are given consecutive subscripts starting at 1. Standard subscripting syntax e.g. color(3) is the 3rd color in varray color Most flexible. Size can increase/ decrease dynamically. Elements can be added to any position in the list and deleted from any position. Almost like index-by tables, except that subscript values are not as flexible. Deletions are possible from non- contiguous positions. Not very flexible. You must retrieve and update all the elements of the varray at the same time. Hash tables Sets and bags Arrays PROCEDURES: Stored procedure: • It is named P L SQL subprograms • It is compiled and stored in database for repeated execution • It can accept an argument and can return a value • It is a schema object • It improves the performance of an application by reducing network trafficking • It can accept parameter • If procedure is created outside the package then it is called as stored subprogram or standalone subprogram • If procedure is created in package then it is called as packaged subprogram.
  • 48. 48 48 Note: • We can create a procedure inside anonymous block • We can create procedure inside package • We can create procedure inside procedure • Used to business logic development • May or may not have return value Local procedure [private procedure]: • Whenever you create a procedure inside the anonymous block it is called local procedure • This procedure doesn’t store in database and cannot be called outside anonymous block Parameters: • This indicates that value must be supplied when you execute the procedure • in , out , in/out To view entire query of a procedure: select * from user_source where name = ’P_first’; Create Or Replace: it would not affect grants which is given to objects and not affect the dependencies select * from user_dependencies create: completely clears the grams and dependencies REF CURSOR: Cursor→static Ref cursor→ dynamic • It is a data type • It will close implicit • entire table result output • mostly give ref cursor to front end user strong ref cursor: • we know structure at compilation time • it returns a value which can be of any data type weak ref cursor: • doesn’t know structure at compilation time • query result will be stored
  • 49. 49 49 bind variable: (:Y) • it is a placeholder in SQL statement • by using this you can write a SQL statement that accept inputs or parameter at runtime • it can improve SQL query performance also Hard phrase Soft phrase Query→buffer cache→data block Query→buffer cache Select * from V$SQL order by first_load_time DESC. Each query has unique ID 13 digit EXCEPTIONS: • Exceptions are used to handle error in PLSQL block • The action to be performed when error occurs Rules: • Exception must be declared the declaration section • Exception must be raised in exception section • Exception should be handled exception section SQLERRM→SQL ERROR MESSAGE SQL CODE→ SQL ERROR CODE Type of exceptions: • Pre-defined (oracle error no→error message) • Non-predefined(oracle error no→own message) • User defined(own error no→own message) Pre-defined: • This can be called as system defined exception or unnamed system exception • PLSQL predefined some common Oracle error as exception • 20 predefined exception (SYS_INVALID_ROWID, CURSOR_ALREADY_OPENED, NO_DATA_FOUND, TOO_MANY_ROWS, ZERO_DIVIDE, INVALID_NUMBER, VALUE_ERROR, OTHERS, INVALID_CURSOR) Non-predefined: • The system exception for which oracle doesn’t have name is called non-predefined (or) unnamed system exception. • Hear, we use ‘PRAGMAEXCEPTION_INIT’ is used to bind defined exception to a particular error number of others
  • 50. 50 50 Rules for writing exception: • If you use more than one exception in a block then only one exception fires that will be based on first error occurrence. • If you use ‘other’ exception another exception then ‘other’ it must be lost in exception section. User Defined: • Apart from system exception you could explicitly define and raise exception. • In user defined we use ‘RAISE’ keyword to forcibly raise an exception • Error range(-20000 to -20999). Save exception: The save exceptions clause allows the bulk operation to continue past any exceptions, but if any exceptions where raised in the whole operation, then it will jump to the exception handler once the operation is complete. FUNCTIONS: • it is a PLSQL program which can be called as stored function • It must always return a value • It is a compiled and stored in database for repeated execution • It can accept arguments • We can also call to function in select statement • Return only one value for multiple we use out parameter function • Functions compute a value • Function also can be called as part of execution • Function cannot perform DML • Function can use only parameter IN • It is a schema object Note: • We can create function inside the package • We can create function inside anonymous block • We can create function inside the procedure • If a function is created outside the package then it is called stored subprogram • If it is created inside the package then it is called package subprogram What are functions and their usage in SQL? SQL functions are simple code snippets that are frequently used and re-used in database systems for data processing and manipulation. Functions are the measured values. It always performs a specific task. The following rules should be remembered while creating functions:
  • 51. 51 51 o A function should have a name, and the name cannot begin with a special character such as @, $, #, or other similar characters. o Functions can only work with the SELECT statements. o Every time a function is called, it compiles. o Functions must return value or result. o Functions are always used with input parameters. SQL categories the functions into two types: o User-Defined Function: Functions created by a user based on their needs are termed user-defined functions. o System Defined Function: Functions whose definition is defined by the system are termed system-defined functions. They are built-in database functions. SQL functions are used for the following purposes: o To perform calculations on data o To modify individual data items o To manipulate the output o To format dates and numbers o To convert data types Procedure Function Procedure perform an action Function performs complete value It can accept and may or may not return a value It can accept the value and must return a value It cannot be called from select statement It can be called from select statement Procedures can have multiple out parameters Function are generally restricted to return a single value Not useful in queries More useful in queries It is slightly easier to call It is not easier to call compared to function PACKAGES: It is group of logically related sub-programs. It is schema object. It has 2 parts 1.)specification and 2.)Body Local or Private Procedure: The subprogram defined in specification should be defined in body. The subprogram defined in body may or may not be defined in specification. Over Loading Concept: When we have some sub program in packages difference in no of parameters, name of parameter, , datatype of parameter. Package Specification: • It contain a declaration • You can decide cursor, type, variable, sub-program, exception and constant • You can create a package specification without package body
  • 52. 52 52 • Whatever declared in package specification is global. • Subprogram which is defined in specification should be declared in body. • we can compile only specification Package body: • it contains definitions • it contained definition of subprogram that is listed in package specification • it also contain the definition of subprogram that is listed in the package specification. • It also contains local procedure it will be one time procedure it is also called as private procedure. • You can delete the package body without deleting the package specification. Note: • Subprogram which is defended package may or may not be present in specification. • You can compile specification body by using • We can compile body also. Advantages: • When package subprogram are executed for first time it is loaded to memory, further execution of subprogram doesn’t require disk I/O. • Packages supports Overloading concepts. • Subprogram defend in package specification are global subprogram or global variable in specification. Overloading: [by using assign parameters]: • P1 (difference in number of arguments) • P2 (difference in parameter data type) • P3(difference in their parameter name) Grant execute on (pkg132 systems); SQL query tuning: • Select field instead of select * • Avoid using select distinct • Create join using with inner join [not using word] • Use where instead of having for filter purpose • use wild card operator at the end of phrase only (%) • use limit to sample query result • run your query during off peak hours Pragma serially reusable: • Memory allocation of constant • Declaration in specification
  • 53. 53 53 Bodiless packages: • You can use the bodiless packages for execution • Here this variable exists only in this session Performance tuning: • First we will check for the date counts • We will go For the table statistics which place primary role in performance tuning ( no of rows in explain plan is based on status gathered] • If not we use gathered status for all the table • Then we will check for the index and make sure index are in valid state or not • If not we will rebuild the index Block level: • for any block level tuning we will go for DBMS profiler (it’s getting ROWID and long running SQLID then process goes for explain plan • we also get AWR report from DBA Team getting SQL statistics information that is (automated workload repository) from there we get long running SQL ID) • then we take explain plan for the query • From explain plan we get what type of scan it goes for o Table full scan o Index scan o Index unique scan o Index range scan o Index full scan o Index fast full scan • Then we use the hints to change the optimizer plan • We check up on the cardinality, costs and bytes like this performance tuning goes on. PARTITION AND INDEX (ORACLE INDEX):: TABLE PATITIONING:- • Table partition is a method of splitting an object (table or index) into separate partitions based on some criteria. The criteria can be date, number or character. • If table contains more number of rows then queries takes more time to execute a query and table becomes harder to manager. So in that case we use table partitioning to overcome those issues. We can partition Table, Index & Materialized View. • Partition allows table, index and index organized a table to be subdivided into smaller pieces • It is used to reduce the cost and improving performance of application.
  • 54. 54 54 Advantages: • Increase performance • Increase availability • Enable storage cost optimization • Enable simple management Where we use: • Tables greater than 2GB • Tables contain historical old data • When content needs to be distributed • when table performance this week What is Partition key? ANS: The partition key is a set of one or more columns that determines the partition for each row. Oracle automatically directs insert, update, and delete operations to the appropriate partition through the use of the partition key. What is use of Partition? ANS: The PARTITION BY clause sets the range of records that will be used for each "GROUP" within the OVER clause. In your example SQL, DEPT_COUNT will return the number of employees within that department for every employee record. What are the types of Partition? ANS: Oracle provides the following partitioning methods: Range Partitioning. List Partitioning. Hash Partitioning. Composite Partitioning Table Partition: • Segmenting the data • Partition allows table, index are sub divided into small pieces • It reduces cost and improves performance of the application When we go for: • In master table • Table greater than 2 GB • Tables contain historically old records • When table performance is weak
  • 55. 55 55 Advantages: • Increases performance • Increases availability • Optimize the storage cost • Simpler management Types: • Range partition • List partition • Hash partition • Composite partition Range Partition: CREATE TABLE sales_range (salesman_id NUMBER(5), salesman_name VARCHAR2(30), sales_amount NUMBER(10), sales_date DATE) PARTITION BY RANGE(sales_date) INTERVAL(NUMTOYMINTERVAL(1,'MONTH')) (PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','MM/DD/YYYY'))); Interval partition: • Available only after oracle 11g version • When we adding new data, there must be error (not in range) • This overcome by using interval partition • When max limit reaches oracle itself create a partition called interval partition • When we drop the table partition then data also trauncated List partition: (region wise partition): CREATE TABLE sales_list (salesman_id NUMBER(5), salesman_name VARCHAR2(30), sales_state VARCHAR2(20), sales_amount NUMBER(10), sales_date DATE) PARTITION BY LIST(sales_state) (PARTITION sales_west VALUES('CHENNAI', 'MADURAI'), PARTITION sales_east VALUES ('New York', 'VADODRA', 'DELHI'), PARTITION sales_central VALUES('BANG', 'COCHIN'), PARTITION SYS_PART VALUES('COIM'), PARTITION SYS_PAR1 VALUES('TRICHY'), PARTITION sales_other VALUES(DEFAULT));
  • 56. 56 56 Automatic: • Only after 12c version • When we insert ‘AAA’,’BBB’ it automatically inserts their loation • Otherwise it create sales_others by own name. Hash Partition: • It is partitioned by datablocks • Most not used • When we don’t know to do partition on which column in that case we go for hash partition Composite Partition: • Combination of any two partition Global index: Create on the table Local index: • Create on each partition • Effective once Prefixed local index: • Create index year_idx On all_fact(sale_date)→ partition key Local (partition sales_jan 2021); Sub-prefixed local index: Create index year_idx on all_fac(sale_amount)→partition key Local(partition sale_jan2021); How to create a partition in already created table? • We go for “exchange partition” • Method: a. New table with all partition b. Load data from old to new c. Rename new table d. Drop a old table TRIGGER: • Trigger is a database object which automatically occurs when a triggering event occurs. • Event fires another event • You can enable & disable trigger
  • 57. 57 57 Event option: • DML (insert,delete,update) • DDL (create,alter) • User logon/logoff • System (startup/Shutdown) Used for: • Prevent invalid transaction • Generating values for any derived column • Auditing purpose • To maintain having historic data of core table Restriction: • We cant use DDL in trigger because they have implicit cursor • We cant use commit, savepoint or rollback • We cant call trigger inside any function/procedure • We can call others inside the trigger SELECT * FROM USER_TRIGGER ALTER TRIGGER TRG1 DISABLE Projectin Trigger: We use to capture the history data/table in core schema, it will be capture in the trigger table with userid. Row level trigger Statement level trigger When triggering event takes place many times, that much time trigger is fired When triggering event takes place many times it fires only once to target table For each row clause is present That clause not present Used for data auditing purpose :old word only in row level trigger Used for additional security on the transaction performed in the table Ex: if 1500 rows are to be inserted then 1500 times trigger fires If 1500 rows are to be inserted then only one trigger fires Mutating table / Mutating errors: (ORA-04091) Recursive SQL • If any DML operation is taking place in a table and your trying to make another change in middle of first change. • When we do DML operation on a table, trigger associated with the table automatically fire and make another change (DML) to the same table • This is overcome by using compound trigger • It is 11G new feature
  • 58. 58 58 Compound Trigger: More than one trigger in same table in called compound trigger. It fires as: Before statement level follows by Before row level follows by After row level follows by After statement level Pragma autonomous transaction: • Pragma→complier directive • Provide information to the computer • Performs independent transaction • You must use commit or rollback, otherwise we get error ‘ORA-06519’ • Independent transaction between begin & end without affecting entire transaction or other transaction • We can do DDl,,DML in function & procedure using Pragma autonomous transaction. HINTS AND TABLE REGONIZATION: • Optimizer directive • Used to change the optimizer directive plan Hints of Joining Order: • Leading • Ordered • Used to determine in which order to join the table • Optime will go to RBC Select/*+ordered*/from employees; Hints of access path: • Index /* index(emp_dep_x)*/ • No_index /*+no_index(emp_department_lX)*/ • Append • Full Append: • Direct load datablock • Faster • Not stored in buffer/redo logs Hints for parallel execution: /*+parallel(2)*/ → depend upon space
  • 59. 59 59 Technique is multithreading: • Use multiple I/O to run fast • We need DBA confirmation & proper server space, then only we use the parallel hint • For this DBA team generate certain formula Hints for Join condition: USE_HASH NO_USE_HASH USE_NL NO_USE_NL USE_MERGE NO_USE_MERGE Example: select/* + no_use_hash*/ from employees; Select * from table (DBMS_xplan.Display()); Types of Scan: 1. Table full scan: • Analyse all records in the table. • For look up table , we go for table full scan 2. Index scan: • When we use primary or unique key column in a where clause • It automatically goes for index unique scan. 3. Index range scan: • When we use range between or limits in a where clause 4. Index fast scan: • When a column used in where clause contains index • All column must contain index 5. Index fast full scan: • When a column used in select clause contain index and also columns used in where clause contain index. 6. Index skip scan: • When we create a composite index (A,B) we call only one composite index column where as skip another column using filters Table recognition: By using this we can remove empty blocks in the table Tablespace→multiple space→multiple extend→datablocks Create table ‘HR’,’Prawin’ (Id number name varchar2(50)) Tablespace A; alter table prawin move to buffer_TB; alter table prawin move to A; (by using this, we can shrink the empty blocks)
  • 60. 60 60 NORMALIZATION: What is Normalization? ANS: Normalization is a systematic approach of decomposing tables to eliminate data redundancy and undesirable characteristics like Insertion, Update and Deletion Anomalies. It is a multi-step process that puts data into tabular form by removing duplicated data from the relation tables. What is Normalization in a Database? Normalization is used to minimize redundancy and dependency by organizing fields and table of a database. There are some rules of database normalization which commonly known as Normal From and they are: First normal form(1NF) Second normal form(2NF) Third normal form(3NF) Boyce-Codd normal form(BCNF) Using these steps, the redundancy, anomalies, inconsistency of the data in the database can be removed. What is the primary use of Normalization? Normalization is mainly used to add, delete or modify a field that can be made in a single table. The primary use of Normalization is to remove redundancy and to remove the insert, delete and update distractions. Normalization breaks the table into small partitions and then link them using different relationships so that it will avoid the chances of redundancy. What is Denormalization in a Database? Denormalization is used to access the data from higher or lower normal form of database. It also processes redundancy into a table by incorporating data from the related tables. Denormalization adds required redundant term into the tables so that we can avoid using complex joins and many other complex operations. Denormalization doesn?t mean that normalization will not be done, but the denormalization process takes place after the normalization process. What are the disadvantages of not performing Database Normalization? The major disadvantages are: The occurrence of redundant terms in the database which causes the waste of the space in the disk. Due to redundant terms inconsistency may also occur id any change will be made in the data of one table but not made in the same data of another table then inconsistency will take place, which will lead to the maintenance problem and effects the ACID properties as well.