Вы находитесь на странице: 1из 82

Major Differences between Views and

Materialized Views!.
Views are the virtual projection of an output query or the dynamic view of the data in a database
that is presented to the user whenever requested. Materialized views on the other hand are a nonvirtual schema which is a common part of database warehousing, primarily used for
summarizing, pre-computing, replicating and distributing data etc. Now having said that, lets
move on to some basic differences between Views and Materialized views in order to gain a
better understanding.

Access to the data


The operations performed using Views directly affects the data in the base table. Therefore they
are subjected to the integrity constraints and triggers of the base table.
Materialized views provide an indirect access to the data of the base table. This is due to the fact
that they create a separate schema to store the results of a query.

Storage space
One of the common differences between views and materialized views is the way they take up
storage space. Since Views are the virtual projection of a query result hence they do not take up
any storage area. This helps in reduction of memory usage and encourages the use of Shared
SQL.
Whereas the schema created by Materialized Views take up some storage space as it is saved in
either the same database as its base table or in a different database.

Usage of Views and Materialized Views


Differences between views and materialized views can also be understood in terms of their
usages.
Views have a more restrictive behavior towards a base table.
1. It could be used to isolate an application in order to prohibit any change in base table
definition.
2. It can be used in order to simplify SQL statements for the user.
3. Views could be used to enhance security by restricting access to a predetermined set of
columns and rows

Existence of Materialized Views is transparent to the SQL except when used for query rewrites.
1. Query rewrites are said to improve the performance of SQL execution and are useful in a
data warehouse environment.
2. Users can insert, delete and update the data by means of updatable materialized views.
Apart from these differences between views and materialized views, some other important points
to keep in mind which further clears the concept of views and materialized views are:
1. Views can be based on each other in addition to operating on base tables. A view can
JOIN another view with a table using GROUP BY or UNION clause.
2. Materialized views can be defined on a base table, partitioned table or Views whereas
indexes are defined on Materialized views.
3. Ultimately a materialized view log is a schema object which records changes to a master
table's data so that the materialized view defined on that master table can be refreshed
incrementally.
Sysdate.

Sysdate is a function in oracle database which returns system current date and time.
So lets move ahead and see how we can retrieve system current date and time using Sysdate
function of Oracle Database.
1. How to retrieve system current date using Sysdate function
By default, Sysdate function returns system current date in oracle default date
format which is DD-MON-RR
SELECT Sysdate FROM dual;
2. How to retrieve current date and time using Sysdate function
Using Sysdate function you can also retrieve system current time along with the
date. Let's see how
SELECT TO_CHAR(Sysdate, DD/MON/YYYY HH24:MI:SS) FROM dual;
In the above query, in order to print the system current time along with the date we
used TO_CHAR() conversion function where we passed Sysdate as the first
parameter of the function and a date format. As you can see in the date format, we
have explicitly specified that along with the date (DD/MON/YYYY) we also want time
of the system (HH24:MI:SS). This query upon execution will give you system current
date along with the system current time.

3. How to retrieve system current time using Sysdate function


Its also possible to find out just the current time of your system using Sysdate
function of oracle database.
SELECT TO_CHAR(Sysdate, HH24:MI:SS) FROM dual;
Query is pretty similar to the previous one, the only difference is the format which
we have specified in the TO_CHAR() conversion function. As you can see, unlike the
previous query this time format involves elements only for the system time. This
query will return you the system current time on execution.

COALESCE ( ).

Similar to NVL ( ) and NVL2 ( ) functions which we have seen in previous tutorial, COALESCE
( ) is also a function which will help you in handling null values stored. However unlike NVL ( )
and NVL2 ( ) functions, COALESCE ( ) function does not restrict you with the number of
parameters you pass to the function.
Coalesce ( ) function can take N number of arguments and as a result it returns the first not null
parameter from the argument list. If in case all the arguments are evaluated as null then this
function returns NULL as a result.
Syntax
COALESCE (expr1, expr2 exprn);
Examples of COALESCE ( ) Function In Oracle Database
In order to better explain you the working of COALESCE ( ) function lets start with
some simple examples.
Example 1:
SELECT COALESCE (null, 1, 2, 3) FROM dual;
As you can see in the above example we have passed 4 parameters for the
COALESCE ( ) function from which the first parameter is NULL and as mentioned
before, a COALESCE ( ) function returns the first Not Null value from the parameter
list. Thus on execution the result will be 1 which is the first Not Null value in the
argument list.
Example 2:
SELECT COALESCE ('Rebellion', 'RIDER', null) FROM dual;
In this example I have passed three parameters to the COALESCE ( ) function in
which the first two parameters are character string and the third parameter is a
NULL. On successful execution this query will return the first Not Null value from

the argument list, which is the string Rebellion in our case.


The core purpose of above two examples is to make you understand How COALESCE
( ) function works. Now lets take a step ahead and see a slightly more complex yet
easy to understand example.
Example 3:
For the demonstration of this example I have created a table with the name
AVENGERS which has four columns:
1. First name
2. Last name
3. Mobile number
4. Landline.

Ta
ble: Avengers

For better understanding of the concepts I have also inserted some rows into this table.
Now suppose you have to write a query or say make a report to list the name of all the avengers
along with their contact numbers. However what if I say that some of the avengers only have

mobile number or some only have landline number? In this case the possible queries that may
strike your mind will be:
SELECT first_name, last_name, mobile FROM avengers;
Or
SELECT first_name, last_name, landline FROM avengers;
Both the queries are correct but the only problem with them is that you will not be
able to get the contact of all those avengers who dont have either mobile number
query1 or landline number query 2.

There are two solutions to this problem. First is to write a query which will return the data from
both landline and mobile columns.
SELECT first_name, last_name, mobile, landline FROM avengers;
The second and more efficient solution of this problem is that you can use
COALESCE function on the columns landline and mobile. That will make your report
clearer.
SELECT first_name, last_name, COALESCE (mobile, landline) AS contact FROM
avengers;

Thats all about Coalesce Null Function In Oracle Databae. Hope it helped you in understanding
this concept better. Please share it with your friends on social networking and help me reach out
to more people. Thanks and have a great day!

NVL2.
NVL2 is the second null function in the series of Null function. We can say its a null function
like NVL but on steroids as NVL2 expands the functionality of NVL function. NVL2 function
lets you substitute the values when a null value or a non-null value is encountered.
Syntax
NVL2 (Expression, value1, value2)
Unlike NVL null function NVL2 function has 3 parameters. Expression, value1 and value 2.
First parameter Expression can either be column name or an arithmetic expression whose result
will be evaluated, whereas the second parameter is the value which will be returned if the first
parameter value is Not Null. Furthermore if the first parameter value is Null the NVL2 returns
the third parameter.

In Simple words if the data returned from first parameter is Not Null then value from the second
parameter will be displayed otherwise value from third parameter will be returned.

Example
SELECT commission_pct, NVL2 (commission_pct, 'Not Null', 0) FROM employees WHERE
salary>13000;
On execution this query will return values in two columns where first column will display the
actual values from commission pct column and second will display the string Not Null where
some actual values exist in commission pct otherwise it will display 0 in place of Null.
Now if you want to display the actual value of commission pct column instead of Not Null string
then you can simply write the column name which is commission pct at the place of this string.
Let me show you how
SELECT commission_pct, NVL2(commission_pct, commission_pct,0) FROM employees
WHERE salary>13000;
Now you have to comment on my YouTube or tweet me on my twitter and tell me. According to
you what are the applications or say uses of this particular function NVL2? Where and how you
can use this function? And if you have a crazy query with this NULL function NVL2 you can
also comment that in the comment section below.

NVL().
As we all know that unlike other programming languages NULL in oracle database does not
signify zero or a blank space rather it is a value that is unavailable, unassigned, unknown, or
inapplicable.
Thus NULL value can a problem and requires intensive handling for driving an accurate result.
Problems!!! What kind of problems? Glad you asked.
1. Result is always NULL
If you are performing any arithmetic expression containing Null as an operand then
oracle will evaluate that expression as null. As you can see here.
2. Hard to distinguish
Though some graphic user tools such as SQL Developer will show you NULL value
stored in a column explicitly but in case you are working on your database using
command prompt, Linux terminal or SQL*Plus interface then in most of the cases these
tools show nothing in place of null.

Now the question arises here is how to overcome these problems?


To handle NULL in oracle database we have a few pre-defined functions which come as freebies
in the package. These functions are NVL, NVL2, NULLIF, COALESCE and many more.
So lets dig in and see what are these functions for and what are they capable of doing. We will
start with the first function NVL.

NVL
Using NVL function you can substitute a value in the place of NULL values. The substituted
value then temporarily replaces the NULL values in your calculations or expression. Remember
that the substituted value only replaces the NULL value temporarily for the session and does not
affect the value stored in the table.
Here is the syntax of NVL function.
NVL (exp, replacement-exp)
As you can see NVL function takes two parameters exp and replacement exp. First parameter
exp can be a column name of a table or an arithmetic expression and the second parameter
replacement expression will be the value which you want to substitute when a NULL value is
encountered.
Always remember the data type of both the parameters must match otherwise the compiler will
raise an error.

Example
SELECT NVL (commission_pct, 0) FROM employees
WHERE salary>13000;
On execution all the null values in the result set will get replaced by 0. Similarly we can use
NVL null function while performing arithmetic expression. Again lets take the same arithmetic
expression which we used in the previous query where we added 100 to the values of
commission pct column.
SELECT NVL(commission_pct,0), NVL(commission_pct,0)+100 FROM employees WHERE
salary>13000;

LPAD & RPAD.

The story isnt finished yet and I am back to complete it!!! Last year I had done some tutorials on
SQL functions and this one is in the continuations of those. So lets get started.
These two widely used functions return an expression padded with special characters to a
specific length. The expression can be a value stored in a column or any user specific expression.
LPAD
LPAD stands for Left Pad. This function returns an expression padded with the
special character to the left side of that expression returned.
RPAD
RPAD stands for Right Pad. RPAD function returns an expression padded with the
special character to the right side of that expression returned.
Apart from the name both the functions share similar syntax.
LPAD (expression/column name, length, padding-expression)
And
RPAD (expression/column name, length, padding-expression)
Expression/column name: First input is the expression which you want to pad.
This can be any mathematics expression, character strings or a column name.
Length: Length is the second parameter, using which you can set the maximum
length of the return value as it is displayed on your screen.
Padding-expression: The last parameter is padding expression which is a text
expression that specifies the padding characters. The default value of padding
expression is a single blank. Here also as a padding expression you can either
specify a special character such as asterisk (*) sign, Hash (#) or dollar ($) sign etc.
or a mathematics expression or for that matter string. But generally we use special
characters.

Examples
1. LPAD and RPAD with Character String as Expression.

SELECT LPAD ('RebellionRider', 20, '#') FROM dual;

In this query RebellionRider is our expression which has a length of 14 characters,


and hash sign (#) is our padding character which will get added to the left side of
the string RebellionRider, and 20 will be the total length of the string.
By Total I mean padding expression + the expression which is a string i.e.
RebellionRider in our case.
Lets try RPAD function in the same query
SELECT RPAD ('RebellionRider',

20,

'#') FROM dual;

2. LPAD and RPAD with Column name


SELECT LPAD (salary, 20, '*') FROM employees;

Here in this query we are using values stored in salary column of employees table
as the first parameter of LPAD function. We set the total length of the result string
on 20 and we are using asterisk sign as our padded character. Lets execute

Lets execute the same query with RPAD function


SELECT RPAD (salary, 20, '*') FROM employees;

Intersect and Minus


In the previous tutorial we learnt about Union and Union All set operators, the differences
between them and their usage. Now in this tutorial we will learn the remaining Set operators in
oracle database which includes Intersect and Minus.

Intersect Set Operator


The INTERSECT operator returns rows that are common to both queries. Lets see an example.
For this example I will be using the same tables from the previous tutorial that are Cricket and
Football.
SELECT first_name, last_name FROM cricket
INTERSECT
SELECT first_name, last_name FROM football;
On execution the resulting set will consists of only those rows that are common to both these
tables.

Minus Set Operator.

The MINUS operator returns rows in the first query that are not present in the second query. The
definition is self-explanatory. Therefore if we execute MINUS set operator on cricket and
football tables then all the rows from cricket table which are not present in the second table i.e.
football will get returned and vice versa.
SELECT first_name, last_name FROM cricket
MINUS
SELECT first_name, last_name FROM football;
On execution the result set of this query will contain two rows from the cricket table which were
not present in the football table.

Union and Union All Set Operators


Set operators allow us to combine rows returned from two or more queries. In SQL we have four
set operators.
1. Union
2. Union All
3. Intersect
4. Minus
In this tutorial we will learn the concept of Union and Union All set operator. For the
demonstration purposes I have created and populated two tables Cricket and Football. Both of
these have two columns first name and last name with the same data type which is Varchar2. I
have also inserted some rows into the tables, here are the screenshots of the data in these tables.
Both these tables have 3 rows of data and if you will look carefully you will notice that there is a
duplicate row in both of them. This is row 1 where first name is Clark and last name is Kent.
Well now that we have terminologies straightened out lets come to the topic and see what are
Union and Union All Set Operators in Oracle SQL.

Union Set Operator


The UNION set operator returns results from all the participating queries after eliminating
duplications. Lets see the example

SELECT first_name, last_name FROM cricket


UNION
SELECT first_name, last_name FROM football;
Here we have 2 separate queries. In the first query we are selecting rows from first name and last
name column of Cricket table and in the second query we are retrieving rows from first and last
name column of Football table and both these queries are bound using union set operator.
On executing this query all the rows of both the columns of both the tables will be returned
except the duplicate one.

Union All Set Operator


The UNION ALL operator returns results from all the participating queries, including the
duplicate rows. This means that if we will execute the same query then we will get all the rows
returned from both the tables along with the duplicate one.
Let me demonstrate this to you. For that I will copy this query and modify it accordingly.
SELECT first_name, last_name FROM cricket
UNION ALL
SELECT first_name, last_name FROM football;

Restrictions of Set Operators in Oracle Database

The expressions in the SELECT lists must match in number and data type.

Parentheses can be used to alter the sequence of execution.


The ORDER BY clause:
Can appear only at the very end of the statement
Will accept the column name, aliases from the first SELECT statement, or the positional
notation

Duplicate rows are automatically eliminated except in UNION ALL.


Column names from the first query appear in the result.
The output is sorted in ascending order by default except in UNION ALL.

Tablespace- The Introduction


I promised this tutorial a while ago but never had a chance to do it since then. However here I am
today, finally starting a new series on Tablespaces in Oracle database.
Oracle database stores schema objects such as tables, indexes, Views etc. logically into the
tablespace and physically in datafiles associated with corresponding tablespace. So we can say
Tablespace are logical storage units made up of one or more datafiles.
I know this whole deal with datafiles and tablespaces is slightly confusing but dont worry. Let
me try to explain it to you in detail.

Datafiles
Datafiles are physical files stored on your disk created by oracle database and has .dbf extension.
These files are not only capable for storing tables but also indexes, synonyms, views and other
schema objects created by you. These are physical files because they have existence on your
OSs file system and you can see them. These files are written by database writer (DBWR)
processes and used by oracle database for proper functioning of your database system. Do not try
to modify these files manually. A datafile cannot be shared between multiple tablespaces which
means that every datafile belongs to a specific tablespace.

Tablespaces
Then comes the Tablespace. Tablespaces are logical entity in your database and logically
organized data which is physically stored in datafiles. They are called logical storage units
because they are not visible in the OSs file system. A tablespace belongs to only one database,
and has at least one datafile that is used to store data for the associated tablespace. You can also
define tablespaces as logical storage units made up of one or more datafiles. One tablespace can
have up to 1022 datafiles this number also depends upon your OS.

Types of Tablespaces
We can differentiate tablespace on the basis of two factors
1. Type of Data
2. Size of Data
Type of data consists 3 kinds of tablespace including
1. Permanent Tablespace
2. Temporary Tablespace
3. Undo Tablespace
And on the basis of Size of Data we have 2 kinds of tablespace
1. Big file tablespace
2. Small file tablespace

Permanent Tablespace
It is the tablespace which contains persistent schema object which means the data stored in the
permanent tablespace persists beyond the duration of a session or transaction. Objects in
permanent tablespaces are stored in datafiles.

Temporary tablespace
On The contrary temporary tablespace are the tablespaces which contain schema objects only for
the duration of a session which means that data stored in the temporary tablespace exists only for
the duration of a session or a transaction. Objects in temporary tablespaces are stored in
tempfiles.

Undo Tablespace
Then there comes Undo tablespace. Undo tablespace is a special type of tablespace used by
oracle database to manage undo data if you are running your database in automatic undo
management mode. Undo tablespace stores data permanently which means that undo tablespace
are permanent in nature. Undo tablespace play a vital role in providing

Read consistency for SELECT statements that access tables which in turn consist of rows
which are in the process of being modified.

The ability to rollback a transaction that has failed to commit.

Next we have Big-file tablespace and small file tablespace.

Big-File tablespace
The new concept started from Oracle 10g. Big file tablespace is best suited for storing large
amounts of data. Big file tablespace can have maximum 1 datafile which means bigfile
tablespaces are built on single data files which can be as many as 232 data blocks in size. So, a
bigfile tablespace that uses 8KB data blocks can be as much as 32TB in size.

Small-File tablespace
This is the default type of tablespace in oracle database. Small file tablespace can have multiple
datafiles and each datafile can be as many as 222 data blocks in size. A small file tablespace can
have maximum up to 1022 data files but this number depends on your Operating system also.
Info Byte: You can create Permanent, temporary or undo tablespace either as big-file tablespace
or small-file tablespace but by default they are always small-file tablespace.

Interview Questions
Q: What are the default tablespaces in Oracle Database?
A: The SYSTEM and SYSAUX tablespaces are always created when the database is created.
One or more temporary tablespaces are usually created in a database along with an undo
tablespace and several application tablespaces. Because SYSTEM and SYSAUX are the only
tablespaces always created with the database, they are the default tablespaces.
Q: What type of tablespace does SYSTEM and SYSAUX belong to?
A: SYSTEM and SYSAUX are always created as SMALLFILE tablespace.
Thats all about the introduction of Tablespaces. I hope you found this article on Tablespaces in
Oracle Database helpful. Kindly please share it on your social network and help me reach out to
more people. Thanks & have a great day!
Permanent Tablespace

Permanent tablespace contains persistent schema object which means that the data stored in the
permanent tablespace persists beyond the duration of a session or transaction. Objects in
permanent tablespaces are stored in data files.
In this web article I will explain to you how to create a small file as well as a big file permanent
tablespace in oracle database. So lets start.
Suggested Reading: Tablespace Introduction
Database Connection.
The first step in the creation of any type of tablespace is to connect to your
database. You can do this using sys user or any other user which either has sysdba
privileges or CREATE TABLESPACE system privilege. I will connect to my database
using SYS user with sysdba privileges.
C:\> sqlplus / as sysdba
How To create smallfile permanent tablespace
To create a tablespace we use CREATE TABLESPACE ddl statement
CREATE SMALLFILE TABLESPACE rebellionrider
DATAFILE
C:\app\TBSP_DEMO\Rebell1.dbf SIZE 100M,
C:\app\TBSP_DEMO\Rebell2.dbf SIZE 100M
LOGGING

EXTENT MANAGEMENT LOCAL UNIFORM SIZE 100M


SEGMENT SPACE MANAGEMENT AUTO;

This ddl statement starts with CREATE TABLESPACE where both of which are oracle reserved
keywords. Next, since we are creating a small file tablespace thus we can explicitly specify this
by writing keyword smallfile in between CREATE and TABLESPACE.
CREATE SMALLFILE TABLESPACE
Though this step is optional since oracle, by default, creates all the tablespaces as
small file tablespace yet it is a good practice as it makes your code more readable.
After CREATE SMALLFILE TABLESPACE you have to give the name of your
tablespace. Tablespace name is completely user defined which means that you can
give whatever name you want to your tablespace. In my case I will name my
tablespace RebellionRider.
DATAFILE:
Using this clause we can add one or more datafiles to our tablespace. As I
mentioned in my previous tutorial that Tablespaces are nothing but logical storage
units made up of one or more datafiles.
To add the datafile you just have to write the name of the clause which is DATAFILE
and then inside the single quote you either have to specify the name of datafile &
the directory path (where you want to put your datafile) as I did here or you can
simply write the name of your datafile. In latter case, oracle engine will create your
datafile and placed it in the default directory.
After writing the name of your datafile you have to specify the size for your datafile
using SIZE clause which is mandatory, if you forget to do so then oracle engine will
give you an error. Lets say I want to specify 100MB as the size for my datafile
rebel1. For that I will write.
LOGGING CLAUSE:
The logging clause lets you specify whether creation of a database object will be
logged in the redo log file (LOGGING) or not (NOLOGGING). Logging clause has two
options:
1. Logging and
2. Nologging
If you specify Logging then oracle engine will Generate redo logs for creation of
tables, indexes and partitions, and for subsequent inserts. But in case you do not
want to generate redo logs for all those operations which I just mentioned then
simply write NOLOGGING. However logging is always better as it makes recovery
much easier.

EXTENT MANAGEMENT:
Extents are the group of fixed number of bytes of disk space called data blocks or
we can also say that extents are a group of data blocks.
You can use tablespaces either with local extent management or the older
technique of dictionary extent management. The local extent management clause
lets you specify how the extents of the tablespace will be managed. Oracle gives
you two ways to manage extents:
1. Uniform
2. Autoallocate
Uniform option tells the database to allocate and de-allocate extents in the
tablespace with the same unvarying size that you can specify or let extents default
to be 1MB. UNIFORM is the default for temporary tablespaces and cannot be
specified for undo tablespaces.
On the other hand, AUTOALLOCATE specifies that the tablespace is system
managed. Users cannot specify an extent size. The above query demonstrates the
Uniform Extent Management with size 100MB.
If you want to switch extent management from uniform to auto-allocate then you
just have to simply write auto allocate at the place of size because in this mode the
oracle engine decides the sizes for the extents of your tablespace.
EXTENT MANAGEMENT LOCAL AUTOALLCOATE;
SEGMENT SPACE MANAGEMENT
Similar to the extents, Segments are the collection of one or more extents. For
tablespaces that have local extent management, you can use either manual or
automatic segment space management. Unlike extent management here we do not
have to specify the size. But Oracle strongly recommends AUTOMATIC segment
space management for permanent and locally managed tablespaces. In the above
query I have set the Segment space management as AUTO. If you want to switch
segment space management from auto to manual then simply replace the
SEGEMENT SPACE MANAGEMENT clause with this one
SEGMENT SPACE MANAGEMENT MANUAL;
Execution of the above query will create you a small file permanent tablespace
How To Create Big file Permanent Tablespace.

While creating a big file tablespace you just have to take care of a few things such
as a big file tablespace can have only 1 data file unlike the small file tablespace
where we have to add several data files. Also while creating a big file tablespace its
mandatory to write keyword BIGFILE in between Create and tablespace keywords
otherwise oracle engine will create a small file.
Info Byte: Always remember, no two tablespaces and data files in a database can
have the same name. Thus dont forget to change the name of your tablespace and
its data files.

The query for creating a big file permanent tablespace will be:
CREATE BIGFILE TABLESPACE "RebellionRider2"
DATAFILE
'C:\APP\MANN\ORADATA\ORCL\Big_Rebell.dbf' SIZE 1G LOGGING
EXTENT MANAGEMENT LOCAL
SEGMENT SPACE MANAGEMENT AUTO;
In this query I am creating a big file permanent tablespace with the name of
RebellionRider2 which has only 1 datafile Big_Rebell.dbf apart from this rest of the
clauses are the same as in above query.

Create Undo Tablespace


Undo tablespace is a kind of permanent tablespace used by oracle database engine to manage
undo data if you are running your database in automatic undo management mode. This undo data
or say undo records are generally used to:

Roll back transactions when a ROLLBACK statement is issued

Recover the database

Provide read consistency

Analyze data from an earlier point in time by using Oracle Flashback Query

Recover from logical corruptions using Oracle Flashback features

How to Create Small file Undo Tablespace


Similar to other two tablespaces i.e. Permanent and Temporary tablespace which we have
discussed in the previous two tutorials, undo tablespace can also be created as small file as well

as big file tablespace.


Since we are creating an undo tablespace thus we will use CREATE UNDO TABLESPACE
clause.
CREATE SMALLFILE UNDO TABLESPACE "tbsp_undo"
DATAFILE 'C:\APP\TBSP_DEMO\tbsp_undo.dbf' SIZE 100M
AUTOEXTEND ON NEXT 500M
MAXSIZE UNLIMITED
RETENTION NOGUARANTEE;
The create undo statement is slightly different than the others which we have done so far. So lets
delve deeper into this statement and see what we have done here.
The first line is self-explanatory, here we are creating a small file undo tablespace by the name of
tbsp_undo.
In the second line we have our data file clause using which I have added a data file
tbsp_unod.dbf to our undo tablespace which has initial size 100MB. As its a small file
tablespace therefore we can add multiple data files into it which is not true in case of big file
tablespace which can have maximum of 1 data file. For the simplicity of the demonstration here I
have added only one data file.
In the third line we have auto extend clause. Using this clause we are ensuring that as soon as our
data file tbsp_undo.dbf which is of 100MB size gets filled with undo segments, oracle engine
will extend it automatically and increase it by 500 Megabytes.
In the fourth line we have clause MAXSIZE. Using this clause we can set the maximum size to
which the data file of undo tablespace can extend or say grow. Here I have set the maximum size
of our data file tbsp_undo.dbf to UNLIMITED. You can also limit the max size of your data file
by simply writing the size. For example say you want to set the max size of your data file to
50MB in that case simply write 50M at the place of UNLIMITED.
In the 5th and last line we have a Retention clause which is right now set on No Guarantee. You
can set Retention clause either on Guarantee or No Guarantee.

RETENTION GUARANTEE specifies that Oracle Database should preserve unexpired


undo data in all undo segments of tablespace. This setting is useful if you need to issue an
Oracle Flashback Query or an Oracle Flashback Transaction Query to diagnose and
correct a problem with the data.

RETENTION NOGUARANTEE returns the undo behavior to normal. Space occupied


by unexpired undo data in undo segments can be consumed if necessary by ongoing
transactions. This is also the default setting.

If you do not specify this clause then oracle engine will by default set the retention on No
Guarantee.

How to Drop Undo Tablespace


To drop a tablespace from the database, we use the DROP TABLESPACE statement. The
optional clause INCLUDING CONTENTS recursively removes any segments (tables, indexes,
and so on) in the tablespace, like this:
DROP TABLESPACE dba_sandbox INCLUDING CONTENTS;
Dropping a tablespace does not automatically remove the datafiles from the file system. Use the
additional clause INCLUDING CONTENTS AND DATAFILES to remove the underlying
datafiles as well as the stored objects, like this:
DROP TABLESPACE hr_data INCLUDING CONTENTS AND DATAFILES;

What is Sequence In Oracle Database

A Sequence is a database object which generates integer sequence. We generally use it for
populating numeric Primary Key columns.
In order to create a sequence we use create sequence DDL statement. Lets take a look at
CREATE SEQUENCE DDL Syntax
CREATE SEQUENCE sequence_name
[START WITH start_num]
[INCREMENT BY increment_num]
[MAXVALUE maximum_num | NOMAXVALUE]
[MINVALUE minimum_num | NOMINVALUE]
[CACHE cache_num | NOCACHE]
[CYCLE | NOCYCLE]
[ORDER | NOORDER];

Create Sequence DDL statement starts with CREATE and SEQUENCE, both of which are
Oracle Reserved keywords followed by the name of the sequence which is purely user defined
meaning you can give any name of your choice to your sequence. Next we have few attributes of
the sequence. First attribute is

START WITH
Here you have to specify a numeric value from which you want your sequence to
start. Whatever number you specify will be the first number generated by your
sequence.
INCREMENT BY
This attribute also takes a numeric value, to increment the sequence by. The
number that you specify here will serve as the interval between sequence numbers.
The value for INCREMENTED BY cannot be 0 but it can be any positive or negative
value. If this value is negative, then the sequence descends. If the value is positive,
then the sequence ascends. If you omit this clause, then the interval defaults to 1.
MAXVALUE / NOMAXVALUE
Next attribute is MAXVALUE or NOMAXVALUE Using these attributes you can set the
maximum upper bound for your sequence. Always remember MAXVALUE must be
equal to or greater than START WITH and must be greater than MINVALUE attribute.
In case you dont want to set the MAXVALUE for your sequence then you can use
NOMAXVALUE attribute.
MINVALUE / NOMINVALUE
Similar to MAXVALUE we use MINVALUE attribute to set the lower bound of our
sequence. As a value this attribute also accepts the numeric value and should be
less than or equal to START WITH as well as less than MAXVALUE. In case you dont
want to set the lower bound for your sequence then you can use NOMINVALUE
attribute instead.
CACHE/ NOCACHE
As value of cache attribute you specify the number of integers to keep in memory.
The default number of integers to cache is 20. The minimum number of integers
that may be cached is 2. The maximum integers that may be cached is determined
by the formula:
CEIL(maximum_num -minimum_num)/ABS(increment_num).
Specify NOCACHE to indicate that values of the sequence are not pre-allocated. If
you omit both CACHE and NOCACHE, the database caches 20 sequence numbers by
default.
CYCLE/NOCYCLE
CYCLE and NOCYCLE are two flags which you have to set. If you set the flag on cycle
then your sequence continues to generate values after reaching either its maximum
or minimum value. You specify NOCYCLE flag when you do not want your sequence
to generate more values after reaching its maximum or minimum value. If in case
you omit both these flags then by default oracle engine will set the flag on
NOCYCLE.

ORDER/ NOORDER
At last we have two more flags which are ORDER and NOORDER. ORDER Flag
guarantees that sequence numbers are generated in order of request. This clause is
useful if you are using the sequence numbers as timestamps. Guaranteeing order is
usually not important for sequences that are used to generate primary keys.
Set the flag on NOORDER if you do not want to guarantee that the sequence
numbers are generated in order of request. NOORDER is the default flag in case you
omit either of them.
How to Create a Sequence
Lets create a sequence by the name of sq_demo
CREATE SEQUENCE sq_demo1
START WITH 1
INCREMENT BY 2
MAXVALUE 10
MINVALUE 1
CACHE 3
CYCLE
ORDER;
This is a simple sequence by the name of sq_demo which is starting with 1 and the
interval between every sequence is 2. The Max value for this sequence is 10 and
Min value is 1 and this sequence will cache 3 integers at a time and will cycle after
reaching the maximum value which is 10. Also I have set ORDER FLAG which means
the numbers will be generated in the guaranteed order. Few things which you
should know:
1. You can specify any of these attributes and flags in any order. Means order of
these flags is not fixed.
2. All these attributes and flags are optional. If you omit all of them then oracle
engine will create a default sequence for you. Lets see an example
CREATE SEQUENCE sq_demo02;
How To Use A Sequence
To use a sequence we use NEXTVAL and CURRVAL. Both these are pseudo columns
of a sequence using which we can retrieve next value and current value of a
sequence. NEXTVAL column returns the next value of the sequence as well as
initializes the sequence whereas CURRVAL column will return the current value of
the sequence.
SELECT sq_demo.NEXTVAL FROM dual;

This query will initialize and return the first value of your newly created sequence.
To get the current value of your sequence you use CURRVAL pseudo column of a
Sequence lets see how:
SELECT sq_demo.CURRVAL FROM dual;
This query will give you the current value stored in your sequence.
Points to be remembered: Before using any sequence its mandatory to initialize it
first. If you will try to retrieve current value without initializing it then it will give you
an error and we use NEXTVAL pseudo column to initialize a sequence as well as to
retrieve next value of the sequence. This means after creating a sequence you have
to execute the NEXTVAL query before the CURRVAL one.
How To Populate Numeric Primary key column using a Sequence
Suppose there is a table by the name of demo which has two columns demo_id and
demo_name where column demo_id is a numeric primary key column and column
demo_name is capable of holding variable character string as its data type is
VARCHAR2. You can use sequence to populate primary key column. Let see how:
INSERT INTO demo VALUES (sq_demo.nextval, xyz);
How To Modify A Sequence
You can modify a sequence using the ALTER SEQUENCE statement. There are some
limitations on what you can modify in a sequence such as:
1. You cannot change the start value of a sequence.
2. The minimum value cannot be more than the current value of the sequence.
3. The maximum value cannot be less than the current value of the sequence.
Suppose you want to modify the value of INCREMENT BY attribute from 2 to 4, so for
that ALTER SEQUENCE command will be:
SQL>ALTER SEQUENCE sq_demo INCREMENT BY 4;
This very simple statement starts with ALTER SEQUENCE followed by the name of
the sequence which is sq_demo next is the INCREMENT BY attribute which we want
to modify.
How To Drop A Sequence
To delete any sequence from the schema we use DROP DDL statement. Say you
want to delete the Sequence sq_demo which we just created, so for that the
statement will be
SQL>DROP SEQUENCE sq_demo;

What is SQL View In Oracle Database

SQL view is nothing but a logical table or a virtual table stored in a database. We can also define
a VIEW as a SELECT Statement with a name which is stored in a database as though it were a
table. All the DML commands which you can perform on a table can be performed on a view
also.
Use of SQL View in Oracle Database
Views in any database are majorly used for two reasons
1. Security
2. Reducing complexity of a query.
Security:
Using a view you can mask columns of a table and restrict any user to use the data
from that column. For example,
Suppose you have a large table containing a mixture of both sensitive as well as
general interest information. In this case it will be very handy for you to create a
view which only queries the general interest columns of the original table and in
turn grants privileges on this view to the general users. In this case the population
of general users can query the view and have direct access only to the general
information omitting the sensitive information present in the underlying table. Thus
in this way views can be used to give access to selective data in a table.
Reducing the complexity of a query
Another reason for using a view is to reduce the complexity of a query which is
made by joining various tables. For example,
A view built on a complex join can be created in order to include the complexity in
the view itself. The result of this is a regular view object that looks to be a single
table which could be queried by you as any regular table. The view can be joined
with other views and tables as well. Thus here in this way, view can be used to
reduce the complexity of a common Join.
Syntax of SQL VIEW in Oracle Database
CREATE VIEW view_name AS
SELECT column_name(s) FROM table_name WHERE condition;

This is a syntax of a very simple view which starts with the CREATE and VIEW
keyword followed by the name of the View, you can assign any name of your desire
to your view. Next we have AS which is again an oracle reserved keyword and
followed this we have our Select statement.
Suggested Tutorial [Video]: How to retrieve data using SELECT DML statement in
Oracle Database
Prerequisites
To create a view in your own schema, you must have the CREATE VIEW system
privilege. To create a view in another user's schema, you must have the CREATE
ANY VIEW system privilege.
Create a Simple View
In this example I will create a view by the name of vw_rebellion on Employees table
of HR schema. You can give whatever name you want to your view.
CREATE VIEW vw_rebellion AS
SELECT first_name, email, phone_number FROM employees;
This is a very simple view created on Employees table of HR user and it will hold
all the rows of First name, email and phone number column of the base table
employees. Once a view is created, it can be referred to in your select statement as
if it were a table.
How to recreate a View (OR REPLACE)
We use OR REPLACE to recreate the definition of a view after creating it. Suppose in
the above view vw_rebellion you realize that along with the first name column you
also wanted to have the last name column. There are two options to do this task
either drop the view and recreate it or just recreate the view without dropping it.
Lets see how
CREATE OR REPLACE VIEW vw_rebellion AS
SELECT first_name, last_name, email, phone_number FROM employees;
Apart from the OR REPLACE and the column LAST NAME nothing is different in the
query. This query will replace the definition of old vw_rebellion view by the definition
of new vw_rebellion view.
As I mentioned earlier that once you have created a view you can execute all the
DML statements on that view as though it were a table. Lets see how
How to check the definition of a SQL VIEW in Oracle Database (Describe/
desc dml)
You can use Describe/ DESC dml command to see the definition of your view e.g.

DESC vw_rebellion;
I know Describe is a DDL statement not DML but I thought this tip is worth
sharing.
How To retrieve Rows from a VIEW in Oracle Database (SELECT ddl)
You can use SELECT ddl command to retrieve rows from a VIEW similar to the way
we do with tables in oracle database.
SELECT * FROM vw_rebellion
You can also use ORDER BY clause to sort the result.
SELECT * FROM vw_rebellion ORDER BY first_name;
Furthermore you can even use WHERE clause in your SELECT statement to filter the
result.
SELECT * FROM vw_rebellion WHERE first_name = 'Nancy';
Info Byte: In case you want to use WHERE and ORDER BY clause in a single SELECT
statement then always remember WHERE clause will come before the ORDER BY
clause in the query. For Example
SELECT * FROM vw_rebellion
first_name;

WHERE first_name = 'Nancy' ORDER BY

How to UPDATE rows in a VIEW (UPDATE ddl)


Similar to the SELECT ddl we can also execute UPDATE ddl on a VIEW. Suppose you
want to update the email address of employee Nancy then query for this will be:
UPDATE vw_rebellion SET email ='nancy@example.com' WHERE first_name
='Nancy';
How to delete rows in a VIEW (DELETE ddl)
You can execute DELETE DML command to delete one or more rows from the table
using VIEWS.
DELETE FROM vw_rebellion WHERE first_name = 'Nancy';
How to insert Row in a VIEW in Oracle Database (INSERT ddl)
To insert a row, a view has to satisfy all the constraints on any column of underlying
table over which its created. Insert DML is subject to several restrictions when
executed on a View in Oracle database such as:

1. A view must contain the entire Not Null column from underlying table. The
failure to include any columns that have NOT NULL constraints from the
underlying table in the view will result the non-execution of the INSERT
statement. However an UPDATE or DELETE statement can be issued.
2. If there is any column with referential key constraint in underlying table then
view must contain that column and a proper value must be provided to that
column while performing Insert on the View and many more.
Thus to perform an INSERT dml on a view, it has to include all the columns which
either have NOT NULL constraint or Referential constraint or any other mandatory
constraint from the base table employees.
E.g.
INSERT INTO vw_superheroes VALUES ('Steve', 'Rogers', 654765);
Where vw_supereheroes is another view created over Superheroes table which has
5 columns first name, last name, and real name, Phone number and SSN. This table
has no constraint on any column.
How to create a complex view (View by joining two tables)
Complexity of a view depends upon the complexity of its SELECT statement. You can
increase the complexity of a view by increasing the complexity of the SELECT
statement.
CREATE OR REPLACE VIEW vw_join AS
SELECT first_name, department_name FROM employees emp
FULL OUTER JOIN departments dept
ON (emp.DEPARTMENT_ID = dept.DEPARTMENT_ID);
As I told you above that by using a View you can reduce the complexity of a query. A
view built on a complex join can be created in order to include the complexity in the
view itself. The result of this is a regular view object that looks to be a single table
which could be queried by you as any regular table. The view can be joined with
other views and tables as well. Thus here in this way, view can be used to reduce
the complexity of a common Join.

Simple Case Expression.

Using Case expression you can achieve the IF-THEN-ELSE logic in Oracle SQL that too
without invoking any kind of SQL procedures.
CASE expression can do all the work of a DECODE expression. Several books recommend
using CASE over DECODE because

CASE expressions are easier to read in comparison to DECODE expression and

CASE expression is ANSI-compliant and forms part of the SQL/92 standard.

In Oracle there are two types of CASE expressions

Simple case expressions

Searched case expressions

Simple Case Expression


As the name suggests it is the simplest version of CASE expression in other words we can say
that it is a flexible and easiest version of DECODE expression.
The syntax of Simple Case Expression is
CASE search_expression
WHEN input_expression 1 THEN output_result 1
WHEN input_expression 2 THEN output_result 2
...
WHEN input_expression N THEN output_result N
ELSE Else_result
END
Where

Search_Expression is the expression to be evaluated.

Input_Expressions are the expressions to be evaluated against search_expression.

Output_Results are the returned results (one for each possible expression). If expression1
evaluates to search_expression, result1 is returned, and similarly for the other
expressions.

Else_Result is returned when no matching expression is found.

The Simple Case Expression uses search expression to determine the return value. Means simple
case expression evaluates all the input expressions against the search expression. Once a match is
found the corresponding result is returned otherwise Else result is displayed. Furthermore the

Else statement is optional so in case you omit it then Null is displayed when the simple case
expression cannot find a match.
Points to remember

The data type of all the input expressions must match with the data type of search
expression. Means data type of search expression and input expression must be the same.

The datatype of all the output results must match with Else result means the data type of
output result along with else result must be the same.

The maximum number of arguments in a CASE expression is 255. All expressions count toward
this limit, including the initial expression of a simple CASE expression and the optional ELSE
expression. Each WHEN ... THEN pair counts as two arguments. To avoid exceeding this limit,
you can nest CASE expressions so that the output_result itself is a CASE expression.

Query 1: Column Name as Search Expression.


SELECT first_name,department_id,
(CASE department_id
WHEN 10 THEN 'Administration'
WHEN 20 THEN 'Marketing'
WHEN 30 THEN 'Purchasing'
WHEN 40 THEN 'Shipping'
WHEN 50 THEN 'Shipping'
ELSE 'Sorry'
END) Departments
FROM employees
WHERE department_id BETWEEN 10 AND 50
ORDER BY 2;
Lets take a look at the case block of this query. We are using column department_id of
employees table as our search expression and the values from department id column (10, 20, 30,
40 and 50) are serving as input expressions of WHEN-THEN pairs.
Whenever we specify a column name of a table as search expression the oracle engine treats all
the data from this column as an array and matches all the input_expressions with every element
of this array and if a match is found, it returns the corresponding result values, Otherwise the else
statement gets return.

Query 2: String as Search Expression.


In case you specify a string instead of a column name as a search expression then oracle will find
the first best fit match and then return the corresponding result value.
SELECT
CASE 'Dog'

WHEN 'Cat' THEN '1 Flase'


WHEN 'Dog' THEN '2 True'
WHEN 'Cow' THEN '3 False'
WHEN 'Dog' THEN '4 True'
ELSE 'Sorry'
END
FROM dual;
Here in this simple case, the search expression is Dog along with 4 When-and-Then pairs. The
input expression of 2nd and 4th pair is a string Dog which is a perfect match for our search
expression but on executing this query, oracle engine will return the result value from the first
best match which in our case is the 2nd pair.

SQL Delete and Truncate Command.


Till so far we have learned how to insert data into a table using INSERT statement, SQL
Developer and from some other table so the only thing which is left is how to delete data from a
table.
Among several different ways of deleting data from a table the two most used ways are SQL
Delete and Truncate command. Although both perform the same task yet they are still different.
In this blog you will learn how to use SQL Delete and truncate command as well as the various
differences between them.

SQL DELETE command


SQL Delete is a DML command which removes entire rows of data from a specified table or
view.
Syntax
DELETE FROM table_name WHERE condition;
As its a DELETE query thus it starts with DELETE keyword followed by FROM keyword.
After that you have to specify the table name from which you want to delete the data and at the
end we have our WHERE clause. WHERE clause enables you to choose rows from the
references table or view that need to be deleted conditionally. That is only those rows that meet
these search conditions are deleted. If you omit the WHERE clause, all rows in the table or view
are deleted.
For example

Query 1 : Lets say you want to delete only those rows from employees table of HR schema
where job id is ST_CLERK
DELETE FROM employees WHERE job_id = 'ST_CLERK';
This query will delete all the rows from employees table where job id is st clerk.
Query 2 :Now, what if, you want to delete all the rows from the employees table? For that we
just need to do a slight modification in the above query.
DELETE FROM employees;
As I mentioned above If we use DELETE command without the WHERE clause, all the rows in
the table or view are deleted. On executing this query all the rows from employee table will get
deleted.
There are few things which you should know about SQL DELETE command
1. DELETE is a DML command.
2. Whenever you perform DELETE operation all the triggers associated with DELETE
command gets executed.
3. DELETE checks all the constraints on all the columns of the rows which are getting
deleted before deleting the rows and accordingly set the Index.
4. If you accidently deleted some data then there are still chances that you can get it back by
performing ROLLBACK command. Roll back will not work if you have already
performed the commit.

SQL Truncate Command


Truncate command deletes all the rows from a table.
For example say you want to delete all the rows from countries table of HR schema.
TRUNCATE TABLE countries;
Things to remember
1. Truncate is a DDL command.
2. You cannot roll back a TRUNCATE statement.
3. You cannot use WHERE clause with TRUNCATE statement. This means that unlike SQL
DELETE there are no options for conditional delete.

4. Unlike SQL delete when you perform Truncate no trigger gets executed.
5. Truncate doesnt use much UNDO space as SQL Delete.
6. Truncate is significantly faster than the SQL Delete. This is because when you use
DELETE, all the data first gets copied onto the Undo Tablespace after which the delete
operation gets performed. Thats why when you type ROLLBACK after deleting a table;
you can get back the data . All this process takes time. But when you type TRUNCATE, it
removes data directly without copying it onto the Rollback Tablespace. Thats why
TRUNCATE is faster. Once you truncate you cant get back the data

Natural Joins.
Definition:
A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based
on the common columns in the two tables being joined. Common columns are
columns that have the same name in both tables.
A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a RIGHT OUTER join.
The default is INNER join.
Source: Oracle

We will start with Natural Join. But before jumping over to natural join let me tell you a few
terminologies
Source table: Table which comes after FROM clause in the select statement
Target table: All the tables which come after JOIN clause in the query.
When the join query is executed then oracle starts matching data from the source table to the
target table. If there is a hit for a matching source table data in the target table then the value is
returned.

Examples of Natural Joins in Oracle Database


Scenario 1: When there is only one identical name column between source
and target tables.
Lets use Departments table and locations table for the demonstration.

Department table has 4 columns DEPARTMENT_ID, DEPARTMENT_NAME,


MANAGER_ID, LOCATION_ID
And Locations table has 6 columns
Location id, street address, postal code, city, state province and country id
Upon minutely observing you will notice that location id is a common column
between our source and target tables. It is the foreign key and thus has same data
type and column width. Lets write the query for natural join.
Say you want to find the City for all your Departments
SELECT department_name, city FROM departments NATURAL JOIN locations;
In this query we are selecting department name from departments table and city
from locations table. You can select other columns too
Departments is our source table as its coming right after FROM keyword and
locations is our Target table as its coming after JOIN clause.
The best part of using Natural join is that you do not need to specify the join column
because column with the same name in source and target table are automatically
associated with each other.
On executing this query oracle returns all the rows from department column of
departments table and from city column of locations table, where location id of
departments table is equal to the location id of location table.

Scenario 2: What if when our source and target tables have more than one identical name
column.
To demonstrate this scenario we will use employees and departments table these two tables
shares two common columns which are department id and manager id.
Here if we put Natural join on these two tables then oracle engine will use these two common
columns to return the result.
Say we want to see the name of employee and the name of department in which he or she is
working. For that we will select first name from employee table which is our source table and
department name from departments table.

SELECT first_name, department_name FROM employees NATURAL JOIN


departments;
As I have already mentioned that when we use natural join, there is no need to
specify join columns explicitly. All the columns which are common in both source
and target table get associated automatically.
The queries in which all the common columns of source and target table get
associated automatically are known as Pure Natural Join.
Which means in this query, oracle has automatically associated our common
columns which are department id and manager id.

To help you understand more clearly lets write same query but this time using ON clause.
SELECT first_name,department_name FROM employees JOIN
ON (employees.manager_id = departments.manager_id AND
employees.department_id = departments. department_id);

departments

Here is a slight change in the natural join syntax as we are using ON clause this
time, instead of writing natural join we will only write JOIN.
Both these queries produce the same results as both are same query written in
different ways.
In this query we emphasize natural join using ON clause. As we are using ON clause
thus it becomes mandatory to specify the columns over which we want to perform
the join.

Scenario 3: Natural join with USING clause


Here Once again we will use our natural join query.
SELECT first_name, department_name FROM employees
departments;

NATURAL JOIN

As we can see here in this query that when we have more than one common column
oracle engine uses all of them to produce the result
Now, here in this query we are using employees and department tables which have
2 common columns department id and manager id.

What if you want to use only department id in your natural join instead of both
manager and department id?
In this situation we use natural join with USING clause.
Say we want to select all the first name and department name from source table
employees and target table departments from where we have equal values of
manager ids in both the employees table and the departments table.
Lets write the query
SELECT first_name, department_name FROM employees JOIN departments
USING(manager_id);

Right Outer Join In SQL.


As the name suggests Right Outer Join is a form of Outer Join that returns each and every record
from the source table and returns only those values from the target table that fulfil the Join
condition.
*Note: The Source table is the one situated on the right side of the Right Outer Join Clause
whereas The Target table is the one on the left side of this clause.
Syntax :
SELECT
columns
FROM
target_table RIGHT OUTER JOIN source_table
ON(source_table.column = target_table.column)
WHERE condition
ORDER BY column_names;

Examples:
To demonstrate the working of Right Outer Join, I have created two tables by the name of emp
and dept and have also inserted some data in them.

Structure of emp table

Structure of dept table

Data In emp table

Data In dept table


If you have noticed that in dept table IT and marketing department dont have any employees.

Query 1: Right Outer Join with ON clause


Now when should we use ON Join Condition in SQL Joins you ask?
1. When columns which are participating in ON join condition have Different name and
Same Data type or
2. When columns which are participating in ON join condition have SAME NAME and
SAME Data-type.
Lets write a very simple Right outer join query.
SELECT
emp_name,dept_name
FROM dept RIGHT OUTER JOIN emp
ON (emp.EMP_ID = dept.EMP_ID);
In the above query we are selecting emp_name from emp table and dept_name from dept
table. Emp table is the source table as its on the right hand side of join clause thus
automatically making dept table as the target table.
Column emp_id is a primary key in emp table and foreign key in dept table thus column emp_id
is the column which is establishing a relationship in between these two tables. As column emp_id
is common in both tables thus its a best fit for Join condition (ON clause).
If you execute this query you will get all the rows of emp_name column of emp table as emp is
the source table and only those rows of dept_name column of dept table which satisfy the join
condition (condition in ON clause).

Query 2: Right Outer Join with WHERE clause


You can use WHERE clause with any type of JOIN and limit or Filter the result. In case of
JOINS, WHERE clause always comes after Join Condition (ON or USING) Say you want to see
employees name and department name whose salary is less than 50,000
SELECT emp_name,dept_name
FROM dept RIGHT OUTER JOIN emp
ON (emp.EMP_ID = dept.EMP_ID) WHERE emp_salary < 50000;

Query 3: Right Outer Join with USING clause


Using clause can be used on the place of ON clause when
1. We are performing Equi Join.
2. We want to put join on that column of source and target table which are common i.e. have
same name and data type.
Most of the joins youll perform will be equijoins, and if you always use the same name as the
primary key for your foreign keys, then:
SELECT emp_name,dept_name FROM dept RIGHT OUTER JOIN emp USING
(emp_id);

Full Outer Join In SQL.

Todays SQL article is all about Full Outer Join.


Before moving ahead just want to say that in order to better understand the concept of full outer
Join please read my last two SQL tutorial article on right and left outer join.
Here once again we will be using same table which we have used so far in this Outer Join series.
These are the emp and the dept tables.
Lets have a quick look of the structure and the data of these two tables.
Desc emp;

Our table emp has 3 columns


emp id, emp name and emp salary. Here column emp id is a primary key.
Desc dept;

Table dept also has 3 columns


dept id, dept name and emp id. Here in this table column dept id is a primary key
where column emp id is a foreign key reference from the emp table.

Now lets have a look at the data of these two tables.


SELECT * FROM emp;

Emp table has 5 rows where


column one has emp id and column 2 has emp name and column 3 consist the
salary of these employees.

Now data of dept table


SELECT * FROM dept;

Table Dept also has 5


columns. Column one hold dept id where column two has dept name and column
three emp id which is the foreign key has only 3 records corresponding to
department name sales account and finance.

We can interpret this data easily. For example the employee with employee id 1 is named Steve
in our emp table and works in department of Sales. Similarly employee with employee id 2 is
Nancy who works in Accounts department and employee with employee id 3 is Guru who works
in finance. Also we have not assigned any employee id for department of IT and Marketing
which signifies that no one works in these departments.
Lets jump over to full outer join.
Full outer join is kind of a combination of both right outer join and left outer join because
it returns all the rows from left as well as the right side table.
Lets have look of FULL OUTER JOIN syntax.
Syntax
SELECT column names FROM

table1 FULL OUTER JOIN / FULL JOIN table 2


ON(expression) or USING(column_name)
WHERE(expression) ORDER BY column names;
Syntax is pretty similar to our left or right join as you can see. We have our SELECT
statement where you can specify the name of the columns from both the
participating tables followed by FROM clause. And our JOIN clause which is full outer
join. Here you can either write full outer join or just outer join since both are
permissible and perform the same task. And then we have our Join condition ON and
USING followed by WHERE and ORDER BY clause.
Query 1 : Full Outer Join With ON clause
SELECT emp_name, dept_name FROM emp FULL OUTER JOIN dept ON
(emp.emp_id = dept.emp_id);
Here in this query we are selecting emp name column from emp table and dept
name column from dept table. In our full outer join clause we have emp table on left
side and dept table on right side and then we have Our ON clause where we are
comparing the values of emp id columns from the both the tables.

On executing this query the result will be.

If you will observe minutely then you can see that the result till row 5 is similar to that of right
outer join, As all the records from right side table is here and only those records from left side

table which satisfy the join condition are here in the result. Followed by all the remaining records
from the tables thus the last row 6 and 7 contains the remaining emp names.
Here in this ON join clause we used columns which have same name and data type. Now lets
use columns which have different name and same data type for example column
dept id.
SELECT emp_name, dept_name FROM emp FULL OUTER JOIN dept ON
(emp.emp_id = dept.dept_id);
and the result of this query is

Query 2 : Full Outer Join With USING clause


We use USING join condition when
The column in join condition share the same name and same data type and are
compared only using = comparison operator and no other comparison operator
such as greater than, less than etc.
As you can see, in the join condition (ON clause) of Query 1 we have used emp id
column of both the tables. This column shares the same name and same data type
hence we can easily replace this ON clause with USING clause. Lets do it.
SELECT emp_name, dept_name FROM emp FULL OUTER JOIN dept USING
(emp_id);

The result of this query is

If you compare this result with the result of our first query then you will find them as
exactly the same.
Query 3 : Full Outer Join With WHERE clause
You can also limit the result by using WHERE clause. Say you want to see the name
of only those employees and their departments who have a salary of less than
50000
For that we can modify our query 2 and add a where clause to it.
SELECT emp_name, dept_name, emp_salary FROM emp FULL OUTER JOIN
dept USING (emp_id)
WHERE emp.emp_salary < 50000;
On executing this query you will get only those employee and their departments
who has salary less than 50,000

Query 4 : Full Outer Join With ORDER BY clause


Similarly you can sort the result using ORDER BY clause. Say you want to sort the
result of query 3 in ascending order according to the employee name (emp_name
column) For that just add the ORDER BY clause followed by the column name which
is emp_name in our case.
SELECT emp_name, dept_name FROM emp FULL OUTER JOIN dept USING
(emp_id)
WHERE emp.emp_salary < 50000 ORDER BY emp_name;
If you execute this query then by default the result will be sorted in ascending order.

If you write DESC right after the column, your result will be sorted in descending
order. For Example
SELECT emp_name, dept_name FROM emp FULL OUTER JOIN dept USING
(emp_id)
WHERE emp.emp_salary < 50000 ORDER BY emp_name DESC;

Inner Join In SQL.

This is the fifth tutorial in the Join series and till now we have seen Natural Join, Right Outer
Join, Full Outer Join and left Outer Join.
And in this tutorial we will cover the concepts of INNER Join.
Definition
Inner Join is the join which returns all those rows from both the participating
tables that satisfy the Join condition or for that matter expression of ON/USING
clause.
Syntax
SELECT column names FROM
table1 INNER JOIN / JOIN table 2
ON(expression) or USING(column_name)
WHERE(expression) ORDER BY column names;

In the first line of our syntax we have our SELECT statement where you specify all those
columns from both the participating table (table1 and table2) whose data you want to fetch in
your result set. The SELECT statement is followed by FROM keyword.
In the second line of our syntax we have our JOIN clause which is INNER join as obvious. You
can either write INNER JOIN or simple JOIN as both are permissible and perform the same task.
On both side of our Join clause we have our tables which are TABLE 1 and TABLE 2.
Followed by our join clause we have our Join condition. Basically we have two types of join
condition that we can use one at a time but never together. These two join conditions are ON and
USING. Usage of each join condition depends on certain conditional parameters.
And at the end of the syntax we have our WHERE and ORDER BY clause.
*Note here if you are using ORDER BY clause then it must be the last
statement of your query.
When to use ON and USING clause

Hope syntax is clear.

Lets do some practical exercise. Ill be using the same table which we have been using in all our
JOIN tutorial emp and dept.
(for tables you can refer to Table for SQL Joins tutorial)
QUERY 1: INNER JOIN with ON clause
SELECT emp_name,dept_name FROM emp INNER JOIN dept ON(emp.EMP_ID =
dept.EMP_ID);
Here in this query we are selecting emp name from emp table and dept name from
dept table while in JOIN condition which in this case is the ON clause we are
comparing emp_id column of both the tables.
As here in this query we are using ON join condition thus we can use any column as
expression of ON clause as long as columns share same data types. The name of

the column doesnt matter here.


For example we have dept_id column in dept table which shares same data type as
of emp_id column of emp table which is a NUMBER thus here in our ON clause we
can use this dept_id column too.
SELECT emp_name,dept_name FROM emp INNER JOIN dept ON(emp.EMP_ID =
dept.DEPT_ID);

QUERY 2: INNER JOIN with USING clause.


We already know that we can use USING clause when the column in join condition
share same name and same data type and are compared only using equal to ( = )
comparison operator and no other comparison operator such as greater than, less
than etc.
SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID);
Here we used emp_id column in USING clause because its common in both tables
(foreign key relation in emp and dept table) and shares same name as well as data
type. We can easily compare its value using equal to operator in both the tables as
we did in our first query where we used emp_id column of both the tables in the
expression of ON clause.

QUERY 3: INNER JOIN with WHERE clause.


We use WHERE clause to limit the result of a Query, similarly you can use WHERE
clause here with Inner join to do the same. Say you want to see the name and
departments of only those employees who have a salary of less than 50000 For that
you just have to add the where clause right after the JOIN condition in the query.
For example
SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID) WHERE
emp.emp_salary < 50000;

QUERY 4: INNER JOIN with ORDER BY clause.


Feel free to use ORDER BY clause if you want to sort the result returned by your

query in Ascending or Descending order.


NOTE here ORDER BY clause must be the last statement of a QUERY.
ORDER BY clause by default sorts the result in ascending order. But if you want to
arrange the result in Descending order then you have to specify it by using
DESCENDING or DESC keyword with the ORDER BY clause.
For example
1. Sort the result in ascending order according to emp_name column
SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID)
ORDER BY emp_name;
2. Sort the result in descending order according to emp_name column.
SELECT emp_name,dept_name FROM emp INNER JOIN dept USING(EMP_ID)
ORDER BY emp_name DESC;

Cross Join In SQL.

Hey guys hope you are enjoying my articles. This one is all about cross outer join
Definition
Cross Join produces Cartesian product of the tables which are participating in
the Join queries thats why its also known by the name of Cartesian Join.
Generally we use CROSS JOIN when there is no relationship between participating
tables.
Syntax
SELECT column names FROM table1 CROSS JOIN table 2 WHERE
(expression) ORDER BY column names;
Or
SELECT column names FROM table1, table 2 WHERE (expression) ORDER BY
column names

In the first line we have our Select statement where you can specify the list of columns from both
the participating tables.

In the second line we have our tables and the CROSS JOIN clause. Here you can write either
Cross Join or just put a comma in between the names of both tables.
Also with cross join we do not have any ON or USING join condition. But you may, however,
specify a WHERE and ORDER BY clause.
Note if you are using ORDER BY clause then make sure it must be the last statement of
your SQL query.
Example:
Ill be using the same table which we have been using in all our JOIN tutorial so far.
These are the emp and dept tables.
(For tables you can refer to Table for SQL Joins tutorial)
Query 1: CROSS JOIN
SELECT emp_name, dept_name FROM emp CROSS JOIN dept;
This query is fairly simple; we are selecting emp name and dept name from emp
and dept tables respectively.
On executing this query, the first record of emp name column of emp table that is
Steve, gets paired with all the rows of the second table dept. Similarly second
record Nancy gets paired with all the rows of dept table and so on.

Since this cross join produces a Cartesian product therefore the total number of rows in the result
will be equal to total number of rows in table 1 multiplied by total number of rows in table 2.
Since in our case we have total 5 rows in each table thus total number of rows in our result is 25.
Query 2: CROSS JOIN with WHERE clause.
Say you want to see only those records where dept name is IT.
SELECT emp_name,dept_name FROM emp CROSS JOIN dept WHERE dept_name
= 'IT';
On execution this query will return all the emp name which are corresponding to
Department name IT
Query 3 : Cross Join with Order By clause
Similarly you can use ORDER BY clause if you want to sort the result returned by
your query in Ascending or Descending order.

NOTE: Here ORDER BY clause must be the last statement of a QUERY.


ORDER BY clause by default sorts the result in ascending order. But if you want to
arrange the result in Descending order then you have to specify it by using
DESCENDING or DESC keyword with the ORDER BY clause.
SELECT emp_name,dept_name FROM emp CROSS JOIN dept WHERE dept_name
= 'IT' ORDER BY emp_name;
And if you want to reverse the order meaning if you want to sort the result in
Descending order, then you just need to add DESC or DESCENDING keyword after
the column name of ORDER BY clause
SELECT emp_name,dept_name FROM emp CROSS JOIN dept WHERE dept_name
= 'IT' ORDER BY emp_name DESC;
How To Define Primary Key Constraint?

Whenever we talk about database constraint the first thing which comes into the mind is the
primary key constraint. So today in this tutorial we will see what is a Primary key constraint and
the different ways of defining a primary key constraint on a table.
What is a Primary Key Constraint?
Primary key constraint is the combination of NOT NULL and UNIQUE constraints. In
more proper manners you can define a primary key constraint as an Input/output
Data constraint which serves the purpose of uniquely identifying the rows in a table.
Definition
Primary key constraint is an Input/output Data constraint which serves the purpose
of uniquely identifying the rows in a table.
Types of Primary Key
There are two types of Primary keys:
1. Simple Primary key and
2. Composite Primary Key.

Simple Primary Key


A primary key constraint that is defined using only one column of a table in the
database is called Simple Primary Key Constraint.
Composite Primary Key
A primary key constraint that is defined using more than one column of a table in
the database is called Composite Primary key constraint.
Primary key has a single function of identifying a unique row in the table. In case
the simple primary key fails to identify that unique row, the user must then define a
composite primary key. There are some restrictions on composite primary key such
as. A composite primary key can be defined using up to 32 columns a table in oracle
database.
Quick Tip
How to ensure the uniqueness of a primary key constraint?
Oracle automatically creates a unique index so that the requirement of the
uniqueness of the PRIMARY KEY constraint is fulfilled.

How to Create a Primary Key Constraint in Oracle Database


Primary key constraint can be defined by two ways:
1. Using CREATE TABLE statement and
2. Using ALTER TABLE statement
You can define a primary key constraint either during the creation of a table using
CREATE TABLE statement or after creating a table using ALTER TABLE statement.
If you choose to define a primary key using CREATE TABLE statement then you have
two different levels of defining a primary key.
1. At Column Level
2. At Table Level.

Lets learn all the above mentioned way of defining a Primary Key constraint one by one.
Define Primary Key Using CREATE TABLE.
As mentioned above we can define primary key in two ways using create table. Lets
start with the first way which is Define Primary key at Column Level.

Suggested Reading: How to Create a Table

Define Primary key at Column Level.


In create table statement you define any column a primary key column just by
putting reserved phrase Primary key right after defining the column. This means
you just have to put reserved phrase Primary Key after data type and size in
column definition. For example
Example 1: Primary Key at Column Level
CREATE TABLE product_master
(
Product_id NUMBER(3) PRIMARY KEY,
Product_name VARCHAR2(30),
Product_price NUMBER(5)
);
As you can see in the above code the column product_id is a primary key column.
But it is always a good practice to give a unique and meaningful name to your
primary key constraint every time you create it. This will make managing of your
constraint much easier.
How to Name Your Constraint in Oracle Database?
In case you do not provide a meaningful name to your constraint then the oracle
database server gives a default name to the constraint automatically. In case if you
have several constraints on your table then using this default name makes it very
difficult to find a specific constraint.
You use keyword CONSTRAINT to give your constraint a meaningful name. Lets
modify the above code and give our constraint a name.
Example 2: How to name a primary key constraint.
CREATE TABLE product_master
(
Product_id NUMBER(3) CONSTRAINT promstr_col1_pid_pk
PRIMARY KEY,
Product_name VARCHAR2(30),
Product_price NUMBER(5)
);
That is how we define a primary key constraint at column level using Create Table
Statement in Oracle database. Now lets see the second way of creating a primary
key.
Define Primary key at Table Level.

Defining the primary key constraint at table level is one of my favorite ways as it
helps me to manage all my constraints specially when dealing with a huge line of
code.
Defining a constraint at table level separates the column definition from the
constraint definition. In this way you first define all the columns of a table and then
you define all your constraints in the Create Table Statement. For Example
Example 3: Primary Key Constraint at Table Level
Lets again take the above example and see how we can define the primary key
constraint promstr_col1_pid_pk at table level:
CREATE TABLE product_master
(
Product_id NUMBER(3),
Product_name VARCHAR2(30),
Product_price NUMBER(5),
CONSTRAINT promstr_col1_pid_pk PRIMARY KEY (product_id)
);
Please watch the video tutorial on the same topic for line by line explanation of the
above code.
How to Define Primary Key Using ALTER TABLE statement?
You can use ALTER TABLE statement to add the constraint in an already created
table or to change the definition of already defined constraint in the table.
Example 4:
Lets say we have a table Customer with 3 columns Cust_id, cust_name, phone_no
and we dont have any Primary Key constraint on any column and now we want to
add Primary Key constraint on cust_id column. To do this task we will use ALTER
TABLE statement:
ALTER TABLE customer ADD CONSTRAINT cust_cid_pk PRIMARY KEY (cust_id);
That is how we use ALTER TABLE statement to add a primary key constraint in an
already created table.

How to Define a Composite Primary Key Constraint?

As said above that the primary key defined using more than one column is called a
composite primary key. Lets see how to define a composite primary key
Example 5: Composite Primary Key
CREATE TABLE customer
(
cust_id NUMBER(3),
cust_name VARCHAR2(3),
phone_no NUMBER(10),
CONSTRAINT cust_cid_pk PRIMARY KEY ( cust_id, phone_no)
);
In the above code we create a table with the name Customer which has 3 columns
and primary key constraint is defined using two columns cust_id and phone_no.

Example 6: Composite Primary Key Using ALTER TABLE


Similar to simple primary key you can add a composite primary key to an already
created table using ALTER TABLE statement.
ALTER TABLE customer ADD CONSTRAINT cust_cid_pk PRIMARY KEY
(cust_id,phone_number);

How To Enable and Disable a Primary Key Constraint?


If you were wondering what is the requirement of giving a name to a constraint then
here is the answer. Modifying a constraint becomes easier if your constraint has a
unique and meaningful name. If you do not provide a name to your constraint then
oracle server gives a default name to it which is not very meaningful and it
becomes difficult to find a specific constraint using that name.
So lets modify the primary key constraint and see how to enable or disable it using
the name of the constraint.
Example 7: Enable or Disable primary key.
For example lets say you want to disable cust_cid_pk constraint which we earlier
defined on the Customer table.
Disable Primary key constraint
ALTER TABLE customer DISABLE CONSTRAINT cust_cid_pk;
If you want to enable this constraint then simply write

Enable Primary key constraint


ALTER TABLE customer ENABLE CONSTRAINT cust_cid_pk;

How to Check Constraint on A Table


As we know that DESC statement shows nothing about constraints on a table. But
Oracle Database provides us several DATA DICTIONARIES for checking or describing
all the constraints which we have defined on our table.
These Data Dictionaries are

USER_CONSTRAINTS

USER_CONS_COLUMNS

Where USER_CONSTRAINTS gives a brief about constraint on table.


USER_CONS_COLUMNS is a Data Dictionary which holds detailed information about
columns of a table. Lets see how to use them to get information about the primary
key constraint.

For example lets say you want to see constraint details on customer table
USER_CONSTRAINTS
SELECT
CONSTRAINT_NAME,
CONSTRAINT_TYPE,
TABLE_NAME,
STATUS,
INDEX_NAME
FROM user_CONSTRAINTS WHERE table_name = 'CUSTOMER';
USER_CONS_COLUMNS
SELECT
CONSTRAINT_NAME,
TABLE_NAME,
COLUMN_NAME,
POSITION
FROM user_cons_columns WHERE table_name = 'CUSTOMER';

Restrictions on a primary key constraint

1. You cannot delete a Primary key if it is referenced by a foreign key in some


other table.
2. A table can have only One Primary key no matter whether its Simple Primary
Key Or Composite Primary Key.
3. Columns which are participating in Primary Key cannot have NULL values.
This means you cannot leave them unattended or you cannot put NULL value
into them.
4. As primary key is all about Row or Records uniqueness thus it will not allow
duplicate values.
5. When a Primary Key constraint has been defined on multiple columns then its
values can be duplicated provided the duplication is happening within one
single column. However the combination of values of all the columns defining
each primary key constraint should be unique.
6. Data-types such as LOB, LONG, LONG RAW, VARRAY, NESTED TABLE, BFILE,
REF, TIMESTAMP WITH TIME ZONE, or user-defined type are not allowed with
the columns which are part of Primary key. Any attempt of creating a primary
key with the column of these data-types will raise SQL Error: ORA-02269.
7. The size of the primary key cannot exceed approximately one database block.
8. As I have already mentioned above that a composite primary key can have
32 columns maximum.
9. The Primary key and Unique key should never be designated as the same
column or combination of columns.
10.You cannot specify a primary key when creating a sub view in an inheritance
hierarchy. The primary key can be specified only for the top-level (root) view.
11.Unique cluster Index gets created automatically on the time creating Primary
key.
12.Although it is not necessary for you to define a primary key yet it is always
recommended to do so.

So thats all about PRIMARY KEY. Hope it gives you a detailed insight into the concept. You
can visit my YouTube channel for tutorials on Primary Key. Do like and Subscribe to my videos.
Thanks for reading & have a great day!

Foreign Key.

Oracle Database Foreign Key Explained in Detail


In the last tutorial we learnt about Primary key constraint and today Another topic in oracle
database that I would like to elaborate is referential integrity constraint or Foreign Key.
Foreign key is an Input/output data constraint which is also known as referential integrity
constraint.
Foreign key represent a link or say a relationship between columns of tables.
Similar to primary key constraint Foreign Key constraint is also of two types.
1. Simple Foreign key constraint and
2. Composite Foreign key constraint.
Constraint which involves only one column in foreign key in child table and one
column in reference key in parent table is called Simple Foreign Key. While the
constraint which involves more than one column in foreign key in child table and
more than one column in reference key in the parent table is called Composite
Foreign Key.

There are few things which you should know about foreign key ( Features of Foreign Key)
1. You cannot define a foreign key constraint in a CREATE TABLE statement that
contains an AS sub query clause. Instead, you must create the table without
the constraint and then add it later with an ALTER TABLE statement
2. None of the columns in the foreign key can be of LOB, LONG, LONG RAW,
VARRAY, NESTED TABLE, BFILE, REF, TIMESTAMP WITH TIME ZONE, or userdefined type. However, the primary key can contain a column of TIMESTAMP
WITH LOCAL TIME ZONE.
3. A composite foreign key cannot have more than 32 columns.
4. Referenced key in parent table must either be Primary Key or Unique Key.
5. Records in parent table cannot be updated if child record exist.
6. Foreign Key Constraint can be specified on child table not on parent table

Foreign key involves two different tables. First one is PARENT TABLE or referenced Table and
second one is CHILD TABLE or foreign table.
1. The column of parent table which will get referenced by foreign key must be
either Primary Key or Unique Key.

2. Column(s) in child table can contain NULL or Duplicate values while vice
versa is not true and.
3. Column(s) of parent table column(s) of child table which are participating in
foreign key should be of same data-type and size (column width).

How to create/ Define Foreign key


You can define foreign key constraint either by using CREATE TABLE statement or by
using ALTER TABLE statement.

1. Defining Foreign Key Using Create table at Column Level


This way of defining constraint is called column level because we define constraint
with column definition while creating table.
Syntax Column_name Datatype(size) REFERENCES
parent_table_name (parent_column_name)

For example
To demonstrate this we will use two tables parent table with the name of Authors
and child table with the name of Books Parent table authors is a simple table with 2
columns Author_id and Author_name. Where Author_id is a Primary key column.You
can add as many column as you want.
Read how to create table and how to define primary key on a table.
CREATE TABLE author
(
author_id NUMBER(3) CONSTRAINT athr_aid_pk PRIMARY KEY,
author_name VARCHAR2(30)
);

Now lets create our child table BOOKS. The structure of this table contain columns book_id
which will be the primary key for this table, book_title and Book_price and the 4th column will
be book_author_id this column will be the foreign key which will reference the author_id
column of author table you can give whatever name to this column but data-type and the size
(column width) of this column must be the same as of author_id column in author table.
CREATE TABLE books
(
book_id NUMBER(3),
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3) CONSTRAINT bok_ai_fk
REFERENCES author(author_id)
);

2.How to define foreign key using CREATE TABLE at table Level.


To define foreign key Using create table at table level. You have to define all the
column of your child table first then you have to define foreign key at the end of the
table.
Lets see the syntax first
CONSTRAINT constraint_name FOREIGN KEY(child_table_column)
REFERENCES Parent_table_name(parent_table_column)

To demonstrate how to define foreign key using create table at table level Ill recreate our child
table BOOKS.

CREATE TABLE books


(
book_id NUMBER(3) CONSTRAINT bok_bi_pk PRIMARY KEY,
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3),
CONSTRAINT bok_ai_fk FOREIGN KEY (book_author_id)
REFERENCES author(author_id)
);
As you can see I defined all the column first and then I define foreign Key constraint
in the last statement of Create table.

Define Foreign Key Using ALTER TABLE statement.


We define Foreign Key through ALTER TABLE statement when we already have a
table and then we want to emphasize the constraint over that
Suppose we have a simple table with primary key by the name of BOOKS [Please
watch my How to create table tutorial] and now you have emphasize the FOREIGN
KEY constraint on this table. In this scenario we will use ALTER TABLE statement.
Lets how
First see the syntax
ALTER TABLE child_table_name ADD FOREIGN KEY (child_column)
REFERENCES parent_table_name(parent_column)
For Example
ALTER TABLE books ADD CONSTRAINT bok_ai_fk FOREIGN KEY
(book_author_id)REFERENCES author(author_id);
Thats all you have to do.

If you try to delete parent table which is having primary or unique key which was
referenced by child table then oracle will give you a SQL Error: ORA-02449.But you can
still drop child table without any error.

On Delete Set Null.

On Delete Set Null clause of Foreign Key Explained in Detail


As we discussed in our last tutorial that Foreign key constraint establishes a link / relation
between PARENT and CHILD table. Because of this link we cannot update or delete the rows of
parent table. Foreign key is defined in the child table and parent table contains the reference
column.
By default Oracle engine is set to ON DELETE NO ACTION clause when you define a simple
foreign key. This means that you are allowed to update the rows in parent table however you
cannot delete rows from parent table.

Activity

Go To my previous tutorial on foreign key and create parent (authors) and child
(books) table with foreign key and after creating them try to drop the parent
(authors) table and see what will happen.
(To drop parent table AUTHORS execute DROP TABLE AUTHORS; ddl)

Read how to define foreign key.

This default behavior is called Restrict rule. This Restrict rule doesnt allow user to delete or
update reference data in parent table.
But we can change this default behavior of oracle, either to SET NULL or to DELTE
CASCADE by
1. ON DELETE SET NULL or
2. ON DELETE CASCADE
Referential action. Lets see how
First we will see ON DELETE SET NULL.
Remember parent table holds REFERENCE COLUMN and Child table holds FOREIGN KEY COLUMN.

When you change default restrict rule (ON DELETE NO ACTION) to ON DELETE SET
NULL then the corresponding value of foreign key in child table will set to NULL on deleting
the rows from parent table.

How to set ON DELETE SET NULL clause with foreign key.


Parent table: Authors
Note: Parent table is simply a table with primary key constraint on Author id column
which in turn is the reference column.
CREATE TABLE author
(
author_id NUMBER(3) CONSTRAINT athr_aid_pk PRIMARY KEY,
author_name VARCHAR2(30)
);
Child table: Books
CREATE TABLE books
(
book_id NUMBER(3),
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3) CONSTRAINT bok_ai_fk REFERENCES
author(author_id) ON DELETE SET NULL
);
This is how you define foreign key with ON DELETE SET NULL with create table in
column level.

You can check this constraint by executing the query - USER_CONSTRAINTS data dictionary
SELECT
constraint_name, delete_rule
FROM user_constraints
WHERE table_name = 'BOOKS' ;

On Delete Cascade.

On Delete cascade clause of Foreign Key Explained in Detail


Before jumping ahead Ill suggest you to read and watch my tutorials on foreign key and On
Delete Set Null clause for a better understanding of this topic.

On Delete Cascade as the name suggests deletes the dependent column entry in child table when
there is any attempt of deleting the corresponding value in Parent table.
You can define foreign key with ON DELETE CASCADE clause either using create table or
using alter table statement.
Lets see how
We will again define two table with the name of Authors and Books. Authors will be our parent
table with two columns author_id and author_name. We will use author_id column as reference
column for our foreign key constraint thus its mandatory for us to define this column either as
primary key or unique key. Please read about Foreign Key for more information.
Lets create parent table Authors
CREATE TABLE author
(
author_id NUMBER(3) CONSTRAINT athr_aid_pk PRIMARY KEY,
author_name VARCHAR2(30)
);

Read How To Define Primary Key Using Create Table


Now we will create our child table Books. Child table books will consist of 3 columns - book_id,
book_title and book_author_id. We will define foreign key on book_author_id column.
CREATE TABLE books
(
book_id NUMBER(3),
book_title VARCHAR2(30),
book_price NUMBER(3),
book_author_id NUMBER(3) CONSTRAINT bok_ai_fk REFERENCES
author(author_id) ON DELETE CASCADE
);

Rename Table.
Rename table using SQL alter table statement Explained in Detail
Sometimes we need to rename our table after we have already created it. In such cases there are
two ways in which you can rename your table:

1. Drop the whole table altogether and recreate it with the new name. This is a logical
choice if you are a student using your table for practice purposes only and can afford to
lose the valuable data that your table contains. In practical environment there is a BIG
NO for this method as Data held by database in tables is valuable and we cannot afford to
lose it. If you opt for this method then for you I have a disclaimer
I do not recommend this method of renaming a table. If you opt this method then
you will be responsible for your own loss.

2. Second way of renaming a table is by using ALTER TABLE data manipulation language
(DDL) statement. This is the recommended way of renaming a table. Lets see how.
In order to demonstrate how to rename a table using SQL ALTER TABLE DDL statement we
will create a very simple table by the name of TEST
Test table will have only one column test_name. You can define as many columns as you want
but since we are concentrating over the renaming of the table therefore I am taking into account
only one column.
CREATE TABLE test
(
test_name VARCHAR2(15)
);
Lets say we want to change the name of this table from TEST to EXAMPLE for that we have to
execute an ALTER TABLE statement.
First lets see the syntax of ALTER TABLE statement
Syntax
ALTER TABLE old_name_of_table RENAME TO new_name_of_table;
Now lets change the name of our table from TEST to EXAMPLE according to above syntax.
ALTER TABLE test RENAME TO example;

Add column to an existing Table.

Add column to an existing table using SQL alter table statement Explained in Detail
This is the second tutorial in the alter table series. In the last tutorial we saw How to rename a
table using ALTER TABLE statement.
Has it ever happened with you that after creating a table, you realized that you need to add

another column to it? It generally happens with me.


The first thing which comes into the mind in this scenario is to Drop the table and recreate it with
that extra column. But what if your table has a data which you cannot compromise. Means
dropping a table is not the solution here.
Dont worry there is a solution for this problem.
It is possible to add a column to an existing table using ALTER TABLE statement. By Using
ALTER TABLE statement you can add one or more than one columns to an existing table.
Lets see how.
In the previous tutorial we have created a very simple table by the name of Test. Test table has
only one column test_name.
DESC test
Name Null Type
--------- ---- -----------TEST_NAME VARCHAR2(15)
Say you want to add another column test_id to this table. Test_id column will be of
NUMBER data type and column width (size of column) will be 3.

Lets see how to add test_id column to Test table using alter table statement.

In order to add test_id column to our existing table Test using alter table we have to
first understand the syntax of the alter table statement.
Syntax
ALTER TABLE existing_table_name ADD new_column_name data_type (size);
Note here we didnt write "COLUMN" after key word ADD.
Do not write ADD COLUMN after existing table name otherwise Oracle will raise
ORA-00904: : invalid identifier SQL error.

Hope syntax is clear. So now lets write a SQL query for adding test_id column to Test table.
ALTER TABLE test ADD test_id NUMBER(3);
On executing the above query you will get a test_id column in the already created
table Test.
How To add Multiple Columns In a Table.

Similarly you can add multiple columns to an existing column. For that you just have
to put your columns definitions in a parenthesis after Keyword ADD.
Syntax for adding multiple columns to an existing table
ALTER TABLE existing_table_name
ADD (
column_name1 DataType(size),
column_name2 DataType(size),

column_name n DataType(size)
);
How to drop a column in a table.
Similarly you can drop a column from your existing table using alter table
command. Say you want to drop test_name column from Test table.
Syntax ALTER TABLE existing_table_name DROP COLUMN column_name;
e.g.
ALTER TABLE test DROP COLUMN test_name;

Rename and Modify column of a table.

Rename and Modify column of a table using SQL alter table statement Explained in Detail
This is the third tutorial in ALTER table series. Till now in previous tutorials we have seen
1. How to rename table using ALTER TABLE and
2. How To add / delete a column from an existing table using ALTER TABLE.
In this tutorial we will see how to rename a column/s of a table and how to modify
one or more columns of a table.
How to rename a column of a table.
Syntax
ALTER TABLE table_name RENAME COLUMN old_name_of_column TO
new_name_of_column;
For example
In the previous tutorial we have created a simple table by the name of TEST so we

will be using that for this example.


Table test has only one column test_name.
Structure of table Test is as follows:
DESC test
Name Null Type
------- ---- --------TEST_ID NUMBER(3)
Say you want to rename the column test_id to col1
ALTER TABLE test RENAME COLUMN test_id TO col1;
On executing the above query the column test_id of table test will be renamed to
col1. You can check it by describing the structure of TEST table.
DESC test
Name Null Type
------- ---- --------COL1 NUMBER(3)
How To modify the column definition using ALTER TABLE.
Above we saw how to rename a column of a table. Now we will see how to modify
the column definition of a table.
By modifying the column definition, what I mean is to change the Data type and
column width of the column.
Syntax
ALTER TABLE table_name MODIFY colun_name data_type (size);

Example:
Above we renamed column test_id to col1. Column col1 has NUMBER data type and column
width 3;
Now lets say we want to change the data type of column col1 from NUMBER to VARCHAR2
and data width from 3 to 30;
ALTER TABLE test MODIFY col1 VARCHAR2(30);
You can verify the change by describing the structure of the test table by DESCRIBE
command
DESC test
Name Null Type
------- ---- --------COL1 VARCHAR2(30)
Character Manipulation Functions
SQL Substr Function.

After SQL Concat function , SQL Substr function is the second character manipulation function
in the hierarchy.
As name the suggests SQL Substr function will return substring from a given source string.
Syntax: Substr ( source_string, start_pos, Substr_length )
As we can see SQL substr function takes 3 parameters.
First one is Source string from which you want to extract the segment. Second
parameter is Starting position for sub string from the Source string. And the third
parameter is Substr_length which is the length for the substring.
First two parameters are MANDATORY to specify while third one is OPTIONAL.
So we can say.
SQL Substr function will return a sub string of a specified length from the source
string beginning at a given position.
First parameter source string can be of any data type CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB and both start_pos, Substr_length parameters must
be number data type. The returning result of SQL Substr function is of same data
type of source string.
Lets see an example of SQL Substr function.
SQL> SELECT substr( 'www.RebellionRider.com', 5, 14 ) FROM dual;
Here in this query url of my website www.RebellionRider.com is our source string
with the total length of 22 characters. I want to extract the name of my website
which is RebellionRider. So if you count the total length of the name of the website,
it is 14 Thats why I have specified 14 as my third parameter of SQL Substr function
which is substr_length. Also the name of the website RebellionRider is starting from
position 5th therefore I have specified 5 at second parameter of SQL substr function
which is strt_pos starting position.
On Execution the output of this example will be the name of the Website
'RebellionRider'.

Scenarios
There are few scenarios related to SQL Substr function such as -

First scenario

When starting position is larger than the length of source string.


In this case SQL Substr function will return NULL as a result. Lets do an example.
SELECT substr( 'www.RebellionRider.com', 23, 14 ) FROM dual;
As you can see here I have specified 23 at starting position and the total length of
our source string is 22 characters. On executing this query we will get NULL in
return.

Second scenario
When the Substr_length is greater than source string
In this case the segment return is the substring from starting position to the end of
the String.
For example
SELECT substr( 'www.RebellionRider.com', 5, 23 ) FROM dual;
Our starting position is at 5 means at the first R of RebellionRider and length of
substring is set to 23 which is greather than the length of source string that is 22.
On executing this query will get a substring from first R of RebellionRider till the end
of the source String.
Third scenario
When you supply numeric or arithmetic expression or a Data as Source
string to SQL Substr function
In this scenario If you have supplied a numeric string instead of character as source
string, the oracle engine casts them as a character when they occur as parameter
to SQL Substr function. And if you have supplied Arithmetic expression or a DATE
then The Oracle engine first solves or evaluates the Arithmetic expression or the
DATE. it casts them as a character.
Means if you have arithmetic expression in your source string then oracle will first
solve it and then change or say cast the value of its result into character. Lets see
some example.
SELECT substr( 50000-7, 2, 4 ) FROM dual;
Oracle first evaluates the arithmetic expression that is 50000-7 equal to 49993.And
then oracle engine casts this result 49993 into a character string. Means 49993 will
be a 5 characters string.
Starting position of substring is 2, that means from the first 9 of 49993
We specified the length of substring is 4 so we must get 9993 as our result. Lets
check execute Here is our result Similarly if you give a data as your source string it
first gets evaluated and then gets casted Lets do an example

SELECT Substr ( sysdate, 4, 3) FROM dual;


Above query first evaluates the SYSDATE function and then converts the date
returned into a character string. Assume that the current system date is 02-APR-14.
The search for the substring begins at position 4 and the three characters from that
position onward are extracted, yielding the substring APR.

Fourth scenario
When Starting position (start_pos) is set To 0 (Zero)
In this scenario when user sets the starting position which is the second argument
of SQL Substr function to 0 (Zero) then the oracle engine treats this zero as One and
starts searching or say extracting sub string from the starting of Source string.
For example
SELECT substr( 'www.RebellionRider.com', 0, 14 ) FROM dual;
In the above query we set the starting position for our sub string on Zero and the
Length of substring on 14. This means The search for the substring begins at
position 1 that is from the first w of www and the 14 characters from that position
onward are extracted, yielding the substring www.RebellionR
Fifth scenario
When Starting position (start_pos) is set To a Negative number
In this scenario when user sets starting position of the second argument of SQL
Substr function to a negative number say -3 then oracle engine counts backward
from the end of the source string
For example
SELECT substr( 'www.RebellionRider.com', -9, 5 ) FROM dual;
Here searching of sub string will start from the character R of Rider as character R
is at the 9th position from the end of the source string. Then five characters from
that position onward are extracted, yielding the substring RIDER.
Sixth scenario
when the length of substring (substr_length)is omitted
I have already mentioned above that the Third argument of SQL Substr function is
optional, which means that its not mandatory for you to specify the length of
substring. In case the user does not specify length for Sub string then Oracle engine
returns all characters to the end of source string.
For example
SELECT substr( 'www.RebellionRider.com', 5 ) FROM dual;

As you can see I didnt specify the third argument of SQL Substr function which is
Substr_length (sub string length) in the above query. In this case oracle engine will
start searching substring from the specified position which is 5 in our query and all
the characters till the end from that position onward are extracted, Yielding the
substring RebellionRider.com .

Character Manipulation Functions


SQL Concat Function.

As we have already seen the hierarchy of SQL functions in my previous article SQL Concat ()
function is a character manipulation SQL function. As the name suggests SQL Concat () function
concatenates or combines two separate character strings and returns a single character strings.
Syntax: CONCAT (string_1, String_2)
In oracle, the SQL Concat () function takes only two arguments. These arguments
can be of any data-types CHAR, VARCHAR2, NCHAR, NVARCHAR, and CLOB or NLOB.
You can even specify the columns of the table here.
For example
Say if you want to retrieve full name of employee from employees table then you
can use SQL Concat () function as
SQL> SELECT Concat (first_name, last_name) FROM employees;
Here first_name and last_name are two columns of hr. employees table.
The output of this query will be the full name of employee without any space
between first name and last name. And if you want to concatenate two strings then
you can specify two separate character strings as arguments of SQL Concat
function.
For example
SQL> SELECT concat ('hello ','world!')FROM dual;
As you can see we have used two separate character strings Hello and World!
here as arguments to our SQL concat function. On execution the output of this
query will be Hello World!
So from the above two examples its clear that SQL concat function returns a single
string which is a combined string of parameter String_1 and String_2.

SQL concat function is equivalent to SQL concat operator?


Yes, it is true that both SQL concat function and SQL concat operator perform the
same task. Then question arises here that what is the difference between SQL
concat function and SQL concatenation operator?
Both SQL concat function and SQL concatenation operator have their advantages
and disadvantages.
While SQL concat function takes only two parameters, SQL concat
operator can be repeated as often as is necessary.

As we have seen above that we can only provide two arguments to SQL concat function neither
more than two nor less than two but with SQL concatenation operator scenario is totally
different. With SQL concatenation operator you can combine as many strings as you want

How to combine more than two strings using SQL concat


function?
Now you must be thinking that How to combine more than two strings using
SQL concat function that can have only two parameters?
Although SQL concat takes only two parameters you can still combine more than
two strings. But for that you will have to use the concept of Nesting SQL concat
function.
How? Let me explain.
Say you want to concatenate the string - Hi! How are you? using SQL concat
function. For that we will be nesting concat function.
Lets see how.
SELECT
CONCAT(CONCAT(CONCAT(CONCAT(
CONCAT(CONCAT(CONCAT
('Hi!',''),'How'),' '),'are'),' '),'You'),'?')
FROM dual;
As you can see here that just to concat a single string Hi! How are you? We
have to use seven concat functions.
Thanks to SQL developer who helps us in remembering all the parenthesis

phewww!!
Incidentally this task can be achieved much easily if you use SQL concatenation
operator.
Lets see how
SELECT
'Hi!'||' '||'How'||' '||'are'||' '||'you'||'?'
FROM dual;

Archiving in Oracle Database explained.


What is archiving in oracle database?
The configuration of a database at the time of its creation is necessary in order to easily recover
your data in case of any occurrence of system failure. Online redo log files are the ones that
contain the complete record of any changes that were made to the primary data files. These
online redo log files are stored in online redo log groups. It is important to have at least two
online redo log groups for your database. Once an online redo log files belonging to a group have
been filled, the log writer process (LGWR) switches to a new group for continuing the writing
process of redo log records. The inactive group of online redo log files can be automatically
saved by the Oracle database at one or multiple offline destinations. These destinations are
collectively addressed as archived redo log or the archive log. This process of converting online
redo log files into archived log is called Archiving.
The process of archiving can only be performed when the database is running in the
ARCHIVELOG mode. It is important to note that unless the group of online redo log files is
archived, they cannot be reused by the log writer (LGWR). In case the LGWR switches to a new
group and leaves the previous one inactive for some time then that inactive group becomes
readily available for immediate reuse by the LGWR process provided the database is running in
NOARCHIVELOG mode.

A database instance failure could be avoided in NOARCHIVELOG mode however this mode
does not protects the database from media failure. The most recent changes made to the database
that is stored in the online redo log files are only ones available for instance recovery. Therefore
in order to restore the database operating in NOARCHIVELOG mode, you can only use the

entire database backups that were taken while it was closed. Therefore it is essential that you
frequently back-up the entire database when operating it in NOARCHIVELOG mode.
The advantages of archiving online redo log files are:
1. A database backup, with online and archived redo log files, ensures that you can recover
all committed transactions in case of the failure of operating system or hardware.
2. If you have a copy of the archived log files that were written while the database was
being backed up then you can easily recover the database using that backup which was
taken while the database was open and being used.
3. You can perform online tablespace backups, and use these backups to restore a tablespace
following media failure.
4. You can keep a standby database current with its original database by continuously
applying the original archived redo log files to the standby database.
The destination to which you want to archive the online redo log files must be decided
beforehand. It is recommended by Oracle that archive log should be stored in such areas that are
capable of fast recovery in order to simplify the operations of backup and recovery. There is a
difference between fast recovery area and database area. The former is where the Oracle database
stores and manages files related to backup and recovery whereas the latter is the location of the
current database files that include data files, control files and online redo log files.

Вам также может понравиться