Manish SQL Notes
Manish SQL Notes
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.
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.
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.
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
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.
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;
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.
20,
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
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.
The expressions in the SELECT lists must match in number and data type.
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.
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
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.
Analyze data from an earlier point in time by using Oracle Flashback Query
If you do not specify this clause then oracle engine will by default set the retention on No
Guarantee.
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;
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;
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.
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
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.
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 : 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.
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.
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.
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.
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);
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.
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
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
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
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;
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
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
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.
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.
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.
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.
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.
USER_CONSTRAINTS
USER_CONS_COLUMNS
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';
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.
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).
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)
);
To demonstrate how to define foreign key using create table at table level Ill recreate our child
table BOOKS.
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.
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)
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.
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 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)
);
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 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
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 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
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
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
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 .
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.
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
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;
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.