01 - SQL - Oracle SQL Training Manual
01 - SQL - Oracle SQL Training Manual
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 industry-
standard, 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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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 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
Single row functions,
Multiple row functions
Null functions
Analytical functions
Search functions
Hierarchical functions
Error functions
Regular expressions(10g);
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
DATATYPES
DEFINITION:
Specifies what kind of Data We have to store in a Memory
SQL won’t support Boolean datatypes.
Boolean Data types (TRUE, FALSE, NULL)
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
1) NUMBER:
SYN: X NUMBER (P, (S));
To store numeric values
Max size is 38 digits.
2) CHAR:
SYN: X CHAR(S [BYTES|CHAR]);
To store alphanumeric values
Max size 2000 bytes;
Memory allocation is constant (wastage of memory).
3) VARCHAR (ANSI) OR VARCHAR2 (ORACLE).
SYN: X VARCHAR2(S);
TO STORE ALPHANUMBERIC DATA
MAXSIZE 4000 BYTES;
MEMORY ALLOCATION IS DYNAMIC(NO WASTAGE OF MEMORY)
4) DATE
SYN: X DATE; (DD-MON-YY HH:MI:SS)
To store the date value.
Max size 7 bytes.
Disadvantage:
Not possible to store fraction of seconds.
Internally date value get stored in the form of julian day
number
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:
Not possible to store timezones (tzh:tzm)
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.
8) INTERVAL DATATYPE
I) Interval Year to Month
SYN: X INTERVAL YEAR TO MONTH.
To Store Year to Month Interval Data
II)Interval Day to Second:
SYN: X INTERVAL DAY TO SECOND.
To Store Day, Hour, Minute, Seconds Data.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
Max size 2000 bytes.
c) LONG RAW:
SYN: X LONG RAW.
To store information+ images
Max sized 2gb
Not preferable, so many disadvantages.
2) BLOB:
SYN: X BLOB;
To store images.
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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 won’t 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:
It is an unknown, undefined, insufficient, missing and junk values.
It is neither empty nor zero
Even system doesn’t know what exactly the null value is
Null is not applicable in a row concept
It will be displayed as a blank space on the screen
A special operator ‘IS NULL’ is used to handle the null values
A reserved word ‘NULL’ is used to assign null values
Every null is unique
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 T F NULL
O
R
T F N
T
T T T
F F F
F
T F N
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
& F N T OR T N F
F T T N F
F T T F
SQL STATEMENTS
It’s a structured query language(SQL) pronounced as SEQUEL
It’s a set oriented language which means handles the bunch of records at a time that’s way
it’s more faster than the PL/SQL
SQL is a sub-language
Case-insensitive
Gateway to the RDBMS
It’s the only language that directly interacts with databse
Fourth generation language[PL/SQL is 3 rd generation]
SQL won’t supports the control structures and Boolean data type
You can embed this language with other languages like java, PL/SQL….[embed SQL]
It’s a database standard language
DDL DML
DCL DRL
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
SEE TO DIAGRAM
1) DDL (DCL)
2) DML (DRL OR DQL)
3) TCL
4) ALTER SESSION
5) ALTER SYSTEM
6) EMBEDDED SQL
CREATE
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)MIDIFY - To modify column datatypes and size
c)RENAME -To rename column and table names
d)DROP- To drop columns.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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):
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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’;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
INSERT
UPDATE
DELETE
MERGE(INSERT+UPDATE+DELETE)
SELECT(DRL OR DQL)
INSERT
VALUE METHOD
REFRENCE METHOD
SELECT METHOD
VALUE METHOD
SYN: INSERT INTO TABLENAME [(COL1, COL2,..)] VALUES (VAL1, VAL2,)
EG:INSERT INTO NEWTAB VALUES (10,’A’);
INSERT INTO NEWTAB (SNO) VALUES (11);
SELECT METHOD:
SYN: INSERT INTO TABLENAME SELECT …..
EG: CREATE TABLE TB1 AS SELECT * FROM TB;
CREATE TABLE TAB2 AS SELECT * FROM TB WHERE 1=2;
SELECT * FROM TAB2;
DESC TB2;
INSERT INTO TB2 SELECT * FROM TB;
INSERT INTO T1 VALUES SELECT * FROM T: ERROR;
INSERT INTO T SELECT * FROM T;
INSERT INTO T1 (C3) SELECT C2 FROM T;
INSERT INTO T1 VALUES (10, SELECT C2 FROM T): ERROR;
INSERT INTO T1 VALUES (10, (SELECT C2 FROM T WHERE C1=1));
UPDATE:
SYN: UPDATE TABLENAME SET COL=VAL [, COL1=VALUES,…]
[WHERE CONDITION];
EG: UPDATE NEWTAB SET SNAME=’B’ WHERE SNO=10;
UPDATE NEWTAB SET SNAME=NULL;
UPDATE T SET C2= (SELECT C3 FROM T1);
UPDATE T SET C2= (SELECT C2 FROM T WHERE C1=2);
TRUNCATE:
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
DELETION:
Delete the records temporarily.
Possible to delete specific records.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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)
INTO TABLENAME VALUES (VALUES)
SELECT * FROM TABLENAME;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
Types of literals
1) Number literals:
USAGE: 1, 10,
EG: SELECT 1 FROM DUAL;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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 2*100+10, 2*(100+10) FROM DUAL;
SELECT SAL, SAL+SAL/10 FROM EMP;
SELECT * FROM EMP WHERE DEPTNO>-1;
RELATIONAL OR COMPARISON :
EG: SELECT * FROM EMP WHERE DPETNO=10 AND SAL>1000;
SELECT * FROM EMP WHERE DEPTNO<>10;
SELECT * FROM EMP WHERE DEPTNO!=10;
SELECT * FROM EMP WHERE ENAME =’KING’;
SELECT * FROM EMP WHERE ENAME >’KING’;
SPECIAL OPERATORES:
1)IS:TO HANDLE NULL VALUES
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
3) LIKE:To search the patterns we use ‘like’ operator with the help of wild card
Characters
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
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 can’t exist individually.
Order of presidence:
Level Operators
1 Unary (+, -, ~, connect_by_root)
2 Arithmetic
3 ||
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
SINGLE ROW FUNCTIONS
MULTIPLE ROW FUNCTIONS (OR) GROUP FUNCTIONS (OR)
AGGREGATE FUNCTIONS (OR) SUMMARY FUNCTIONS
WINDOW FUNCTIONS
ANALYTICAL (RANK FUNCTIONS)
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
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);
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
STRING FUNCTIONS:
LENGTH
VSIZE
DUMP
REVERSE
SOUNDEX
UPPER
LOWER
INITCAP
LTRIM
RTRIM
LPAD
RPAD
TRANSLATE
REPLACE
DECODE
SUBSTR
INSTR
SUBSTRB
SUBSTRC
SUBSTR2
SUBSTR4
CONCAT
----FROM 10G ON WARDS THEY INTRODUCED REGUAL EXPRESSIONS----
REGEXP_LIKE
REGEXP_COUNT(11G)
REGEXP_SUBSTR
REGEXP_SUBSTR
REGEXP_REPLACE
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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’);
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
INSTR:
SYN: INSTR (S,’C’,[P [,O]]);
S=STRING;
C=CHARACTER
P=POSITION
O=OCCURANCE
DATE FUNCTIONS:
DATE FORMATS
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
DATE FUNCTIONS
SYSDATE
CURRENT_DATE
SYSTIMESTAMP
CURRENT_TIMESTAMP
LOCAL TIMESTAMP
DBTIMEZONE
ADD_MONTHS
MONTHS_BETWEEN
NEXT_DAY
LAST_DAY
EXTRACT
ROUND
TRUNC
NEW_TIME
EG:SELECT SYSDATE,CURRENT_DATE FROM DUAL;
SELECT SYSTIMESTAMP,CURRENT_TIMESTAMP FROM DUAL;
SELECT LOCALTIMESTAMP FROM DUAL;
SELECT DBTIMEZONE FROM DUAL;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
SYN: LAST_DAY (DATE);
EG: SELECT LAST-DAY (SYSDATE) FROM DUAL;
EXTRACT:
SYN: EXTRACT (YEAR|MONTH|DAY|HOUR|MINUTE|SECOND FROM DATE);
EG:SELECT EXTRACT (YEAR FROM SYSDATE) FROM DUAL;
SELECT EXTRACT (MONTH FROM SYSDATE) FROM DUAL;
SELECT EXTRACT ( DAY FROM SYSDATE) FROM DUAL;
SELECT EXTRACT (HOUR FROM SYSTIMESTAMP) FROM DUAL;
SELECT EXTRACT (MINUTE FROM SYSTIMESTAMP) FROM DUAL;
SELECT EXTRACT (SECONDS FROM SYSTIMESTAMP) FROM DUAL;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
CONVERSION FUNCTIONS:
TO_CHAR;
TO_DATE;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
GENRAL FUNCTIONS
GREATEST
LEAST
USER
UID
DECODE
CASE
NVL
NVL2
NULLIF
COALESCE
GREATEST
SYS_CONNECT_BY_PATH (HIERARCHIAL FUNCTION);
EG:SELECT GREATEST (1, 2, 3), LEAST (1, 2, 3) FROM DUAL;
SELECT GREATEST (‘A’,’B’,’C’), LEASTA (‘A’,’B’,’C’) FROM DUAL;
SELECT GREATEST (SYSDATE, HIREDATE) FROM EMP;
NULLIF:
SYN: NULLIF (EXP1,EXP2); IF EXP1=EXP2 THEN RETURNS NULL ELSE EXP1;
EG:SELECT NULLIF(1,1),NULLIF(1,2) FROM DUAL;
2) AVG
SYN: AVG ([ALL|DISTINCT] VALUE|EXP|COLUMN);
3) MIN
SYN: MIN (([ALL|DISTINCT] VALUE|EXP|COLUMN);
4) MAX
SYN: MAX ([ALL|DISTINCT] VALUE|EXP|COLUMN);
5) COUNT:
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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;
CLAUSES
WHERE
CONNECT BY
START WITH
GROUP BY
HAVING
ORDER BY
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
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];
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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(UNIQUE+NOT NULL)
UNIQUE
NOT NULL
CHECK
FOREIGN KEY
REF
DEFAULT(KEY WORD)
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
USER DEFINED
SYSTEM DEFINED
By taking all the above things into consideration, we can provide the
constraints in following wayss
MIXED METHOD:
CREATE TABLE CONTAB8(SNO NUMBER(5) PRIMARY KEY,SNAME
VARCHAR2(10),LOC VARCHAR2(10),BAL NUMBER(5),CHECK(BAL>2000));
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
COMPOSITE PRIMARY KEY:When a primary key holds more than one column, those are said
to be composite primary keys.
EG: CREATE TABLE CONTABX(X NUMBER(5),Y VARCHAR2(10),LOC VARCHAR2(10),CONSTRAINT
CPY PRIMARY KEY(X,Y));
CREATE TABLE CONTABY(S NUMBER(5),Y VARCHAR2(10),
CONSTRAINT CFY FOREIGN KEY(X, Y) REFERENCES CONTABX(X,Y));
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
ALTER TABLE CON21 ADD CONSTRAINT KP10 PRIMARY KEY(SNO);
ALTER TABLE CON21 ADD CONSTRAINT CHK10 CHECK(BAL>100)
ADD UNIQUE(LOC);
NOTE: NOT POSSIBLE TO ADD ‘NOT NULL ‘CONSTRAINT;
DISABLE:
EG: ALTER TABLE CON21 DISABLE CONSTRAINT KP10;
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 WON’T ALLOW FOLLOWING THINGS.
SUBQUERY
SCALAR SUBQUERY
NEXTVAL
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
CURRVAL
LEVEL
ROWNUM
SYSDATE
USER
UID
USERENV
DBTIMEZONE
SESSION TIMEZONE
TIMESTAMP WITH TIMEZONE
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;
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
SQL> select e.empno employno, e.ename employname, m.empno managerno, m.ename managername from
emp e , emp m where e.mgr = e.empno;
NOTE : we have to split one table to ‘n’ no.of tables(virtual tables) physically the 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 (+).
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Output:
rtab.sno ltab.sno
20 10
30 10
40 10
30 20
40 20
50
60
100
Compound query
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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)
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
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
10 A
20 B
50 C
30 X
40 D
RAJU CHINTHAPATLA
Sno Loc
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);
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));
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Empemp
empno ename sal deptno deptno Sal ename empno
1 x 100 10 10 100 x 1
2 y 200 10 10 200 y 2
3 z 300 10 10 300 z 3
4 a 500 20 20 500 a 4
5 b 400 20 20 400 b 5
6 c 300 20 20 300 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
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’;
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’);
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
200 200
500 500
100 100
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
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Select * from (select rownum r,emp.* from emp) where r in (1,(select count(*) from emp));1,14
rows.
Select * from (select rownum r,emp.* from emp) where r=2;1 row.
Select * from (select rownum r,emp.* from emp) where r not in(1,(select count(*) from emp));12
rows.
Select * from (select rownum r,emp.* from emp) where rownum=2;
no rows.
Select * from (select rownum r,emp.* from emp) where r>5; 5 rows.
Select * from (select rownum r,emp.* from emp) where r=&n;
Select * from (select rownum r,emp.* from emp) where r!=&n;
Select * from (select rownum r,emp.* from emp) where r=(select count(*) from emp);1 row.
Select * from (select rownum r,emp.* from emp) where r=(select count(*)-1 from emp);1 row.
Select * from (select rownum r,emp.* from emp) where r not between 6 and 10;9 rows.
Select * from (select rownum r,emp.* from emp) where r in(1,14);2 rows.
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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’);
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
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
RAJU CHINTHAPATLA
Child/Leaf
Oracle SQL Training Document Raju Ch
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
2 100
3 100
sal 1 2 3 4
300 300 200 100
200 400 100
400 200 100
100 100
200 100
300 100
200 100
100
Select level,max(sal) from emp where 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;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
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)
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
Example:
Where [[start with condition1]
Group by connect by condition2]
Having
Order by
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
empno,ename,sal from emp
start with mgr is null
connect by prior empno=mgr;6 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;
Select
level,count(empno) from emp
start with mgr is null
connect by prior empno=mgr group by level
having level=(select max(level from emp
start with mgr is null
connect by prior empno=mgr);
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Select
level,ename,hiredate,prior ename,prior hiredate from emp
start with hiredate=(select min(hiredate) from emp
connect by prior empno=mgr);
Select
level,ename,hiredate,prior ename,prior hiredate from emp
start with hiredate=(select max(hiredate) from emp
connect by prior empno=mgr);s
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
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
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.
SQL>create table con1 (sno number (5) references con(sno), loc varchar2(10));
System defined table level:
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
SQL>create table con2(sno number(5), name varchar2(10), bal number(5), primary key(sno),
unique (name), check(bal between 1000 and 5000));
SQL>create table con3(sno number(5), loc varchar2(10), foreign key(sno) references con2(sno));
SQL>ceate table con6 (sno number (5) constraint keyfl references con5 (sno), loc varchar2(10));
(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));
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Mixed method:
SQL>create table con10 (sno number (5) primary key, loc varchar2 (10),name varchar2(10),
constraint un5(loc));
Eg:-
SQL>create table bt(sno number(5), loc varchar2(10),name varchar2(10), constraint comkey
primary key(sno,loc));
SQL>create table ct(sno number(5),addr varcar2(10), constraint comfkey foreignkey(sno, addr)
references bt(sno,loc));
SQL>insert into bt(sno,loc) values(10,’x’);
SQL>Insert into ct values (10,’x’);
SQL>Insert into ct values (10,’y’); //invlid
SQL>Insert into ct values (10, null);
SQL>Insert into ct values (20, null);
SQL>create table utab(sno number(5),name varcar2(10),unique(sno,name));
SQL>Insert into utab values (10,’x’);
SQL>Insert into utab values (10,’y’);
SQL>Insert into utab values (10,’x’); //invalid
SQL>Insert into utab values (10, null);
SQL>Insert into utab values (10,null); //invald
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
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’.
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’));
Rename:
Syn: Alter table <table_name> rename constraint oldname to newname;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
But by default enable means enable-validate and disable means disable no validate.
While disabling and enabling constraints indexes get dropped and re-created but by using ‘keep
index’ we can prevent the index by dropping.
Note: Without knowing the name of a PK unique constraint we can enable and disable and drop the
constraints of a table.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Delete rules:
Event Action
Deleting the parent records On deleting (while defining FK)
Dropping parent column and Cascade constraint
table Cascade
Dropping/disabling PK when it
is 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 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.
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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 FK’s
SQL>alter table mtab1 drop constraint PK4 cascade; //valid
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’.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Synonyms
They are the alternate names to tables, views, synonyms and so on……
They are virtual/mirror objects
Useful in frontend application and to hide the table owner name
Useful in distribution databases
They don’t have their own structure(it won’t occupy any memory area)
They are simply logical names
They again depends on base tables for SQL statements
It is not possible to alter the structure of base table by using synonyms
We can define synonym on another synonym
A table can have ‘n’ no of synonyms but each synonym can be defined only on single table, which
means a synonym can’t hold more than one table
We can also define synonym on non_exixting objects
It is not possible to hide partial part of table data by using synonym like views
They are two types of synonyms
1. Public synonym
2. Private synonym
Private synonym share the same table name space
Public synonym does not share same table name space, so we can define public synonym names
with table names
If you drop the synonym base table won’t get effect but, if you drop base table , synonym
becomes invalid
SQL>desc user_synonym;
SQL>desc all_synonym;
SQL>select table_name from user_synonyms where synonym_name= ‘s’;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
User_synonym:
Table name Synonym name
T S
S S1
Note:Table/view is not existed for dx, but synonym creted we can do this.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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 won’t 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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
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;
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
materialized view:
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:
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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. Read only
2. Partition
3. Complex
4. Views which are having following tings
We cannot perform DML operations on these if anything is present in diagram in select list.
Note:View and synonym are subject to the table constraints. View and synonyms are transactions are
also considered by the table constraints
C1 c2
RAJU CHINTHAPATLA
C1 c2 c3
Oracle SQL Training Document Raju Ch
1o x –
20 -
-
o Updating the not null column with null values through view is not possible in the above
ex
o Deleting is possible if we perform delete on c1,c2 also entire record will delete
View without not null column but in table:
Insert is no way possible
Update is very possible
Deletion also possible
View with check option:
When where clause condition matches the we can perform below operations
It works as check constraint
SQL>create or replace view chview as select * from newtab where sno=10 with check option
As it is not possible to provide check constraint on views, we can use ‘view with check
option’ to impose same restriction.
SQL>select * from chview;
Through this we can insert only values 10 and deletion also possible values 10
SQL>insert into chview values (10);
SQL>delete from chview where sno=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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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]
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
Minvalue Maxvalue
+ve 1 1*1027
-ve -1*1026 -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
Cache:
It is a memory area which is in saea(instance), which stores the pre-generated 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’
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
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.
SQL> select * from user_squences where sequence_name=’seq’;
Usage of sequence:
Select list Insert value clause
To assign pl/sql variables(11g) Update set clause
Eg:
Declare
V number(5):=sq.nextval;
Begin
DOPL(v);
End;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
Dense-rank():It works as same to that of rank but it won’t skip the sequential
ranking.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Row-num():Provides the row numbers for each of the record this row
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;
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 won’t 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
SQL>select * from ftab; //table/view doesn’t exist
SQL>flashback table ftab to before drop;//flashback completed
SQL>select * from ftab;
Sno
10
10
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
EG: SQL>purge recycle bin;//total tables will be deleted permanently
SQL>desc recycle bin;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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.
SQL>select * from mdept;
SQL>update set x.loc=’bang’;
SQL>delete where x.loc=’bang’
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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 index’s for data
maintenance
Defining an index won’t 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 rowid’s
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 ‘selectivity’s’.
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 won’t 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 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
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 */
Here it providing hint to query for multiline comment
SQL>select count(*) from emp;
SQL>select count(1) from emp;
SQL>select count(rowed) from emp;
SQL>select * from t where c2=’balu’;
->based on rowed concept data will pick up directly and get displayed instead of total table scan
Types of indexes:
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
SQL>drop index indsal;
SQL>delete from plan_table;
SQL>explain plan for select * from emp where sal>1000;
Complex index:
In this we define indexes on more than one column
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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:
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.
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
Regular expressions(10g)
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:
Any single character
? Zero or one character
+ One or more characters
Zero or more characters
/ Alternate symbol
[…] To specify optional characters
() Grouping an expression
^ Anchors the starting character of line
$ Anchors the end character of line
+?
*?
??
{m} Match exactly m characters
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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
Oc-occurance
Ropt-return option(0,1) default 0
Mp-match parameter(I,c,m,n,x)
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
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)
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’);
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’
SQL>select regexp-substr(‘abc’,’a b c’,1,1,’y’) from dual;
RAJU CHINTHAPATLA
Oracle SQL Training Document Raju Ch
BEGIN
--> EMP Table
INSERT INTO EMP VALUES (7369, 'SMITH', 'CLERK', 7902, TO_DATE('17-DEC-1980', 'DD-
MON-YYYY'), 800, NULL, 20);
INSERT INTO EMP VALUES (7499, 'ALLEN', 'SALESMAN', 7698, TO_DATE('20-FEB-1981', 'DD-
MON-YYYY'), 1600, 300, 30);
INSERT INTO EMP VALUES (7521, 'WARD', 'SALESMAN', 7698, TO_DATE('22-FEB-1981', 'DD-
MON-YYYY'), 1250, 500, 30);
INSERT INTO EMP VALUES (7566, 'JONES', 'MANAGER', 7839, TO_DATE('2-APR-1981', 'DD-
MON-YYYY'), 2975, NULL, 20);
INSERT INTO EMP VALUES (7654, 'MARTIN', 'SALESMAN', 7698, TO_DATE('28-SEP-1981', 'DD-
MON-YYYY'), 1250, 1400, 30);
INSERT INTO EMP VALUES (7698, 'BLAKE', 'MANAGER', 7839, TO_DATE('1-MAY-1981', 'DD-
MON-YYYY'), 2850, NULL, 30);
INSERT INTO EMP VALUES (7782, 'CLARK', 'MANAGER', 7839, TO_DATE('9-JUN-1981', 'DD-
MON-YYYY'), 2450, NULL, 10);
INSERT INTO EMP VALUES (7788, 'SCOTT', 'ANALYST', 7566, TO_DATE('09-DEC-1982', 'DD-
MON-YYYY'), 3000, NULL, 20);
INSERT INTO EMP VALUES (7839, 'KING', 'PRESIDENT', NULL, TO_DATE('17-NOV-1981', 'DD-
MON-YYYY'), 5000, NULL, 10);
INSERT INTO EMP VALUES (7844, 'TURNER', 'SALESMAN', 7698, TO_DATE('8-SEP-1981', 'DD-
MON-YYYY'), 1500, NULL, 30);
INSERT INTO EMP VALUES (7876, 'ADAMS', 'CLERK', 7788, TO_DATE('12-JAN-1983', 'DD-
MON-YYYY'), 1100, NULL, 20);
INSERT INTO EMP VALUES (7900, 'JAMES', 'CLERK', 7698, TO_DATE('3-DEC-1981', 'DD-
MON-YYYY'), 950, NULL, 30);
INSERT INTO EMP VALUES (7902, 'FORD', 'ANALYST', 7566, TO_DATE('3-DEC-1981', 'DD-
MON-YYYY'), 3000, NULL, 20);
INSERT INTO EMP VALUES (7934, 'MILLER', 'CLERK', 7782, TO_DATE('23-JAN-1982', 'DD-
MON-YYYY'), 1300, NULL, 10);
COMMIT;
END;
RAJU CHINTHAPATLA