SQL Narayana Reddy
SQL Narayana Reddy
SQL Narayana Reddy
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.
Oracle Database is the first database designed for enterprise grid
computing, the most flexible and cost effective way to manage information
and applications. Enterprise grid computing creates large pools of industrystandard, modular storage and servers. With this architecture, each new
system can be rapidly provisioned from the pool of components. There is no
need for peak workloads, because capacity can be easily added or
reallocated from the resource pools as needed.
The database has logical structures and physical structures. Because
the physical and logical structures are separate, the physical storage of data
can be managed without affecting the access to logical storage structures.
ORACLE SQL
CONTENT
Fundamentals of Database
Introduction to Database
Database Models
Introduction to Oracle Database
Oracle Database History
Oracle 11g Server and DB Architecture
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 its options
Pseudo columns Introduction
Table Truncation and its 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 its clauses
Operators Types of Operators in Oracle 11g & Filters
Functions
ORACLE SQL
ORACLE SQL
Alter session language
Alter system language
Sql developer
PL/SQL
ORACLE SQL
ORACLE SQL
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:
Specifies what kind of Data We have to store in a Memory
SQL wont support Boolean datatypes.
Boolean Data types (TRUE, FALSE, NULL)
1)
2)
3)
4)
5)
6)
7)
8)
NUMBER
CHAR
VARCHAR OR VARCHAR2
DATE
TIMESTAMP
TIMESTAMP WITH TIMEZONE
TIMESTAMP WITH LOCAL TIMEZONE
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:
SYN:
X CHAR(S [BYTES|CHAR]);
To store alphanumeric values
Max size 2000 bytes;
Memory allocation is constant (wastage of memory).
X VARCHAR2(S);
4) DATE
SYN: X DATE;
(DD-MON-YY HH:MI:SS)
Disadvantage:
5) TIMESTAMP (9I)
SYN:
X TIMESTAMP [(P)].
ORACLE SQL
6) TIMESTAMP WITH TIMEZONE (9I) (DD-MON-YY HH: MI: SS.FS THZ:
TZM)
SYN: X TIMESTAMP [(P)] WITH TIMEZONE;
In addition with timestamp values it stores time zone values.
7) TIMESTAMP WITH LOCAL TIMEZONE
SYN: X TIMESTAMP WITH LOCAL TIMEZONE.
Normalize the given time into ISO/GMT standard time
8) INTERVAL DATATYPE
I) Interval Year to Month
SYN: X INTERVAL YEAR TO MONTH.
To Store Year to Month Interval Data
9) LONG:
a) LONG:
SYN: X LONG;
To store information.
Max size 2 gb.
Disadvantage:
We have to use long datatype only once in an entire table.
So many disadvantages are there for long this is why notPreferable.
b) RAW:
SYN: X RAW(S).
To store the images.
ORACLE SQL
c) LONG RAW:
SYN: X LONG RAW.
To store information+ images
Max sized 2gb
Not preferable, so many disadvantages.
10) LOB: (LARGE OBJECTS (OOPS))
1)CLOB :( CHARACTER LARGE OBJECTS);
SYN: X CLOB;
To store huge information.
Max size depends on sql and pl/sql.
2) BLOB:
SYN: X BLOB;
To store images.
3) BFILE: (EXTERNAL DATATYPE)
SYN: X BFILE;
TO store files.
11) ROWID:
SYN: X ROWID;
It is a datatype which is user to store the physical address of the
records rowid values.
Rowid values are usefull to identify the records in a table.
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
They introduced from 10 g.
They are used to store float values so to increase the performance.
15) SIMPLE_INTEGER
16) SIMPLE_FLOAT
17) SIMPLE_DOUBLE
They are introduced from 11g.
Useful in performance.
Unlike other datatypes they wont allow null values.
18) NCHAR
19) NVARCHAR2
20) NCLOB
They are used to store the national database character set
They support multi languages.
Null value:
ORACLE SQL
Null values are taken higher values than number and character in
order by clause
All the arithmetic operators with null values will result in null values
Decode function will treats the null values equal
Concatenation operator will ignore the null values
Codes without any space will also be treated as null value
Oracle database allocates one byte for null value when it fall between
column values
A concept of null is not applicable to row or record
Truth Table
AND
NULL
OR
T
T
F
F
T
N
T
F
T
T
F
ORACLE SQL
&
OR
F
F
SQL STATEMENTS
Its a structured query language(SQL) pronounced as SEQUEL
Its a set oriented language which means handles the bunch of records
at a time thats way its more faster than the PL/SQL
SQL is a sub-language
Case-insensitive
Gateway to the RDBMS
Its the only language that directly interacts with databse
Fourth generation language[PL/SQL is 3 rd generation]
SQL wont supports the control structures and Boolean data type
You can embed this language with other languages like java,
PL/SQL.[embed SQL]
Its a database standard language
SQL - Sub divided into 6 sub languages
ORACLE SQL
DDL
DML
DCL
DRL
SEE TO DIAGRAM
1)
2)
3)
4)
5)
6)
1)
DDL (DCL)
DML (DRL OR DQL)
TCL
ALTER SESSION
ALTER SYSTEM
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.
SYN: CREATE TABLE TABLENAME (COL DTPS(S), COL DTPS(S),.);
EG: CREATE TABLE NEWTAB (SNO NUMBER (5),SNAME VARCHAR2(10));
Note: A table can contain max of 1000 columns.
ALTER: We use alter to modify the structure of database objects with the
help of keywords.
KEY WORDS:
a)ADD - To add columns
b)MODIFY - To modify column datatypes and size
c)RENAME -To rename column and table names
d)DROP- To drop columns.
a) ADD:
SYN: ALTER TABLE TABLENAME ADD(COL DTPS(S),COL1 DTPS(S),);
ORACLE SQL
EG : DROP TABLE NEWTAB1;
TRUNCATE(DELETE+COMMIT):
SYN: TRUNCATE TABLE TABLENAME;
EG:TRUNCATE TABLE NEWTAB;
PURGE:TO DROP THE TABLE FROM RECYCLEBIN;
SYN: PURGE TABLE TABLENAME;
TO BIPASS THE TABLE FROM RECYCLEBIN;
SYN: DROP TABLE TABLENAME PURGE;
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)
SYN: FLASHBACK TABLE TABLENAME TO BEFORE DROP;
EG: DROP TABLE TL;
SELECT * FROM TL;
FLASHBACK TABLE TL TO BEFORE DROP;
SELECT * FROM TL;
ORACLE SQL
ORACLE SQL
COMMENT:
SYN: COMMENT ON TABLE TABLENAME|COLUMN TABLENAME.COLUMNAME IS
TEXT
EG:COMMENT ON TABLE TL IS HELLO;
SELECT * FROM USER_TAB_COMMENTS WHERE TABLE_NAME=TL;
INSERT
UPDATE
DELETE
MERGE(INSERT+UPDATE+DELETE)
ORACLE SQL
SELECT(DRL OR DQL)
INSERT
VALUE METHOD
REFRENCE METHOD
SELECT METHOD
VALUE METHOD
SELECT METHOD:
ORACLE SQL
SYN: DELETE FROM TABLENAME [WHERE CONDITION];
EG:DELETE FROM NEWTAB;
DELETE FROM NEWTAB WHERE SNO=10;
TRUNCATE:
SYN: TRUNCATE TABLE TABLENAME;
DELETION:
Delete the records temporarily.
Possible to delete specific records.
ORACLE SQL
3) DRL OR DQL (DATA QUERY/RETRIEVE LANGUAGE)
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)
EG: SELECT * FROM EMP;
SELECT 1 FROM EMP;
SELECT ALL * FROM EMP;
SELECT DISTINCT * FROM EMP;
SELECT DISTINCT DEPTNO FROM EMP;
SELECT 2*2 FROM EMP;
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;
SYN:
INSERT ALL
INTO TABLENAME VALUES (VALUES)
INTO TABLENAME VALUES (VALUES)
ORACLE SQL
INTO TABLENAME VALUES (VALUES)
SELECT * FROM TABLENAME;
EG: INSERTING MULTIPLE VALUES INTO SAME TABLE;
INSERT ALL
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
INTO MULTAB VALUES (1,X,HYD)
INTO MULTAB VALUES (10,Y,BANG)
SELECT * FROM DEPT;
EG: INSERTING MULTIPLE VALUES INTO SPECIFIED COLUMNS
INSERT ALL
INTO MULTAB (DEPTNO, LOC) VALUES (DEPTNO, LOC)
INTO MULTAB VALUES (1,X,HYD)
INTO MULTAB VALUES (10,Y,BANG)
SELECT * FROM DEPT WHERE DEPTNO=10;
EG: INSERTING INTO MULTIPLE TABLES
INSERT ALL
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
SELECT * FROM DEPT WHERE DEPTNO=10;
EG: INSERTING BASED ON WHEN CONDITION WITH OUT ELSE
INSERT ALL
WHEN DEPTNO=10 THEN
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
WHEN DEPTNO=20 THEN
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
WHEN DEPTNO=30 THEN
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
SELECT * FROM DEPT;
ORACLE SQL
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
ELSE
INTO MULTAB VALUES (DEPTNO, DNAME, LOC)
SELECT * FROM DEPT;
4) TCL COMMANDS
TCL: Transaction control language.
Commit
Roll Back
Save Point
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;
2) String literals: anything enclosed in quotes is considered string.
USAGE: A,10,13-SEP-13
EG: SELECT A,10,13-SEP-13 FROM DUAL;
3) Date literals
USAGE: DATE YYYY-MM-DD
EG:SELECT DATE 2013-09-13 FROM DUAL;
EG:SELECT DATE 2013-09-13+1 FROM DUAL
4) Timestamp literal:
USAGE: TIMESTAMP YYYY-MM-DD HH: MI: SS.FF
EG: SELECT TIMESTAMP 2013-06-10 10:10:10.10
FROM DUAL;
5) Timestamp with time zone literal:
USAGE: TIMESTAMP YYYY-MM-DD HH: MI: SS.FF +TZH: TZM;
EG: SELECT TIMESTAMP '2012-09-10 10:10:10.000 +05:30'
FROM DUAL;
6) Interval Literals:
a) Interval year to month literals:
USAGE: INTERVAL YY-MM YEAR TO MONTH;
EG: SELECT INTERVAL '10-10' YEAR TO MONTH FROM DUAL;
b) Interval day to second:
USAGE: INTERVAL DD HH: MI: SS.FF DAY TO SECOND;
EG: SELECT INTERVAL '10 10:10:10.1000' DAY TO SECOND FROM
DUAL
ORACLE SQL
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:
EG:
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
ORACLE SQL
RELATIONAL OR COMPARISON :
EG:
3) LIKE:To search the patterns we use like operator with the help of wild card
Characters
% ANY OR NO NUMBER OF CHARACTERS
_ SINGLE CHARACTERS COMPARISION
EG:
ORACLE SQL
4) BETWEEN:
To provide range of values.
Always lower limit must be less than upper limit if not Condition becomes
false.
Range includes the boundary values also.
EG:SELECT * FROM EMP WHERE SAL BETWEEN 1000 AND 2000;
SELECT * FROM EMP WHERE SAL NOT BETWEEN 1000 AND 3000;
SELECT * FROM EMP WHERE SAL BETWEEN 5000 AND 1000; NO ROWS
SELECT * FROM EMP WHERE SAL BOT BETWEEN 5000 AND 1000;
(ALL THE ROWS ;)
5) ANY/SOME:In any, the given value has to become true with any of
the list of values
6) ALL:In all, the given value hat to become true with all of the list values.
7) EXISTS:returns true if record is found else false.
NOTE:we have to use any & all along with relational operators.
They cant exist individually.
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
SELECT
*
*
*
*
*
*
*
FROM
FROM
FROM
FROM
FROM
FROM
FROM
EMP
EMP
EMP
EMP
EMP
EMP
EMP
WHERE
WHERE
WHERE
WHERE
WHERE
WHERE
WHERE
DEPTNO>ANY(10,20);
DEPTNO<ANY(10,20);
DEPTNO!=ANY(10,20);
DEPTNO!=ANY(10,NULL,20);
DEPTNO!=ALL(10,NULL,20);
DEPTNO=ANY(10,NULL,20);
DEPTNO=ALL(10,NULL,20);
3 * 100/5 + 20/10 5
300/5 + 20/10 5
60 + 20/10 5
60+2-5
62-5
ORACLE SQL
=>
57
Order of presidence:
Level
1
2
3
4
5
6
7
8
9
10
Operators
Unary (+, -, ~,
connect_by_root)
Arithmetic
||
=, >, <, >=, <=
[not] like, is [not], [not] in
[not] between
!=, <>, ^=
Not
And
Or
TABLE ALIASES
To qualify the columns
We use it to increase the performance
EG: SELECT DEPTNO FROM EMP, DEPT; ERROR (AMBIGUOUS)
SELECT E.DEPTNO, D.LOC FROM EMP E,DEPT D
WHERE E.DEPTNO=D.DEPTNO;
EG: SELECT SAL SALARY OF FROM EMP;
SELECT 2*2 EXP FROM DUAL;
ORACLE SQL
ORACLE SQL
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
ORACLE SQL
USER AND UID: They specify username and USERID
SELECT USER,UID FROM DUAL;
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.
SINGLE ROW FUNCTIONS
MULTIPLE ROW FUNCTIONS (OR) GROUP FUNCTIONS (OR)
AGGREGATE FUNCTIONS
(OR) SUMMARY FUNCTIONS
WINDOW FUNCTIONS
ANALYTICAL (RANK FUNCTIONS)
ORACLE SQL
They get execute for each of the row and return a value
Based on data we can classify the functions in following ways
Number (or) numerical functions or
arthimatic functions(old versions)
String functions or character functions or text functions
Date functions
Conversion functions
Null functions
Search functions
Conditional functions
Hierarchical functions
General functions
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);
ABS:Returns absolute value irrespective of sign
SYN: ABS (V);
LOG:LOG VALUES
LN :NATURAL VALUES
ORACLE SQL
EG:SELECT POWER(5,2),POWER(0,0),POWER(1,0),POWER(0,1) FROM DUAL;
SELECT MOD(2,5) ,MOD(1,2),MOD(4,2) FROM DUAL;
SELECT REMAINDER(5,2) FROM DUAL;
SELECT MOD(3,-2),REMAINDER(3,-2) FROM DUAL;
SELECT SIN(45),SINH(50) FROM DUAL;
SELECT SIGN(-30),SIGN(0),SIGN(+30),ABS(-30),ABS(0),ABS(+30)FROM DUAL;
SELECT CEIL(-12.45),FLOOR(-14.56),CEIL(0.56),FLOOR(-0.567) FROM DUAL;
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
EG: SELECT ROUND (12.567, 2) FROM DUAL;
SELECT ROUND (12.563999, 2) FROM DUAL;
SELECT ROUND (12.56, 3) FROM DUAL;
SELECT ROUND (13.56, 1) FROM DUAL;
SELECT ROUND (13.56) FROM DUAL;
SELECT ROUND (15.56,-1) FROM DUAL;
SELECT ROUND (-16.99,-1) FROM DUAL;
SELECT ROUND ( -56.99,-2) FROM DUAL;
SELECT ROUND ( -56.99,-3) FROM DUAL;
SELECT ROUND (12.56, 1 ) ,TRUNC(12.56,1) FROM DUAL;
SELECT ROUND ((TRUNC (98.56),-2) FROM DUAL;
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
INTERNALLY IT
ORACLE SQL
ORACLE SQL
TRIM: TO TRIM FROM BOTH ENDS.
SYN: TRIM([LEADING|BOTH|TRAILING [C FROM]],TEXT);
NOTE: DEFAULT TRIMS SPACES;
EG: SELECT LTRIM(WELCOME,W) FROM DUAL;
SELECT LTRIM(WELCOME,E) FROM DUAL;
SELECT RTRIM(WELCOMEEE,E) FROM DUAL;
SELECT LTRIM(EEEWELCOMEE,E) FROM DUAL;
SELECT LTRIM(EEEWELCOME,WE) FROM DUAL;
SELECT LTRIM(RTRIM(EWEWELCOME,EW),WE) FROM DUAL;
SELECT TRIM(E FROM EEEWELCOMEEE) FROM DUAL;
SELECT TRIM( WELCOME ) FROM DUAL;
SELECT TRIM(LEADING E FROM EEEWELCOME) FROM DUAL;
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);
EG:SELECT LPAD(WELCOME,10,*) FROM DUAL;
SELECT RPAD(WELCOME,9,*@) FROM DUAL;
SELECT RPAD(WELCOME,10,*@) FROM DUAL;
SELECT LPAD(WELCOME,7,*) FROM DUAL;
SELECT LPAD(WELCOME,6,*) FROM DUAL;
SELECT RPAD(WELCOME,6,*) FROM DUAL;
TRANSLATE: To translate character wise
SYN: TRANSLATE(S,C,C): It takes strings only individually
SELECT TRANSLATE(WELCOME,E,A) FROM DUAL;
SELECT TRANSLATE(WELCOME, EL,A) FROM DUAL;
SELECT TRANSLATE(WELCOME EL,AB) FROM DUAL;
SELECT TRANSLATE(WELCOME,EL,A_) FROM DUAL;
DISADV:NOT POSSIBLE TO REPLACE STRING WISE
REPLACE:To replace string wise
SYN: REPLACE(S,S,S);
EG: SELECT TRANSLATE(INDIA,IN,XY),REPLACE(INDIA,IN,XY)
FROM DUAL;
SELECT JOB,REPLACE(JOB,MANAGER,MGR) FROM EMP;
DISADV: NOT POSSIBLE TO REPLACE MORE THAN ONE STRING
DECODE: (ORACLE) It works as same to that of IF CONDITION IN SQL;
ORACLE SQL
SYN:DECODE (COLUMN|EXP|VALUE|NULL, COND1, DO1,COND2,DO2,[ELSE]);
NOTE: It considers the null values. In decode nulls are equal
MAX 255 ARGUMENTS ARE ALLOWED;
MIN 3 ARGUMENTS MANDATOREY;
EG:SELECT DECODE(1,2,3) FROM DUAL;
SELECT DECODE(1,2,3,1,2,3) FROM DUAL;
SELECT DECODE(NULL,1,NULL,2) FROM DUAL;
SELECT DECODE(1,DECODE(1,2,3),2,NULL) FROM DUAL;
SELECT DECODE(JOB,MANAGER,MGR,SALESMAN,SLS,JOB)
FROM DUAL;
DISADV:Wont allow relational operator
SUBSTR:TO DISPLAY THE SET OF CHARACTERS FROM A GIVEN POSITION
SYN: SUBSTR(S,M,(N));
M=POSITION,
S=STRING,
N=NO OF CHARACTERS
ORACLE SQL
SELECT INSTR(WELCOME,E) FROM DUAL;
SELECT INSTR(WELCOME,E,1) FROM DUAL;
SELECT INSTR(WELCOME,E,-3,1) FROM DUAL;
DATE FUNCTIONS:
DATE FORMATS
D(1,2,..)
DD(1 TO 31)
DDD(1 TO 365)
DY(SUN,MON,..)
Dy
DAY(SUNDAY,)
Day
MM(1-12)
MON(JAN,FEB,..)
MONTH(JANUARY,..)
Month
Y(3)
YY(13)
YYY(013)
YYYY(2013)
SYYYY (AD AND BC)
RR(13)
RRRR(2013)
I
IY
IYY
IYYY
W(1-5)
WW(1-52)
IW
FM
FF
XF
HH
HH12
HH24
MI
SS
SP
TH
Q
J
RM
DL
DS
TZH
TZM
TZR
TZA
AM/PM
.
:
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
ORACLE SQL
SYN: MONTHS_BETWEEN (DATE1, DATE2);
EG:
ORACLE SQL
ORACLE SQL
CONVERSION FUNCTIONS:
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;
ORACLE SQL
TO_DATE: Converts character format to date format
SYN: TO_DATE (C,FORMAT);
EG:
SELECT
SELECT
SELECT
SELECT
SELECT
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;
SELECT NUMTOYMINTERVAL(11,MONTH) FROM DUAL;
SELECT NUMTOYMINTERVAL(9999,YEAR) FROM DUAL;
SELECT NUMTODSIINTERVAL(10,DAY) FROM DUAL;
SELECT NUMTODSINTERVAL(10,HOUR) FROM DUAL;
SELECT NUMTODSINTERVAL(10,SECONDS) FROM DUAL;
SELECT ORA_ROWSCN FROM DUAL;
SELECT SCN_TO_TIMESTAMP(ORA-ROWSCN) FROM DUAL;
SELECT TIMESTAMP_TO_SCN(SCN_TO_TIMESTAMP(ORA_ROWSCN))FROM
DUAL;
SELECT TO_NUMBER (99) FROM DUAL;
SELECT SYSDATE+TO_NUMBER(10) FROM DUAL;
ORACLE SQL
NUMBER FORAMTS:
$
9
0
.
,
PR
MI
S
L
B
C
D
EEEE
G
U
V
X
N
DIGIT REPRESENTATION
SPECIFIES THE DECIMAL
ENCLOSE THE VE VALUES IN ANGLE BRACKETS
REPRESENTS THE VE SIGN
SIGN
LOCAL CURRENT SYMBOL
BLANK SPACE
CURRENCY CODE
DECIMAL POINT
SPECIFIES THE EXPONENTIAL
GROUPING
GENRAL FUNCTIONS
GREATEST
LEAST
USER
UID
DECODE
CASE
NVL
NVL2
ORACLE SQL
NULLIF
COALESCE
GREATEST
SYS_CONNECT_BY_PATH
(HIERARCHIAL FUNCTION);
NULLIF:
2) AVG
SYN: AVG ([ALL|DISTINCT] VALUE|EXP|COLUMN);
3) MIN
SYN: MIN (([ALL|DISTINCT] VALUE|EXP|COLUMN);
ORACLE SQL
4) MAX
SYN: MAX ([ALL|DISTINCT] VALUE|EXP|COLUMN);
5) COUNT:
SYN: COUNT (*|[ALL|DISTINCT] VALUE|EXP|COLUMN);
6) STDDEV
7) VARIANCE
EG:SELECT SUM(SAL),AVG(SAL),MIN(SAL),MAX(SAL) FROM EMP;
SELECT MIN(HIREDATE),MAX(HIREDATE) FROM EMP;
SELECT MIN(ENAME),MAX(ENAME) FROM EMP;
SELECT STDDEV(SAL),VARIANCE(SAL) FROM EMP;
COUNT (*):Count Counts the records.it also consider the null values
whereas count column ignore the null values
EG: SELECT COUNT (*) FROM EMP;
SELECT COUNT (COMM) FROM EMP;
SOME MORE EXAMPLES
SELECT COUNT(0) FROM EMP;
SELECT COUNT(NULL) FROM EMP;
SELECT SUM(0) FROM EMP;
SELECT SUM(1) FROM EMP;
NOTE: A concept of null doesnt work for a row as a whole
Count never returns null.
CLAUSES
WHERE
CONNECT BY
START WITH
GROUP BY
HAVING
ORACLE SQL
ORDER BY
WHERE: We use where clause to filter the table records.
This phenomena is called selection.
EG: SELECT EMPNO,
SELECT * FROM
SELECT * FROM
SELECT * FROM
SELECT * FROM
SELECT * FROM
SELECT * FROM
GROUP BY CLAUSE:
It groups the same kind of data into segments
All the select list normal columns, single row functions must be in
group by clause but reverse is not so.
EG:
ORACLE SQL
SELECT C1,C2 FROM EMP GROUP BY C1,C2;
SELECT C1 FROM EMP GROUP BY C1,C2;
SELECT C1 FROM EMP GROUP BY C1,C2(WONT ALLOWS);
In the presence of group by clause group functions are forced to execute
for each of the grouping sets
EG:SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO;
SELECT DEPTNO,COUNT(*) ,SUM(SAL),MAX(SAL),MIN(SAL) FROM EMP
GROUP BY DEPTNO;
SELECT TO_CHAR(HIREDATE,YY),COUNT(*) FROM EMP
GROUP BY TO_CHAR (HIREDATE,YY);
SELECT JOB,COUNT(*) FROM EMP GROUP BY JOB;
SELECT DEPTNO,JOB,COUNT(*) FROM EMP GROUP BY DEPTNO,JOB;
SELECT 1,JOB FROM EMP GROUP BY JOB;
SELECT 1,JOB FROM EMP GROUP BY JOB;
SELECT HIREDATE,COUNT(*) FROM EMP GROUP BY HIREDATE;
SELECT DEPTNO||SAL FROM EMP GROUP BY DEPTNO,SAL;
SELECT DEPTNO||SAL FROM EMP GROUP BY DEPTNO||SAL;
NOTE: Without group by clause we cant nest group functions.
Maximum we can nest two group functions in one another.
SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO;
SELECT MAX(MIN(SAL)) FROM EMP GROUP BY DEPTNO;
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 wont 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.
ORACLE SQL
We can user the having clause very individually as shown in following
examples
SELECT COUNT(*) FROM EMP HAVING COUNT(*)>10;
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.
SYN: SELECT .FROM ORDER BY COLUMNS|EXP|FUNCTIONS|COLUMN
POSITION [ASC|DESC] [NULLS FIRST|NULLS LAST];
EG:SELECT * FROM EMP ORDER BY DEPTNO;
SELECT * FROM EMP ORDER BY DEPTNO DESC;
SELECT * FROM EMP ORDER BY DEPTNO ASC;(DEFAULT);
SELECT * FROM EMP ORDER BY ENAME(ASCII)
SELECT * FROM EMP ORDER BY HIREDATE;
SELECT * FROM EMP ORDER BY DEPTNO,SAL;
SELECT * FROM EMP ORDER BY DEPTNO ASC, SAL DESC;
SELECT * FROM EMP ORDER BY 6
(COLUMN POSITION IN SELECT LIST);
SELECT * FROM EMP ORDER BY 6,2;
SELECT * FROM EMP ORDER BY COMM;
NOTE: NULLS ARE CONSIDERD AS HIGHER VALUES
SELECT
SELECT
SELECT
SELECT
ORACLE SQL
INTIGRITY CONSTRAINTS
DEFINITION: They are the rules or restrictions, which are imposed on a table
column to restrict the invalid data.
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:
Wont allow duplicate values, for even unique constraints also an unique
index get defined.
It allows null values.
NOT NULL:Wont allow null values, but allows duplicate values.
DEFAULT:To provide default 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
ORACLE SQL
ORACLE SQL
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.
EG: DROP TABLE CONTAB; (ERROR);
DROP TABLE CONTAB CASCADE CONSTRAINT;
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.
EG: CREATE TABLE SAM(SNO NUMBER(5) PRIMARY KEY);
INSERT INTO SAM VALUES(10);
INSERT INTO SAM VALUES(20);
INSERT INTO SAM VALUES(30);
CREATE TABLE SAMC(SNO NUMBER(5) REFERENCES SAM(SNO) ON
DELETE CASCADE);
INSERT INTO SAMC VALUES(10);
INSERT INTO SAMC VALUES(20);
DELETE FROM SAM WHERE SNO=10;
(SAMC TABLE 10 VALUES ALSO GET DELETED);
ORACLE SQL
ORACLE SQL
INSERT INTO CON21 VALUES (10, NULL, 4000,BAN);
INSERT INTO CON21 VALUES (10, NULL, 4000,C); DUPLICATE VALUES;
SELECT * FROM CON21;
ENABLE:
NOTE: BEFORE ENABLING A CONSTRAINT OR IMPOSING CONSTRAINT ON A
COLUMN, COLUM DATA MUST NOT VOILATE THE RULES;
EG: ALTER TABLE CON21 ENABLE CONSTRAINT KP10;
DROP:
EG: ALTER TABLE CON21 DROP CONSTRAINT KP10;
NOTE:WHEN YOU DROP TABLE AUTOMATICAL CONSTRAINTS GET DROPED;
RENAME:
SYN: ALTER TABLE TABLENAME RENAME CONSTRAINT CONSTRAINTNAME TO
NEWNAME;
Note: CHECK CONSTRAINT WONT ALLOW FOLLOWING THINGS.
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
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;
Emp m
Empno
Ename
1
X
2
Y
3
Z
4
A
5
B
Output: e.empno
Mgr
2
3
4
3
e.ename
Empno
Ename
1
X
2
Y
3
Z
4
A
5
B
m.empno
m.ename
NOTE: here emp table is splitting as 2 emp tables i.e. copy of emp.
Mgr
2
3
4
3
ORACLE SQL
SQL> select e.empno employno, e.ename employname, m.empno managerno,
table not available but logically it takes values from virtual tables.
Virtual tabler ---> no data (logically it takes data).
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 (+).
rtab
Sno
10
20
30
40
ORACLE SQL
SQL>select rtab.sno, ltab.sno from ltab, rtab where rtab.sno(+) = ltab.sno;
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
Left outer join example:
SQL> select rtab.sno, ltab.sno from rtab, ltab where rtab.sno = ltab.sno(+);
Rtab.sno
ltab.sno
10
10
20
20
30
null
40
null
Compound query
component query
(component query)
ORACLE SQL
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.
2.
3.
4.
5.
Union
Union all
Intersect
Minus
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 doesnt sort data.
Note : Union all is more faster than union.
Intersect :Display the common records between tables. It also suppresses
duplicate values.
ORACLE SQL
Minus :We will get records from one table which are not matching with other
table. Result wont 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;
Joins (9i) : (ISO/sql 1999)
1.
2.
3.
4.
5.
Cross join
Natural (pure nj)
Join.....using
Join.....on
Outer..join
1) Left outer join
2) Right
3) Full
ORACLE SQL
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)
ORACLE SQL
Sql>select * from rtab,ltab where rtab.sno=ltab.sno;
Snosno
10
10
20
20
Sno
10
20
Sno
10
20
Ltab
Sn
10
20
30
Sql>select * from ltab natural join rtab;
(which is a Cartesian product ) i.e 4*5=20 records.
Sql>alter table rtab rename column sno to sn;
Sno
Sql>select * from ltab;
10
Sql>select * from rtab;
20
50
Sql>select * from rtab natural join ltab;
60
Reslt is same to the following example.
100
Sql>select * from ltab,rtab where
ltab.sno=rtab.sno and ltab.loc=rtab.loc;
Disadvantage:
In pure natural join it is not possible to specify
join condition only for particular columns.
When there is more no. of same columns, same
sets across the tables.
Rtab
Sno
10
20
50
60
loc
A
B
C
X
Sno
50
10
20
30
40
loc
X
A
B
C
ORACLE SQL
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 cant be qualified in an entire select statement. Using
clause column must be there in both of tables.
Sql>select * from ltab join rtab using (sno);
Result: snolocloc
10
20
50
20
50
20
Disadvantages: In using clause at least one set of column names must exist with
same name, if not using clause is not applicable.
Note: Join...... using clause will works like natural joins also but natural joins
will not work like using clause as same join ......on clause will.
ORACLE SQL
Join.....on(cond/.....):(it is preferable) We use join on to provide
condition.
Sql>select * from rtab join ltab on (rtab.sno1=ltab.sno);
Sno1 Loc1
Result:Sno1
loc1 sno
Sno
loc
loc
10
10
20
20
50
50
ORACLE SQL
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);
Sno
Loc
Sno1 Loc1
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
20
---50
40
A
B
---X
D
ORACLE SQL
30
QUERIES
Sub queries:
ORACLE SQL
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));
Single row Operators:=,>,<,<>,..,etc.
Multiple row operators:In, any/some, all, exit.
Note: If a sub query returns more than one value, we have to
make use of multiple row operators.
ORACLE SQL
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.
deptno
ORACLE SQL
1
2
3
4
5
6
x
y
z
a
b
c
100
200
300
500
400
300
10
10
10
20
20
20
deptno
10
10
10
20
20
20
Sal
100
200
300
500
400
300
ename empno
x
1
y
2
z
3
a
4
b
5
c
6
Select * from emp e where sal >(select sal from emp where
e.mgr=empno);
empno ename sal
Mgr
mpno ename sal
mgr
1
x
300
2
1
x
300
2
2
y
100
4
2
y
100
4
3
a
500
4
3
a
500
4
4
z
100
1
4
z
100
1
Select * from emp e where deptno=(select deptno from emp where
e.mgr=empno);
Select * from emp e where sal in (select max(sal) from emp group by
deptno union select min(sal) from emp group by deptno);7 rows
selected.
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
sal
400
300
200
500
100
Emp
sal
400
300
200
500
100
ORACLE SQL
From clause query provides the data to the outer query as same to that of
table data.
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?
To display unique records, to display duplicate records?
To delete first records, last five records?
Select * from emp where hiredate>to_date(01-feb-80,dd-mon-yy)+30;
Select * from emp where ename>KING;
ORACLE SQL
ROW NUMBER:
ORACLE SQL
Select * from (select rownum r,emp.* from emp) where r in(1,14);2
rows.
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
MULTI ROW OPERATORS: - IN, SOME/ANY, ALL,EXISTS.
IN: Search the list of values.
ORACLE SQL
ANY: In any the given value become true any one of the value.
ALL: The given value has to be the true with all of the listed values.
ANY & ALL: It will always come with relational operators. It wont exist
individually.
Example:
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from
Select * from emp where deptno=10 and not exists (select * from emp where
deptno=20 and job=MANAGER);
HIERARCHICAL SUB QUERIES:
ORACLE SQL
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
3
sal
300
200
400
100
100
100
1
2
300
400
300
200
100
200
100
200
100
100
3
200
100
100
4
100
100
ORACLE SQL
Select level, empno, ename, connect_by_isleaf from emp where connect
by_isleaf=1 or 0 start with ename =KING
connect by prior empno=mgr;8 rows.
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
where and having clauses of outer queries.
Select - SQ
From - SQ - order by
Where - SQ
not possible to order by
Having - SQ
clause
We can use scalar sub queries as a correlated sub queries.
ORACLE SQL
We can use ANY and ALL an alternatives to a group functions particularly
minimum and maximum.
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.
ORACLE SQL
Example:
Where [[start with condition1]
Group by connect by condition2]
Having
Order by
Empid
Ename
Mid
1
K
2
Blake
1
3
Jones
1
4
Clark
1
5
X
2
6
Y
2
7
Z
2
8
A
3
9
B
3
10
C
4
Delete from emp where empid in(select empid from emp mstart with
ename=Blake connect by prior empid=mid;
Example:
Select level,lpad( ,2*(level-1))||ename xname from emp
Start with mgr is null
Connect by prior empno=mgr
Order by siblings by ename;
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.
ORACLE SQL
Select empno,ename,sal from emp
start with mgr is null
connect by prior empno=mgr;6 rows.
Select max(level) from emp
start with mgr is null
connect by prior empno=mgr;4 rows.
Select x.ename,x.sal,(select sum(sal) from emp y
start with y.ename=x.ename
connect by prior by y.empno=y.mgr), sum(sal) from emp x;
Select level,ename,deptno from emp
start with mgr is null
connect by prior empno=mgr and
prior deptno!=deptno;KING,JONES,BLAKE.
Select level,count(empno) from emp
start with mgr is null
connect by prior empno=mgr group by level;
ORACLE SQL
Select level,ename,hiredate,prior ename,prior hiredate from emp
start with hiredate=(select max(hiredate) from emp
connect by prior empno=mgr);s
Select * from emp where ename=BLAKE
start with ename=JONES
connect by prior mgr=empno;
Select * from emp where ename=JONES
start with ename=KING
connect by prior empno=mgr group by level;
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.
2.
3.
4.
5.
Primary key
Unique
Not null
Check
Ref(log)
ORACLE SQL
6. Default
7. Foreign key
1. Primary key:
It acts as both (unique +not null) which means it wont 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 keys
Generally we call primary key table as master table/parent
table.
2. Unique key:
It allows only unique (null) and values (wont 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 wont allow null values, but allows duplicate values.
Note:
ORACLE SQL
6) Foreign key:
Its 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.
ORACLE SQL
Schema:The logical collection of dat structures called schema.
Schema objects and name spaces:-
ORACLE SQL
(or)
SQL>create table con9 (constraint key3 primary key (sno), constraint
un3 unique (name),sno number(5),name varchar2(10));
SQL>create table con8 (sno number (5),loc varchar2(10), constraint
keyf2 foreign key(sno) references con7(sno));
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
C2
X
X
Y
Null
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 wont allow.
In the above example null values become equal when all of the non-null values are
same.
ORACLE SQL
Defining constraints on existing table by using alter command:
By using alter command we can also provide constraints in two levels.
1. Columns level. (inline constraints)
2. Table level (dat_of_line constraints).
Generic sysntax: (not exact syntax)
SQL>alter table <table_name>
add|modify|disable|enable|validate|nonvalidate|rename|drop|enforce constraint
<constraint_name>;
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.
Defining our own index name on a PK column:
SQL>create table ctab(sno number(5) primary key using index
(create index dex on ctab(sno));
if index is already exists
SQL>create table ctab1 sno number(5) primary key using index <index_nme>;
Add:
SQL>create table con15(sno number(5),nme varchar2(10),bal number(5));
SQL>alter table con15 add constraint PK15 primary key(sno);
SQL>alter table con15 add unique(name)
add constaint c15 check(bal>1000)
add check(loc in(hyd));
SQL>alter table con15 add foreign key(bal) references con15(sno);
Modify:
SQL>create table con16(sno number(5) null);
//it is not a constraint
SQL>alter table con16 modify sno constraint nn15 not null;
SQL>alter table con16 modify sno null;
SQL>alter tble con15 modify (sno not null, name unique);
Rename:
Syn: Alter table <table_name> rename constraint oldname to newname;
ORACLE SQL
SQL>create table ct(sno number(5) constraint kp10 primary key, name
varchar2(10) constraint un10 unique);
SQL>alter table ct rename constraint kp10 to kp11;
Note: we cannot alter more than one column at a time.
Constraint states:
Enable/disable: works for futex data.
Validate/novalidate: past data.
ORACLE SQL
SQL>alter table lb enable primary key;
SQL>alter table lb disable primary key;
Note: Without knowing the name of a PK unique constraint we can enable
and disable and drop the constraints of a table.
Eg for keep index:
SQL>alter
SQL>alter
SQL>alter
SQL>alter
SQL>alter
table
table
table
table
table
lb
lb
lb
lb
lb
Delete rules:
Event
Deleting the parent records
Dropping parent column and table
Dropping/disabling PK when it is
relation with FK
Action
On deleting (while defining FK)
Cascade constraint
Cascade
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 cant 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 deleting cascade: Generally it is not possible to delete the parent
records/master records directly when they are having child records but by
providing on delete cascade at the time of FK definition it is possible.
ORACLE SQL
On delete set null: It provides null values for department child records
while deleting parent record.
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.
Cascade:
If you to drop/disable PK/unique key constraint when they are in
relation with FK you have use cascade.
SQL>create table mtab(sno number(5)) constraint kp3 primary key, loc
varchar2(10));
SQL>create table mtab1(sno number(5) constraint kp4 primary key, name
varchar2(10));
SQL>create table ctab(sno number(5) conatrnt fk3 references matb(sno) on
delete cascade);
SQL>create table ctab1(sno number(5) constraint fk4 references mtab(sno)
on delete set null);
SQL>insert into mtab(sno) values(10);
SQL>insert into mtab(sno) values(11);
SQL>insert into ctab(sno) values(10);
SQL>insert into ctab(sno) values(10);
SQL>insert into ctab(sno) values(10);
SQL>delete from mtab where sno=10;
SQL>select * from ctab;
SQL>delete from mtab1 where sno=10;
SQL>select * from ctab1;
SQL>alter table matb drop column sno;
//error
SQL>alter table mtb column sno cascade constraint;
SQL>drop table mtab;
//valid
Note: Ere already we dropped PK column so that table is dropped in the
below statement mtab1 is in relation so, table is not dropped it gives error.
SQL>drop table mtab1; //invalid
SQL>drop table mtab1 cascade constraint; //valid
SQL>alter table mtab1 drop constraint pk4;
//error: this unique/PK is referenced by some FKs
SQL>alter table mtab1 drop constraint PK4 cascade;
//valid
ORACLE SQL
Constraint checking:
Constraint checking is takes place in two ways:
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.
Eg for initially immediate:
SQL>create table mtab4(sno number(4) primary key initially immediate);
SQL>insert into mtab4 values(10);
SQL>insert into mtab4 values(10);//invalid
Error: unique constraint (apps-sys-c00209..) violated.
SQL>set constraint all deferrable.
Eg for initially deferrable:
SQL>create table mtab5(sno number(5) constraint keyp primary key
deferrable);
SQL>set constraint keyp deferrable;
ORACLE SQL
Note:here in the (create table) above eg we used deferrable, after that.
Disadvantages of constraints:
Constraints cant handle varying data, but by using trigger we can handle
varying data.
Constraint can check the old data but triggers cant check the existing
data.(it checks only incoming data)
Constraints are more useful than trigger.
Constraints can give guarantee for centralized data.
ORACLE SQL
Tables regarding with constraints:
Data dictionary tables:
ORACLE SQL
SQL>select count(column_id) from user_tab_columns where
table_name=emp;
->To find out the constraint_name once we know the tablename;
SQL>select constraint_name, constraint_type, table_name, status,index_name
from user_constraints where table_name=emp;
we use following query to find out constraint name and table name once
we know the column name.
SQL>select column_name,table_name,constraint_name from
user_cons_columns where column_name=sno;
Constraint types:
Primary key
Unique
Foreign key
Check
Not null
P
U
R
C
C
ORACLE SQL
Synonyms
ORACLE SQL
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:
Table name
T
S
Synonym name
S
S1
ORACLE SQL
Views
They are an advance of synonym
They are mirror/logical names
Views are stored queries
They do not have their own structure, they again depends on base tables
for SQL statements
It is not possible to modify the structure of table by using views
We can define views on synonyms and even on views
We can define a view on more than one table
We can also define views on non-existing objects
It is possible to hide the partial part of data by using views so, to provide
security
Views makes the application design easy
Views provide the location transparency
Views makes the client work easy which means client no need to know
about the technical things like join conditions, functions and so on..
Views represents the summarized data
Views display the table data in a client perspective
Views are useful in like tool like data ware housing and so on..
Materialized views are useful for performance and to store historical data
We can provide constraints even on views
Views wont allow check and not null constraints
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
Simple view:This view is defined on single table
SQL>create or replace view <view_name>[view column] as select
statements;
SQL>create table new(sno number(5), loc varchar2(10));
SQL>create or replace view sview as select * from new;
SQL>select * from sview;
SQL>insert into sview values(10,x);
SQL>insert into sview(sno) values(20);
SQL>select * from new;
SQL>select * from sview;
Read only view:These views are only read only purpose
Syntax:
SQL>create or replace view <viewname> as select statement with read
only;
SQL>create or replace view rview as select * from new wit read only;
SQL>select * from rview;
SQL>insert into rview values(30,y); //invalid
Note: DML operations are not allowed on read only view.
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
ORACLE SQL
Functional view:In this we will make use of functions while defining a view
in select statements
Note: In view select statements expressions and functions has to be defining
with aliases, as shown in below
Eg:
SQL>create view asview as select 2*3 from dual;
Error: must name this expression with column alias
SQL>create view sview as select min(sal),max(sal) from emp;
SQL>create view sview as select min(sal) minsal,max(sal) maxsal from
emp;
SQL>ceate or replace view pview(minsal,maxsal) as select min(sal),max(sal)
from emp;
SQL>ceate view svw as select sal from emp;
SQL>select * from svw;
SQL>create or replace view svw1(minsal) as select min(sal) ename from
emp groupby ename;
SQL>create or replace view svw1(minsal,vname) as select min(sal), ename
from emp groupby ename;
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
SQL>creae or replace view vview as select empno,ename,job from emp;
Horizontal view:To hide rows, usage of horizantal view as mentioned below
in diagram
Note: Vertical and horizontal views are useful in administration side
ORACLE SQL
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.
SQL>create or replace view comview as select empno, ename, emp.deptno,
loc, dname from emp,dept where emp.deptno=dept.deptno;
Object view:They are the views which are defined on object tables
Object table:A table which is defined by using object data type
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
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)
Views without DML operations:
1.
2.
3.
4.
Read only
Partition
Complex
Views which are having following tings
ORACLE SQL
C1 c2
C1 c2 c3
1o x
20 -
ORACLE SQL
o
o
Updating the not null column with null values through view is not
possible in the above ex
Deleting is possible if we perform delete on c1,c2 also entire record
will delete
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 wont 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]
Start with value:
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
Min value:Min value of the sequence
Max value:
Max value of the sequence
+ve
-ve
Minvalue
1
-1*1026
Maxvalue
1*1027
-1
Cycle:
To generate the sequence values in cyclic manner(looping/iterations) we use
cycle
Default nocycle
For the second iteration sequence starts with min value
ORACLE SQL
Cache:
It is a memory area which is in saea(instance), which stores the pregenerated value, so has to increase the performance
Cache values get vanished/erased when system abnormally shutdown
By default it stores upto 20 values
While exporting and importing the data we may have the chances of skipping
sequence values
By default min value of the cache is 2
ORACLE SQL
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)
Usage of sequence: We use sequence with the help of sequence pseudo
columns They are:
1. Next lavel
2. Curr level
Next level:displays the next value of sequence
Curr value:displays the current status of the sequence or currently
generated value
Note:We have to use currval only after nextval
Syntax: Sequencename.nextval;
Sequencename.currval;
SQL>create sequence sq;
SQL>select sq.nextval from dual;
SQL>select sq.nextval from dual;
SQL>select sq.currval from dual;
SQL>create table t(sno number(5));
SQL>insert into t values(sq.nextval);
SQL>select * from t;
SQL>Update t set sno=sq.nextval;
SQL>create synonym st for t;
SQL>insert into st values(sq.nextval);
SQL>select * from st;
SQL>create sequence sq1 start with 5 increment by 2 minvalue 1
maxvalue 10 cycle cache 5
Output:sequence created
SQL>alter sequence sq1 nocycle;
SQL>alter sequence sq1 maxvalue 20;
ORACLE SQL
Note: We can alter all other parameters except start with value
Usage of sequence:
Select list
To assign pl/sql variables(11g)
Eg:
Declare
V number(5):=sq.nextval;
Begin
DOPL(v);
End;
We wont use sequence in the following cases:
Sub queries
View query (create or replace view sview as select * from..) in this select list
wont 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)
ORACLE SQL
Empno Sal
101
102
103
Flag
Empno Bones
102
1000
101
0
3000
2000
5000
Empno Sal
Flag
101
102
103
Y
Y
Null
3000
2000
5000
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
Dense-rank():It works as same to that of rank but it wont skip the
sequential
ranking.
Percent-rank(): Percent rank work based on rank values by using
following formulaeRecord rank-1/total rank-1
Cumu-rank():Calculate the cumulative distribution by using following
Formulae
Row-num():Provides the row numbers for each of the record this row
number allows partition unlike pseudo column row numbers
ORACLE SQL
Ntile():Segments the records into given number of partitions
(or)
divides the records into n number of partitions
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;
Note:Some of the group functions also works as analytical functions as in the
following case
SQL>select deptno,sal,sum(sal) over(partition by deptno order by sal desc)
ssal from emp;
Flashback: (DDL commands 10g)
Hear flashback wont applicable to rollback because flashback is DDL
command, commit and rollback are DML commands. And DDL are permanent
and DML are temporary.
It retrives DB objects from recycle-bin
Eg:
SQL>select * from ftab;
SQL>drop table ftab;
Note:
From 10g onwards if drops an object that will be placed in recycle bin
ORACLE SQL
10
10
ORACLE SQL
[delete where condition]
When notmathed then
Insert[(col1,col2)] values(val1,val2);
[where condition];
SQL>select * from dept;
SQL>create table mdept as select * from dept where 1=2;
ORACLE SQL
Indexes
Indexes are the database objects, defined on table columns, which makes
the optimizer work easy
Indexes are useful to enhances the performance oracle by default make use
of indexs for data maintenance
Defining an index wont give any guarantee for its usage it all depends on
how optimizer chooses
Defining excess of indexes is not appropriate or preferable
If you define an index on a column index stores that column data along with
rowids
If you provide a condition on index column now optimizer will search the
index column data with the help of rowed it identifies the table record vary
directly instead of scanning entire table data
Define indexes on column which are frequently used in where and order by
clauses
Optimizer search the indexes based on column selectivitys.
Selectivity:
More selectivity=less duplicity
Less selectivity=more duplicity
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:
Function wont allow the indexes to make use of it unless it is a functional
index
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 wont 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 wont 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 */
Here it providing hint to query for multiline comment
SQL>select
SQL>select
SQL>select
SQL>select
->based on rowed concept data will pick up directly and get displayed instead of
total table scan
Types of indexes:
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
SQL>explain plan for select * from emp where sal>1000;
Output:explained
ORACLE SQL
SQL>desc plan_table;
Options
By index rowed
Object_nme
Emp
Once we drop the index optimizer go for complete table scan as shown in the
following
EG:
SQL>drop index indsal;
SQL>delete from plan_table;
SQL>explain plan for select * from emp where sal>1000;
Operation
Table access
Options
Full(complete table scan)
Object_name
Emp
Complex index:
In this we define indexes on more than one column
Note: Defining an index on indexed column is not possible
SQL>create index indsql on emp(sal); //invalid
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 wont
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
Attempting on define unique index on a column which is having duplicate
data ends in error.
SQL>create unique index uniindex on emp(ename);
Non-unique index: If index is creating on duplicate values i.e
SQL>create unique index unidex2 on emp(deptno);
It is invalid statement because deptno is having duplicate data
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.
ORACLE SQL
?
+
/
[]
()
^
$
+?
*?
??
{m}
{m,}
ORACLE SQL
{m.n}
\n
\
character
[:alnum:]
[.:alpha:]
[:digit:]
[:punct!]
[:cntrl:]
[:upper:]
[:lower:]
[:print:]
[:space:]
[:graph]
[0-9]
[1-9]
[A-Z]
[a-z]
[^..]
[.coll.]
[=eq=]
\d
\D
\w
\W
\s
\S
\A
\z
\Z
\x
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:
SQL>select regexp-substr(name,(\(\d{3}\)[-/.])(\/) from regtab;
SQL>select regexp-substr(name,\(\d{3}\)[-1.]\(\d{3}\)[-/.]\(\d{3}\))
Output:(123)-(456)-(789)
(123)-(456)-(789)
(123)-(456)-(789)
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
SQL>select
SQL>select
SQL>select
ORACLE SQL