SQL Notes
SQL Notes
SQL Notes
ORACLE (12c)
An Oracle database is a collection of data treated as a unit. The
purpose of a database is to store and retrieve related information. A
database server is the key to solving the problems of information
management. In general, a server reliably manages a large amount of data
in a multiuser environment so that many users can concurrently access the
same data. All this is accomplished while delivering high performance. A
database server also prevents unauthorized access and provides efficient
solutions for failure recovery.
SQL
Introduction to SQL
Introduction to SQL *Plus
Role of SQL in Oracle 11g
Classification of SQL Commands
Data Definition Languages (DDL) commands
Oracle database 11g Schema Objects
Oracle Data Dictionary
Oracle Naming conventions
Oracle Data types
Alternation of Table Definition and it’s options
Pseudo columns Introduction
Table Truncation and it’s advantages
Data Manipulation Language (DML) Commands
Insertion of Data (Value , Address and Select method )
Insertion of Nulls and Overriding the Nulls with User defined Values
Insertion of Data in required formats
Data Loading methods in Oracle 11g
Data Updation
Techniques of updation
Complex Data Updation
Correlated Query mechanism in Update
Data Deletion
Simple Data Deletion
Critical Data Deletion
Table Delete Vs Table Truncation
Transaction Control Language commands
Data Retrieving Language(DRL) command SELECT
Conditions
Expressions
Restricting ans Sorting data
SELECT command and it’s clauses
Operators Types of Operators in Oracle 11g & Filters
Functions
ORACLE SQL
Single row functions,
Multiple row functions
Null functions
Analytical functions
Search functions
Hierarchical functions
Error functions
Regular expressions(10g);
Types of functions in Oracle 11g
Pseudo Columns of Oracle 11g
Displaying data from multiple tables(joins)
Introduction to Table Join
Types of Joins
Inner & Outer Join/partition outer join(10g)
Equi / Non Equi / Self Join / Cartesian Join/natural joins
Vertical joins(set operators)
Sub Queries and Simple sub query
Complex Sub Query on multiple data source and Co-related Sub
Query
Top-n queries, hierarchical queries, scalar queries, flashback
queries,version queries.
Intigrity Constraints
Oracle Database Objects
Index and Introduction to Index
Clusters and Introduction to Cluster
Type of Clusters and Their Usage
Explain plan Command Usage and Oracle Scripts
Views and Introduction to Views
Type of Views and usage
Performance issues with Views
Background process of Views
DML restrictions on Views
Materialized View and Usage
Synonym and Introduction to Synonyms and Usage
Sequence and Introduction to Sequence and Usage
Pseudo Columns Usage in Sequence
Data Control Language commands
What is privilege
What is role
Grating Privilege
Removing Privilege
Cascading Privilege
Sql * Plus Commands
Environment setting commands
ORACLE SQL
Alter session language
Alter system language
Sql developer
PL/SQL
Introduction to Programming Language
Procedures Vs Non-Procedures Language
Limitation of ANSI SQL and Oracle SQL
Introduction to Oracle PL/SQL
PL/SQL Usage in Production Database
Key benefits of PL/SQL over SQL
Anchor datatypes or Attributes
Composite datatypes
Collections
PL/SQL block structure & Designing
Scope and Visibility
Constructs of PL/SQL
Assignment operations
Debugging statement
Flow Control Statement
IF / NESTED IF / EXIT / GOTO /
Iterative statements
Simple Loop / While Loop / For Loop
Continue statement(11g)
Embedded SQL
Introduction to Embedded SQL
Role of Embedded SQL in PL/SQL
Constructs of Embedded SQL
Transaction Mngmt Using Embedded SQL
Dynamic SQL
Introduction to Dynamic SQL
Usage of Dynamic SQL in PL/SQL
Introduction to Exceptions
Importance of Exceptions in PL/SQL
Type of Exceptions
Exception handling
Save exceptions
Introduction and STANDARD Package
Introduction to User Defined Exceptions
Non predefined exceptions
Exception cases
Usage of PRAGMA EXCEPTION_INIT()
Cursor Management in PL/SQL
Introduction to cursor management
Pictorial presentation of cursor mechanism
Introduction and usage of implicit cursor
ORACLE SQL
Introduction and usage of Explicit cursors
Cursor attributes
Cursor using simple loop
Cursor using while loop
Cursor using for loop
Cursor exceptions
Cursor expression
Data Locking
Data Manipulation through Cursor
REF cursor(strong and weak)
Using ref cursor variable as parameter
Bulk Fetch and Bulk Data Retrieval in PL/SQL
Bulk Collection
Bulk Binding mechanism of Cursor (for all statement)
Dynamic behavior of cursor mnt.
SUB PROGRAMS
Types of PL/SQL blocks
Labelled blocks
Anonymous PL/SQL blocks
Named PL/SQL blocks
Forward Declaration of Local Block
Introduction to storage PL/SQL block
Stored Procedures
Stored Functions
Nocopy(9i)
Autonomous Transaction Management of PL/SQL
PACKAGES
Introduction to Package
Stand-alone schema Vs Packaged Object
Encapsulation mechanism of Package
Data security
Function overloading mechanism of Package
Introduction and Usage of Package
Oracle supplied packages
Package data
Restrict Reference and Complex Hints
Usage of Pragma Serially_ reusable
DB TRIGGERS
Introduction to Database Trigger
Types of Triggers
Triggering events
Usage of Old & New Reference
Instead of Trigger
Enforcing the referential integrity constraint
Compound Trigger(11g);
Follows key word(11g);
Defining a disable trigger(11g)
ORACLE SQL
Trigger Cascading
Enabling/Disabling Trigger
Schema Trigger
Table Mutation Error
Transaction Audit Trigger
Advanced Pl/sql Topics
User Defined Types (RECORDS)
Subtypes of Pl/sql
Automation Transaction
Advantages of Autonomous Transaction
Usage of Autonomous Transaction
Scope of autonomous Transaction
Usage of Autonomous Transaction in Trigger
Suing FORALL Statement
About % BULK_ROWCOUNT
FGA and FGAC(VPD)
Table functions
Managing database dependencies
Designing pl/sql code
Using collections
Working with lobs
Using secure file lobs
C ompiling pl/sql code
Tuning pl/sql code
Pragma inline(11g)
Caching to improve performance
Analysing pl/sql code
Profiling pl/sql code
Tracing pl/sql code
Safeguarding pl/sql code against sql injection
Pl/sql Architecture.
ORACLE SQL
DATATYPES
DEFINITION:
1) NUMBER
2) CHAR
3) VARCHAR OR VARCHAR2
4) DATE
5) TIMESTAMP
6) TIMESTAMP WITH TIMEZONE
7) TIMESTAMP WITH LOCAL TIMEZONE
8) INTERVAL DATATYPES;
I) Interval Year to Month
II) Interval Day to Second.
9) LONG
a) LONG
b) RAW
c) LONG RAW
10) LOB
CLOB
BLOB
BFILE
NCLOB
11) ROWID
12) UROWID
13) BINARY_FLOAT
14) BINARY_DOUBLE
15) SIMPLE_INTEGER
16) SUBTYPES
17) NCHAR
18) NVARCHAR2
19) INTERNET DATAYPES
20) XML DATATYPES.
21) OTHER DATATYPES
ORACLE SQL
1) NUMBER:
2) CHAR:
SYN: X VARCHAR2(S);
4) DATE
Disadvantage:
5) TIMESTAMP (9I)
SYN: X TIMESTAMP [(P)]. (DD-MON-YY HH: MI:SS.FS)
It is derivative of data ,along with date it supports upto fraction
of seconds.
It stores fraction of seconds upto 9 digits,by default 6 digits.
Disadvantage:
8) INTERVAL DATATYPE
9) LONG:
a) LONG:
SYN: X LONG;
To store information.
Max size 2 gb.
Disadvantage:
So many disadvantages are there for long this is why not Preferable.
b) RAW:
SYN: X RAW(S).
To store the images.
ORACLE SQL
Max size 2000 bytes.
c) LONG RAW:
SYN: X LONG RAW.
To store information+ images
Max sized 2gb
Not preferable, so many disadvantages.
SYN: X CLOB;
2) BLOB:
SYN: X BLOB;
To store images.
SYN: X BFILE;
TO store files.
11) ROWID:
SYN: X ROWID;
SYN: X UROWID;
ORACLE SQL
We use it to store the logical address of index organized table (IOT).
UROWID even store RDBMS ROWID values.
13) BINARY_FLOAT
14) BINARY_DOUBLE
15) SIMPLE_INTEGER
16) SIMPLE_FLOAT
17) SIMPLE_DOUBLE
18) NCHAR
19) NVARCHAR2
20) NCLOB
Null value:
Truth Table
AND T F NULL
OR
T F N
T
T T T
F F F
F
T F N
& F N T OR T N F
F T T N F
F T T F
SQL STATEMENTS
DD DML
L
DCL DRL
SEE TO DIAGRAM
1) DDL (DCL)
2) DML (DRL OR DQL)
3) TCL
4) ALTER SESSION
5) ALTER SYSTEM
6) EMBEDDED SQL
CREATE
ORACLE SQL
Which is used to define database
Objects (tables, view, sequences…)
Creating a table is our main concern for us here.
ALTER: We use alter to modify the structure of database objects with the
help of keywords.
KEY WORDS:
a) ADD:
SYN: ALTER TABLE TABLENAME ADD(COL DTPS(S),COL1 DTPS(S),…);
EG: ALTER TABLE NEWTAB ADD(ID NUMBER(5),LOC VARCHAR2(10));
TRUNCATE(DELETE+COMMIT):
SYN: TRUNCATE TABLE TABLENAME;
EG:TRUNCATE TABLE NEWTAB;
FLASHBACK:
To retrieve the drop table
From 10g onwards we have a concept called recycle in
If you drop the table or database object for that matter
They store in the recyclebin.to get back the object from
Recycle in we user flashback (10g)
COMMENT:
INSERT
UPDATE
DELETE
MERGE(INSERT+UPDATE+DELETE)
ORACLE SQL
SELECT(DRL OR DQL)
INSERT
VALUE METHOD
REFRENCE METHOD
SELECT METHOD
VALUE METHOD
SELECT METHOD:
UPDATE:
TRUNCATE:
DELETION:
Delete the records temporarily.
Possible to delete specific records.
ORACLE SQL
SELECT:
SYN:
[WITH CLAUSE]
SELECT [DISTINCT|ALL] *|COLUMNS|EXP|FUNCTIONS|LITERAL|
SUBQUERIES
FROM TABLENAME|VIEWS|SUBQUERIES|TABLE FUNCTIONS
[WHERE CONDITION]
[START WITH CONDITON]
[CONNECT BY CONDITION]
[GROUP BY COLUMNS|EXP]
HAVING CONDITIONS (COLUMNS|FUNCTIONS)
ORDER BY COLUMNS|EXP|VALUES [ASC|DESC] [NULLS FIRST|NULLS LAST]|
ANALYTICAL FUNCTIONS)
DUAL:
It is a dummy table.
Dual table is having single record.
To display the required result only for once we use dual table.
MULTIPLE INSERT:
TABLES: MULTAB,MULTAB1,MULTAB2;
4) TCL COMMANDS
Commit:
It makes temporary transaction permanent
It empties the buffer memory area
A SCN number get generated for each of the transaction (or) for
every commit
It makes temporary piece of work as permanent
Roll Back
It cancels the transaction or piece of work
It also empties the buffer memory area permanently
Partial roll backing is also possible with the help of save point.
Save Point:
It is a mark which specifies teset of statements or piece of work.
Note:
It is not possible to nest the transactions directly but by using some
other means (program autonomous transaction) it is possible.
A DDL command also makes the above temporary work permanent
while becoming permanent.
LITERALS
Literals are predefined values or constants identified by oracle server
ORACLE SQL
Types of literals
1) Number literals:
USAGE: 1, 10,
EG: SELECT 1 FROM DUAL;
USAGE: ‘A’,’10’,’13-SEP-13’
EG: SELECT ‘A’,’10’,’13-SEP-13’ FROM DUAL;
3) Date literals
4) Timestamp literal:
OPERATORES
Athematic
Concatenation
Relational or Comparison
Special
Logical
Row Operators
Hierarchical Operators;
Set Operators
Table Operators
ORDER OF PRECEDENCE:
UNIARY OPERATORES>1>2>3>4>5
1) ARITHEMATIC: *, / , + , -
2) CONCATINATION: || (JOIN STRINGS)
3) RELATIONAL: =,>, <,>=, <=,!=,<>,^=,~=
4) SPECIAL IS,IN,LIKE( _ ,%),BETWEEN(AND),ANY/SOME,ALL,EXISTS,
5) ROW: DISTINCT, ALL, PRIOR
6) LOGICAL: NOT, AND, OR;
7) HIERARCHICAL: CONNECT_BY_ROOT, PIROR
8) TABLE: THE;
NOTE: We can override the order of precedence or we can divert the order of
precedence by interpreting parantasis ( )
ARTHIMATIC OPERATORES:
RELATIONAL OR COMPARISON :
SPECIAL OPERATORES:
3) LIKE:To search the patterns we use ‘like’ operator with the help of wild card
Characters
4) BETWEEN:
5) ANY/SOME:In any, the given value has to become true with any of
NOTE:we have to use any & all along with relational operators.
They can’t exist individually.
Order of presidence:
Level Operators
1 Unary (+, -, ~,
connect_by_root)
2 Arithmetic
3 ||
4 =, >, <, >=, <=
5 [not] like, is [not], [not] in
6 [not] between
7 !=, <>, ^=
8 Not
9 And
10 Or
TABLE ALIASES
PSEUDO COLUMNS:
They are the false columns or dummy columns which behaves as same to that of
table columns. They are actually functions.
SYSDATE;
ROWNUM
ROWID
USER
UID
LEVEL
NEXTVAL
CURRVAL
CONNECT_BY_ISLEAF
CONNECT_BY_ISCYCLE
XML PSEUDO COLUMNS
COLUMN_VALUE
OBJECT_VALUE
ROWNUM:
o ROWNUM provides the sequential number to the rows.
o They are temporary numbers only to that query.
ROWID:
o It is the physical address of the row
o It is in hexadecimal ,generated for each of the row useful to identify
the records and to increase the performance and they are permanent
o They differ even for duplicate records also
FUNCTIONS
They are built in programs which are used to modify the existing date or for
calculations so as to full fill the business requirements followingare function types.
They get execute for each of the row and return a value
Based on data we can classify the functions in following ways
NUMBER FUNCTIONS:
POWER
SQRT
MOD
REMINDER
SIN, COS,
SIGN
ABS
SINH, COSH
EXP
LOG
LN
CEIL
FLOOR
ORACLE SQL
TRUNC
POWER:To find out the power values
SYN: POWER (M, N) (M TO THE POWER OF N)
SIN,COS,…:Tringometric functions
SIGN:RETURNS -1 FOR ALL OF THE –VE VALUES
+1 FOR ALL OF THE +VE VALUES
0 FOR ZERO VALUE
SYN: SIGN (V);
LOG:LOG VALUES
LN :NATURAL VALUES
ROUND:Round rounds the value to given position and it also checks the
position i.e. if the last eliminating value is greater than are equal to 5 or >5
then it simply add one value to the left adjacent value
STRING FUNCTIONS:
LENGTH
VSIZE
DUMP
REVERSE
SOUNDEX
UPPER
LOWER
INITCAP
LTRIM
RTRIM
LPAD
RPAD
TRANSLATE
REPLACE
ORACLE SQL
DECODE
SUBSTR
INSTR
SUBSTRB
SUBSTRC
SUBSTR2
SUBSTR4
CONCAT
REGEXP_LIKE
REGEXP_COUNT(11G)
REGEXP_SUBSTR
REGEXP_SUBSTR
REGEXP_REPLACE
LPAD
RPAD: To append the character from left or from right end of a given string
to a given position
SYN:LPAD(S,N,’C’);
RPAD(S,N,’C’);
SYN: SUBSTR(S,M,(N));
S=STRING,
M=POSITION,
N=NO OF CHARACTERS
INSTR:
S=STRING;
C=CHARACTER
P=POSITION
O=OCCURANCE
DATE FUNCTIONS:
DATE FORMATS
I
IY
IYY
IYYY DIGITS OF THE YEAR IN ISO FORMATS
W(1-5) WEEK OF THE MONTH
WW(1-52) WEEK OF THE YEAR
IW WEEK OF THE YEAR IN ISO STANDARDS
FM FILL MODE( ELEMENATES SPACES AND ZEROES)
FF FRACTION OF SECONDS
XF EXACT FORMAT
HH HOUR FORMAT(DEFAULT 12 HOUR)
HH12 12 HOUR FORMAT
HH24 24 HOUR FORMAT
MI MINUTES
SS SECONDS
SP TO SPELL THE DIGITS
TH ORDINALS(TH,RD,ST,..)
Q QUARTER OF THE YEAR
J JULIAN DAY(A/C TO JULIAN CALENDRE)
RM ROMAN NUMBERICAL LETTERS WHICH REPRESENTS NO OF……… MONTHS
DL LONG DATE
DS SHORT DATE
TZH TIMEZONE HOUR
TZM TIMEZONE MINUTE
TZR TIMEZONE REGION
TZA TIMEZONE ABBAR
AM/PM
. Period
:
ORACLE SQL
-
“TEXT”
DATE FUNCTIONS
SYSDATE
CURRENT_DATE
SYSTIMESTAMP
CURRENT_TIMESTAMP
LOCAL TIMESTAMP
DBTIMEZONE
ADD_MONTHS
MONTHS_BETWEEN
NEXT_DAY
LAST_DAY
EXTRACT
ROUND
TRUNC
NEW_TIME
SELECT SYSDATE,HIREDATE,ROUND(MONTHS_BETWEEN
(SYSDATE,HIREDATE)) FROM EMP
LAST_DAY:Based on the given date.it displays the last day date of the
month
EXTRACT:
TO_CHAR;
TO_DATE;
TO_NUMBER;
TO_TIMESTAMP;
TO_TIMESTAMP_TZ;
TO_YMINTERVAL;
TO_DSINTERVAL;
TO_BINARY_FLOAT;
TO_BINARY_DOUBLE;
TO_BLOB;
TO_CLOB;
TO_LOB
BIN_TO_NUM;
NUMTOYMINTERVAL;
NUMTODSINTERVAL;
RAWTOHEX
TIMESTAMP_TO_SCN
SCN_TO_TIMESTAMP;
TO_NCHAR;
TO_NCLOB;
EG:
SELECT TO_TIMESTAMP(‘11’,’FF’) FROM DUAL;
SELECT TO_TIMESTAMP(‘11’,’HH’) FROM DUAL;
SELECT TO_TIMESTAMP_TZ(‘05’,’TZH’) FROM DUAL;
SELECT TO_YMINTERVAL (’10-06’) FROM DUAL;
SELECT SYSDATE,SYSDATE+TO_YMINTERVAL(’10-06’) FROM DUAL;
SELECT SYSTIMETAMP, SYSTIMESTAMP+TO_DSINTERVAL (’10 10:10:10’)
FROM DUAL;
SELECT BIN_TO_NUM(1,1,1) FROM DUAL;
SELECT NUMTOYMINTERVAL(11,’YEAR’) FROM DUAL;
SELECT SYSDATE,SYSDATE+NUMTOYMINTERVAL(11,’YEAR’) FROM DUAL;
NUMBER FORAMTS:
$
9 DIGIT REPRESENTATION
0
. SPECIFIES THE DECIMAL
,
PR ENCLOSE THE –VE VALUES IN ANGLE BRACKETS
MI REPRESENTS THE –VE SIGN
S SIGN
L LOCAL CURRENT SYMBOL
B BLANK SPACE
C CURRENCY CODE
D DECIMAL POINT
EEEE SPECIFIES THE EXPONENTIAL
G GROUPING
U
V
X
N
GENRAL FUNCTIONS
GREATEST
LEAST
USER
UID
DECODE
CASE
NVL
ORACLE SQL
NVL2
NULLIF
COALESCE
GREATEST
SYS_CONNECT_BY_PATH (HIERARCHIAL FUNCTION);
NULLIF:
2) AVG
3) MIN
ORACLE SQL
SYN: MIN (([ALL|DISTINCT] VALUE|EXP|COLUMN);
4) MAX
5) COUNT:
6) STDDEV
7) VARIANCE
COUNT (*):Count Counts the records.it also consider the null values
whereas count column ignore the null values
CLAUSES
WHERE
CONNECT BY
START WITH
ORACLE SQL
GROUP BY
HAVING
ORDER BY
GROUP BY CLAUSE:
It groups the same kind of data into segments
ORACLE SQL
All the select list normal columns, single row functions must be in
group by clause but reverse is not so.
EG:
HAVING CLAUSE:
It filters the group by data.
Generally we user having clause to provide group function condition.
Normally we user having clause along with group by clause so to
get meaning full data.
We can also use the having clause very individually but it is not preferable.
It won’t allow column aliases and analytical functions.
We can also provide normal columns conditions in having clause but we have
to see that all the normal columns in having clause must be in group by
clause and select list.
ORDER BY CLAUSE:
It displays the table data in one proper order that is either ascending or
descending.
Order by clause comes last in the list of clauses.
Order by clause allows column aliases and analytical functions unlike other
clauses.
CONSTRAINT KEYS:
PRIMARY KEY:
It acts has both UNIQUE+NOT null
There must be only one primary key for an entire table
Table which are having primary key constraint are called as
Master tables (0r) parent tables
A primary key can contain n number of columns;such keys are called as
composite keys
Implicitly an unique index get defined on a primary key column
A primary key can hold maximum of 32 columns
UNIQUE:
Won’t allow duplicate values, for even unique constraints also an unique
index get defined.
It allows null values.
FOREIGN KEY:
It is a referential constraint, which refers to the primary key or unique key.
It allows nulls, duplicates.
CHECK:
We use check constraints to fulfill the user requirements.
To enforce business rules.
ORACLE SQL
USER DEFINED
SYSTEM DEFINED
By taking all the above things into consideration, we can provide the
constraints in following wayss
MIXED METHOD:
SELF KEY:Referring a foreign key with in a same table primary key column.
EG: CREATE TABLE SELFTAB (SNO NUMBER (5) PRIMARY KEY, LOCVARCHAR2
(10), IDNUMBER (5) REFERENCES SELFTAB (SNO));
CASCADE CONSTRAINT:
Dropping master table directly is not possible when it is having child tables.
We have to drop child tables before dropping master tables, but by using
‘cascade constraint’.
It is possible.
ON DELETE CASCADE
ON DELETE SET NULL
ON DELETE RESTICT (DEFAULT)
ON DELETE CASCADE:
It is not possible to delete the parent records when they are having
dependent child records very directly, but by using on delete cascade it is
possible.
We have to mention on delete cascade while defining foreign key.
It is not possible to provide on existing foreign key.
Instead of deleting dependent records ,on delete set null sets the null value.
DEFINING CONSTRAINTS ON EXISTING TABLE:
GENERIC SYNTAX:
ALTER TABLE TABLENAME ADD|MODIFY|DISABLE|ENABLE(VALIDATE|INVALIDATE)|
ENFORCE|DROP
|RENAME CONSTRAINT CONSTRAINTNAME;
EG:
CREATE TABLE CON21(SNO NUMBER(5),SNAME VARCHAR2(10),BAL
NUMBER(5),LOC VARCHAR2(10));
ADD:
DISABLE:
ENABLE:
DROP:
RENAME:
NEWNAME;
SUBQUERY
SCALAR SUBQUERY
NEXTVAL
CURRVAL
LEVEL
ROWNUM
SYSDATE
USER
UID
USERENV
DBTIMEZONE
SESSION TIMEZONE
TIMESTAMP WITH TIMEZONE
ORACLE SQL
JOINS
Join is a query which is used to retrieve data from more than one table by
providing join condition.
We provide the join condition in “where clause” and even in “from clause”.
Join condition columns must be compatible data types or same data types.
Oracle Traditional or Native joins: (prior to 9i)
Inner join:
o Equi join
o Non-Equi join
Self-join
Outer join
o Left outer join
o Right outer join
o Full outer join
9i joins:
Cross Join
Natural join
Join on
Join using
Outer join
Left outer join
Right outer join
Full outer join
Q: To find out the table which we have in database
A: desc user_object
desc user_table
Cartesian Product:
NOTE: In the absence of join condition, if you combine more than one table than
the result will be ‘Cartesian Product’ results. Which means each record of one
table will combine with multiple records of another table.
SQL> select * from emp,dept;
ORACLE SQL
o Equi joins: In this join we will provide the join condition with equal to (=)
operator.
SQL> select * from emp, dept where emp.deptno=dept.detpno;
SQL> select * from emp e, dept d where e.detpno=d.detpno;
Note: We can provide ‘n’ no.of join conditions by separated by and (or) or.
o Non-equi join: In non-equi join we provide the join condition between the
columns with other than equal to (=) operator.
SQL> select * from emp e, dept d where e.deptno!=d.deptno;
SQL> select * from emp e, dept d where e.detpno<=d.deptno;
Note: Inner join will skip null record values.
Self-join: Join in the same table columns is called self join.
SQL> select e.empno, e.ename, m.empno, m.ename from emp e , emp m where
e.mgr=m.emp no;
Emp e Emp m
Empno Ename Mgr Empno Ename Mgr
1 X 2 1 X 2
2 Y 3 2 Y 3
3 Z 4 3 Z 4
4 A 4 A
5 B 3 5 B 3
Output:
e.empno e.ename m.empno m.ename
1 x 2 y
2 y 3 z
3 z 4 a
5 b 3 z
NOTE: here emp table is splitting as 2 emp tables i.e. copy of emp.
ORACLE SQL
Outer join:-
Along with matched records further if we want to get additional records from
either of the table we use outer joins.
We will perform outer joins with outer join operator (+).
Output:
rtab.sno ltab.sno
10 10
20 20
50
60
100
SQL> select rtab.sno, ltab.sno from ltab, rtab where rtab.sno(+) > ltab.sno;
Output:
rtab.sno ltab.sno
20 10
30 10
40 10
30 20
40 20
50
60
100
ORACLE SQL
Rtab.sno ltab.sno
10 10
20 20
30 null
40 null
o Full outer join:
Concept of full outer join is from 9i onwards. But still if we want to
achieve full outer join result even prior to 9i.
We use following example:
In full outer join we will combine both left & right outer joins with union operator.
It display the all records from both of the rables.
SQL> select * from rtab,ltab where ltab.sno = rtab.sno(+) union select * from rtab,
ltab where ltab.sno(+) = rtab.sno;
Compound query
ORACLE SQL
Select * from tset operatorselect * from t1set operatorselect * from t2;
In compound query all the component queries must contain same no.of
columns with compatible data types. This rule we call it as
‘Union Combination Condition’:
In compound queries order by clause will be allowed at the end.
Providing order by clause for individual component queries will not be
allowed.
In compound queries result will be displayed with the first component query
select list columns.
Order by clause in compound query allows only the first component query
select list columns.
All the set operators has equal priority ,except union all , all the set operators
will sort & suppress duplicate values.
Set Operators:
1. Union
2. Union all
3. Intersect
4. Minus
5. Multiset (11g)
In set operators default execution takes place from left to right but we can alter
default execution by using parenthesis.
Union :
It displays the records from both tables by suppressing the duplicate records and
also sort data.
Note (for restrictions) : Elimination of duplicate records becomes a problem
when we use order by clause for component query.
Union all :It displays all the records from both tables regardless of duplicating and
it doesn’t sort data.
ORACLE SQL
Note : Union all is more faster than union.
Intersect :Display the common records between tables. It also suppresses
duplicate values.
Minus :We will get records from one table which are not matching with other
table. Result won’t get effect or varies. When you change the order of component
query except in minus operator.
Sql> select sno from rtab union select sno from ltab;
Sql> select sno from rtab unionall select sno from ltab;
Sql> select sno from rtab intersect select sno from ltab;
Sql> select sno from rtab minus select sno from ltab;
Sql> select sno from rtab minus select sno from ltab union select * from rtab;
Sql> select 1 from dual union select 2 from dual;
Sql> select sno from rtab union select sno from ltab order by sno;
Cross joins :It works as same to that of Cartesian product (or) display the
Cartesian result.
Sql> select * from emp cross join dept; (56 records..Cartesian product results)
Join using:-In join using we use using clause to specify the columns.
So we provide equal join condition between mentioned columns.
Using clause columns can’t be qualified in an entire select statement. Using
clause column must be there in both of tables.
Note: Natural join , join on & join using are mutually exclusive.
Sql> select * from ratb join ltab on (rtab.sno=ltab.sno and ltab.sno>rtab.sno);
(Using normal condition)
Sql>select * from rtab joins ltab on .ltab.sno=rtab.sno and ltab.lov=rtab.loc;
(using without parenthesis)
Outer joins:-
1) left outer,
2) right outer,
3) full outer.
Sql>select * from rtab left outer join ltab on (rtab.sno1=ltab.sno and
rtab.loc1=ltab.loc);
Sno1 Loc1 Sno Loc
10 A 10 A
20 B 20 B
50 C
30 X
40 D
Sql> select * from rtab right outer join ltab on (rtab.sno1=ltab.sno and
rtab.loc1=ltab.loc);
Sno Loc Sno Loc
Sno1 Loc1
10 A 10 A
10 A 20 B 20 B
20 B 50 C 50 C
30 X 60 X
40 D 100 --
-- --
-- --
-- --
Sql> select * from rtab full outer join ltab on (rtab.sno1=ltab.sno and
rtab.loc1=ltab.loc);
Sno1 Loc1
10 A
20 B
ORACLE SQL
-- --
-- --
-- --
50 X
40 D
30 C
QUERIES
Sub queries:
Simple Sub queries
Correlated Sub queries
Single row Sub queries
Multiple row Sub queries
Inline Sub queries
Hierarchical Sub queries
Flashback Sub queries
Scalar Sub queries
Simple Sub queries
Examples:
Select * from emp where sal=(select max(sal) from emp);
Select * from emp where hiredate=(select min(hiredate) from emp);
ORACLE SQL
Select * from emp where sal=(select max(sal) from emp where
deptno=10);
Select * from emp where sal=(select max(sal) from emp where sal<(select
max(sal) from emp));
Select * from emp where hiredate=(select min(hiredate) from emp where
hiredate<(select max(hiredate) from emp));
Select * from emp where hiredate=(select min(hiredate) from emp where
hiredate>(select min(hiredate) from emp));
Select * from emp where empno in(select mgr from emp); 6 rows
selected.
Select * from emp where empno not in (select mgr from emp); no rows
selected.
Select * from emp where empno not in (select mgr from emp where mgr
is notnull);
Select * from emp where sal>(select avg(sal) from emp where
deptno=10);
Select * from emp where sal>(select avg(sal) from emp where deptno=10
and deptno<>10);
Select * from emp where sal>=(select max(sal) from emp where
sal<(select max(sal) from emp));
Select * from emp where sal=(select max(sal) from emp where sal>(select
max(sal) from emp));no rows selected.
Select * from emp where sal<(select min(sal) from emp where sal>(select
min(sal)from emp));
Select * from emp where hiredate=(select max(hiredate) from emp where
hiredate<(select max(hiredate) from emp));
Select job from emp where deptno=10 and job not in(select job from emp
where deptno in (30,20));
Select sal from emp where sal in(select sal from emp); 14 rows
selected.
Select sal from emp where sal=(select sal from emp); error.
Examples:
Select * from emp e where e.sal=(select max(sal) from emp where
e.deptno=deptno);
300 10
500 20
Select * from emp where sal in(select max(sal) from emp group by
deptno);
10 300
20 500
empno deptno
ename Sal
sal deptno
ename empno Empemp
1 10x 100
100 10 x 1
2 10y 200
200 10 y 2
3 10z 300
300 10 z 3
4 20a 500
500 20 a 4
5 20b 400
400 20 b 5
6 20c 300
300 20 c 6
ORACLE SQL
Select * from emp e where sal >(select sal from emp where
e.mgr=empno);
empno mpno
ename ename
sal Mgr
sal mgr
1 1x 300
x 2300 2
2 2y 100
y 4100 4
3 3a 500
a 4500 4
4 4z 100
z 1100 1
Queries:
Display the employee numbers and names working as clerks and
earning highest salary among clerk?
Select * from emp where job=’CLERKS’ and sal=(select max(sal
) from emp where job=’CLERKS’;
ORACLE SQL
Select * from emp where job=’SALESMAN’ and sal>(select max(sal)
from emp where job=’CLERKS’;
Display the name of clerks who earn salary more than that of James
and lesser than that of the Scott?
Select * from emp where job=’CLERK’ and sal>(select sal from emp
where ename=’JAMES’) and sal<(select sal from emp where
ename=’SCOTT’);
Display the names of the employees who earn highest salary in the
respective job groups?
Select * from emp e where sal=(select max(sal) from emp where
e.job=job);
Display the employee names who are working in Chicago?
Select * from emp where deptno=(select deptno from dept where
loc=’CHICAGO’);
Select * from emp where mgr in(select empno from emp where
ename=’JONES’);
Delete these employees who joined the company before 31st dec ’82
while their location is New York or Chicago?
Find out the top five earners of the company?
Select * from emp where 1= (select count(*) from emp where e.sal<=sal);
Emp e Emp
sal sal
400 400
300 300
Inline sub queries (INLINE VIEWS OR TOP-
N 200 200 QUERIES)
500 500 If you write a query in from clause or Instead of table
100 100 name or in front of from clause such queries are said
to be ‘Inline queries’.
We can provide unlimited number of queries in from clause.
From clause query provides the data to the outer query as same to that of
table data.
ORACLE SQL
Once outer query get executes inner query data evaporates or vanishes on
the fly.
Example:
Select * from (select * from table name);
Select * from (select * from emp);
Select * from (select * from emp) where deptno=10;
Select * from (select * from emp where deptno in(10,20))
where deptno=10;
Select * from (select * from emp) where deptno in(10,20)
where deptno=10;
Queries:
Write a question to display first five records, last five records , random
records, nth record, range of records, last two records, last but one record,
first and last record, except first five records, except last five records,
except random records, except nth record, except range of records, except
last two records, except last but one record, except first and last record,
salary wise first five records, salary wise last five records, salary wise
random wise records, salary wise nth record, salary wise range of
records, salary wise last two records, salary wise last but one record,
salary wise first and last record?
ROW NUMBER:
Select * from emp where rownum=1;1 record. N and N N
ORACLE SQL
Select * from emp where rownum>1;no rows. N and F F
Select * from emp where rownum<5;5 rows. N and T N
Select * from emp where rownum!=5;4 rows. N or N N
Select * from emp where rownum=5;no rows. N or F N
Select rownum,emp.* from emp;14 rows. N or T T
Select * from emp where rownum<=5;5 rows. NULL is NULL T
Select * from emp where rownum>5;no rows. NULL = NULLF
Select * from emp where rownum in(1,2,3);3 rows.
Select * from emp where rownum in (3,1,2);3 rows.
Select * from emp where rownum in (5,4,1);3 rows.
Select * from emp where rownum not in (5,4,1);no rows.
Select * from emp where rownum +3<-1;no rows.
Select * from emp where decode(rownum,rownum,1)>=0;14 rows.
Select * from (select rownum r,emp.* from emp) where r=(select
count(*) from emp);(n-1) rows.
Select * from (select rownum r,emp.* from emp) where r between 1 and
6;
Example:
Select &col from emp;
Select * from &n;
Enter value for n:emp
We get 14 rows.
How come the SQL * PLUS allows to provide our own values as a (by
using ampersand).
By using double (&&) ampersand we can provide a value only once for
N of occurrences throw out the session.
All of the SQL elements can replace with &.
Examples:
Select * from emp where &col;enter value for col:sal>3000.
Select &&col from emp order by &col;enter value for col:deptno.
Define:It is used to list out the variables and also to define the variables
this defined variables last for the session.
Example:
Select * from (&n);
Enter value for n: select * from emp
Select &n;
Enter value for n:* from emp
Select * from emp where deptno=&x;
Enter value for x:10
Examples:
Select * from emp where deptno=10 and exists (select * from emp where
deptno=20 and job=’MANAGER’);3 rows.
Select * from emp where deptno=10 and not exists (select * from emp where
deptno=20 and job=’MANAGER’);
1) Start with:
Start with specifies root record, in the absence of start with each and every
record will be treated as a root record.
To the root record level provides 1 and for the subsequent child records
provides 2,3,4….and so on.
2) Connect by:
This clause specifies relation between parent and child records.
3) Prior:
Represents the prior record with respect to current record.
4) Level:
Level is pseudo column which provides number values to that root
subsequent child records. It supports maximum of 255 values.
ORACLE SQL
5) Sys_connect_by_path:
It is a hierarchical function. It results the path from root to current node.
6) Connect_by_isleaf:
To the leaf record provides 1,the other provides 0.
Root/parent
Child/Parent Child/Leaf
Child/Leaf
Examples:
Select level,empno,ename,prior empno,prior ename from emp
start with mgr is null connect by prior empno=mgr;
Select level,max(sal) from emp where level <=3 connect by prior
sal>sal;error.
Select level,max(sal) from emp where level <=3 connect by prior sal>sal
group by level;
1 400
2 300
3 200
Select level,min(sal) from emp where level <=3 connect by prior sal>sal
group by level;
1 100
ORACLE SQL
2 100
3 100
sal 1 2 3 4
300 300 200 100
200 400 100
400 200 100 Select
100 100
level,max(sal)
200 100
from 300 100 emp where
200 100
100
level<=3,connect by prior sal<sal group by level;
Q) Write a query to display all the managers to the smith?
Select level,empno,ename from emp
start with ename=’SMITH’
connect by prior mgr=empno;
Select level,empno,ename,prior ename from emp
start with ename=’SMITH’
connect by prior mgr=emp[no;
SCALAR SUBQUERIES:
Using sub queries instead of column names is said to be scalar queries.
Scalar queries have to return only one value for each of the outer query
record.
Scalar query contains only one column.
Example:
Select ename, (select loc from dept where dept.deptno=emp.deptno), job from
emp;
Note:
It is a special case of single row sub query.
It is not possible to provide the order by clause, which are used in
Examples:
Select * from emp where sal>(select max(sal) from emp where deptno=10);
Select * from emp where sal>all(select sal from emp where deptno=10);
Note:
=ALL
<ALL(Smaller than the Lesser)
>ALL(More than the Greater)
>ANY(More than the Lesser)
<ANY(Smaller than the Lesser)
=ANY
Example:
Create table ‘space tab’ (sno number(5));
#,/,-,$,char,number are allow in table name.
Table name space allow specifying with in double coats.
Select * from “space tab”;
Sub query value cannot be used as a default value. Only we have to use
literals or functions.
Sno Sname
10 A
20 20
30 X
40 Y
Select * from sam1
Delete (select sno s from sam1) where s<30; 3 rows.
Update (select sname m from sam1) set m=’D’; 2 rows.
ORACLE SQL
Example:
Where [[start with condition1]
Group by connect by condition2]
Having
Order by
SIBILINGS: (9i)
It place the child nodes there parent nodes while preserving hierarchy.
In the absence of siblings hierarchy get disturbed.
Example is given above.
Select sum (sal) from emp start with ename=’BLAKE’ connect by prior
empno=mgr;9400.
CONSTRAINTS
They are the data integrity rules/restrictions which allows only valid
data into tables.
Through constraints we can fulfil the business requirements
We provide constraints on tables and even on views.
Constraint keys:
1. Primary key
2. Unique
3. Not null
4. Check
5. Ref(log)
6. Default
ORACLE SQL
7. Foreign key
1. Primary key:
It acts as both (unique +not null) which means it won’t allow
duplicate and null values
Implicitly an unique index et defined on primary key columns
These should be only one primary key for an entire table
A P.K can hold maximum of 32 columns(i.e unique index
limitation)
Materialized view get defined only on tables, which are aving
primary key’s
Generally we call primary key table as master table/parent
table.
2. Unique key:
It allows only unique (null) and values (won’t allow duplicates)
Not null values are allowed through unique constraint
For unique key also an implicit unique index get defined
An unique key can hold maximum of 32 columns
3) Not Null: It won’t allow null values, but allows duplicate values.
Note:
Not null constraint are allowed only in columns levels
Views won’t allow not null constraints
4) Check:
To restrict/enforce other than standard integrity rules
(Primary key (unique + not null) we use check constraints.
Check constraint throws an error only when condition becomes
false, won’t throw for ‘true and null’
5) Default:
It takes default values (if user won’t provide any value to a
columns then default provides default values to columns).
It won’t allow sub queries and user defined functions.
6) Foreign key:
ORACLE SQL
It’s a reference integrity constraint (RIC), if ever you provide
any value into the foreign key columns before begin inserted
that value will be referred through F.K with primary/unique
column
F.K allows null values for flexibility and allows duplicates
PK and FK columns names could be different but data types
should be same/compatible, size should also be same.
System defined column level (CL)
System defined table level (TL)
User defined column level
User defined table level.
(or)
Mixed method:
SQL>create table con10 (sno number (5) primary key, loc varchar2
(10),name varchar2(10), constraint un5(loc));
Composite key:
It holds more than one column (PK +FK +unique). Whichever the number of
columns PK is having FK also s to contain same number of columns.
ORACLE SQL
Eg:-
C1 C2
10 X
10 X
10 Y
10 Null
10 Null
In the above table last two rows are unique or same values then null also treat as
same at that time it treats as duplicate record, so won’t allow.
In the above example null values become equal when all of the non-null values are
same.
ORACLE SQL
Note: It is not possible to add Not Null constraint rather we modify it from Null to
Not Null and Not Null to Null by using one alter we can use ‘n’ number of ‘adds’.
SQL>create table ctab1 sno number(5) primary key using index <index_nme>;
Add:
Modify:
Rename:
Syn: Alter table <table_name> rename constraint oldname to newname;
Constraint states:
Delete rules:
Event Action
Deleting the parent records On deleting (while defining FK)
Dropping parent column and table Cascade constraint
Dropping/disabling PK when it is Cascade
relation with FK
If you want to delete the PK record you can not delete because table is in
relation with FK and you have child records so, you can not delete, first you
need to delete child records, these is a chance to delete the records by using
‘on delete cascade’.
If tables are in rlation (PK with FK) you can’t delete PK column and PK record
and PK table and PK until unless deleting the CT, but we have the chance to
drop and delete by using one table.
On delete set null: It provides null values for department child records
while deleting parent record.
ORACLE SQL
Cascade constraint: Vary directly dropping master/parent table and PK
column is not possible when they are in relation with FK , but by using
cascade constraint it is possible.
Constraint checking:
1. Initially immediate(default)
2. Initially deferrable
If constraint checking takes place at the individual statements i.e called
‘initially immediate’ which is default.
But if constraint checking takes place at the time of transaction is called
‘transaction specific’ we do this with ‘initially deferrable’.
Disadvantages of constraints:
Constraints can’t handle varying data, but by using trigger we can handle
varying data.
Constraint can check the old data but trigger’s can’t check the existing
data.(it checks only incoming data)
Constraints are more useful than trigger.
Constraints can give guarantee for centralized data.
ORACLE SQL
we use following query to find out constraint name and table name once
we know the column name.
Constraint types:
Primary key P
Unique U
Foreign key R
Check C
Not null C
SQL>desc user_synonym;
SQL>desc all_synonym;
SQL>select table_name from user_synonyms where synonym_name= ‘s’;
SQL>select synonym_name from user_synonym where table_name=’emp’;
User_synonym:
Note:Table/view is not existed for dx, but synonym creted we can do this.
Types of views:
Simple view
Complex/composite view
Read only
Inline
Join
Functional
Force
Partition
Object
Materialized
Vertical
Horizontal
View wit check option
ORACLE SQL
Inline view:
Unlike other views they are not stored objects
They are only temporary queries
In inline views we will mention subsequeries in from clause of another query
Partial view:These are the views which are defined on compound queries
SQL>create view pview as select * from emp union select * from emp
Functional view:In this we will make use of functions while defining a view
in select statements
Vertical View:In this will create a view by selecting specific columns from a
table so as to hide few of columns in a vertical manner
Complex view:
If you define a view by making use of more than one table those views are
aid to be ‘complex views’
Generally most of the complex views will have join conditions that views are
considered as ‘join views’.
Object view:They are the views which are defined on object tables
Object table:A table which is defined by using object data type
It is a oops concept
It is user defined permanent data type wich is having fields to store
homogenous data.
Object data types are useful to full fill the real time applications and
also alter the performance
Syntax:
SQL>create or replace type obj as object(eno number(5), ename
varchar2(10). Mail varchar2(10));
SQL>create table lt(comp varchar2(10),empdet obj);
SQL>create table objtab of obj:
SQL>create view objview as select * from objtab.
materialized view:
ORACLE SQL
Unlike other views it has own structure, it is a replica
Materialized views are useful to store historical data or summarized
data
These are useful to increase performance in tools like data ware
housing and RAC mobile computing and so on….
It is also useful for backup
We need some special privileges to define materialized view
Materialized views are get defined only on views which are having PK
Before creating materialized view we have to define materialized view
log for that table
Syntax:
Create materialized view viewname refresh on commit/demand
fast/compile as SQL>select * from tablename;
Eg:
SQL>create materialized view log on emp;
SQL>create materialized view mview refresh on commit fast as select *
from emp;
we need to refresh for every n(5/10..) time, if any new record added. If
we give ‘on demand’ we need to type in sql*plus ‘DBMS_mview’ then only
the effect will be populated in replica(mview)
1. Read only
2. Partition
3. Complex
4. Views which are having following tings
ORACLE SQL
Note:View and synonym are subject to the table constraints. View and
synonyms are transactions are also considered by the table constraints
C1 c2 C1 c2 c3
1o x –
20 -
-
Through this we can insert only values 10 and deletion also possible
values 10
Note:If you drop a table department view will get individual if you recreate
a table with the very same name now view becomes valid. If you alter the
structure of a table without disturbing the columns which are used by view,
in this case view won’t become invalid.
If you rename/drop the columns which are used by view then view becomes
invalid. If you recreate the columns which are used by view their view
automatically becomes valid.
ORACLE SQL
Sequences
Sequence is database object
It is a shared object
Sequence display the integer number
Sequence eliminate serialized and improves concurrency
Useful for multiple users across the DB
Useful in frontend applications we can define synonyms on sequences
Syntax:Create sequence <seq_name> [start with value]
[increment by value]
[minvalue value}nomin value]
[maxvalue value|nomax value]
[cycle|nocycle]
[cache value|no cache]
[order}no order]
[default]
It specifies with which value sequence has to start by default it starts with
‘1’.
Always start with values has to equal or greater than min value
Note: We can alter all other parameters except start with parameter
Increment by value:
It specifies with which value sequence has to increment so, to get next value.
By default it increment with ‘1’
This may also have ‘-ve value’
Minvalue Maxvalue
+ve 1 1*1027
-ve -1*1026 -1
Cycle:
Cache:
Note:Cache values has to fit into the cycle by using following formulae we have
to specify the cache values
Formula:Ceil(maxvalue-minvalue)/abs(increment by value)
Eg: Ceil((10-1)/2)
(9/2)
Ceil(4.5)=5
Order:-We have to use tis order parameter only in RAC applications (real
application clusters)
Syntax: Sequencename.nextval;
Sequencename.currval;
Output:sequence created
SQL>alter sequence sq1 nocycle;
SQL>alter sequence sq1 maxvalue 20;
Note: We can alter all other parameters except start with value
ORACLE SQL
Note: If you use the currval just beside of nextval in the same select
statement, firast nextvalue will be consider and also currval displays
the nextval values or currently displayed value.
Usage of sequence:
Eg:
Declare
V number(5):=sq.nextval;
Begin
DOPL(v);
End;
Sub queries
View query (create or replace view sview as select * from..) in this select list
won’t use.
Order by
Group by
Select list where clause and distinct clause
Delete statement
Set operators
Materialized view
Check constraints
Default value(create and alter statement)
Analytical functions:
Rank()
Dense-rank()
Parent-rank()
Cumu-dist()
Row-num()
Ntile()
Log()
Lead()
Rank(): Rank provides the ranking values for each of the table records
rank
skips the sequential ranking values when there is a duplicate records or
values
Row-num():Provides the row numbers for each of the record this row
ORACLE SQL
number allows partition unlike pseudo column row numbers
Log(),lead():
Displays logging and leading values with respect to current record
Eg:
Select deptno,sal ,
rank() over(partitions by deptno order by sal desc) rnk,
dense-rank()over(partitions by deptno order by sal desc) drnk,
perent-rank()over(partitions by deptno order by sal desc) prnk,
cumu-rank()over(partitions by deptno order by sal desc) cd,
row-number()over(partitions by deptno order by sal desc) rn,
ntile(2) over(partitions by deptno order by sal desc) nt,
log(sal,1) over(partitions by deptno order by sal desc) lg,
lead(sal,1) over(partitions by deptno order by sal desc) ld
From emp;
Eg:
SQL>select * from ftab;
SQL>drop table ftab;
Note: From 10g onwards if drops an object that will be placed in recycle bin
EG:
SQL>create table ptab(sno number);
SQL>drop table ptab purge;
SQL>flashback table ptab to before drop; //objects not in recycle bin
We can completely empty the recycle bin by using purge command as shown
in blow.
which rows are involving in condition that column should not use in update
In matched condition we have to write update and delete in table whatever
the rows has updated that rows only will be affected for deletion. In not
matched only we need to write insert.
Columns which are having more selectivity are good choice for indexes
We can define n no of indexes on table columns
More no of indexes are useful for select statement but for DML operations it
is not useful since it hinders the performance.
Equal operator readily invokes the column indexes whenever you use the
index column in where clause with equal operator
Not equal to(!=) will not invoke the indexes(performance degrades)
Like operator will not invoke the indexes when ‘%’ is at leading position (or)
starting character.
Drawback:
SQL optimizer
Here all sql statements are make use of optimizer and optimizer is nothing
but DBMS set of programs it choosing optimizer.
LOBRAW and column won’t allow indexes
Indexes will get automatically defined on a columns which are having unique
and FK constraint. An index can hold maximum of 32 columns but in each bit
map index it is 30
Oracle by default make use of B+ tree index
ORACLE SQL
Indexes won’t store null values except bitmap index
When you drop the table with it, indexes also get dropped
Bitmap indexes are useful for flag columns(less selectivity, high duplicity)
SQL>select /*+hint */
->based on rowed concept data will pick up directly and get displayed instead of
total table scan
Types of indexes:
Simple index:
If you define an index on single column those indexes are called simple
indexes
SQL>create index indsql on emp(sal);
To find out whether the optimizer has chosen the index (or) not we have a
DML command called ‘explain plan’
With the help of explain plan you can find out the path choosen by the
optimizer
Explain plan populates the plan table with optimizer information (or) explain
plan will make use of plan table for optimizer information
So, to find out whether the optimizer preferred index or not we use ‘explain
plan’
Once we drop the index optimizer go for complete table scan as shown in the
following
EG:
Complex index:
Eg:
SQL>create index comind on emp(sal,deptno);
SQL>select * from emp where sal>2000 and deptno>10;
SQL>select * from emp where deptno>10;
Note:here optimizer will make use of index even through you won’t
mention all the index column in where clause this is due to because of ‘skip
column’ mechanism
unique index:
ORACLE SQL
To define an unique index on a column that column should not contain
duplicate values.
Note: Without using PK and unique constraints we can restrict the user not
to provide duplicate values on a column by providing unique index
immediately after defining a table
Bitmap index:
SQL>create bitmap index bindex on emp(deptno);
Cluster index:
It is logical memory area in which related and frequently tables are placed
together binding with a cluster common column
The concept of cluster and cluster indexes is useful to increase the
performance.
Regular expressions(10g)
ORACLE SQL
1. Regexp_instr
->It displays the strating character (or) end character position based on
the occurance (or) it is an extension to ‘instring’
2. Regexp substr
3. Regexp replace
4. Regexp like
5. Regexp count(11g)
Displays the set of characters from a given string when characters are
matched with pattern (or) extension to ‘substr’.
Replace the text with another text when pattern is matched in given
string
It simply returns Boolean value after performing a match if match is
found return true else null.
Meta characters:
Match parameter:
I Case insensitive
C Case sensitive(default)
M Multiline
N Newline
X Ignore space
Syntax:
Regexp-instr(str,patt[,pas[,oc[,ropt[,mp[,subexp]]]]])
Regexp-substr(str,patt[,pos[,oc[,mp[,subexp]]]])
Regexp-replace(str,patt[,reppatt[,pos[,oc[,mp]]]])
Regexp-like(str,patt[,mp]);
Regexp-count(str,patt[,pos]);
Str-source string
Patt-pattern
Pos-position
ORACLE SQL
Oc-occurance
Ropt-return option(0,1) default 0
Mp-match parameter(I,c,m,n,x)
Subexp-subexpression(11g)(1-9)
Reppatt-replace pattern
Regexp-substr:
1. X # gmail.com [email protected]
2. [email protected] y#gmail.com
3. X#gmail.com y#gmail.com
PL/SQL Views
Indexes Constraints
Regular expression always looks for true condition, else return null.
SQL>select ename from emp where ename like ‘A%’ or ename like ‘s%’;
SQL>select ename from emp where regexp-like(ename,’^A/^s’);
ORACLE SQL
SQL>select * from regtab where regexp-like(name,’\s’);
SQL>select * from regtab where regexp-like(name,’\s’);
SQL>select * from regtab where regexp-like(name,’\d’);
SQL>select regexp-count(‘welcome’,’E’,1) from dual;
It counts the records in a given string and if there is no match it returns ‘0’