You are on page 1of 66

Oracle 11g

SQL Lab Guide Part I


This is another document from our learn Oracle SQL query series. We are
committed to provide the BEST learning materials to the beginners. n the
series! this document assists ne" bees to learn SQL Queries. The document
teaches steps by steps "ay to "rite simple to comple# SQL queries. The
document consists of many e#amples to ease your learning. $oin our
professional training program to learn from e#perts.
%rovided By& BS% 'reated By& (bhishe) *umar Srivastava
http&++bispsolutions."ordpress.com ,evie"ed By& (mit Sharma
learnsqlquery."ordpress.com Team BS%
learnsqlquery.wordpress.com | SQL Lab Guide 1
Table of 'ontent--------------------------.../0
(A) ntroduction-------------------------------..1/23
Oracle 22g 4atabase------------------------------.1
4ata 5odels-----------------------------------.1
Entity ,elationship 5odel---------------------------26
,elational 4atabase------------------------------..26
7sing SQL 'ommands-----------------------------..26
SQL 4evelopment Environment------------------------22
Oracle SQL 4eveloper-----------------------------..2./23
'reating 4atabase 'onnection------------------------..2./23
1. 4ata ,etrieving by using SELE'T statement----------.28/..
'reating Table----------------------------------28
nsert 4ata into Table-----------------------------..28
7sing SELE'T statement for (ll 'olumns-------------------28/29
7sing SELE'T statement for Selecting Specific 'olumns----------.29
Way of "riting of SQL Statement-----------------------..29/20
E#ecuting SQL Statements---------------------------.20
'olumn :ames in a Table---------------------------...2;
7sing (rithmetic E#pressions in SQL---------------------.2;/21
Operators %recedence-----------------------------..21/.6
'olumn (liases----------------------------------.6
4efining and 7sing 'oncatenation Operator-----------------.2
4efining and 7sing Literal 'haracter Strings----------------....2
learnsqlquery.wordpress.com | SQL Lab Guide 2
4isplaying Structure of Table-------------------------....
2. ,estricting and Sorting 4ata-------------------.</.1
7sing W=E,E 'lause------------------------------..<
'haracter Strings and 4ates--------------------------.<
4efining and 7sing 'omparison Operator------------------.3/.8
7sing BETWEE: Operator as for ,ange 'ondition------------.....8/.9
7sing L*E Operator for %attern 5atching-----------------...9
Wildcard 'haracters------------------------------..0
7sing :7LL 'onditions-----------------------------.0
4efining conditions using Logical Operators----------------..;/.1
7sing (:4 Operator------------------------------...;
7sing O, Operator-------------------------------...;
7sing :OT Operator-------------------------------.1
3. 7sing Single/,o" >unctions to 'ustomi?e Output-------.<6/<3
SQL >unctions----------------------------------.<6
Single/,o" >unctions------------------------------<6
'haracter >unctions-------------------------------<6
7sing 'ase 'onversion >unction------------------------<2/<.
7sing 'haracter 5ultiplication >unctions------------------..<.
:umber >unctions--------------------------------<./<<
7sing ,O7:4 >unction---------------------------..<.
7sing T,7:' >unction----------------------------<<
7sing 5O4 >unction-----------------------------.<<
Wor)ing "ith 4(TE >unction-------------------------..<</<3
learnsqlquery.wordpress.com | SQL Lab Guide 3
S@S4(TE-----------------------------------..<3
4. 7sing 'onversion >unctions and 'onditional E#pressions--..<8/0<
'onversion >unction------------------------------...<8
mplicit------------------------------------..<8
7sing TOA'=(, >unction "ith 4(TE----------------------<8
7sing :esting >unction-----------------------------.<9/<0
7sing :BL >unction-------------------------------.<9
7sing :BL. >unction------------------------------..<9
7sing :7LL> >unction-----------------------------.<9
7sing 'O(LES'E >unction---------------------------..<9
'onditional E#pressions----------------------------..<0
'(SE E#pression-------------------------------.<0
4E'O4E >unction------------------------------..<0
5. ,eporting aggregated 4ata using Croup >unctions------<;/3.
Croup >unctions--------------------------------..<;
7sing (BC and S75 functions-------------------------<;
7sing 5(D and 5: functions-------------------------<1
7sing the 'O7:T function---------------------------.<1
7sing the 4ST:'T )ey"ord-------------------------..36
Croup >unctions and :7LL Balues----------------------..36
'reating Croups of 4ata----------------------------..36/32
7sing Croup By clause on multiple columns-----------------32
7sing =aving 'lause---------------------------.---..32
:esting Croup >unctions----------------------------.3.
learnsqlquery.wordpress.com | SQL Lab Guide 4
6. 4isplaying 4ata from 5ultiple Tables--------------.3</38
Types of $O:-----------------------------------.3<
:atural $oins---------------------------------.3</33
:atural $oin clause----------------------------3<
7S:C clause-------------------------------.33
O: clause---------------------------------.33
:on/equiEoins--------------------------------...33
Outer $oins----------------------------------..38
Left Outer---------------------------------.38
,ight Outer $oin-----------------------------..38
>ull Outer $oin------------------------------..38
'ross $oins----------------------------------..38
7. 7sing Sub queries to solve queries----------------39/3;
Sub/query-------------------------------------39
Single/ro" sub/query------------------------------.39/30
7sing Croup >unctions in a sub/query---------------------30
7sing =(B:C clause "ith sub/queries--------------------..30
5ultiple/ro" sub/query-----------------------------.3;
: Operator--------------------------------..3;
(:@ Operator-------------------------------.3;
(LL operator-------------------------------...3;
8. 7sing the SET Operators---------------------..31/8.
learnsqlquery.wordpress.com | SQL Lab Guide
SET Operators----------------------------------.31
Oracle server and Set operators------------------------31
7sing the 7:O: Operator---------------------------.31/86
7sing the 7:O: (LL Operator------------------------...86
7sing :TE,SE'T Operator---------------------------82
7sing 5:7S Operator-----------------------------..82
7sing O,4E, B@ clause in set operations------------------...82/8.
9. 4ata 5anipulation-------------------------.8</81
4ata 5anipulation Language--------------------------8<
(dding :e" ,o" in a table---------------------------.8<
nserting ro"s "ith null values------------------------...8<
nserting special values-----------------------------.83
nserting specific 4ate Balues--------------------------83
'reating a Script---------------------------------..83
'opying ,o"s from one table to another--------------------88
7pdating data in a table------------------------------88
7pdating ro"s based on another table---------------------.88
,emoving ro"s from a table---------------------------..89
T,7:'(TE Statement-------------------------------.89
4atabase Transaction-------------------------------.80
mplicit Transaction %rocessing-------------------------..80
E#plicit Transaction %rocessing--------------------------8;
State of data before 'O55T or ,OLLB('*-------------------.8;
7sing 'O55T statement----------------------------8;
learnsqlquery.wordpress.com | SQL Lab Guide !
7sing ,OLLB('* statement--------------------------..81
Statement/Level ,ollbac)---------------------------..81
26. 7sing 44L statements to create and manage tables------96/9<
4atabase ObEects--------------------------------..96
:aming ,ules----------------------------------..96
',E(TE Table Statement----------------------------.96/92
4ata Types------------------------------------.92/9.
'onstraints------------------------------------.9.
7sing :OT :7LL 'onstraint--------------------------...9<
7sing 7:Q7E 'onstraint----------------------------.9<
22. 'reating Other Schema ObEects------------------93/9;
4atabase ObEects--------------------------------..93
Bie"s---------------------------------------.93
Simple and 'omple# vie"s---------------------------.93
'reating Bie"----------------------------------..93/98
,etrieving data from a Bie"--------------------------.98
5odifying a Bie"--------------------------------...98/99
'reating a 'omple# Bie"----------------------------.99/90
,ules for performing 45L operations on a Bie"---------------90
7sing WT= '=E'* O%TO: clause-----------------------90
4enying 45L Operations----------------------------..9;
,emoving a Bie"---------------------------------.9;
Sequence--------------------------------------9;
ntroduction
learnsqlquery.wordpress.com | SQL Lab Guide "
Oracle 22g 4atabase&/
Oracle 22g database is designed for some features, which helps to the
organizations to manage everthing easil and deliver high!"ualit services#!
$%&'s can increase their productivit, reduce costs, minimize errors and ma(imize
the "ualit of services b using the management automation, fault diagnostics
features, etc)
*e can reduce the ris+ of down time and data loss b using the high availabilit
features)
,ere the performance of the database is so improved because of OL-P, secure files
etc and it helps to secure the information of organization with the data encrption
and mas+ing, and comple( auditing capabilities, so it's protected)
4ata 5odel&/
& data model is used to organize data) It captures the cardinalit and referential
integrit rules needed to ensure that the data is of good "ualit for the users)
-he main aim of data models is to support the development of information sstems
b providing the definition and format of data)
>igure/ (.2
Entity ,elationship 5odel&/
In software engineering, an entity/relationship model .E,5/ is an abstract and
conceptual representation of data)
learnsqlquery.wordpress.com | SQL Lab Guide #
,elational 4atabase&/
& relational database matches data b using common characteristics found within
the data set) -he resulting groups of data are organized and are much easier for
man people to understand) It means it can contain one or man tables)
>igure/ (..
$iagrams created b this process are called entity/relationship diagrams, E,
diagrams, or E,4s)
7sing SQL 'ommand&/
SQL is a standard language for accessing databases) It is a computer language aimed
to store, manipulate, and "uer data stored in relational databases)
SQL provides statements for variet of tas+s, including#
Quering data
Inserting, updating, and deleting rows in a table
0reating, replacing, altering, and dropping ob1ects
0ontrolling access to the database and its ob1ects
SQL Statements&
,ere are the SQL Statements, which we are used for "uering with database, as!
2. 4ata 5anipulation LanguageF45LG/
learnsqlquery.wordpress.com | SQL Lab Guide $
2etrieve data from database, enter new rows, 0hanges in e(isting rows, and
removes the rows which we no need to use from the tables in the database)
SELE'T! :SE,T! 7%4(TE! 4ELETE! 5E,CE)
.. 4ata 4efinition LanguageF44LG/
Sets up, changes and removes data structures from tables)
',E(TE! (LTE,! 4,O%! ,E:(5E! T,7:'(TE! 'O55E:T)
<. 4ata 'ontrol LanguageF4'LG/
Provides or removes access rights to Oracle database and structures within
it)
C,(:T! ,EBO*E)
3. Transaction 'ontrol/
3anages the changes made b $3L statements)
'O55T! ,OLLB('*! S(BE%O:T)
SQL 4evelopment Environment&/
4or this, we used SQL 4eveloper and SQL%L7S)
Oracle SQL 4eveloper and 4atabase 'onnection& /
&fter installing the Oracle 22g on Oracle Enterprise Linu#8, login as the Oracle
user)
learnsqlquery.wordpress.com | SQL Lab Guide 1%
5ow first, as we have to open the SQL4EBELO%E,, so for opening this, open the
Terminal and go to the folder where SQL4EBELO%E, e(ists) &s shown in the
Creen bo() &nd run the sqldeveloper shell file)
5ow e(ecute this command as an oracle user#!
H cd +u62+app+oracle+product+22.2.6+dbA2+sqldeveloper
H .+sqldeveloper.sh
>igure& (. <
&fter e(ecuting this command, s"ldeveloper starts to wor+ properl)
>igure& (. 3
5ow we have to open the SQL%L7S) So for running this, we have to e(ecute the
following commands)
So we have to set the 'O,('LEAS4', 6O,('LEAB(SE', and 6O,('LEA=O5E')
learnsqlquery.wordpress.com | SQL Lab Guide 11
4or setting the O,('LEA=O5E, we have to set the path for the dbAhome as here
dbA2#!
H e#port O,('LEAS4Iorcl
H e#port O,('LEAB(SEI+u62+app+oracle+product+22.2.6+dbA2
H e#port O,('LEA=O5EI+u62+app+oracle+product+22.2.6+dbA2
&nd then set the Environment Bariable as 6orcl' as shown in the figure#!
H oraenv
>igure& (. 8
&fter the 7nvironment variable, go to the dbAhome as dbA2 here and give the
permission to the sqlplus and then go inside the 6bin' folder and again give the
permission to sqlplus and e(ecute the 6)sqlplus' shell file)
H cd +u62+app+oracle+product+22.2.6+dbA2
learnsqlquery.wordpress.com | SQL Lab Guide 12
H chmod 000 sqlplus
H cd bin
H chmod 000 sqlplus
H. +sqlplus
&fter e(ecuting these commands the sqlplus wants the userAname and pass"ord
before starts)
So give the correct userAname and pass"ord.
-hen sqlplus is read for use that is shown in the green bo()
'hapter/ 2
1. 'reating Table& / 4or creating table, we have to give the table name and the
columns name and their data tpe and the size of the data which we can insert) 5ow
e(ecute the following SQL command for creating the table!
learnsqlquery.wordpress.com | SQL Lab Guide 13
>igure/2.2
2. nsert 4ata into Table& / *hen table will create, and then we have to insert data
into the table, which will be inserting in the following columns that are specified
before) So we can insert data b e(ecuting the following SQL command!
>igure/2..
3. 7sing SELE'T Statement for (ll 'olumns& /
SELE'T identifies the columns to be displaed)
>,O5 identifies the table containing those 0olumns)
>igure/2.<
*e can displa all columns of data in a table b e(ecuting the SELE'T statement
with an asteris) FJG)
In the above e(ample, the employee table contains two columns name and
address) -he table contains four rows of data for each column)
learnsqlquery.wordpress.com | SQL Lab Guide 14
*e can also show all data b e(ecuting all the column names!
>igure/2.3
4. Selecting some Specific 'olumns& / *e can use the SELE'T statement to displa
some specific columns onl)
>igure/2.8
5. Ways of Writing SQL Statement& /
SQL Statements are not case sensitive)
SQL Statements can be entered on more than one line)
8ewords cannot be Split or abbreviated)
In SQL 9 Plus, we are re"uired to end each SQL Statement with a Semicolon FKG) %ut
in SQL $eveloper it's optional, but when we e(ecute multiple SQL Statements then
Semicolon is re"uired)
6. E#ecuting SQL Statements& /In SQL $eveloper, clic+ on the ,un Script icon or
press >8 button to run the command in SQL *or+sheet) *e can also clic+ on
E#ecute Statement or press >1 button to run the command in SQL *or+sheet)
learnsqlquery.wordpress.com | SQL Lab Guide 1
>igure/2.9
In SQL 9 Plus, terminate the SQL Statement with a semicolon FJG and press E:TE, to
run the command)
7. 'olumn :ames in a Table& / 0olumn name in SQL $eveloper is alwas displa in
Left!aligned and in :pper case)
0olumn name in SQL 9 Plus also is alwas displa in Left!aligned and in :pper case)
learnsqlquery.wordpress.com | SQL Lab Guide 1!
>igure/2.0
8. 7sing (rithmetic E#pressions& /*e ma need to modif the data and also have to
perform some calculations) &ll these are possible using the arithmetic e(pressions)
&n arithmetic e(pression contains the 0olumn names, &rithmetic operators and
0onstant numeric values) -hese are the arithmetic operators!
L F(ddG,
M FSubtractG,
JF5ultiplyG,
+ F4ivideG
w, we have a table and there is a salary column and we have to update this column)
learnsqlquery.wordpress.com | SQL Lab Guide 1"
>igure/2.;
5ow, we will increase the salar of all emploees b ;<<) So e(ecute the following
command!
>igure/2.1
9. Operators %recedence& /If in an arithmetic e(pression, more than one operator is
used then there is some precedence for using the operators)
So there are some rules of precedence of the arithmetic operators!
3ultiplication and $ivision operators occur before the &ddition and Subtraction
operators)
Operators of same priorit are evaluated from left to right)
learnsqlquery.wordpress.com | SQL Lab Guide 1#
Parentheses are used to override the default precedence)
>igure/2.26
n the above e(ample, there used the parentheses and the operators also)
10. 'olumn (liases& /% this, we can rename the column headings) -here is used (S
+eword in between the column name and the alias)
-here is used $ouble "uotation mar+ FNOG, if alias contains space or Special
'haracters)
>igure/2.22
In the above e(ample, there used $ouble "uotes for alias name because there is space in
between the name) &nd now we can see the 0olumn name has been changed)
11. 'oncatenation Operator& /It lin+s 0olumns or character strings to other columns)
It is represented b two vertical bars FPPG)
learnsqlquery.wordpress.com | SQL Lab Guide 1$
>igure/2.2.
12. Literal 'haracter String& /& literal is a character, a number, or a date that is
included in SELE'T statement)
>igure/2.2<
0haracter and $ate literals must be enclosed within Single Quote mar+s FQQG whereas
5umber literals need not be enclosed)
Li+e in above e(ample, QfromR is as literal character string)
learnsqlquery.wordpress.com | SQL Lab Guide 2%
13. 4isplaying Structure of Table& /:se the 4ES' command to displa the structure
of a table)
>igure/2.23
'hapter/ .
1. 7sing W=E,E 'lause& /& W=E,E clause contains a condition that must be met and
it directl follows >,O5 clause) If condition will be true, the row meeting the
condition is returned)
learnsqlquery.wordpress.com | SQL Lab Guide 21
-he W=E,E clause can compare values in columns, literal, arithmetic e(pression
and functions)
>igure/..2
In the above e(ample, we used the condition with name and getting the
employeeA)ey in result)
2. 'haracter Strings and 4ates& / 0haracter strings and $ate values are enclosed with
single "uotation mar+s FQRG) 0haracter values are case!sensitive and $ate values are
4ormat!sensitive)
>igure/...
In the above e(ample, there is condition with character string, so we enclosed it with
single "uotation mar+s)
$efault format for displaing the date is 44/55/@,)
3. 'omparison Operators& /0omparison operators are used in conditions that
compare one e(pression with another e(pression or value) -he are used with
W=E,E clause li+e this!
SQLS Select e#pr from tableAname "here e#pr operator valueK
,ere are some operators, which are used for comparing two e(pressions or values!
learnsqlquery.wordpress.com | SQL Lab Guide 22
I F7"ual toG!
S FGreater thanG!
SI FGreater than or e"ual toG!
T FLess thanG!
TI FLess than or e"ual toG!
TS F5ot e"ual toG!
BETWEE: value (:4 value .%etween two valuesG!
:.set/ F3atch an of list of valuesG!
L*E F3atch a character planG
S :7LL FIs a null valueG
>igure/..<
5ow, here is an e(ample for comparing the value!
learnsqlquery.wordpress.com | SQL Lab Guide 23
>igure/..3
7sing BETWEE: operators for ,ange condition /*e can displa rows based on a
range of values using BETWEE: operators) -he range that we specif will contain
lower and upper limit of range)
>igure/..8
7sing : Operator/ 4or testing for values in a specified set of values, use the I5
operator) If there is used character or date, then it must be enclosed within the
single "uotation mar+s FQRG)
-he : operator can be used with an data tpe)
-he : operator is used onl for logical simplicit)
learnsqlquery.wordpress.com | SQL Lab Guide 24
>igure/..9
In the above e(ample, there is used the managerAmb3 and on the basis of this, the
employeeA)ey and managerAcode3 will show)
4. 7sing L*E Operator& /-he L*E operator can be used as a shortcut for some
BETWEE: comparisons) *e ma not alwas +now the e(act value to search for) *e
can select rows that match a character pattern b using L*E operator) -here is two
smbols can be used to construct the search string!
J U F2epresents an se"uence of zero or more charactersG
J A F2epresents an single characterG
>igure/..0
learnsqlquery.wordpress.com | SQL Lab Guide 2
In the above e(ample, the data of employeeA)ey and managerAmb3 will show for
the ear of .66< because we used the U6< with L*E operator)
. Wildcard 'haracters& /-he U and A smbols can be used in an combination with
literal characters for pattern matching)
>igure/..;
!. 7sing :7LL 'onditions& /& null value means that the value is unavailable,
unassigned or un+nown) *e cannot test with I operator because null cannot be
e"ual or une"ual to an value)
:7LL conditions include S :7LL or S :OT :7LL condition) -he IS 5:LL condition
tests for null value)
>igure/..1
In the above e(ample, there is shown the firstAname whose recordAendAdate
columns have :7LL value)
learnsqlquery.wordpress.com | SQL Lab Guide 2!
". Logical Operators& /& logical condition combines the result of two component
conditions to produce a single result based on those conditions or inverts the result
in a single condition) & row is returned if the overall result of the condition is true)
-here are three logical operators are available in SQL!
(:4! 2eturns -2:7 if both component conditions are true)
O,! 2eturns -2:7 if either component condition is true)
:OT! 2eturns -2:7 if the condition is false)
(:4 Operator& &5$ operator re"uires both the conditions to be true)
>igure/..26
In the above e(ample, here is chec+ing the managerAmb3 and managerAcode8b
giving condition and give the result for employeeA)ey)
O, Operator& O, operator re"uires either component condition to be true)
>igure/..22
In the above e(ample, whenever one condition will be true employeeA)ey will be
shown)
learnsqlquery.wordpress.com | SQL Lab Guide 2"
:OT Operator&
>igure/..2.
In the above e(ample, all other productA)ey is showing that is not related with the
productAlineAcode condition)
learnsqlquery.wordpress.com | SQL Lab Guide 2#
'hapter/ <
1. SQL >unctions& /4unctions are a ver powerful feature of SQL) SQL 4unctions
sometimes ta+e arguments and alwas return a value) -he can be used to do the
following!
Perform calculations on data
3odif individual data items
3anipulate output for groups of rows
4ormat dates and numbers for displa
0onvert column data tpes
-here are two tpes of SQL 4unctions!
F(G. 5ultiple/ro" functions/ 4unctions can manipulate groups of rows to give one
result per group of rows) -hese functions are also +nown as group functions)
FBG. Single/ro" functions/ -hese functions operate on single rows onl and return one
result per row) -here are different tpes of single!row functions!
'haracter >unctions& &ccept character input and can return both character and
number values)
:umber >unctions& &ccept numeric input and return numeric values)
4ate >unctions& Operate on values of the 4(TE data tpe)
2. 'haracter >unctions& /Single!row character functions accept character data as
input and can return both character and numeric values) 0haracter functions can be
divided into the following!
0ase!conversion functions
0haracter!manipulation functions
LOWE, Fcol+e#prG ! 0onverts alpha character values to lowercase
7%%E, Fcol+e#prG ! 0onverts alpha character values to uppercase
:T'(% Fcol+e#prG ! 0onverts alpha character values to uppercase for first
character of the word and all other in lowercase)
learnsqlquery.wordpress.com | SQL Lab Guide 2$
'O:'(T Fcol2+e#pr2! col.+e#pr.G = 0oncatenates the first character value to the
second character value)
&nd more are!
S7BST,! LE:CT=! :ST,! L%(4! ,%(4! T,5! ,E%L('E)
3. 'ase conversion functions& /-hese functions convert the case for character strings)
LOWE,& 0onverts character strings to lowercase)
7%%E,& 0onverts character strings to uppercase)
:T'(%& 0onverts first letter to uppercase and all in the lowercase)
>igure/<.2
>igure/<..
learnsqlquery.wordpress.com | SQL Lab Guide 3%
In the e(ample 4igure!>)?, the manager names are in upper and lower case both and
we are searching b onl lower case b LOWE, function and the result will be same
as in the database)
4. 'haracter/manipulation function& /-here are some character!manipulation
functions!
'O:'(T! S7BST,! LE:CT=! :ST,! L%(4! ,%(4! ,E%L('E! T,5)
>igure/<.<
. :umber >unctions& /5umber functions accept numeric input and return numeric
values) -here are some number functions that are used!
7sing ,O7:4 >unction/ It rounds the column, e(pression, or value to n decimal
places) If the second argument is zero or is missing, the value is rounded to zero
decimal places)
>igure/<.3
7sing T,7:' >unction/ -runcates the column, e(pression, or value to n decimal
places or, if n is omitted, n defaults to zero)
learnsqlquery.wordpress.com | SQL Lab Guide 31
>igure/<.8
7sing 5O4 >unction/ -he 3O$ function finds the remainder of the first argument
divided b the second argument)
>igure/<.9
!. 4(TE >unctions& / Oracle database stores dates in an internal numeric format) -he
default displa and input format for an date is 44/55/,,)
>igure/<.0
S@S4(TE/ It is a function that returns $&-7 and -I37) It returns the current
database server date and time) S@S$&-7 returns the current date and time set for
the operating sstem on which the database resides)
learnsqlquery.wordpress.com | SQL Lab Guide 32
>igure/<.;
'hapter/3
2. 'onversion >unctions& /
learnsqlquery.wordpress.com | SQL Lab Guide 33
mplicit/ In the e(pressions, the Oracle server can automaticall convert the
following!
B(,'=(,. or '=(, to :75BE,
B(,'=(,. or '=(, to 4(TE
:75BE, to B(,'=(,. or '=(,
4(TE to B(,'=(,. or '=(,
'=(, to :75BE, conversions succeed onl if the character string represents a
valid number)
2. 7sing TOA'=(, >unction "ith 4(TE& / -OA0,&2 converts a datetime data tpe to
a value of B&20,&2? data tpe in the format specified b format model) & format
model is a character literal that describes the format of datetime stored in a
character string)
-he format model must be enclosed with single "uotation mar+s and is case!
sensitive)
-he format model can include an valid date format element) %ut be sure to separate
the date value from the format model with a comma)
>igure/3.2
3. 7sing :esting >unctions& /5ested functions are evaluated from the innermost level
to the outermost level)
-here is some function that wor+s with an data tpe and pertain to the use of null
values in the e(pression list!
learnsqlquery.wordpress.com | SQL Lab Guide 34
7sing :BL >unction/-his function converts the null value to an actual value)
:BL Fe#pr2! e#pr.G
E#pr2 is the source value that ma contain a null)
E#pr. is the target value for converting the null)
*e can convert an data tpe, but the return value is alwas the same as the
data tpe of e#pr2)
$ata tpes that can be used are date, character, and number)
7sing :BL. >unction/-his function e(amines the first e(pression) If first
e(pression is not nullC then the 5BL? function returns the second function) If first
function is null, then the third e(pression is returned)
:BL. Fe#pr2! e#pr.! e#pr<G
E#pr2 is the source value that ma contain a null)
E#pr. is a value that is returned if e(pr1 is not null)
E#pr< is a value that is returned is e(pr1 is null)
7sing :7LL> >unction/It compares two e(pressions) If the are e"ual, function
returns a null) If the are not e"ual, then function returns e(pr1) ,owever we cannot
specif the literal 5:LL for first e(pression)
:7LL> Fe#pr2! e#pr.G
7sing 'O(LES'E >unction/ 0O&L7S07 function can ta+e multiple alternate values
over the 5BL function) If first e(pression is not null, this function returns that
e(pression, otherwise it does same for the remaining e(pressions) &ll e(pressions
must be of the same data tpe)
'O(LES'E Fe#pr2! e#pr.--.e#prnG
E#pr2 returns this e(pression if it is not null)
E#pr. returns this e(pression if the first e(pression is null and this
e(pression is not null)
learnsqlquery.wordpress.com | SQL Lab Guide 3
E#prn returns this e(pression if the preceding e(pressions are null)
4. 'onditional E#pressions& /-he two methods that are used to implement
conditional processing .I4!-,75!7LS7/ in a SQL statement are '(SE e(pression and
4E'O4E function) -he 0&S7 e(pression compiles with &5SI SQL) -he $70O$7
function is specific to Oracle Snta()
'(SE E#pression/It facilitates conditional in"uiries b doing the wor+ of an I4!
-,75!7LS7 statement without having to invo+e procedures)
'(SE e#pr W=E: comparisonAe#pr2 T=E: returnAe#pr2
VW=E: comparisonAe#pr. T=E: returnAe#pr.
VW=E: comparisonAe#prn T=E: returnAe#prn
ELSE elseAe#prW
E:4
4E'O4E >unction/It facilitates conditional in"uiries b doing the wor+ of a 0&S7
e(pression or I4!-,75!7LS7 statement)
-he $70O$7 function decodes e(pression after comparing it to each search value) If
the e(pression is the same as search, result is returned)
If the default value is omitted, a null value is returned where a search value does not
match an of the result values)
4E'O4E Fcol+e#pression! search2! result2
V! search.! result.W
V! defaultWG
'hapter/8
1. Croup >unctions& /Group functions operate on sets of rows to give one result per
group) -hese sets ma comprise the entire table or the table splits into groups)
-here are some tpes of group functions and that functions accepts an argument!
(BC .&verage values of n, ignoring null values/
learnsqlquery.wordpress.com | SQL Lab Guide 3!
'O7:T .5umber of rows/
5(D .3a(imum value of e(pr, ignoring null values/
5: .3inimum value of e(pr, ignoring null values/
ST44EB .Standard deviation of n, ignoring null values
S75 .Sum of n values, ignoring null values/
B(,(:'E .Bariance of n, ignoring null values/
-he Group functions are placed after the S7L70- +eword and we ma have
multiple group functions separated b commas)
2. 7sing (BC and S75 functions& /*e can use &BG and S:3 functions for numeric
data)
>igure/8.2
In the above e(ample, there is average and sum of the unitAprice)
3. 7sing 5(D and 5: >unctions& /*e can use 3I5 and 3&D functions for numeric,
character, and date data tpes)
learnsqlquery.wordpress.com | SQL Lab Guide 3"
>igure/8..
In the above e(ample, there is ma(imum and minimum of the birth!date of the
emploee)
4. 7sing 'O7:T >unction& /It returns the number of rows in a table including the
duplicate rows)
>igure/8.<
In the above e(ample, there is total of EF? rows as count all the rows count FJG but
when we count the termination!date, there are onl 1>; rows, because it don't
counts the rows that have null value)
5. 7sing 4ST:'T *ey"ord& /It suppresses the counting of an duplicate values in a
column)
learnsqlquery.wordpress.com | SQL Lab Guide 3#
>igure/8.3
In the above e(ample, the total number of manager? is showing as there are
duplicate names of same name also)
6. Croup >unctions and :ull Balues& /Group functions ignore null values in the
column whereas the 5BL function forces Group functions to include null values)
>igure/8.8
In the above e(ample, that rows also counted for getting the average, which have
null)
7. 'reating Croups of 4ata& /&t times, we need to divide the table of information into
smaller groups) -his can be done b using the C,O7% B@ clause)
So it is used in con1unction with the aggregate functions to group the result!set b
one or more columns)
-he Group % column does not have to be in the S7L70- list)
CroupAbyAe#pression specifies columns determine the basis for grouping
rows)
learnsqlquery.wordpress.com | SQL Lab Guide 3$
>igure/8.9
Sometimes we need to see results for groups within groups)
8. 7sing Croup By clause on 5ultiple 'olumns& /Sometimes we need to see results
for groups within groups)
>igure/8.0
9. 7sing =aving 'lause& /*e use the ,aving 0lause to restrict the groups in the same
wa that we use the "here clause to restrict the rows that we select)
>igure/8.;
learnsqlquery.wordpress.com | SQL Lab Guide 4%
10. :esting Croup >unctions& /Group functions can be nested to a depth of two
functions)
>igure/8.1
'hapter/9
learnsqlquery.wordpress.com | SQL Lab Guide 41
1. Types of $O:& /-o 1oin tables, we can use 1oin snta()
FaG :atural $oins/
5&-:2&L GOI5 clause
:SI5G clause
O5 clause
FbGOuter $oins/
L74- O:-72 GOI5
2IG,- O:-72 GOI5
4:LL O:-72 GOI5
FcG 'ross $oins/
FaG :atural $oins/
'reating :atural $oins clause&
-he 5&-:2&L GOI5 clause is based on all columns in the two tables that have the
same name) It selects rows from the two tables that have e"ual values in all matched
column) If columns having the same names have different data tpes, an error is
returned)
*e can 1oin tables automaticall based on the columns in two tables that have
matching data tpes and names) *e do this b using 5&-:2&L GOI5 +eword)
>igure/9.2
'reating Eoins "ith 7S:C clause clause&
learnsqlquery.wordpress.com | SQL Lab Guide 42
If several columns have same names but data tpes do not match, natural 1oin can be
applied using the :SI5G clause to specif the columns that should be used for an
e"ui1oin) :SI5G clause is used to match onl one column when more than one
column matches)
>igure/9..
'reating Eoins "ith O: clause&
:se the O5 clause to specif arbitrar conditions or specif columns to 1oin) -he 1oin
condition is separated from other search conditions)
>igure/9.<
Self/$oin using O: clause& -he O5 clause can also be used to 1oin columns that have
different names, within the same table or in a different table)
:onequiEoins& /& none"ui1oin is a 1oin condition containing something other than
an equality operator)
(b) Outer $oins/If a row does not satisf a 1oin condition, the row does not appear in
the "uer result)
learnsqlquery.wordpress.com | SQL Lab Guide 43
Left Outer $oin& Goining tables with the 5&-:2&L GOI5, :SI5G, or O5 clauses
results in an inner 1oin)
>igure/9.3
,ight Outer $oin& &n unmatched rows are not displaed in the output) -o
return the unmatched rows, we can use an outer 1oin)
>ull Outer $oin& It retrieves all rows of all the tables, even if there is no match
in the tables)
(c) 'ross $oins/*hen a 1oin condition is invalid or omitted completel, the result is
a 'artesian product, in which all combinations of rows are displaed) &ll rows
in the first table are 1oined to all rows in the second table)
-he 'ross $oin clause produces the cross!product of two tables) -his is also
called a 0artesian product between the two tables)
>igure/9.8
'hapter/0
1. Sub/Query& /& sub!"uer is a S7L70- statement that is embedded in the clause of
another S7L70- statement) *e can build powerful statements out of simple ones b
learnsqlquery.wordpress.com | SQL Lab Guide 44
using sub!"ueries) *e can place the sub!"uer in a number of SQL clauses, including
the following!
W=E,E clause
=(B:C clause
>,O5 clause
Operators can be used for the comparison conditions)
-he sub!"uer is often referred to as nested S7L70-, sub!S7L70-, or inner!S7L70-
statement)
&lwas enclose the sub!"uer within the parentheses and place on the right side of
the comparison condition)
2. Single/ro" sub/query& /Queries that return onl one row from the inner S7L70-
statement) It uses single!row comparison operators!
I! T! TI! S! SI! TS
>igure/0.2
In the above e(ample, there is onl one sub!"uer comparison condition)
& S7L70- statement can be considered as a "uer bloc+)
learnsqlquery.wordpress.com | SQL Lab Guide 4
>igure/0..
In the above e(ample, there is two sub!"uer comparison conditions) So when both
of the condition will be true, then "uer will be e(ecuted) %ecause all "ueries return
single values, so this SQL statement called single!row sub!"uer)
3. 7sing Croup >unctions in a sub/query& /*e can displa data from a main "uer b
using a group function in a sub!"uer to return a single row)
>igure/0.<
4. 7sing =(B:C clause "ith sub/queries& /-he Oracle server e(ecutes the sub!
"uer and the results are returned into the =(B:C clause of the main "uer)
>igure/0.3
*hen sub!"ueries e(ecute, then some result shows but when there is not an data
searched, then it returns 6 ro"s selected)
. 5ultiple ro"s sub/query& /Sub!"ueries that return more than one row are called
multiple!row sub!"uer) *e use multiple!row operator, with a multiple!row sub!
"uer!
: 7"ual to an number in list
(:@ 0ompares a value to each value in a list or returned b a "uer)
learnsqlquery.wordpress.com | SQL Lab Guide 4!
(LL 0ompares a value to ever value in a list or returned b a "uer)
(LL and (:@ must be preceded b H, I H, J, C, JH, CH)
7sing : Operator/
>igure/0.8
7sing (:@ Operator/-he &5@ operator compares a value to each value returned b
a sub!"uer)
T(LL 3eans less than the minimum
S(LL 3eans more than the ma(imum
7sing (LL Operator/-he &LL operator compares a value to ever value returned b
a sub!"uer)
-he :OT operator can be used with I5, &5@ and &ll operators)
'hapter/;
1. SET Operators& /Set operators combine the results of two or more component
"ueries into one result) Queries containing set operators are called compound
queries)
7:O: 2ows from both "ueries after eliminating duplications)
7:O: (LL 2ows from both "ueries, including all duplications)
:TE,SE'T 2ows that are common to both "ueries)
learnsqlquery.wordpress.com | SQL Lab Guide 4"
5:7S 2ows in first "uer that are not present in second "uer)
&ll set operators have e"ual precedence) If SQL statement contains multiple set
operators, it evaluates from top of left to bottom of right) *e should use
parentheses to specif the order of evaluation e(plicitl in "ueries that use the
I5-72S70- operator with other set operators)
Set operators can be used in sub!"ueries)
2. Oracle Server and St Operators& /*hen a "uer uses set operators, the oracle
server eliminates duplicate rows automaticall e(cept in the case of the :5IO5 &LL
operator) If component "ueries select numeric data, then the data tpe of the return
values is determined b numeric precedence) If all "ueries select values of the
5:3%72 tpe, then the return values have the 5:3%72 data tpe)
3. 7sing the 7:O: Operator& !-he :5IO5 Operator returns all rows that are
selected b either "uer) *e can use the :5IO5 Operator to return all rows from
multiple tables and eliminate an duplicate rows)
Some Cuidelines/
5umber of columns being selected must be the same)
$ata tpes of columns must be in the same data tpe group)
-he names of the columns need not be identical)
:5IO5 operates over all of the columns being selected)
5:LL values are not ignored during duplicate chec+ing)
-he output is alwas sorted in ascending order of the columns of the S7L70- clause)
>igure/;.2
learnsqlquery.wordpress.com | SQL Lab Guide 4#
In the above e(ample, there is displaed all the emploeeA+e of both table
employee and salesAfact) &nd all the duplicate records will eliminate because of
:5IO5 operator)
4. 7sing 7:O: (LL Operator& /-he :5IO5 &LL operator returns all rows from
multiple "ueries) 7verthing will be same li+e :5IO5 operator, but b the :5IO5
&LL operator, all duplicate records will also show and record will not be sorted)
>igure/;..
In the above e(ample, the :5IO5 &LL operator will displa all the records of
emploeeA+e of both the table employee and salesAfact with unsorted and
duplicate records)
. 7sing :TE,SE'T Operator& /-he I5-72S70- operator returns rows that are
common to multiple "ueries)
Some Cuidelines/
-he number of columns and the data tpes of columns being selected b the S7L70-
statements in "ueries must be identical in all the S7L70- statements used in the
"uer)
2eversing the order of the intersected tables does not alter the result)
I5-72S70- operator does not ignore 5:LL values)
learnsqlquery.wordpress.com | SQL Lab Guide 4$
-he names of the columns need not be identical)
>igure/;.<
In the above e(ample, the I5-72S70- will displa those records of emploeeA+e
that will be common in the table employee and salesAfact)
!. 7sing 5:7S Operator& /-he 3I5:S operator returns all the distinct rows selected
b first "uer, but not present in second "uer result set)
-he number of columns must be same and the data tpes of the columns being
selected b S7L70- statements in the "ueries must belong to the same data tpe
group in all the S7L70- statements used in the "uer) -he names of the columns
need not be identical)
>igure/;.3
In the above e(ample, the emploeeA+e that presents onl in employee table and
not in the salesAfact table)
". 7sing O,4E, B@ clause in set operations& /-he order b clause can appear onl
once at the end of compound "uer)
learnsqlquery.wordpress.com | SQL Lab Guide %
0ompound "ueries cannot have individual O2$72 %@ clauses)
O2$72 %@ clause recognizes onl the columns of the first S7L70- "uer, not the
second S7L70- "uer)
% default, the first column of the first S7L70- "uer is used to sort the output in an
ascending order)
'hapter/1
1. 4ata 5anipulation Language F45LG& /$3L is core part of SQL) *hen we want to
add, update, or delete data in the database, then we e(ecute a $3L statement) &
collection of $3L statements that form a logical unit of wor+ is called a transaction)
2. (dd a ne" ,o" in a table& /*e can add a new row in a table b :SE,T statement)
>igure/1.2
learnsqlquery.wordpress.com | SQL Lab Guide 1
In the above e(ample, we e(ecuted the insert statement and the result is 2 ro"
created that is the inserted data in the organi?ation table)
*ith this snta(, we can insert one row at a time) &ll the character and date values
will be enclose within the single "uotation mar+s and it is not recommended that we
enclose numeric values within single "uotation mar+s)
3. nserting ro"s "ith :ull Balues& /%e sure that we can use 5ull values in the
targeted column b verifing the 5ull status with the $7S02I%7 command) -he :ot
:ull columns have onl mandator value) &n column that is not listed e(plicitl
obtains a null value in the new row)
>igure/1..
4. nserting Special Balues& /4or inserting the special values in a table, we can use the
functions)
>igure/1.<
In the above e(ample, we are entering data b the S@S$&-7 function in
introductionAdate column of the product table)
5. nserting specific 4ate Balues& /-he 44/55/,, format is generall used to insert
a date value) *ith ,, format, the sstem provides the correct centur automaticall)
*e ma also suppl the date value in the 44/55/@@@@ format) If a date must be
learnsqlquery.wordpress.com | SQL Lab Guide 2
entered in a format other than the default format, we must use the TOA4(TE
function)
>igure/1.3
6. 'reating a Script& /% using the scripts, we can enter the values again and again
with different values) % this we can save the time and writing the command again
and again)
>igure/1.8
7. 'opying ,o"s& /*e can use the :SE,T statement to add rows to a table where the
values are derived from e(isting table) SO we write the statement with sub!"uer
and do not use the B(L7SES clause) &nd alwas match the number of columns in the
I5S72- clause to those in the sub!"uer)
>igure/1.9
8. 7pdating data in a table& /*e can modif the e(isting values in a table b using the
7%4(TE statement) Balues for a specific row or rows are modified if we specif the
W=E,E clause)
learnsqlquery.wordpress.com | SQL Lab Guide 3
>igure/1.0
In the above e(ample, the value of the column orderAmethodAen of the table
salesAordermethod, whose orderAmethodA)ey is 962)
SO, the 7%4(TE statement updates the particular table and SET statement sets the
value to the particular column) &nd W=E,E statement clarif that what will be the
condition for updating the values of the column of a table)
9. 7pdating ,o"s based on another table& /*e can use sub!"ueries in the :P$&-7
statements to update values in a table)
>igure/1.;
10. ,emoving ro"s from a table& /*e can remove e(isting rows from a table b using
4ELETE statement) If no rows are deleted, the message 6 ro"s deleted is returned)
If we specif W=E,E clause, then specific rows are deleted)
>igure/1.1
In the above e(ample, the row of the product table will be removed whose
productA)ey is <6.09)
learnsqlquery.wordpress.com | SQL Lab Guide 4
11. 7sing Truncate statement& /It removes all rows from a table and leaving the table
empt and the table structure intact) -he -2:50&-7 statement is a data definition
language statement and generates no rollbac+ information)
-runcating a table does not fire the delete triggers of the table)
>igure/1.26
12. 4atabase Transaction& /& database transaction consists of one of the following!
$3L statements that constitute one consistent change to the data)
One $$L statement)
One $0L statement)
$atabase transaction begins when the first $3L SQL statement is e(ecuted)
7nd with one of the following events!
& 'O55T or ,OLLB('* statement is issued)
& $$L or $0L statement e(ecutes)
-he user e(its SQL $eveloper or SQL 9 Plus)
-he sstem crashes)
&fter one transaction ends, the ne(t e(ecutable statement automaticall starts the ne(t
transaction)
& $$L or $0L statement is automaticall committed and therefore implicitl ends a
transaction)
13. mplicit Transaction %rocessing& /&n automatic commit occurs in the following
circumstances!
learnsqlquery.wordpress.com | SQL Lab Guide
& $$L statement is issued)
& $0L statement is issued)
5ormal e(it from SQL $eveloper or SQL 9 Plus without 0O33I- or 2OLL%&08)
&n automatic 2OLL%&08 occurs when there is an abnormal termination of SQL
$eveloper or a sstem)
(utomatic 'ommit/$$L or $0L statement issued and SQL $eveloper or SQL 9 Plus
e(ited normall, without e(plicitl issuing 0O33I- or 2OLL%&08 commands)
(utomatic ,ollbac)/&bnormal termination of SQL $eveloper or SQL 9 Plus or
sstem failure)
14. E#plicit Transaction %rocessing& /*e can control the logic of transactions b
using the 0O33I-, 2OLL%&08 and S&B7POI5- statements)
15. State of 4ata before 'O55T or ,OLLB('*& /&ll data change made during the
transaction is temporar until the transaction is committed) So these are the
following states before 0O33I- or 2OLL%&08!
-he previous state of the data can be recovered)
-he current user can review the results of the data manipulation operations b
"uering the tables)
Others users cannot view the results of the data manipulation operations made b
current user)
-he affected rows are loc+edK other users cannot change the data in affected rows)
16. 7sing 'O55T Statement& /3a+e all pending changes permanent b using
'O55T statement) &fter commiting!
$ata changes are written to the database)
-he previous state of data is no longer available with normal SQL "ueries)
&ll users can view the results of transaction)
&ll savepoints are erased)
-he loc+s on affected rows are released)
learnsqlquery.wordpress.com | SQL Lab Guide !
>igure/1.22
*hen we e(ecute the commit statement then all the data will be saved in the
database)
17. 7sing ,OLLB('* Statement& /$iscards all pending changes b using the
2OLL%&08 statement, which results in the following!
$ata changes are undone)
-he previous state of data is restored)
Loc+s on the affected rows are released)
>igure/1.2.
18. Statement/Level ,ollbac)& /& part of transaction can be discarded through an
implicit rollbac+ if a statement e(ecution error is detected) If a single $3L statement
fails during e(ecution of transaction, its effect is undone b a statement!level
rollbac+, but changes made b previous $3L statements in transaction are not
discarded) -he can be committed or rolled bac+ e(plicitl b the user) -erminate
the transactions e(plicitl b e(ecuting a 0O33I- or 2OLL%&08 statement)
learnsqlquery.wordpress.com | SQL Lab Guide "
'hapter/26
1. 4atabase ObEects& /-he oracle database can contain multiple data structures)
Table stores the data)
Bie" is the subset of data from one or more tables)
Sequence generates numeric values)
nde# improves the performance of some "ueries)
Synonym gives alternative name to an ob1ect)
-ables can be created at an time, even when users are using the database)
*e do not need to specif the size of a table because the size is ultimatel defined b
the amount of space allocated to the database as a whole)
-able structure can be modified online)
2. :aming ,ules& /5ames are not case!sensitive) -here is some standard rules for
naming the database tables and columns!
-able names and column names must begin with a letter and must be 2/<6
characters long)
5ames must not duplicate the name of another ob1ect owned b the same Oracle
server user)
5ames must contain onl the characters (/X, a/?, 6/1, A F7nderscoreG, H, Y)
5ames must not be an Oracle server!reserved word)
learnsqlquery.wordpress.com | SQL Lab Guide #
3. ',E(TE Table Statement& /-o create table, a user must have the ',E(TE T(BEL
privilege and a storage area in which to create ob1ects) *e create tables to store data
b e(ecuting the SQL 027&-7 -&%L7 statement) -he database administrator uses
data control language .$0L/ statements to grant privileges to users) %ecause
creating a table is a $$L statement, an automatic commit ta+es place when this
statement is e(ecuted) *hen we define a table, we can specif that a column should
be given a default value b using the $74&:L- option)
>igure/26.2
In the above e(ample, table is created, now we have to chec+ that table is created or
not) So e(ecute the following statement!
4ES',BE TableA:ame
>igure/26..
% this statement, we can view the structure of the table and can confirm that table
is created)
4. 4ata Types& /*hen we identif a column for a table, we need to provide a data tpe
for the column) -here are different tpes of data tpes!
B(,'=(,. Fsi?eG Bariable!length character data
'=(, Fsi?eG 4i(ed!length character data
:75BE, Fp!sG Bariable!length numeric data
learnsqlquery.wordpress.com | SQL Lab Guide $
4(TE $ate and time values
LO:C Bariable!length character data
'LOB 0haracter data
,(W Z LO:C ,(W 2aw binar data
BLOB %inar data
B>LE %inar data stored in an e(ternal file
,OW4 & base!LM number sstem represents uni"ue address of a row)
Some Cuideline/
& LO5G column is not copied when a table is created using a sub!"uer)
& LO5G column cannot be included in a G2O:P %@ or O2$72 %@ clause)
Onl one LO5G column can be used per table)
5o constraint can be defined on a LO5G column)
There are some 4ate/time data types/
T5EST(5% $ate with fractional seconds
:TE,B(L @E(, TO 5O:T= Stored as an interval of ears and months
:TE,B(L 4(@ TO SE'O:4 Stored as an interval of das, hours, minutes and
seconds)
5. 7sing 'onstraints& /-he oracle server uses constraints to prevent invalid data entr
into tables) *e can use the constraints to do the following!
7nforce rules on the data in a table whenever a row is inserted, updated, or deleted
from that table)
Prevent the deletion of a table if there are dependencies from other tables)
-here are following tpes of constraints!
:OT :7LL Specifies that the column cannot contain the null value
7:Q7E Specifies a column or a combination of columns whose values
must be uni"ue for all rows in the table
learnsqlquery.wordpress.com | SQL Lab Guide !%
%,5(,@ *E@ :ni"uel identifies each row of the table
>O,EC: *E@ 7stablishes and enforces a referential integrit between
column and a column of the referenced table such that values
in one table match values in another table)
'=E'* Specifies a condition that must be true)
0onstraints are usuall created at the same time as the table) 0onstraints can be
added to a table after its creation and also be temporaril disabled)
6. 7sing :OT :7LL 'onstraint& /-he 5O- 5:LL constraint ensures that column
contains no null values) 0olumns without 5O- 5:LL constraint can contain null
values b default) 5O- 5:LL constraint must be defined at the column level)
7. 7sing 7:Q7E 'onstraint& /& :5IQ:7 +e integrit constraint re"uires that ever
value in a column or a set of columns be uni"ue that is no two rows of a table can
have duplicate values in a specified column or a set of columns) -he column or set of
columns included in the definition of the :5IQ:7 87@ constraint is called the
unique )ey) If the :5IQ:7 constraint comprises more than one column, the group
of columns is called a composite unique )ey) :ni"ue constraint enables the input
of nulls unless we also define 5O- 5:LL constraints for the same columns)
learnsqlquery.wordpress.com | SQL Lab Guide !1
'hapter/22
1. 4atabase ObEects& /-here are several ob1ects in a database!
Table %asic unit of storage
Bie" Logicall represents subsets of data from one or more tables
Sequence Generates numeric values
nde# Improves the performance of data retrieval "ueries
Synonym Gives alternative names to ob1ects)
2. Bie"& /*e can present logical subsets or combinations of data b creating vie"s of
tables) & vie" is a logical table based on a table or another view) & view contains no
data of its own, but is li+e a window through which data from tables can be viewed
or changed) -he tables on which a view is based are called base tables)
(dvantages of Bie"/
Biews restrict access to the data because it displas selected columns from the table)
Biews can be used to ma+e simple "ueries to retrieve the results of complicated
"ueries)
Biews provide data independence for ad hoc users and application programs) One
view can be used to retrieve data from several tables)
Biews provide groups of user's access to data according to their particular criteria)
3. Simple and 'omple# Bie"s& /Simple view derives data from onl one table) It
contains no functions or groups of data and can perform $3L operations through
the view) *hereas a comple( view derives data from man tables) It contains
functions or groups of data and does not alwas allow $3L operations through the
view)
learnsqlquery.wordpress.com | SQL Lab Guide !2
4. 'reating a Bie"& /*e can create a view b embedding a sub!"uer in the 027&-7
BI7* statement) -he sub!"uer can contain comple( S7L70- snta(, including 1oins,
groups and sub!"ueries)
>igure/22.2
In the above e(ample, we have created a view table of the employee table as there is
selected the employeeA)ey, firstAnameAmb, and dateAhired and the view table
name is empAlevelA8) &s there is condition, the emploees who have level 8 will be
selected)
5. ,etrieving 4ata from a Bie"& /&s we have created a view for a table, so now we
have to retrieve the data from the view table) *e can show data as how we show the
data of an other table)
>igure/22..
In the above e(ample, the emploee's detail is showing whose level is ; in the
original table)
learnsqlquery.wordpress.com | SQL Lab Guide !3
6. 5odifying a Bie"& /&s we have created a view table and now we have to modif this
table as we have to add one more column employeeAlevel) So, the following "uer
will help to add the column and also will fetch the value of that column from the
original table of that view table)
>igure/22.<
7. 'reating a 'omple# Bie"& /0reate a comple( view that contains group functions to
displa values from two tables)
>igure/22.3
In the above e(ample, there are data from two table organi?ation and salesAfact)
learnsqlquery.wordpress.com | SQL Lab Guide !4
>igure/22.8
In the above e(ample, the data is retrieved from the view table orgA)ey, in which
there is organi?ationA)ey, organi?ationAcode, employeeA)ey, and productA)ey
that is fetched from the organi?ation and salesAfact table)
8. ,ules for performing 45L operations on Bie"& /*e can perform $3L operations
on data through a view if those operations follow certain rules)
.a/ *e can remove a row, cannot modif data, cannot add data from a view unless it
contains an of the following!
Group functions
& G2O:P %@ clause
-he $IS-I50- +eword
-he pseudo!column 2O*5:3 +eword
0olumns defined b e(pressions
5O- 5:LL columns in the base tables that are not selected b the view)
9. 7sing WT= '=E'* O%TO: 'lause& /-he view can be used to protect data
integrit, but the use is ver limited) -he *I-, 0,708 OP-IO5 clause specifies that
I5S72-s and :P$&-7s performed through the view cannot create rows that the
view cannot select) -herefore it enables integrit constraints and data validation
chec+s to be enforced on data being inserted or updated) If there is an attempt to
perform $3L operations on rows that the view has not selected, an error is
displaed, along with the constraint name if that has been specified)
10. 4enying 45L Operations& /*e can ensure that no $3L operations occur on our
view b creating it with the *I-, 27&$ O5L@ option) &n attempt to remove, insert
learnsqlquery.wordpress.com | SQL Lab Guide !
or remove a row using the view with a read!onl constraint results in an error) &nd
the error will be same for all these three)
11. ,emoving a Bie"& /*e can remove a view without losing data because a view is
based on underling tables in the database) *e can remove the view definition from
the database b using the 4,O% BEW statement)
>igure/22.9
In the above e(ample, there were a view table empAlevelA8 that is deleted b the
4,O% statement and for verifing that table is deleted or not 1ust follow the
4ES',BE statement)
12. Sequence& /& se"uence is user!created database ob1ect that creates integer values)
*e can create se"uences and then use them to generate numbers) *e can define a
se"uence to generate uni"ue values and use the same numbers again) & se"uence is
generated and incremented or decremented b an internal Oracle routine) Se"uence
numbers are stored and generated independent of tables) -herefore, the same
se"uence can be used for multiple tables)
learnsqlquery.wordpress.com | SQL Lab Guide !!

You might also like