You are on page 1of 137

COURSE MATERAL

For
SQL

1
SQL is a language, which can communicate with Database Server.

When SQL was introduced initially it was called by a name, SEQUEL(Structured English Query
Language), later was renamed to SQL.

SQL is a product of IBM. Later this product has been used by various other companies and they
have modified and released with their standards.

SQL is a universal language or common database language, since it can get understand by any
RDBMS.

SQL is a command based language.

SQL is called non-procedural language.

SQL supports to work with the following languages;

1. Data Query or Retrieval Language (DQL or DRL) : This language will support to retrieve the data
from a database in different procedures.

This language includes SELECT command.

2. Data Manipulation Language (DML) : Insertion of new rows, Modification of existing rows,
Removing unwanted rows collectively known as DML.

It includes INSERT,UPDATE,DELETE,MERGE(introduced in Oracle 12c)

3. Transaction Control Language (TCL) : This language will make the data permanent in a
database or supports to cancel the data.

It includes COMMIT,ROLLBACK,SAVEPOINT

4. Data Definition Language (DDL) : This language is used to create database objects, alter the
existing objects, remove the existing objects,.......etc.

It includes CREATE,ALTER,TRUNCATE,RENAME,DROP

5. Data Control Language (DCL) : This language will support to give rights to access the data of 1
user to the other user. It also supports to cancel those given rights.

It includes GRANT,REVOKE

6. Session Control or Protein Language (SCL or SPL)

DEMONSTRATION TABLES:

2
Oracle provides the following 5 demonstration tables.

1. EMP 8 COLUMNS 14 ROWS

2. DEPT 3 COLUMNS 4 ROWS

3. SALGRADE 3 COLUMNS 5 ROWS

4. BONUS 4 COLUMNS NO ROWS

5. DUMMY 1 COLUMN 1 ROW

The demonstration tables are provided thru a file called DEMOBLD.sql

This file is found at the following path

c:\Oracle\Ora90\sqlplus\demo

In order to run this .sql file, the following procedure is used.

SQL> @c:\oracle\ora90\sqlplus\demo\demobld

In order to have the execution of demobld.sql in a easy way, copy the file from its original location
to C: drive or any other drive.

SQL> @c:\demobld

DATA QUERY OR RETRIEVAL LANGUAGE (DQL OR DRL):

This language is used to retrieve the data in different ways from a database.

1. Selection : It is a process of retrieving all the columns of a table.

2. Projection : It is a process of retrieving required columns of a table.

3. Joins : It is a process of joining the data from 2 or more tables always producing a new
table.

Syntax:

SELECT * / list_of_columns [ alias_names ] / Literals / Mathematical Expressions / Pseudo


Columns / Functions

FROM table1 [table1_alias, table2 table2_alias,............]

[ WHERE condition(s) ]

[ GROUP BY col1[,col2,col3,...............]]

[ HAVING condition(s) ]

[ ORDER BY col1[,col2,col3,...............][ASC/DESC]];

3
Points to be remembered to work with SELECT statement:

1. Oracle is not case sensitive, so commands and options can be used in any case.

2. SELECT statement will be executed always from left to right.

3. SELECT statement will not support to perform selection and projection simultaneously.

4. SELECT statment should be followed by the clauses in the same way as they are mentioned.

5. SELECT statement can be typed in a single or multiple lines

6. SELECT statement should and must be terminated by ;

examples:

1. display all the employees information?

SELECT * FROM emp;

2. display all the departments information?

SELECT * FROM DEPT;

3. display all the salgrade information?

SELECT * FROM salgrade;

4. display ename,job,deptno of all the employees?

SELECT ename,job,deptno FROM emp;

5. display dname,loc of all the departments?

SELECT dname,loc FROM dept;

COLUMN ALIASES:

Column alias is the other name for column of a table.

Column alias will provide its affect only in the output of a query.

Column alias cant be used at other clauses of SELECT statement.

Column alias can be specified with and without using AS keyword.

Column alias when specified directly, it will convert the alias name from small letters to capital
letters in the output of a query. It does not support balnk spaces.

Column alias if mentioned in double quotes then it displays the alias name in the output of a
query in the same way as it is mentioned. It will allow to enclose blank spaces.

display empno,ename,job,sal,deptno of all the employees with respective alias names.


4
SQL> SELECT EMPNO ECODE,ENAME EN,JOB DESIG,SAL PAY,DEPTNO DNO FROM EMP;

OR

SQL> SELECT EMPNO AS ECODE,ENAME AS EN,JOB AS DESIG,SAL AS PAY,DEPTNO AS DNO


FROM EMP;

OR

SQL> SELECT empno ecode,ename en,job desig,sal pay,deptno dno FROM emp;

OR

SQL> SELECT empno "ecode",ename "en",job "desig",sal "monthly pay",deptno dno FROM emp;

Working with WHERE clause:

This clause is used to restrict the rows from a table.

Where clause provides the data comparision in 2 ways;

1. Magnitude 2. ASCII

| |

| |

Numeric String or Text

| |

| |

Not Case sensitive Case Sensitive

comparision to string and date type date should be always in single quotes.

Comparision to date type data is not case sensitive.

Comparision to numbers can also be placed in single quotes.

Operators:

+,-,*,/ Arithmetic Operators

>,<,>=,<=,=,!= or <> or ^= Relational Operators

AND,OR,NOT Logical Operators

IN,BETWEEN,IS,LIKE,DISTINCT,SOME/ANY

ALL,EXISTS Special Operators

5
We can combine special operators with NOT logical operator.

NOT IN,NOT BETWEEN,IS NOT,NOT LIKE, NOT EXISTIS..... etc

display all those employees who are working in deptno 10?

SQL> SELECT * FROM EMP WHERE DEPTNO=10;

OR

SQL> SELECT * FROM EMP WHERE DEPTNO='10';

display ename,job,sal,deptno of all those employees who are working as clerk?

SQL> SELECT ename,job,sal,deptno FROM emp WHERE job='CLERK';

display all those employees who have been hired on 03-DEC-81?

SQL> SELECT * FROM emp WHERE hiredate='03-DEC-81';

OR

SQL> SELECT * FROM emp WHERE hiredate='03-dec-81';

display ename,job,sal,deptno of all those employees who are working as CLERK,SALESMAN?

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE JOB='CLERK' OR


JOB='SALESMAN';

OR

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE JOB IN('CLERK','SALESMAN');

display ename,sal,deptno of all those employees who are working in 10,30 depts?

SQL> SELECT ENAME,SAL,DEPTNO FROM EMP WHERE DEPTNO IN(10,30);

display ename,job,sal of all those employees who are not working as managers?

SQL> SELECT ENAME,JOB,SAL FROM EMP WHERE JOB!='MANAGER';

OR

SQL> SELECT ENAME,JOB,SAL FROM EMP WHERE JOB NOT IN('MANAGER');

display ename,sal and deptno of all those employees whose sal>=1500 and sal<=3000?

SQL> SELECT ENAME,SAL,DEPTNO FROM EMP WHERE SAL>=1500 AND SAL<=3000;

OR

SQL> SELECT ENAME,SAL,DEPTNO FROM EMP WHERE SAL BETWEEN 1500 AND 3000;

6
display ename and salary of all those employees whose salary is not between 1500 and 2500?

SQL> SELECT ENAME,SAL FROM EMP WHERE SAL NOT BETWEEN 1500 AND 2500;

display ename,job,sal,deptno of all those employees who are working as


CLERK,MANAGER,SALESMAN and they are working in 10,30 depts and their salary is between
1000 and 3000?

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP

WHERE JOB IN('CLERK','MANAGER','SALESMAN') AND

DEPTNO IN(10,30) AND SAL BETWEEN 1000 AND 3000;

using LITERALS in SELECT statement:

Literal is constant value, which does not get change at the execution of a query.

Literal can be numeric, text or any other type data.

DUAL: It is a predefined table which consists of 1 ROW & 1 COL

Column Name -------- Dummy

Row ------ X

DESC DUAL

SELECT * FROM DUAL;

EXAMPLES ON REPRESENTING literals in SELECT statement:

SELECT 'WELCOME' FROM EMP;

SELECT 'ORACLE' FROM DEPT;

SELECT 'ORACLE','12c' FROM DUMMY;

SELECT 'ORACLE','12c' FROM DUAL;

SELECT 'ORACLE'||'12c' FROM DUAL;

|| ----- is called concatination operator.

SELECT ENAME||JOB FROM EMP;

SELECT ENAME||' '||JOB FROM EMP;

write a query to display the following output?

SMITH working as CLERK in deptno 20 on a pay of 800

ALLEN working as SALESMAN in deptno 30 on a pay of 1600


7
SELECT ENAME||' Working As '||JOB||' In Deptno '||deptno||' On a Pay Of '||sal FROM emp;

USING MATHEMATICAL EXPRESSION IN SELECT STATEMENT:

An expression in which arithmetic operators are enclosed is called Mathematical Expression.

SQL> SELECT 12+19 FROM DUAL;

12+19

---------

31

SQL> SELECT 12+19 ADD_NO FROM DUAL;

ADD_NO

---------

31

SQL> SELECT 12*12,10+3*7,(10+3)*7 FROM DUAL;

12*12 10+3*7 (10+3)*7

--------- --------- ---------

144 31 91

display ename,job,sal,annual salary of all the employees?

SQL> SELECT ENAME,JOB,SAL,SAL*12 ANN_SAL FROM EMP;

display ename,job,sal and tax of 8% on salaries of all employees?

SQL> SELECT ENAME,JOB,SAL,SAL*8/100 TAX FROM EMP;

display ename,job,sal and annual salary of all those employees whose annual salary is between
18000 and 36000?

SQL> SELECT ENAME,JOB,SAL,SAL*12 ANN_SAL FROM EMP WHERE SAL*12 BETWEEN 18000
AND 36000;

display ename,job,sal,comm,deptno of all those employees who are working as SALESMAN in


deptno 30 and their comm is more than half of their salary?

SQL> SELECT ENAME,JOB,SAL,COMM,DEPTNO FROM EMP

2 WHERE JOB='SALESMAN' AND DEPTNO=30 AND COMM>SAL/2;

working with IS operator:

8
This operator is used to compare null values, which cant be done by relational operators.

This operator can also be used for any number of times in SELECT statement at WHERE clause.

display all those employees who dont have manager to report?

SELECT * FROM emp WHERE mgr IS NULL;

display all those employees who have a manager to report?

SELECT * FROM Emp WHERE mgr IS NOT NULL;

OR

SELECT * FROM emp WHERE NOT mgr IS NULL;

display all those employees who are not earning the comm?

SELECT * FROM emp WHERE comm IS NULL;

display all those employees who are earning the comm?

SELECT * FROM emp WHERE comm IS NOT NULL;

display ename,job,sal,comm,deptno of all those employees who have manager to report and they
do not earn commission?

SQL> SELECT ename,job,sal,comm,deptno FROM emp WHERE mgr IS NOT NULL AND comm IS
NULL;

WILD CHARACTERS:

These characters are used to have pattern matching i.e. it allows to search the data using partial
value.

Oracle supports to work with the following Wild Characters;

_ (UNDER SCORE) : single character

% (PERCENTAGE) : group of characters.

WORKING WITH LIKE OPERATOR:

This operator is used to provide comparision to Wild characters, that which cant be done using
relational operators.

This operator is used to compare any type of data, enclosed in single quotes.

This operator can be used for any number of times in WHERE clause.

When Wild characters are stored as data then to search for those characters ESCAPE option is
used, followed by the special character by which wild character is converted to data.
9
Comparision to Data thru LIKE operator is case sensitive.

1. display all those employees whose names are starting with A.

SELECT * FROM emp WHERE ename LIKE 'A%';

2. display all those employees whose name are ending with S.

SELECT * FROM emp WHERE ename LIKE '%S';

3. display all those employees whose names are starting with J and Ending with S?

SELECT * FROM emp WHERE ename LIKE 'J%S';

4. display all those employees whose names contain A.

SELECT * FROM emp WHERE ename LIKE '%A%';

5. display ename,job,sal of all those employees whose names contain 4 charaters?

SELECT ename,job,sal FROM emp WHERE ename LIKE '____';

6. display ename,sal of all those employees whose salary ends with 00?

SELECT ename,sal FROM emp WHERE sal LIKE '%00';

7. display ename,job,sal,hiredate of all those employees who have been hired in those months
which starts with A?

SELECT ename,job,sal,hiredate FROM emp WHERE hiredate LIKE '___A%';

8. display ename,job,sal of all those employees whose 3rd character of ename is A?

SELECT ename,job,sal FROM emp WHERE ename LIKE '__A%';

9. display ename,deptno of all those employees whose names does not containt A?

SELECT ename,deptno FROM emp WHERE ename NOT LIKE '%A%';

10. display ename,job,sal of all those employees whose names contain A and salary ends with 00?

SELECT ename,job,sal FROM emp WHERE ename LIKE '%A%' AND sal LIKE '%00';

11. display ename,job,deptno of all those employees whose 2nd character of ename is _ and
ename starts with J?

SELECT ename,job,deptno FROM emp WHERE ename LIKE 'J\_%' ESCAPE '\';

12. display ename of all those employees whose names contain _?

SELECT ename FROM emp WHERE ename LIKE '%\_%' ESCAPE '\';

Working with DISTINCT operator:


10
1. DISTINCT operator can be used only for once in SELECT statement.

2. This operator eliminates duplicates.

3. This operator always arranges the data in Ascending Order.

4. When multiple columns are used with DISTINCT operator, it eliminates the record only if all the
columns contain duplicates.

display distinct deptno from emp table?

SELECT DISTINCT deptno FROM emp;

display distinct jobs of emp table?

SELECT DISTINCT job FROM emp;

display distinct mgr numbers of emp table?

SELECT DISTINCT mgr FROM emp;

note: It includes NULL value.

To eliminate NULL value the query can be written in the following way.

SELECT DISTINCT mgr FROM emp WHERE mgr IS NOT NULL;

display distinct deptno and job of emp table?

SELECT DISTINCT deptno,job FROM emp;

DEPTNO JOB

--------- ---------

10 CLERK

10 MANAGER

10 PRESIDENT

20 ANALYST

20 CLERK

20 MANAGER

30 CLERK

30 MANAGER

30 SALESMAN

11
9 rows selected.

Working with ORDER BY clause:

This clause is used to arrange the data in Ascending Or Descending Order.

By default it arranges the data in Ascending order.

To Arrange the data in descending order, option called DESC should be used.

This clause can arrange the data of any type.

ORDER BY clause will work after the execution of SELECT statement, so it arranges the data in
ascending or descending order for temporary.

ORDER BY clause will arrange the data in ASCENDING or DESCENDING order based on column
positions in SELECT query.

When multiple columns are used at ORDER BY clause, other columns are arranged in order based
on its previous column.

When multiple columns are used at ORDER BY clause, they can be arranged with same order type
or different order type.

display ename,job,sal of all the employees arranging sal in ascending order?

SELECT ename,job,sal FROM emp ORDER BY sal;

OR

SELECT ename,job,sal FROM emp ORDER BY sal ASC;

display ename,job, sal of all the employees arranging job in ascending order.

SELECT ename,job,sal FROM emp ORDER BY job;

display ename,job,sal of all the employees arraging sal is descending order?

SELECT ename,job,sal FROM emp ORDER BY sal DESC;

display ename,job,sal,comm,deptno of all the employees arranging sal in ascending order using
column position?

SELECT ename,job,sal,comm,deptno FROM emp ORDER BY 3;

1 2 3 4 5

display ename,job,sal of all the employees arranging job,sal in ascending order?

SELECT ename,job,sal FROM emp ORDER BY job,sal;

12
display ename,job,sal of all the employees arranging job,sal in ascending order based on their
column positions?

SELECT ename,job,sal FROM emp ORDER BY 2,3;

display ename,job,sal,comm,deptno of all the employees arranging job is ascending order and sal
in descending order based on column positions?

SELECT ename,job,sal,comm,deptno FROM emp ORDER BY 2 ASC,3 DESC;

display ename,job,sal,comm,deptno of all the employees arranging job is descending order and
sal in ascending order based on column positions?

SELECT ename,job,sal,comm,deptno FROM emp ORDER BY 2 DESC,3;

display ename,job,sal,hiredate,comm,deptno of all those employees who have been hired in the
year 81 and they do not earn any comm and they are working in 20,30 depts and their names
contain A and their sal does not end with 00 and their sal is between 1000 and 3000. Arrange the
data in ascending order of sal?

SELECT ename,job,sal,hiredate,comm,deptno FROM emp

WHERE hiredate LIKE '%81' AND comm IS NULL AND deptno IN (10,30)

AND ename LIKE '%A%' AND sal NOT LIKE '%00' AND sal BETWEEN 1000 AND 3000 ORDER BY
sal;

FUNCTIONS

Function is defined as, "Self contained program or predefined program, which returns 1 value".

Returned value can of number, text or date type.

Functions can be used for calculations.

Functions are classified into 2 types;

1. Predefined Functions 2. Stored Functions

OR OR

Built-in Functions User Defined Functions (PL/SQL)

Predefined Functions are those functions which are provided by software. These functions are
classified into 2 types;

I. Single Row Functions II. Multi Row Functions

or or

Individual Functions Group Functions

13
These functions will process These functions will process

single row at a time and returns multiple rows at a time and

1 value. returns 1 value.

1.Number functions (Arithmetic Func's) 1. Aggeregate functions

2.Text Functions(String Manipulation

Functions)

3.Date Functions

4.Data Conversion Functions

or

Type Casting Functions

5.Ranking Functions (Window Functions)

6.General Functions

(NVL,NVL2,COALESCE,NULLIF,CASE expr,

DECODE)

I. Number Functions (Arithmetic Functions):

These functions will take arguments of numeric type and returns value of numeric type.

1. ABS(number) : This function will return unsigned value of a given number.

SQL> SELECT ABS(-89) FROM DUAL;

ABS(-89)

--------

89

SQL> SELECT ABS(-19) FROM DEPT;

ABS(-19)

---------

19

19
14
19

19

SQL> SELECT ABS(78) FROM DUAL;

ABS(78)

---------

78

2. SQRT(number) : This function will return square root of a given number.

SQL> SELECT SQRT(16) FROM DUAL;

SQRT(16)

---------

SQL> SELECT SQRT(8) RES FROM DUAL;

RES

---------

2.8284271

3. POWER(number,number) : This function will find the power of a given number.

SELECT POWER(3,2) FROM DUAL;

4. MOD(number,number) : This function will return remainder.

SELECT MOD(5,2) FROM DUAL; O/P 1

SELECT MOD(6,2) FROM DUAL; O/P 0

SELECT MOD(7,9) FROM DUAL; O/P 7

SELECT MOD(153,10) FROM DUAL; O/P 3

5. ROUND(number[,number]) : This function will round a given number w.r.to integer or decimal
based on specified number of digits.

If the second argument is specified with +ve value then it rounds decimal part. If it is -ve value
then it rounds integer part.

SQL> SELECT ROUND(1234.5678,2) FROM DUAL;

ROUND(1234.5678,2)
15
------------------

1234.57

SQL> SELECT ROUND(1234.5638,2) FROM DUAL;

ROUND(1234.5638,2)

------------------

1234.56

SQL> SELECT ROUND(1234.5678,3) FROM DUAL;

ROUND(1234.5678,3)

------------------

1234.568

SQL> SELECT ROUND(1234.5678,1) FROM DUAL;

ROUND(1234.5678,1)

------------------

1234.6

SQL> SELECT ROUND(1234.5678,0) FROM DUAL;

ROUND(1234.5678,0)

------------------

1235

SQL> SELECT ROUND(1234.5678) FROM DUAL;

ROUND(1234.5678)

----------------

1235

SQL> SELECT ROUND(1234.3678) FROM DUAL;

ROUND(1234.3678)

----------------

1234

SQL> SELECT ROUND(1234.5678,-2) FROM DUAL;


16
ROUND(1234.5678,-2)

-------------------

1200

SQL> SELECT ROUND(5678.123,-2) FROM DUAL;

ROUND(5678.123,-2)

------------------

5700

SQL> SELECT ROUND(6758.123,-3) FROM DUAL;

ROUND(6758.123,-3)

------------------

7000

SQL> SELECT ROUND(6789.123,-4) FROM DUAL;

ROUND(6789.123,-4)

------------------

10000

SQL> SELECT ROUND(1234.567,-4) FROM DUAL;

ROUND(1234.567,-4)

------------------

SQL> SELECT ROUND(1234.7998,3) FROM DUAL;

ROUND(1234.7998,3)

------------------

1234.8

SQL> SELECT ROUND(5/2) FROM DUAL;

ROUND(5/2)

----------

3
17
SQL> SELECT ROUND(22/7) FROM DUAL;

ROUND(22/7)

-----------

6. TRUNC(number[,number]) :

This function is used to truncate a given number based on a required number of digits. It can
truncate decimal or integer part based on specified number of digits.

SQL> SELECT TRUNC(1234.5678,2) FROM DUAL;

TRUNC(1234.5678,2)

------------------

1234.56

SQL> SELECT TRUNC(1234.5678,3) FROM DUAL;

TRUNC(1234.5678,3)

------------------

1234.567

SQL> SELECT TRUNC(1234.5678,0) FROM DUAL;

TRUNC(1234.5678,0)

------------------

1234

SQL> SELECT TRUNC(1234.5678,-2) FROM DUAL;

TRUNC(1234.5678,-2)

-------------------

1200

SQL> SELECT TRUNC(5678.1234,-2) FROM DUAL;

TRUNC(5678.1234,-2)

-------------------

5600

18
SQL> SELECT TRUNC(5678.1234,-4) FROM DUAL;

TRUNC(5678.1234,-4)

-------------------

SQL> SELECT TRUNC(5/2) FROM DUAL;

TRUNC(5/2)

----------

7. SIN(number) : This function will return the sin value of a given number.

By default the argument, which is specified in this function will be in radians. To convert the
radians to degrees it should be used with a standard formula i.e. 3.14/180.

SQL> SELECT SIN(30) FROM DUAL;

SIN(30)

---------

-.9880316

note: The value which it has returned is of SIN 30 Radians

SQL> SELECT SIN(30*3.14/180) FROM DUAL;

SIN(30*3.14/180)

----------------

.4997701

SQL> SELECT ROUND(SIN(30*3.14/180),1) FROM DUAL;

ROUND(SIN(30*3.14/180),1)

-------------------------

.5

note: Function used with in the other function refers to Function cascading.

8. CEIL(number) : This function will increment a given number with a nearest int value, based on a
digit found other than 0 in decimal point.

SQL> SELECT CEIL(1234.0010) FROM DUAL;


19
CEIL(1234.0010)

---------------

1235

SQL> SELECT CEIL(1234.5678) FROM DUAL;

CEIL(1234.5678)

---------------

1235

SQL> SELECT CEIL(1234.0000) FROM DUAL;

CEIL(1234.0000)

---------------

1234

9. FLOOR(number) : This function will decrement a given number to a nearest int value, based on
a digit found at decimal point.

SQL> SELECT FLOOR(1234.5678) FROM DUAL;

FLOOR(1234.5678)

----------------

1234

SQL> SELECT FLOOR(-1234.0000) FROM DUAL;

FLOOR(-1234.0000)

------------------

-1234

SQL> SELECT FLOOR(-1234.0010) FROM DUAL;

FLOOR(-1234.0010)

-----------------

-1235

II. TEXT FUNCTIONS (STRING MANIPULATION FUNCTIONS)

These functions are used to perform manipulations over text type data. Text functions will accept
input of string type and returns number or text type data.
20
1. LENGTH(text) : This function will return length of a given string.

SQL> SELECT LENGTH('COMPUTER') FROM DUAL;

LENGTH('COMPUTER')

-----------------

SQL> SELECT ENAME,LENGTH(ENAME) FROM EMP;

ENAME LENGTH(ENAME)

---------- -------------

SMITH 5

ALLEN 5

WARD 4

JONES 5

MARTIN 6

BLAKE 5

CLARK 5

SCOTT 5

KING 4

TURNER 6

ADAMS 5

JAMES 5

FORD 4

MILLER 6

14 rows selected.

SQL> SELECT ENAME,LENGTH(ENAME) FROM EMP WHERE LENGTH(ENAME)>5;

ENAME LENGTH(ENAME)

---------- -------------

MARTIN 6
21
TURNER 6

MILLER 6

2. LOWER(text) : This function will convert the text from upper case to lower case.

SQL> SELECT LOWER('COMPUTER') FROM DUAL;

LOWER('C

--------

computer

SQL> SELECT ENAME,JOB,SAL FROM EMP WHERE LOWER(JOB)='clerk';

ENAME JOB SAL

---------- --------- ---------

SMITH CLERK 800

ADAMS CLERK 1100

JAMES CLERK 950

MILLER CLERK 1300

3. UPPER(text) : This function will convert the text from lower case to upper case.

SQL> SELECT UPPER('computer') FROM DUAL;

UPPER('C

--------

COMPUTER

4. ASCII(text) : This function will return ASCII code of a given text.

SELECT ASCII('A') FROM DUAL; O/P 65

SELECT ASCII('SHAREEF') FROM DUAL; O/P 83

5. CHR(number) : This function will return character of a given ASCII code.

SELECT CHR(65) FROM DUAL; O/P: A

SELECT CHR(83) FROM DUAL; O/P: S

6. LTRIM(text1[,text2]) : This function will remove blank spaces from left side of a string. It also
supports to remove the text from left side of a string.

22
SQL> SELECT ' COMPUTER' FROM DUAL;

'COMPUTER'

------------------

COMPUTER

SQL> SELECT LTRIM(' COMPUTER') FROM DUAL;

LTRIM('C

--------

COMPUTER

SQL> SELECT LTRIM('XYZABC','XYZ') FROM DUAL;

LTR

---

ABC

7. RTRIM(text1[,text2]) : This function will remove blank spacek from right side of a string. It also
supports to remove the text from right side of a string.

SQL> SELECT RTRIM('COMPUTER ') FROM DUAL;

RTRIM('C

--------

COMPUTER

SQL> SELECT RTRIM('XYZABC','XYZ') FROM DUAL;

RTR

---

XYZ

8. TRIM([BOTH/LEADING/TRAILING] [text/number FROM] text/number):

This function will remove blank spaces from left and right side of a string. It also supports to
remove text or number from left and right side of a given text or number. It also provides the
option of removing only left or right side of text or number.

SQL> SELECT TRIM(' COMPUTER ') FROM DUAL;

TRIM('CO

23
--------

COMPUTER

SQL> SELECT TRIM('L' FROM 'LEVEL') FROM DUAL;

TRI

---

EVE

SQL> SELECT TRIM(LEADING 'L' FROM 'LEVEL') FROM DUAL;

TRIM

----

EVEL

SQL> SELECT TRIM(TRAILING 'L' FROM 'LEVEL') FROM DUAL;

TRIM

----

LEVE

SQL> SELECT TRIM(LEADING 9 FROM 999123459999) FROM DUAL;

TRIM(LEAD

---------

123459999

SQL> SELECT TRIM(9 FROM 99991234599999) FROM DUAL;

TRIM(

-----

12345

9. SUBSTR(text,number,number) : This function will extract the required string from a given string
based on start position and number of characters.

SQL> SELECT SUBSTR('COMPUTER',4,3) FROM DUAL;

SUB

---

24
PUT

10. INITCAP(text) : This function will convert initial characters of a given string to Capital letters.

SQL> SELECT INITCAP('computer software hyderabad technologies') FROM DUAL;

INITCAP('COMPUTERSOFTWAREHYDERABADTECHNO

----------------------------------------

Computer Software Hyderabad Technologies

11. REPLACE(text1,text2,text3) : This function will search for text2 in text1 and if it is found then
replaces text3.

SQL> SELECT REPLACE('COMPILER','IL','UT') FROM DUAL;

REPLACE(

--------

COMPUTER

12. INSTR(text1,text2) : This function will search for text2 in text1 and returns position of that
string else returns with 0.

SQL> SELECT INSTR('COMPUTER','PUT') FROM DUAL;

INSTR('COMPUTER','PUT')

-----------------------

SQL> SELECT INSTR('COMPUTER','PET') FROM DUAL;

INSTR('COMPUTER','PET')

-----------------------

13. LPAD(text,number,text) : This function is used to provide a given text with left padding of size
n with a required char.

SQL> SELECT LPAD('COMPUTER',10,'*') FROM DUAL;

LPAD('COMP

----------

**COMPUTER

25
SQL> SELECT LPAD('COMPUTER',15,'*') FROM DUAL;

LPAD('COMPUTER'

---------------

*******COMPUTER

SQL> SELECT LPAD('COMPUTER',8,'*') FROM DUAL;

LPAD('CO

--------

COMPUTER

SQL> SELECT LPAD('COMPUTER',5,'*') FROM DUAL;

LPAD(

-----

COMPU

Write a query to display the following format?

**

***

****

*****

SQL> SELECT LPAD('*',GRADE,'*') FROM SALGRADE;

LPAD('*',GRADE,'*')

-------------------------------------------------

**

***

****

*****

SQL> SELECT LPAD(SAL,7,'Rs. ') FROM EMP;


26
LPAD(SA

-------

Rs. 800

Rs.1600

Rs.1250

Rs.2975

Rs.1250

Rs.2850

14. RPAD(text,number,text) : This function is used to provide a given text with right padding thru
any character for size n.

SQL> SELECT RPAD('COMPUTER',10,'*') FROM DUAL;

RPAD('COMP

----------

COMPUTER**

SQL> SELECT RPAD(LPAD('COMPUTER',10,'*'),12,'*') FROM DUAL;

RPAD(LPAD('C

------------

**COMPUTER**

WORKING WITH DATE TYPE DATA:

SYSDATE: This pseudo column will return server date and time, where time is hidden.

Date is displayed in the following format.

DD-MON-YY

This pseudo column can be associated to any table.

SQL> SELECT SYSDATE FROM DUAL;

SYSDATE

---------

23-JUN-09

27
Internally date type data is stored in the following format;

Century Year Month Date Hours Minutes Seconds

Arithmetic Operations on DATE Type data:

Internally Date type data is represented in numbers, so it can be performed with arithmetic
operations, which includes;

Date + Number = Date

Date - Number = Date

Date - Date = Number (No. Of Days)

SQL> SELECT SYSDATE+12 FROM DUAL;

SYSDATE+1

---------

05-JUL-09

SQL> SELECT SYSDATE-38 FROM DUAL;

SYSDATE-3

---------

16-MAY-09

SQL> SELECT HIREDATE,HIREDATE+19,HIREDATE-14 FROM EMP;

HIREDATE HIREDATE+ HIREDATE-

--------- --------- ---------

17-DEC-80 05-JAN-81 03-DEC-80

20-FEB-81 11-MAR-81 06-FEB-81

22-FEB-81 13-MAR-81 08-FEB-81

02-APR-81 21-APR-81 19-MAR-81

28-SEP-81 17-OCT-81 14-SEP-81

01-MAY-81 20-MAY-81 17-APR-81

09-JUN-81 28-JUN-81 26-MAY-81

09-DEC-82 28-DEC-82 25-NOV-82

28
17-NOV-81 06-DEC-81 03-NOV-81

08-SEP-81 27-SEP-81 25-AUG-81

12-JAN-83 31-JAN-83 29-DEC-82

03-DEC-81 22-DEC-81 19-NOV-81

03-DEC-81 22-DEC-81 19-NOV-81

23-JAN-82 11-FEB-82 09-JAN-82

14 rows selected.

Display experience of employees in days?

SQL> SELECT SYSDATE-HIREDATE DAYS FROM EMP;

DAYS

---------

10415.723

10350.723

10348.723

10309.723

10130.723

10280.723

Display experience of employees in Days?

SQL> SELECT ROUND((SYSDATE-HIREDATE)) DAYS FROM EMP;

DAYS

---------

10416

10351

10349

10310

Display ename,job,sal and experience in years of all the employees?

SQL> SELECT ENAME,JOB,SAL,ROUND((SYSDATE-HIREDATE)/365) EXP FROM EMP;


29
ENAME JOB SAL EXP

---------- --------- --------- ---------

SMITH CLERK 800 29

ALLEN SALESMAN 1600 28

WARD SALESMAN 1250 28

JONES MANAGER 2975 28

MARTIN SALESMAN 1250 28

Display ename,job,sal and experience of those employees whose experience is more than 28
years?

SQL> SELECT ENAME,JOB,SAL,ROUND((SYSDATE-HIREDATE)/365) EXP FROM EMP

2 WHERE ROUND((SYSDATE-HIREDATE)/365)>28;

ENAME JOB SAL EXP

---------- --------- --------- ---------

SMITH CLERK 800 29

III. DATE FUNCTIONS:

These functions are used to perform operations over date type data.

Oracle supports to work with the following date functions.

1. ADD_MONTHS(date,number) : This function is used to add number of months to a given date.

SQL> SELECT ADD_MONTHS(SYSDATE,3) FROM DUAL;

ADD_MONTH

---------

23-SEP-09

SQL> SELECT ADD_MONTHS('10-JUN-2008',11) FROM DUAL;

ADD_MONTH

---------

10-MAY-09

2. MONTHS_BETWEEN(date1,date2) : This function will find the difference between two dates in
terms of months. 1st Argument should be greater than the second argument.
30
SQL> SELECT MONTHS_BETWEEN('10-JUN-09','12-JAN-09') RES FROM DUAL;

RES

---------

4.9354839

Display ename,job,sal and experience of all the employees in terms of months?

SQL> SELECT ENAME,JOB,SAL,ROUND(MONTHS_BETWEEN(SYSDATE,HIREDATE)) MONTHS


FROM EMP;

Display ename,job,sal and experience of all the employees in terms of years?

SQL> SELECT ENAME,JOB,SAL,ROUND((MONTHS_BETWEEN(SYSDATE,HIREDATE))/12) exp


FROM EMP;

Display ename,job,sal and experience of all the employees whose exp is more than 27 years;

SQL> SELECT ENAME,JOB,SAL,ROUND((MONTHS_BETWEEN(SYSDATE,HIREDATE))/12) exp


FROM EMP WHERE ROUND((MONTHS_BETWEEN(SYSDATE,HIREDATE))/12)>27;

3. LAST_DAY(date) : This function will display last date based on a month specified in a given
date.

SQL> SELECT LAST_DAY(SYSDATE) FROM DUAL;

LAST_DAY(

---------

30-JUN-09

SQL> SELECT LAST_DAY('03-OCT-2005') FROM DUAL;

LAST_DAY(

---------

31-OCT-05

4. NEXT_DAY(date,format) : This function will display next day of a given date based on a given
day of week or day number of week.

SQL> SELECT NEXT_DAY(SYSDATE,'THU') FROM DUAL;

NEXT_DAY(

---------

25-JUN-09
31
SQL> SELECT NEXT_DAY(SYSDATE,'MON') FROM DUAL;

NEXT_DAY(

---------

29-JUN-09

SQL> SELECT NEXT_DAY(SYSDATE,'TUE') FROM DUAL;

NEXT_DAY(

---------

30-JUN-09

SQL> SELECT NEXT_DAY(SYSDATE,5) FROM DUAL;

NEXT_DAY(

---------

25-JUN-09

5. ROUND(date[,format]) : This function will round a given date based on a specified months and
years.

If specified format is months, then it rounds the date on days.

i.e. if days<=15 it rounds the date to 1st of current month.

if days>15 it rounds the date to 1st of next month.

SELECT ROUND(SYSDATE,'MONTH') FROM DUAL;

If date is 23-JUN-09 then it rounds the date to 01-JUL-09

If date is 10-JUN-09 then it rounds the date to 01-JUN-09

If specified format is years, then it rounds the date on months.

i.e. If months<=6 then it rounds the date to 1st of current year.

If months>6 then it rounds the date to 1st of next year.

SELECT ROUND(SYSDATE,'YEAR') FROM DUAL;

If date is 23-JUN-09 then it rounds the date to 01-JAN-09

If date is 23-OCT-09 then it rounds the date to 01-JAN-10

6. TRUNC(date[,format]) : This function will truncate a given date based on a specified months and
years.
32
If specified format is Months, then it truncate the date on days.

i.e. if days<=15 or days>15 it truncates the date to 1st of current month.

SELECT TRUNC(SYSDATE,'MONTH') FROM DUAL;

If date is 23-JUN-09 then it truncates the date to 01-JUN-09

If date is 10-JUN-09 then it truncates the date to 01-JUN-09

If specified format is Years, then it truncates the date on months.

i.e. If months<=6 or months>6 it truncates the date to 1st of current year.

SELECT TRUNC(SYSDATE,'YEAR') FROM DUAL;

If date is 23-JUN-09 then it truncates the date to 01-JAN-09

If date is 23-OCT-09 then it truncates the date to 01-JAN-09

IV) DATA CONVERSION FUNCTIONS (TYPE CASTING FUNCTIONS)

It is a process of converting the data stored with one type to the other type.

Oracle supports to convert the data in 2 ways;

1. Implicit (Automatic) Data Conversion

2. Explicit (Manual) Data Conversion

1. Implicit or Automatic Data Conversion : It is a conversion of data from 1 type to the other type
automatically. Oracle supports to conert the data for the following data types.

From To

CHAR or VARCHAR2 NUMBER

CHAR or VARCHAR2 DATE

DATE VARCHAR2

NUMBER VARCHAR2

SQL> SELECT '16'+'29' FROM DUAL;

'16'+'29'

---------

45

SQL> SELECT '28'+56 FROM DUAL;

33
'28'+56

---------

84

SQL> SELECT * FROM EMP WHERE DEPTNO='10';

2. Explicit or Manual Data Conversion : It is a process of converting the data from one type to the
other type using predefined functions.

TO_CHAR()

TO_NUMBER()

TO_DATE()

TO_CHAR TO_CHAR

NUMBER------------>CHARACTER<---------------DATE

NUMBER<------------CHARACTER--------------->DATE

TO_NUMBER TO_DATE

TO_CHAR(number/date[,format]): This function is used to convert number or date type data into
Character type.

To convert date type data into character type, Oracle provides differnt formatting characters.

Characteristic Format Description Example

Year YYYY displays century and year 2009

YYY displays last 3 digits of

year 009

YY displays only year 09

Y displays only last digit

of year 9

YEAR displays year in Words TWO THOUSAND NINE

Month MM displays 2 digit month

number 06

MONTH displays full name of

month with all capital


34
letters JUNE

MON displays abbreviated name

of the month JUN

Month displays full name of

month with initial character

as capital letter June

Mon displays abbreviated name

of the month Jun

RM displays month in roman nos VI

Day DDD displays 3 digit day of year 175

DD displays 2 digit day of month 24

D displays 1 digit day of week 4

DAY displays full name of a day WEDNESDAY

DY displays abbreviated name of

day WED

Day displays full name of a day

with initial char as capital Wednesday

Dy displays abbreviated name of

day with initial char as

capital letter Wed

J displays Julian day ----

Hours HH or HH12 displays hours in 12 hour

format 05

HH24 displays hours in 24 hour

format 17

Minutes MI displays minutes from 0-59 ----

Seconds SS displays seconds from 0-59 ----


35
Suffix SP displays spell out numbers DDSP

TWENTY FOUR

TH displays ordinal numbers DDTH

(st,nd,rd,th) 24th

SPTH displays spell out ordinal DDSPTH

numbers TWENTY FOURTH

Prefix FM removes all leading zeroes

from a date type data ----

QL> SELECT TO_CHAR(SYSDATE,'DD-MON-YYYY HH:MI:SS') FROM DUAL;

TO_CHAR(SYSDATE,'DD-

-------------------

4-JUN-2009 05:20:12

SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI') FROM DUAL;

TO_CH

-----

17:20

SQL> SELECT TO_CHAR(SYSDATE,'DAY DD-MONTH-YYYY') FROM DUAL;

TO_CHAR(SYSDATE,'DAYDD-MONT

---------------------------

WEDNESDAY 24-JUNE -2009

SQL> SELECT TO_CHAR(SYSDATE,'DDD-MM-YYYY') FROM DUAL;

TO_CHAR(SYS

-----------

175-06-2009

SQL> SELECT TO_CHAR(SYSDATE,'DY D DD-MON-YEAR') FROM DUAL;

TO_CHAR(SYSDATE,'DYDDD-MON-YEAR')
36
-------------------------------------------------------

WED 4 24-JUN-TWO THOUSAND NINE

SQL> SELECT TO_CHAR(SYSDATE,'MONTH') FROM DUAL;

TO_CHAR(S

---------

JUNE

SQL> SELECT TO_CHAR(HIREDATE,'DD-MON-YYYY') FROM EMP;

TO_CHAR(HIR

-----------

17-DEC-1980

20-FEB-1981

22-FEB-1981

02-APR-1981

28-SEP-1981

01-MAY-1981

09-JUN-1981

09-DEC-1982

17-NOV-1981

08-SEP-1981

12-JAN-1983

03-DEC-1981

03-DEC-1981

23-JAN-1982

14 rows selected.

SQL> SELECT TO_CHAR(HIREDATE,'DDSP-MONTH-YYYY') FROM EMP;

TO_CHAR(HIREDATE,'DDSP-MONT

---------------------------
37
SEVENTEEN-DECEMBER -1980

TWENTY-FEBRUARY -1981

TWENTY-TWO-FEBRUARY -1981

TWO-APRIL -1981

TWENTY-EIGHT-SEPTEMBER-1981

ONE-MAY -1981

NINE-JUNE -1981

NINE-DECEMBER -1982

SEVENTEEN-NOVEMBER -1981

EIGHT-SEPTEMBER-1981

TWELVE-JANUARY -1983

THREE-DECEMBER -1981

THREE-DECEMBER -1981

TWENTY-THREE-JANUARY -1982

14 rows selected.

SQL> SELECT TO_CHAR(HIREDATE,'DDTH-MON-YYYY') FROM EMP;

TO_CHAR(HIRED

-------------

17TH-DEC-1980

20TH-FEB-1981

22ND-FEB-1981

02ND-APR-1981

28TH-SEP-1981

01ST-MAY-1981

09TH-JUN-1981

09TH-DEC-1982

17TH-NOV-1981
38
08TH-SEP-1981

12TH-JAN-1983

03RD-DEC-1981

03RD-DEC-1981

23RD-JAN-1982

14 rows selected.

SQL> SELECT TO_CHAR(HIREDATE,'DDSPTH-MM=YYYY') FROM EMP;

TO_CHAR(HIREDATE,'DDSP

----------------------

SEVENTEENTH-12=1980

TWENTIETH-02=1981

TWENTY-SECOND-02=1981

SECOND-04=1981

TWENTY-EIGHTH-09=1981

FIRST-05=1981

NINTH-06=1981

NINTH-12=1982

SEVENTEENTH-11=1981

EIGHTH-09=1981

TWELFTH-01=1983

THIRD-12=1981

THIRD-12=1981

TWENTY-THIRD-01=1982

14 rows selected.

SQL> SELECT TO_CHAR(HIREDATE,'FM DD-MM-YYYY') FROM EMP;

TO_CHAR(HIR

-----------
39
17-12-1980

20-2-1981

22-2-1981

2-4-1981

28-9-1981

1-5-1981

9-6-1981

9-12-1982

17-11-1981

8-9-1981

12-1-1983

3-12-1981

3-12-1981

23-1-1982

14 rows selected.

Following are the different formatting characters, which converts the data from number type to
character type.

Format Description Example

9 represents digit ----

$ provides currency symbol ----

, provides thousand separator ----

. provides decimal point ----

0 provides 0 before a number $9,999.99

$2,975.00

SQL> SELECT TO_CHAR(SAL,'$9,999.99') FROM EMP;

TO_CHAR(SA

---------

40
$800.00

$1,600.00

$1,250.00

$2,975.00

$1,250.00

$2,850.00

$2,450.00

$3,000.00

$5,000.00

$1,500.00

$1,100.00

$950.00

$3,000.00

$1,300.00

14 rows selected.

SQL> SELECT TO_CHAR(SAL,'$09,999.99') FROM EMP;

TO_CHAR(SAL

----------

$00,800.00

$01,600.00

$01,250.00

$02,975.00

$01,250.00

$02,850.00

$02,450.00

$03,000.00

$05,000.00
41
$01,500.00

$01,100.00

$00,950.00

$03,000.00

$01,300.00

14 rows selected.

Write a query to display salaries with Currency as Rs.

TO_NUMBER('number'[,format]): This function is used to convert number which is represented in


text format, into number type data.

SQL> SELECT TO_NUMBER('28') FROM DUAL;

TO_NUMBER('28')

---------------

28

TO_DATE('date'[,format]) : This function will convert the date type data stored in text format into
date type.

SQL> SELECT SYSDATE-TO_DATE('10-FEB-09') FROM DUAL;

SYSDATE-TO_DATE('10-FEB-09')

----------------------------

134.73708

SQL> SELECT TO_DATE('24-APR-09') - TO_DATE('10-FEB-09') FROM DUAL;

TO_DATE('24-APR-09')-TO_DATE('10-FEB-09')

-----------------------------------------

73

Write a query to display salaries in words?

800 EIGHT HUNDRED

1600 ONE THOUSAND SIX HUNDRED

1250 ONE THOUSAND TWO HUNDRED FIFTY

V) RANKING FUNCTIONS (WINDOW FUNCTIONS)


42
These functions are used to calculate ranks.

These functions cant be used at WHERE clause of SELECT statement.

These functions will work with OVER clause, which is associated with ORDER BY clause with
order type specified (ASC/DESC).

These functions will calculate the ranks after the execution of SELECT statement.

Oracle provides the following Ranking functions;

RANK() : It calculates the rank with gaps

DENSE_RANK() : It calculates the rank with no gaps

example for RANK():

SQL> SELECT ENAME,JOB,SAL,RANK() OVER(ORDER BY SAL DESC) RNK FROM EMP;

ENAME JOB SAL RNK

---------- --------- --------- ---------

KING PRESIDENT 5000 1

SCOTT ANALYST 3000 2

FORD ANALYST 3000 2

JONES MANAGER 2975 4

BLAKE MANAGER 2850 5

CLARK MANAGER 2450 6

ALLEN SALESMAN 1600 7

example for DENSE_RANK():

SQL> SELECT ENAME,JOB,SAL,DENSE_RANK() OVER(ORDER BY SAL DESC) RNK FROM EMP;

ENAME JOB SAL RNK

---------- --------- --------- ---------

KING PRESIDENT 5000 1

SCOTT ANALYST 3000 2

FORD ANALYST 3000 2

JONES MANAGER 2975 3

43
BLAKE MANAGER 2850 4

CLARK MANAGER 2450 5

VI) GENERAL FUNCTIONS:

====>NVL(expr1,expr2) : This function will substitute a required value at those rows of a column
where null values are found. if expr1 contains null values substitutes expr2 else provides expr1 as
value.

SELECT ENAME,JOB,SAL,COMM,NVL(COMM,0) RES FROM EMP;

display ename,job,sal,comm and total salary of all the employees.

SELECT ENAME,JOB,SAL,COMM,SAL+COMM TOT_SAL FROM EMP;

This query will calculate total salary of only those employees who are earning the commission. In
order to calculate the total salary of all the employees, substitute comm with 0 where ever null
values are found.

SELECT ENAME,JOB,SAL,COMM,SAL+NVL(COMM,0) TOT_SAL FROM EMP;

====>NVL2(expr1,expr2,expr3) : This functions will substitute a required value at those rows of


expr1 where values are found and not found. if expr1 contains null values, substitutes expr3 else
substitutes expr2

expr2 & expr3 can be substituted with any type of data i.e. numbers or text

SELECT ENAME,JOB,SAL,COMM,NVL2(COMM,'YES','NO') RES FROM EMP;

SELECT ENAME,JOB,SAL,COMM,NVL2(COMM,SAL+COMM,SAL) TS FROM EMP;

====>COALESCE(expr1,expr2,expr3,expr4,...............) :

This functions can have any number of expressions.

This function will search for null values in expr1, if finds substitutes expr2, if expr2 contains null
values substitutes expr3,.................etc.

SELECT ENAME,JOB,SAL,COMM,COALESCE(COMM,SAL,25) RES FROM EMP;

====>NULLIF(expr1,expr2) :

This function will compare the values of 2 expressions and returns boolean value i.e. if the
condition is true returns null value else

returns value of expr1.

SELECT ENAME,LENGTH(ENAME) L1,JOB,LENGTH(JOB)


L2,NULLIF(LENGTH(ENAME),LENGTH(JOB)) RES FROM EMP;

44
====>CASE expr : Case expression will allow to compare the data with multiple conditions
providing different resultant values.

If no condition is satisfied then it returns default value.

syntax:

CASE expr

WHEN condition1 THEN result1

[WHEN condition2 THEN result2

WHEN condition3 THEN result3

.................

ELSE

default_result ]

END [alias_name]

examples:

display ename,job,sal,increment the sal with different percentages on the categories of job.

if job is MANAGER increment the salary by 12%

if job is CLERK increment the salary by 10%

and others by 8%?

SELECT ENAME,JOB,SAL,

CASE job

WHEN 'MANAGER' THEN sal*12/100

WHEN 'CLERK' THEN sal*10/100

ELSE

sal*8/100

END incr FROM emp;

display ename,job,sal,deptno increment the sal with different percentages on the categories of
deptno.

if deptno is 10 increment by 15%

if deptno is 20 increment by 12%


45
if deptno is 30 increment by 10%

SELECT ENAME,JOB,SAL,deptno,

CASE DEPTNO

WHEN 10 THEN SAL*15/100

WHEN 20 THEN SAL*12/100

WHEN 30 THEN SAL*10/100

END INCR FROM EMP;

====>DECODE(expr,condition1,result1[,condition2,result2,condition3,result3,........................,defaul
t_result])

This function will allow to compare the data with multiple conditions providing different resultant
values.

If no condition is satisfied then it returns default value.

example:

display ename,job,sal, increment the sal with different percentages on the categories of job.

if job is MANAGER increment the salary by 12%

if job is CLERK increment the salary by 10%

and others by 8%?

SELECT ENAME,JOB,SAL,DECODE(JOB,'MANAGER',SAL*12/100,'CLERK',SAL*10/100,SAL*8/100)
INCR FROM EMP;

display ename,job,sal,deptno increment the sal with different percentages on the categories of
deptno.

if deptno is 10 increment by 15%

if deptno is 20 increment by 12%

if deptno is 30 increment by 10%

SELECT ENAME,JOB,SAL,DEPTNO,DECODE(DEPTNO,10,SAL*15/100,20,SAL*12/100,SAL*10/100)
INCR FROM EMP;

====>GREATEST(val1,val2,val3,...........) :

This function will find the biggest value among

the set of values.


46
SELECT GREATEST(12,34,56,10,23,16,20) FROM DUAL;

====>LEAST(val1,val2,val3,..........) :

This function will find the least value among the set of values.

SELECT LEAST(12,34,56,10,23,16,20) FROM DUAL;

====>SIGN(number) : This function will provide 0 if a number is +ve,

-1 if a number is -ve, and 0 if number is 0.

SELECT SIGN(12),SIGN(-18),SIGN(0) FROM DUAL;

SIGN(12) SIGN(-18) SIGN(0)

--------- --------- ---------

1 -1 0

II) MULTI ROW FUNCTIONS (GROUP FUNCTIONS):

These funtions will process multiple rows at a time and returns 1 value.

These functions include Aggregate functions.

AGGREGATE FUNCTIONS:

Aggregate functions will avoid null values.

All Aggregate functions can be used with in a single SELECT statement.

Aggregate functions can be made to calculate the data based on conditions on different columns.

*** When aggrgate functions are enclosed in SELECT statement, it does not allow to write
columns that returns multiple rows.

*** Aggregate functions cant be used at WHERE clause.

Oracle provides the following aggregate functions;

SUM(expr) : finds sum of all the values that are present in expr

AVG(expr) : finds avg value of all the values present in expr, it works in the following way.

first it finds sum and then divides with number of rows.

MAX(expr) : finds maximum value among the values in a expr

MIN(expr) : finds minimum value among the values in a expr

COUNT(expr) : counts number of values in a expr excluding null values.

47
OR

COUNT(DISTINCT expr) : counts unique values in expr

OR

COUNT(*) : counts number of ROWS in a table.

display total salary of all the employees?

SQL> SELECT SUM(SAL) FROM EMP;

SUM(SAL)

--------

29025

display avg salary of all the employees?

SQL> SELECT AVG(SAL) FROM EMP;

AVG(SAL)

--------

2073.214

display the total comm being paid among all the employees?

SQL> SELECT SUM(COMM) FROM EMP;

SUM(COMM)

---------

2200

display avg comm being paid among all the employees?

SQL> SELECT AVG(COMM) FROM EMP;

AVG(COMM)

---------

550

find the maximum salary among all employees?

SQL> SELECT MAX(SAL) FROM EMP;

MAX(SAL)
48
--------

5000

find minimum salary among all employees?

SQL> SELECT MIN(SAL) FROM EMP;

MIN(SAL)

--------

800

count the number of employees who are being paid with salary?

SQL> SELECT COUNT(SAL) FROM EMP;

count the number of employees who are being paid with comm?

SQL> SELECT COUNT(COMM) FROM EMP;

count the unique salaries of emp table?

SQL> SELECT COUNT(DISTINCT SAL) FROM EMP;

count the unique jobs of emp table?

SQL> SELECT COUNT(DISTINCT JOB) FROM EMP;

count the number of rows in emp table?

SQL> SELECT COUNT(*) FROM emp;

display total salary,avg salary,max salary,min salary,

number of employees working in deptno 30?

SELECT SUM(SAL),AVG(SAL),MAX(SAL),MIN(SAL),COUNT(*) FROM EMP WHERE DEPTNO=30;

display total salary and avg salary of all those employees who are working in deptno 10,30

SELECT SUM(SAL),AVG(SAL) FROM EMP WHERE DEPTNO=10 OR DEPTNO=30;

GROUP BY clause:

This clause is used to group the data on a required column by eliminating duplicates and
always arranges the data in ascending order.

The column used in GROUP BY clause, the same column can be used at expression list.

Multiple columns can be used at GROUP BY clause, where it eliminates the duplicates only it finds
them at all the columns.
49
display deptno and total salary of all the departments?

SQL> SELECT DEPTNO,SUM(SAL) FROM EMP

2 GROUP BY DEPTNO;

DEPTNO SUM(SAL)

-------- --------

10 8750

20 10875

30 9400

display deptno,total salary,avg salary,max salary,min salary and number of employees w.r.to their
departments?

SQL> SELECT DEPTNO,SUM(SAL),AVG(SAL),MAX(SAL),MIN(SAL),COUNT(*) FROM EMP

2 GROUP BY DEPTNO;

DEPTNO SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL) COUNT(*)

-------- -------- -------- -------- -------- --------

10 8750 2916.667 5000 1300 3

20 10875 2175 3000 800 5

30 9400 1566.667 2850 950 6

display deptno and total salary of deptno 20?

SQL> SELECT DEPTNO,SUM(SAL) FROM EMP

2 WHERE DEPTNO=20

3 GROUP BY DEPTNO;

DEPTNO SUM(SAL)

-------- --------

20 10875

display job and total salaries being paid on each job?

SQL> SELECT JOB,SUM(SAL) FROM EMP

50
2 GROUP BY JOB;

JOB SUM(SAL)

--------- --------

ANALYST 6000

CLERK 4150

MANAGER 8275

PRESIDENT 5000

SALESMAN 5600

using multiple columns at GROUP BY clause:

display deptno,job,and total salary being paid on each deptno and job?

SELECT DEPTNO,JOB,SUM(SAL) FROM EMP

GROUP BY DEPTNO,JOB;

DEPTNO JOB SUM(SAL)

-------- --------- --------

10 CLERK 1300

10 MANAGER 2450

10 PRESIDENT 5000

20 ANALYST 6000

20 CLERK 1900

20 MANAGER 2975

30 CLERK 950

30 MANAGER 2850

30 SALESMAN 5600

HAVING clause:

This clause is used to make conditions on aggregate functions.

It will also allow to make conditions on columns but only those columns which are used at
GROUP BY clause, which means HAVING clause is dependent on GROUP BY clause.

51
display deptno and total salary of those departments

whose total salary is more than 9000?

SQL> SELECT DEPTNO,SUM(SAL) FROM EMP

2 GROUP BY DEPTNO

3 HAVING SUM(SAL)>9000;

DEPTNO SUM(SAL)

-------- --------

20 10875

30 9400

display deptno and number of employees of all those departments where more than 3 employees
are working?

SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO

HAVING COUNT(*)>3;

DEPTNO COUNT(*)

------- --------

20 5

30 6

display deptno and total salary of that department 20 only if the total salary is more than 9000?

SELECT DEPTNO,SUM(SAL) FROM EMP

GROUP BY DEPTNO

HAVING DEPTNO=20 AND SUM(SAL)>9000;

ROLLUP & CUBE FUNCTIONS:

ROLLUP(expr1[,expr2,expr3,........]) :

This function can be used only at GROUP BY clause.

It finds individual totals, group totals and

an additional row is generated that finds Grand total.

display deptno and total salary being to each department including grand total salary?

52
SELECT DEPTNO,SUM(SAL) FROM EMP

GROUP BY ROLLUP(DEPTNO);

display deptno,job and total salary being paid on each job and deptno?

SELECT DEPTNO,JOB,SUM(SAL) FROM EMP

GROUP BY ROLLUP(DEPTNO,JOB);

DEPTNO JOB SUM(SAL)

-------- --------- ---------

10 CLERK 1300

10 MANAGER 2450

10 PRESIDENT 5000

10 8750

20 ANALYST 6000

20 CLERK 1900

20 MANAGER 2975

20 10875

30 CLERK 950

30 MANAGER 2850

30 SALESMAN 5600

30 9400

29025

CUBE(expr1[,expr2,expr3,........]) :

This function can be used only at GROUP BY clause.

It will find individual totals, group totals and an additional row is generated for grand total. Cube
also provides regroup totals.

display deptno,job,total salary being paid on each job and deptno, it finds regroup totals.

SQL> SELECT DEPTNO,JOB,SUM(SAL) FROM EMP

2 GROUP BY CUBE(DEPTNO,JOB);

53
DEPTNO JOB SUM(SAL)

-------- --------- --------

10 CLERK 1300

10 MANAGER 2450

10 PRESIDENT 5000

10 8750

20 ANALYST 6000

20 CLERK 1900

20 MANAGER 2975

20 10875

30 CLERK 950

30 MANAGER 2850

30 SALESMAN 5600

30 9400

ANALYST 6000

CLERK 4150

MANAGER 8275

PRESIDENT 5000

SALESMAN 5600

29025

1 SELECT DEPTNO,JOB,COUNT(*) FROM EMP

2* GROUP BY CUBE(DEPTNO,JOB)

SQL> /

DEPTNO JOB COUNT(*)

-------- --------- --------

10 CLERK 1

10 MANAGER 1
54
10 PRESIDENT 1

10 3

20 ANALYST 2

20 CLERK 2

20 MANAGER 1

20 5

30 CLERK 1

30 MANAGER 1

30 SALESMAN 4

30 6

ANALYST 2

CLERK 4

MANAGER 3

PRESIDENT 1

SALESMAN 4

14

SET JOINS

OR

SET OPERATORS

It is process of joining rows returned by 2 or more queries.

Queries can be on same table or can be on different table.

Columns can be from same table or can be from different tables.

When different columns are used to join the rows, it is must that their datatype should be same. In
the output it provides the column name which is found in 1st query.

Oracle supports to work with the following set operators.

1. UNION

2. UNION ALL

55
3. INTERSECT

4. MINUS

Multiple set operators can be used between different queries.

In order to join the rows of different queries and arrange the data in ascending or in descending
order, order by clause should be used at last query.

1. UNION:

It will support to join the rows returned by 2 or more queries by eliminating duplicates and always
arranges the data in ascending order.

2. UNION ALL :

It will support to join the rows returned by 2 or more queries in the same way as they are extracted
and it does not eliminate the duplicates.

3. INTERSECT :

It will support to join the common rows that are found at result sets of 2 or more queries. It will
eliminate the duplicates and always arranges the data in order.

4. MINUS:

It will support to subtract the data from the result set of 1st query w.r.to the rows found at 2nd
query and returns the remained values of 1st query.

EXAMPLES:

SQL> SELECT JOB FROM EMP WHERE DEPTNO=10;

JOB

---------

MANAGER

PRESIDENT

CLERK

SQL> SELECT JOB FROM EMP WHERE DEPTNO=20;

JOB

---------

CLERK

MANAGER
56
ANALYST

CLERK

ANALYST

SQL> SELECT JOB FROM EMP WHERE DEPTNO=30;

JOB

---------

SALESMAN

SALESMAN

SALESMAN

MANAGER

SALESMAN

CLERK

6 rows selected.

example of UNION operator:

SELECT JOB FROM EMP WHERE DEPTNO=10

UNION

SELECT JOB FROM EMP WHERE DEPTNO=20;

OUTPUT:

ANALYST

CLERK

MANAGER

PRESIDENT

example of UNION ALL operator:

SELECT JOB FROM EMP WHERE DEPTNO=10

UNION ALL

SELECT JOB FROM EMP WHERE DEPTNO=20;

JOB
57
---------

MANAGER

PRESIDENT

CLERK

CLERK

MANAGER

ANALYST

CLERK

ANALYST

8 rows selected.

example of INTERSECT operator:

SELECT JOB FROM EMP WHERE DEPTNO=10

INTERSECT

SELECT JOB FROM EMP WHERE DEPTNO=20;

JOB

---------

CLERK

MANAGER

example of MINUS operator:

SELECT JOB FROM EMP WHERE DEPTNO=10

MINUS

SELECT JOB FROM EMP WHERE DEPTNO=20;

JOB

---------

PRESIDENT

example of using multiple operators:

SELECT JOB FROM EMP WHERE DEPTNO=10


58
MINUS

SELECT JOB FROM EMP WHERE DEPTNO=20

UNION

SELECT JOB FROM EMP WHERE DEPTNO=30;

OUTPUT:

CLERK

MANAGER

PRESIDENT

SALESMAN

example of using different columns:

SELECT JOB FROM EMP WHERE DEPTNO=10

UNION

SELECT DNAME FROM DEPT;

JOB

-----------

ACCOUNTING

CLERK

MANAGER

OPERATIONS

PRESIDENT

RESEARCH

SALES

ordering the data:

SELECT JOB FROM EMP WHERE DEPTNO=10

UNION ALL

SELECT JOB FROM EMP WHERE DEPTNO=20 ORDER BY JOB;

JOB
59
---------

ANALYST

ANALYST

CLERK

CLERK

CLERK

MANAGER

MANAGER

PRESIDENT

multiple columns in queries:

SQL> SELECT JOB,SAL FROM EMP WHERE DEPTNO=10

2 UNION

3 SELECT DNAME,DEPTNO FROM DEPT;

JOB SAL

-------------- --------

ACCOUNTING 10

CLERK 1300

MANAGER 2450

OPERATIONS 40

PRESIDENT 5000

RESEARCH 20

SALES 30

7 rows selected.

JOINS

It is a process of joining COLUMNS from 2 or more tables always producing a new table.

In order to join the columns from 2 or more tables, it is essential that joining condition is must.
60
To join 'n' tables, it is must that n-1 joining conditions are required.

Columns of 2 or more tables can be joined based on 2 syntaxes.

Standard SQL syntaxes ANSI syntaxes

or

Oracle 12c joins

It is used to join the data It is used to join the

from 2 or more tables columns of 2 or more

by making joining condition tables by making joining

thru operators condition using Keywords.

1. Inner joins 1. NATURAL JOIN

i. Equi Join

ii. Non Equi Join 2. CROSS JOIN

2. Outer Joins

i. Left Outer Join 3. outer joins

ii. Right Outer Join i. LEFT OUTER JOIN

3. Cartesian join ii. RIGHT OUTER JOIN

4. Self join iii. FULL OUTER JOIN

1. Inner Join

i) Equi Join : This join concept supports to join the columns of 2 or more tables by making a
joining condition using = operator.

To work with equi join it is essential that the tables should have atleast one common column
w.r.to data.

Table Alias:

It is the other name provided to a table, which is temporary i.e. it works only in that query.

Table alias can be used any where in SELECT statement i.e. at expressions list, where clause,
order by clause etc.

If the tables have common column names, to differentiate them

it is essential that they should be preceeded with table names or table alias names.

61
display empno,ename,job,sal,dname and location of all the employees?

SQL> SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC

2 FROM EMP,DEPT

3 WHERE EMP.DEPTNO=DEPT.DEPTNO;

OR

SQL> SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC

2 FROM EMP E,DEPT D

3 WHERE E.DEPTNO=D.DEPTNO;

OR

SQL> SELECT
SCOTT.EMP.EMPNO,SCOTT.EMP.ENAME,SCOTT.EMP.JOB,SCOTT.EMP.SAL,SCOTT.DEPT.DNAM
E,SCOTT.DEPT.LOC

2 FROM SCOTT.EMP,SCOTT.DEPT

3 WHERE SCOTT.EMP.DEPTNO=SCOTT.DEPT.DEPTNO;

OR

SQL> SELECT E.*,DNAME,LOC

2 FROM EMP E,DEPT D

3 WHERE E.DEPTNO=D.DEPTNO;

OR

SQL> SELECT * FROM EMP E,DEPT D

2 WHERE E.DEPTNO=D.DEPTNO;

OR

SQL> SELECT E.EMPNO,E.ENAME,E.JOB,E.SAL,E.DEPTNO,D.DNAME,D.LOC

FROM EMP E,DEPT D

WHERE E.DEPTNO=D.DEPTNO;

2. NON EQUI JOIN:

At this join concept columns of 2 or more tables can be joined by making a joining condition with
out using = operator.

62
display empno,ename,job,sal,grade of all the employees?

SQL> SELECT EMPNO,ENAME,JOB,SAL,GRADE FROM EMP,SALGRADE WHERE SAL BETWEEN


LOSAL AND HISAL;

display empno,ename,job,sal,dname,loc and grade of all the employees?

SQL> SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC,GRADE

2 FROM EMP E,DEPT D,SALGRADE S

3 WHERE E.DEPTNO=D.DEPTNO AND E.SAL BETWEEN S.LOSAL AND S.HISAL;

display empno,ename,job,sal,deptno,dname,loc and grade of all those employees who are


working in Research,Sales departments,

and they do not earn the commission, and they have been hired in the year 81 and their names
contain A. arrange the data in ascending order of deptno?

SELECT EMPNO,ENAME,JOB,SAL,E.DEPTNO,DNAME,LOC,GRADE

FROM EMP E,DEPT D,SALGRADE S

WHERE E.DEPTNO=D.DEPTNO AND E.SAL BETWEEN S.LOSAL AND S.HISAL

AND DNAME IN('RESEARCH','SALES') AND COMM IS NULL AND HIREDATE LIKE '%81' AND
ENAME LIKE '%A%' ORDER BY E.DEPTNO;

OUTER JOINS:

This join concept will support to join the columns of 2 or more tables that gets match and
unmatch with the condition.

Outer joins at standard sql syntaxes is classified in 2 types;

1. Left outer join

2. Right outer join

Outer joins is implemented with outer join operator i.e.(+)

1. left outer join : At this join concept data from left table is extracted w.r.to match and unmatch
records substituting null values at the columns of right side table. At this join, outer join operator
is placed at right side of a condition.

SELECT ............................

FROM table1,table2

WHERE table1.col1=table2.col2(+);

63
display empno,ename,job,dname and loc from 2 tables which gets match and unmatch with the
condition?

SELECT EMPNO,ENAME,JOB,DNAME,LOC

FROM EMP E,DEPT D

WHERE E.DEPTNO=D.DEPTNO(+);

SELECT EMPNO,ENAME,JOB,DNAME,LOC

FROM EMP E,DEPT D

WHERE D.DEPTNO=E.DEPTNO(+);

2. RIGHT OUTER JOIN :

At this join concept data is completely extracted from right table substituting null values at the
columns of left table.

At this join, outer join operator is placed at left side of joining condition.

SELECT .............................

FROM table1,table2

WHERE table1.col1(+)=table2.col2;

display empno,ename,job,dname,loc from 2 tables using right outer join?

SELECT EMPNO,ENAME,JOB,DNAME,LOC

FROM EMP E,DEPT D

WHERE E.DEPTNO(+)=D.DEPTNO;

NOTE:

1. Outer join operator can be specified at left or right side of a joining condition.

2. outer join condition should not be extended with IN or OR operators.

CARTESIAN JOIN:

This join concept will support to join the data by providing multiplication of rows between tables
used for joins.

display empno,ename,job,dname and loc from 2 tables without using any joining condition?

SQL> SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC

2 FROM EMP,DEPT;

64
(14*4=56 rows are generated)

display empno,ename,job,sal,dname,loc and grade of all the employees without using any joining
condition?

SELECT EMPNO,ENAME,JOB,DNAME,LOC,SAL,GRADE FROM emp,dept,salgrade;

(14*4*5 = 280 ROWS ARE GENERATED)

SELF JOIN:

This join concept is used to join the data by referring to a single table for more than once, but with
different alias names. Data is extracted and joining condition is made on a single table.

Display empno,ename,mgr and mgr name of all the employees?

SQL> SELECT M.EMPNO,M.ENAME,M.MGR,E.ENAME

2 FROM EMP E,EMP M

3 WHERE E.EMPNO=M.MGR;

EMPNO ENAME MGR ENAME

--------- ---------- --------- ----------

7788 SCOTT 7566 JONES

7902 FORD 7566 JONES

7499 ALLEN 7698 BLAKE

7521 WARD 7698 BLAKE

7900 JAMES 7698 BLAKE

7844 TURNER 7698 BLAKE

7654 MARTIN 7698 BLAKE

7934 MILLER 7782 CLARK

7876 ADAMS 7788 SCOTT

7566 JONES 7839 KING

7782 CLARK 7839 KING

7698 BLAKE 7839 KING

7369 SMITH 7902 FORD

13 rows selected.
65
ANSI JOINS

OR

ORACLE 12c JOINS

These joins are introduced thru Oracle 12c, Which supports to join the data by using keywords
specifying them at FROM clause of SELECT statement.

Oracle 12c supports to implement the following types of joins.

1. NATURAL JOIN

2. CROSS JOIN

3. outer joins

LEFT OUTER JOIN

RIGHT OUTER JOIN

FULL OUTER JOIN

Syntax:

SELECT .........................

FROM table1 <join type> table2 [ <join type> table3 ...... ]

[ USING (col_name) ] / [ ON (joining condition) ];

Oracle 12c supports to join the data using JOIN with ON clause and JOIN with USING clause,
specifying them at FROM clause.

1. NATURAL JOIN:

It is similar to equi join. To work with this join it is essential that the tables should contain atleast
1 common column with respect to data and names.

Display ename,job,sal,dname,loc of all the employees using NATURAL JOIN?

SELECT ENAME,JOB,SAL,DNAME,LOC FROM EMP NATURAL JOIN DEPT;

2. CROSS JOIN:

It is similar to Cartesian join.

Display ename,job,sal,dname,loc of all the employees using CROSS JOIN?

SELECT ENAME,JOB,SAL,DNAME,LOC FROM EMP CROSS JOIN DEPT;

(14 * 4 = 56 Rows Are Generated)

66
Display ename,job,sal,dname,loc,grade of all the employees using CROSS JOIN?

SELECT ENAME,JOB,SAL,DNAME,LOC,GRADE FROM EMP CROSS JOIN DEPT CROSS JOIN


SALGRADE;

(14 * 4 * 5 = 280 Rows Are Generated)

working with JOIN....USING clause:

At this concept of joins, JOIN keyword is used between table names at FROM clause of SELECT
statement and USING clause is used to specify the common column name among the tables used
in joins. When column name is mentioned in USING clause, it should not be preceeded by talbe
name or table alias name.

Display ename,job,sal,dname and location of all the employees?

SELECT ENAME,JOB,SAL,DNAME,LOC FROM EMP JOIN DEPT USING (DEPTNO);

working with JOIN....ON clause:

At this concept of joins, JOIN keyword is used between table names at FROM clause of SELECT
statement and ON clause is used to make joining condition, which allows to use table names or
table aliasnames at the joining condition. It supports to implement all types of joins that includes
Equi join, Non Equi join, Self join.

Display ename,job,sal,dname,loc of all the employees using JOIN...ON clause?

SELECT ENAME,JOB,SAL,DNAME,LOC FROM EMP E JOIN DEPT D ON (E.DEPTNO=D.DEPTNO);

Display ename,job,sal,dname,loc and grade of all the employees using JOIN....ON clause?

SELECT ENAME,JOB,SAL,DNAME,LOC,GRADE FROM EMP E JOIN DEPT D

ON (E.DEPTNO=D.DEPTNO) JOIN SALGRADE ON(SAL BETWEEN LOSAL AND HISAL);

Display empno,ename,mgr and mgr name of all the employees?

SELECT M.EMPNO,M.ENAME,M.MGR,E.ENAME

FROM EMP E JOIN EMP M ON (E.EMPNO=M.MGR);

outer joins:

It supports to implement the following outer joins using keywords.

1. LEFT OUTER JOIN

SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC FROM EMP E LEFT OUTER JOIN DEPT D


ON(E.DEPTNO=D.DEPTNO);

2. RIGHT OUTER JOIN

67
SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC FROM EMP E RIGHT OUTER JOIN DEPT D
ON(E.DEPTNO=D.DEPTNO);

3. FULL OUTER JOIN

It is a combination of LEFT & RIGHT outer joins.

SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC FROM EMP E FULL OUTER JOIN DEPT D ON


(E.DEPTNO=D.DEPTNO);

NESTED QUERIES

A query which is written in the other query refers to nested query.

Nested query always provides its execution in the following procedure, "first executes inner query
and then executes outer query".

A query which allows to write the other query is called outer or main query whereas the query
which is written in the other query is called inner or sub query or nested query.

Maximum of 255 sub queries can be written.

CLASSIFICATION TO SUB QUERY

--------------------------------------------------------

| |

BASED ON USAGE BASED ON EXECUTION

(outer qry) - (inner qry)

1. NORMAL SUB QUERY 1.SINGLE COL-SINGLE ROW

2. CO-RELATED SUB QUERY 2.SINGLE COL-MULTIPLE ROWS


3.MULTIPLE COLS-SINGLE ROW

4.MULTIPLE COLS-MULTIPLE ROWS

A subquery can be written;

1. at WHERE clause

2. at HAVING clause

3. at FROM clause (INLINE VIEW)

4. as an Expression (SCALAR SUB QUERY)


68
Writing a subquery at WHERE clause:

A subquery can be written at WHERE clause of outer query.

output of sub query is never displayed on the screen.

output of sub query is compared at the condition of outer query, based on that comparision the
output is displayed by the outer query.

Syntax:

SELECT ............................ (outer query or main query)

FROM table1

WHERE expr operator(SELECT ................... (inner or subquery)

FROM table2

[WHERE condition]);

display empno,ename,job,sal and deptno of the employee who is

earning the maximum salary?

SELECT EMPNO,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL=(SELECT MAX(SAL) FROM


EMP);

display empno,ename,job,sal and deptno of the employee who is earning the least salary?

SELECT EMPNO,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL=(SELECT MIN(SAL) FROM


EMP);

display empno,ename,job of all those employees who are working

on a same job as of SMITH?

SELECT EMPNO,ENAME,JOB FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE
ENAME='SMITH');

display ename,job,sal of all those employees whose salary is more than the avg salary of all the
employees?

SELECT ENAME,JOB,SAL FROM EMP WHERE SAL>(SELECT AVG(SAL) FROM EMP);

display ename,job,sal of all those employees whose salary is more than the min salary of deptno
30?

SELECT ENAME,JOB,SAL FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP WHERE
DEPTNO=30);

display 2nd maximum salary?


69
SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP);

display first 3 maximum salaries?

SELECT MAX(SAL) FROM EMP

UNION ALL

SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP)

UNION ALL

SELECT MAX(SAL) FROM EMP WHERE SAL<(SELECT MAX(SAL) FROM EMP WHERE
SAL<(SELECT MAX(SAL) FROM EMP));

display ename,job,sal,deptno of all those employees who are working in RESEARCH,SALES


departments?

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE DEPTNO IN(SELECT DEPTNO FROM


DEPT WHERE DNAME IN('RESEARCH','SALES'));

NOTE: single col - multiple rows.

display ename,job,sal,deptno of all those employees whose salary is more than the min salary of
Sales Department?

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP


WHERE DEPTNO=(SELECT DEPTNO FROM DEPT

WHERE DNAME='SALES'));

display ename,job,sal,deptno of that employee who is earning the minimum salary in deptno 30?

display all those employees who are working under the other employees?

display all those employees who are working as managers to other employees?

display all those employees who are working on a job as of SMITH and salary is more than the
salary of TURNER?

writing a sub query at HAVING clause:

A subquery can be written at HAVING clause of outer query, where output returned by sub query
can be compared at the condition of outer query.

display deptno and total salary of that department who is being paid with maximum total salary?

SELECT DEPTNO,SUM(SAL) FROM EMP

GROUP BY DEPTNO

HAVING SUM(SAL)=(SELECT MAX(SUM(SAL)) FROM EMP GROUP BY DEPTNO);


70
display deptno and number of employees working of that department where maximum number of
employees are working?

SELECT DEPTNO,COUNT(*) FROM EMP

GROUP BY DEPTNO

HAVING COUNT(*)=(SELECT MAX(COUNT(*)) FROM EMP GROUP BY DEPTNO);

writing a sub query at FROM clause (INLINE VIEW):

Subquery can be written at FROM clause of outer query, where the subquery gets executed in a
line,providing its output as a view to outer query, hence it is named as Inline view.

Output given by the sub query can be manipulated by the outer query.

example:

Display the data given by the inner query?

SELECT * FROM (SELECT ENAME,JOB,SAL,DEPTNO FROM EMP);

Display the details of deptno 10 employees, from a data given by inner query?

SELECT ENAME,JOB,SAL,DNO FROM (SELECT ENAME,JOB,SAL,DEPTNO DNO FROM EMP)


WHERE DNO=10;

NOTE: In this query, DNO at inner query is alias name so it cant be used at the other clauses of
Inner query, but that alias name becomes column name for outer query, so it can be used at any
clause of outer query.

PSEUDO COLUMNS:

SYSDATE

ROWNUM

ROWID

NEXTVAL

CURRVAL

LEVEL

3 Types of files, which Oracle uses internally for its working;

1. DBF files (.dbf)

SYSTEM01.DBF:

71
This file will store the data randomly in the form of blocks, where capacity of a block can be in a
range of 4KB to 8KB.

Data in this file is stored in Encrypted form.

_________________________________________________________________

| |

| _________________________________ |

| |7369| Smith|CLERK|...........|20| |

| |

| |

| |

| 10 ACCOUNTING NEW YORK |

| |

|_________________________________________________________________|

ROWID :

This pseudo column will provide a unique ROWID for every record in a data file.

This pseudo column will be 18bytes alphanumeric type data, which provides the information
about the user_name,table_name and position of a record.

SQL> SELECT ROWID,ENAME,JOB,SAL FROM EMP;

ROWID ENAME JOB SAL

------------------ ---------- --------- ---------

AAAH5RAABAAAPB1AAA SMITH CLERK 800

AAAH5RAABAAAPB1AAB ALLEN SALESMAN 1600

AAAH5RAABAAAPB1AAC WARD SALESMAN 1250

AAAH5RAABAAAPB1AAD JONES MANAGER 2975

SQL> SELECT ROWID,DEPTNO,DNAME FROM DEPT;

ROWID DEPTNO DNAME

------------------ --------- --------------

AAAH5SAABAAAPB4AAA 10 ACCOUNTING
72
AAAH5SAABAAAPB4AAB 20 RESEARCH

AAAH5SAABAAAPB4AAC 30 SALES

NOTE :

The other database files, which are provided by Oracle are;

Temp01.dbf,Users01.dbf,Tools01.dbf,........etc

2. Control files (.ctl)

These files are used to control dbf files.

Oracle provides the following control files;

CONTROL01.CTL | online control file

CONTROL02.CTL | offline control file

CONTROL03.CTL | offline control file

All control files will store same data. At a particular instance only 1 control file will be working and
that file is called online control file, whereas other files are called offline control files.

If any 1 of these control file gets deleted, database gets trashed.

3. Log Files (.log)

These files will store the data for temporary.

Oracle provides the following log files;

REDO01.LOG

REDO02.LOG

REDO03.LOG

These files will work in the following procedure;

When 1st log file gets filled with the data then it automatically uses the 2nd log file. If 2nd log file
gets filled with the data then it uses 3rd log file. If 3rd log file gets filled with the data then it
flushes the data of 1st log file and then uses it.

Note:

All these CRD files are stored at the following path;

C:\oracle\oradata\oracle

ROWNUM :

73
It is a pseudo column which will generate the sequence of numbers.

ROWNUM in every query will start from 1, based on it, condition on this pseudo column can be
provided with relational operators

like <, <=

ROWNUM is generated with sequence of numbers after the execution of SELECT statement

display rownum, ename,job,sal,deptno of all the employees?

SELECT ROWNUM,ENAME,JOB,SAL,DEPTNO FROM EMP;

display rownum,ename,job,sal,deptno of 1st 3 employees of emp table?

SELECT ROWNUM,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE ROWNUM<=3;

SELECT ROWNUM,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE ROWNUM<3;

SELECT ROWNUM,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE ROWNUM>3;

NO ROW IS SELECTED SINCE ROWNUM STARTS ITS EXECUTION FROM 1.

SELECT ROWNUM,ENAME,JOB,SAL,DEPTNO FROM EMP WHERE ROWNUM=3;

NO ROW IS SELECTED SINCE ROWNUM STARTS ITS EXECUTION FROM 1.

SELECT ROWNUM,EMPNO,ENAME,JOB,SAL FROM EMP ORDER BY SAL DESC;

display first 3 maximum salary earning employee details?

SELECT ROWNUM,ENAME,JOB,SAL FROM (SELECT ROWNUM,ENAME,JOB,SAL FROM EMP


ORDER BY SAL DESC) WHERE ROWNUM<=3;

display all those employees whose row positions are more than 7?

SELECT RN,ENAME,JOB,SAL FROM (SELECT ROWNUM RN,ENAME,JOB,SAL FROM EMP)


WHERE RN>7;

display all those employees whose row positions are between 4 and 8?

SELECT RN,ENAME,JOB,SAL FROM (SELECT ROWNUM RN,ENAME,JOB,SAL FROM EMP)


WHERE RN BETWEEN 4 AND 8;

display all those employees whose row positions are at odd positions?

SELECT RN,ENAME,JOB,SAL FROM (SELECT ROWNUM RN,ENAME,JOB,SAL FROM EMP)


WHERE MOD(RN,2)=1;

display all those employees whose row positions are at even positions?

74
SELECT RN,ENAME,JOB,SAL FROM (SELECT ROWNUM RN,ENAME,JOB,SAL FROM EMP)
WHERE MOD(RN,2)=0;

display every 4th record employee details?

SELECT RN,ENAME,JOB,SAL FROM (SELECT ROWNUM RN,ENAME,JOB,SAL FROM EMP)


WHERE MOD(RN,4)=0;

writing a sub query as an expression (SCALAR SUB QUERY):

A subquery can be written as an expression at outer query.

It will allow a user to return data of only 1 column, hence

it is called as scalar sub query.

syntax:

SELECT expr1,expr2,........,(SELECT query) FROM table......;

display ename,job,sal and dname as scalar sub query?

SELECT ENAME,JOB,SAL,(SELECT DNAME FROM DEPT WHERE EMP.DEPTNO=DEPT.DEPTNO)


DN FROM EMP;

SOME/ANY and ALL OPERATORS:

SOME/ANY OPERATOR:

This operator will make a subquery to return more than 1 row.

This operator will work with all the relational operators.

This operator will work for OR logical operator.

=ANY

>ANY

<ANY

>=ANY

<=ANY

!=ANY

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL=ANY(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);

75
ENAME JOB SAL DEPTNO

---------- --------- -------- --------

SMITH CLERK 800 20

ADAMS CLERK 1100 20

J_ONES MANAGER 2975 20

SCOTT ANALYST 3000 20

FORD ANALYST 3000 20

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL>ANY(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);

ENAME JOB SAL DEPTNO

---------- --------- -------- --------

ALLEN SALESMAN 1600 30

WARD SALESMAN 1250 30

J_ONES MANAGER 2975 20

MARTIN SALESMAN 1250 30

BLAKE MANAGER 2850 30

CLARK MANAGER 2450 10

SCOTT ANALYST 3000 20

KING PRESIDENT 5000 10

TURNER SALESMAN 1500 30

ADAMS CLERK 1100 20

JAMES CLERK 950 30

FORD ANALYST 3000 20

MILLER CLERK 1300 10

13 rows selected.

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL<ANY(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);

ENAME JOB SAL DEPTNO


76
---------- --------- -------- --------

SMITH CLERK 800 20

ALLEN SALESMAN 1600 30

WARD SALESMAN 1250 30

J_ONES MANAGER 2975 20

MARTIN SALESMAN 1250 30

BLAKE MANAGER 2850 30

CLARK MANAGER 2450 10

TURNER SALESMAN 1500 30

ADAMS CLERK 1100 20

JAMES CLERK 950 30

MILLER CLERK 1300 10

11 rows selected.

ALL operator:

This operator will also make a subquery to return more than 1 row.

This operator will work with all the relational operators.

This operator will work for AND logical operator

=ALL

>ALL

<ALL

>=ALL

<=ALL

!=ALL

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL=ALL(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);

no rows selected

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL>ALL(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);
77
ENAME JOB SAL DEPTNO

---------- --------- -------- --------

KING PRESIDENT 5000 10

SQL>SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL<ALL(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);

no rows selected

SQL>SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL<ALL(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=10);

ENAME JOB SAL DEPTNO

---------- --------- -------- --------

SMITH CLERK 800 20

WARD SALESMAN 1250 30

MARTIN SALESMAN 1250 30

ADAMS CLERK 1100 20

JAMES CLERK 950 30

SQL> SELECT DISTINCT SAL FROM EMP WHERE DEPTNO=10;

SAL

--------

1300

2450

5000

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE SAL!=ALL(SELECT DISTINCT SAL


FROM EMP WHERE DEPTNO=20);

ENAME JOB SAL DEPTNO

---------- --------- -------- --------

ALLEN SALESMAN 1600 30

WARD SALESMAN 1250 30

MARTIN SALESMAN 1250 30

78
BLAKE MANAGER 2850 30

CLARK MANAGER 2450 10

KING PRESIDENT 5000 10

TURNER SALESMAN 1500 30

JAMES CLERK 950 30

MILLER CLERK 1300 10

9 rows selected.

display ename,job,sal,deptno of all those employees who are working on a job and deptno as of
SMITH?

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE (JOB,DEPTNO)=(SELECT JOB,DEPTNO


FROM EMP WHERE ENAME='SMITH');

NOTE: this query is getting executed based on multiple columns and single row.

display ename,job,sal,deptno of all those employees who are working on a same job and deptno
as of SMITH & TURNER?

SQL> SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE (JOB,DEPTNO)=ANY(SELECT


JOB,DEPTNO FROM EMP WHERE ENAME IN('SMITH','TURNER'));

ENAME JOB SAL DEPTNO

---------- --------- -------- --------

SMITH CLERK 800 20

ADAMS CLERK 1100 20

ALLEN SALESMAN 1600 30

WARD SALESMAN 1250 30

MARTIN SALESMAN 1250 30

TURNER SALESMAN 1500 30

6 rows selected.

NOTE: this query is getting executed based on multiple columns and multile rows.

CO-RELATED SUB QUERIES:

These queries provide different execution to nested queries i.e. corelated queries "first executes
outer query and then executes
79
inner query."

Nested queries are called uni-directional queries and corelated

sub queries are called bi-directional queries.

Corelated subqueries first executes outer query and extracts 1 row(candidate row) and that row is
given to inner query for the processing. inner query will be executed and its output is given to
outer query. if the condition at outer query is found to be true then it will display the extracted row
else row is rejected.

display ename,job,sal,deptno of all those employees whose salary is more than the avg salary of
their respective departments?

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP E WHERE SAL>(SELECT AVG(SAL) FROM EMP


WHERE DEPTNO=E.DEPTNO);

display ename,job,sal,deptno of first 3 maximum salary earning employees?

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP E WHERE 3>(SELECT COUNT(DISTINCT SAL)


FROM EMP WHERE SAL>E.SAL);

display ename,job,sal,deptno of nth maximum salary earning employee?

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP E WHERE 1=(SELECT COUNT(DISTINCT SAL)


FROM EMP WHERE SAL>E.SAL);

NOTE: to find nth maximum salary condition should be provided as n-1.

EXISTS AND NOT EXISTS OPERATOR:

EXISTS operator:

This operator will return boolean value i.e. true or false.

If condition at inner query gets satisfied then this operator will return TRUE else returns with
FALSE.

display deptno and dname of all those departments where atleast 1 employee is working?

SELECT DEPTNO,DNAME FROM DEPT D WHERE EXISTS(SELECT 'X' FROM EMP WHERE
DEPTNO=D.DEPTNO);

DEPTNO DNAME

------- --------------

10 ACCOUNTING

20 RESEARCH

30 SALES
80
NOT EXISTS :

This operator will return boolean value i.e. true or false.

If condition at inner query becomes false then this operator returns true else returns with false.

display deptno and dname of all those departments where no employees are working?

SELECT DEPTNO,DNAME FROM DEPT D WHERE NOT EXISTS(SELECT 1 FROM EMP WHERE
DEPTNO=D.DEPTNO);

DEPTNO DNAME

------- --------------

40 OPERATIONS

HIERARCHICAL QUERIES (TREE WALKING):

It is a process of creating a relationship between the rows of a table in hierarchical format i.e. tree
format.

At this concept data is arranges in the form of nodes, where nodes are classified into 3 types;

1. Root node ---- It will only 1 node

2. Child node ---- Which is expanded by the other sub nodes

3. Leaf node ---- which is not expanded by the other nodes

RDBMS does not store the data in hierarchical format.

The process of creating the natural relationship between rows in the form of parent and child,
refers to tree walking.

Syntax:

SELECT LEVEL,expr1,expr2,...........

FROM table1

[WHERE condition(s)]

START WITH condition

CONNECT BY PRIOR condition;

LEVEL : This pseudo column is used to generate the numbers as 1 for root node, 2 for sub node, 3
for sub sub nodes,...........;

START WITH condition : This clause is used to specify the condition for root node.

81
CONNECT BY PRIOR condition : This clause is used to specify the condition that creates
hierarchical relationship between rows of a table.

SQL> SELECT LEVEL,EMPNO,ENAME,MGR

2 FROM EMP

3 START WITH ENAME='KING'

4 CONNECT BY PRIOR EMPNO=MGR;

LEVEL EMPNO ENAME MGR

--------- --------- ---------- ---------

1 7839 KING

2 7566 JONES 7839

3 7788 SCOTT 7566

4 7876 ADAMS 7788

3 7902 FORD 7566

4 7369 SMITH 7902

2 7698 BLAKE 7839

3 7499 ALLEN 7698

3 7521 WARD 7698

Display employee names in the following format;

SQL> SELECT LPAD(ENAME,LENGTH(ENAME)+(LEVEL*2)-2,'*') TREE FROM EMP

2 START WITH ENAME='KING'

3 CONNECT BY PRIOR EMPNO=MGR;

TREE

------------------------------------------------------------

KING

**JONES

****SCOTT

******ADAMS

82
****FORD

******SMITH

**BLAKE

****ALLEN

****WARD

****MARTIN

CREATING A NEW TABLE FROM EXISTING TABLE:

A new table can be created from existing table to copy meta data + actual data. It will also support
to copy only meta data. To copy only meta data from existing table to a new table, it is essential
that condition should be specified as FALSE condition.
When a new table is created it includes columns with derived mathematical expressions.

Syntax:

CREATE TABLE table_name (target table name)

AS

SELECT query;

EXAMPLE 1:

COPIES META DATA + ACTUAL DATA

SQL> CREATE TABLE EMP1

2 AS

3 SELECT * FROM EMP;

Table created.

EXAMPLE 2:

COPIES ONLY META DATA

SQL> CREATE TABLE EMP2

2 AS

3 SELECT * FROM EMP WHERE 1=2;

Table created.

EXAMPLE 3:

83
COPIES REQUIRED COLUMNS FROM EMP TO EMP3 TABLE.

SQL> CREATE TABLE EMP3

2 AS

3 SELECT EMPNO,ENAME,JOB,SAL,SAL*12 ANN_SAL FROM EMP;

Table created.

EXAMPLE 4:

COPIES REQUIRED COLUMNS BASED ON CONDITION FROM EMP TO EMP3 TABLE?

SQL> CREATE TABLE EMP4

AS

SELECT ENAME,JOB,SAL,DEPTNO FROM EMP WHERE DEPTNO=20;

SQL PLUS

I) EDITING SQL QUERIES

1. L[IST] --- displays last query,which is in buffer

2. A[PPEND] --- adds the required data at the existing lines

3. R[UN] or / --- executes the last query which is in buffer

4. C[HANGE] --- modify the existing statements in last query

Syntax: C[HANGE] /old_data/new_data

5. DEL [n] --- used to delete the required lines from last qry

6. ED [file_name] --- used to edit last query which is in buffer in a

separate area. It will allow to modify multiple lines, add multiple lines, delete multiple
lines,...............etc

7. x --- it is used to make a required line ready for edit in last query, which is in buffer.

II) SAVING, RETRIEVING AND EXECUTING QUERIES

SAVE : This command is used to save a query, which is in buffer into a file. In order to store more
than 1 query into same file, it is essential that option called APPEND is used.

Syntax:

SAVE [drive:\] file1[.ext] [APPEND/REPLACE]

By default file is provided with an extension as .sql


84
In order to over write the existing file, it is essential that REPLACE option should be used.

GET : This command is used to get the queries that are stored in a file into buffer.

Syntax:

GET [drive:\] file1[.ext]

START : This command is used to execute the queries which are stored in a file one after the
other. When all the queries are executed, it will make last query available in buffer.

Syntax:

START [drive:\] file1[.ext]

note: File can be executed using @

@ [drive:\] file1[.ext]

III) SPOOL [drive:\] file[.ext]/ OFF :

This command is used to store a query and output into a file.

It stores everything used at SQL prompt into a file. It stores until spool is not set to OFF. Default
extension for a file will be created as .LST. Any extension can be provided to a file.

SPOOL --- Simultaneous Peripheral Output Online

Example:

SQL> SPOOL C:\TEST.TXT

SQL> SELECT * FROM EMP;

SQL> DESC DEPT

SQL> SELECT * FROM DEPT;

SQL> SELECT * FROM TAB;

SQL> SPOOL OFF

IV) GLOGIN.SQL : This file will be provided with an execution of all the commands and queries
which are stored in it one after the other automatically when a user enters into SQL session. In
Oracle 12c this file will be executed only for once, when a user enters into SQL session.

This file is available at the following path;

C:\ORACLE\ORA90\SQLPLUS\ADMIN

85
In Oracle 10g, this file will provide its execution when a user enter into SQL session from
operating system and it also executes the file when a user transfers the control from 1 user to
other user.

V) SUBSTITUTING VARIABLES USING & AND &&:

& : It is used to substitute a variable at different queries,for which it accepts input from a user at
the execution of a query.

Variables can be substituted in SELECT,INSERT,UPDATE, DELETE queries.

Variables can be substituted in SELECT statement at different areas, like in expressions, for table
name, at condition, and at other clauses.

SELECT ENAME,JOB,&COL1,&cOL2 FROM EMP;

SELECT ENAME,JOB,SAL FROM EMP WHERE DEPTNO=&DNO;

SELECT ENAME,JOB,SAL FROM EMP WHERE &COND;

SELECT ENAME,JOB,&COL1,&COL2 FROM EMP WHERE &COND;

SELECT * FROM &TNAME;

&& : It is used to substitute a variable at different queries, which will accept input from a user only
for once at the execution of a query. The input provided becomes constant from the second
execution.

SELECT ENAME,JOB,&&COL1,&COL2 FROM EMP;

VI) DEFINE AND UNDEFINE commands:

DEF[INE] [VAR[=VALUE]] :

This command is used to create a user defined variable, which will store the data. The variables
can be used at any query. All the variables are temporary. All the variables will be created as
CHAR type. When these variables are used it is essential that they should be preceeded by &.

EXAMPLE:

DEFINE I=10

DEFINE J=20

DEFINE K=CLERK

DEFINE M=DEPTNO

SELECT * FROM EMP WHERE DEPTNO=&I;

SELECT EMPNO,ENAME,JOB,&M FROM EMP;

86
SELECT * FROM EMP WHERE JOB='&K';

SELECT * FROM EMP WHERE DEPTNO=&J;

UNDEF[INE] <VARIABLE> :

This command is used to delete a variable from buffer. It will support to delete only 1 variable at a
time.

EXAMPLE:

UNDEF M

VII) ENVIRONMENT VARIABLES:

These variables will support to do environment settings, which will provides its effect only for
current working session.

If a user closes the session, it returns back to original settings.

Syntax:

SET variable value

1. SET HEAD[ING] ON/OFF : By default it is ON. If it is turned to OFF, the column names, which are
displayed as headings gets disabled.

2. SET FEED[BACK] ON/OFF/6/n : By default it is ON for 6 or more rows.

The confirmation about number of rows selected can be provided for less than 6 rows, when it is
set with user required n value. If it is turned to OFF, then there will be no confirmation.

3. SET VERI[FY] ON/OFF : By default it is ON. If it is turned to OFF then the confirmation about old
and new values will not be provided when variables are substituted at different queries.

4. SET SQLP[ROMPT] 'TEXT' : It is used to change the default prompt to a user required prompt.

5. SET SQLT[ERMINATOR] 'TEXT' : It is used to change the default terminating character i.e. ; to a
user required character.

6. SET PAGES[IZE] 14/n : It is used to change the page size.

7. SET LINES[IZE] 80/n : It is used to change the line size.

8. SET NUMW[IDTH] 10/n : It is used to change the default number width.

SHOW variable/ALL : This command is used to get the changed or default settings of environment
variable.

VIII) SQL REPORTS:

87
Output of SQL queries can be generated in a formatted way, which includes providing headings,
footers, group calculations etc.

It includes the following Commands;

1. TTI[TLE] text/ON/OFF : This command is used to set top title, which gets displayed on every
page. Heading separator (|) is used to set the title for mutiple lines.

2. BTI[TLE] text/ON/OFF : This command is used to set bottom title, which get displayed at the end
of every page.

3. COL[UMN] column_name Options: This command is used to provide column settings with
different options.

Options:

HEADING ---- to specify Column Alias

FORMAT ---- to displau date and numbers in formatted ways

NULL ---- used to substitute a required data at those rows of a column, where
null values are found.

PRINT ---- to hide a column

NOPRINT ---- to unhide a column.

4. BRE[AK] ON col_name [SKIP n] : This command is used to group the data on a specific column.
The column on which data is breaked on that same column it is essential that ORDER BY clause
should be used in SELECT query.

5. COM[PUTE] aggregate_function ON col_name: This command is used to perform calculations


using Aggregate functions on a specific column.

6. CLEAR COLUMN : This command is used to clear all the formats that are applied to different
columnns of a table.

Displaying and clearing column formats:

COLUMN col_name : It will display the column settings provided for a column.

COLUMN : It will display all the settings proviode to all the columns of tables.

COLUMN col_name CLEAR : It will clear the formats of a particular column.

COLUMN CLEAR : It wil also clear all the formats at once specified at different column of 1 or
more tables.

Example:

SQL> ED TEST

88
TTI 'EMPLOYEES LIST|ORACLE CORPORATION|HITECH CITY|HYDERABAD'

BTI 'ALL THE BEST|THANK YOU'

BREAK ON DEPTNO SKIP 1

COMPUTE SUM OF SAL ON DEPTNO

COL ENAME HEADING 'Emp|Name'

COL SAL HEADING 'MONTH|SALARY' FORMAT '$09,999.99'

COL COMM HEADING 'ADDL|INC' FORMAT '$09,999.99' NULL 'NO COMM'

COL DEPTNO HEADING 'DEPT|NO'

SELECT DEPTNO,ENAME,SAL,COMM FROM EMP ORDER BY DEPTNO;

SQL> @TEST

DIFFERENCES BETWEEN SQL AND SQL PLUS:

-----------------------------------------------------------------------

SQL | SQL PLUS

-----------------------------------------------------------------------

1. It is a language, which is |1. It recognizes SQL statements and

used to communicate with | sends them to server for execution.

Database Server. |

2. Data can be manipulated. |2. No Data Manipulation.

3. Commands cant be abbreviated.|3. Commands can be abbreviated.

4. Formatting is done using |4. Formatting is done using commands.

functions |

5. Every command should be |5. It is optional.


89
terminated by ; |

DATA MANIPULATION LANGUAGE (DML):

Insertion of new rows, modifications to existing rows and removing unwanted rows collectively
known as DML.

Oracle 12c supports to work with the following DML commands;

1. INSERT 2. UPDATE 3. DELETE 4. MERGE (Introduced in Oracle 12c)

1. INSERT:

This DML command is used to insert a new row in a table.

It supports to insert complete data or partial data into a table.

It supports to insert values thru constants or thru variables.

syntax:

INSERT INTO table_name[(list_of_cols)] VALUES (list_of_values);

when data related to text type and date type is provided it should be enclosed in single quotes.

When complete data is provided in a table, it is essential that number of columns in a table should
get match with number of values in a sequence.

SQL> INSERT INTO EMP VALUES(1001,'SHAREEF','CLERK',7788,'10-JAN-83',2500,500,20);

SQL> INSERT INTO EMP VALUES(1002,'AHMED','ANALYST',7698,'25-MAY-82',3400,NULL,30);

SQL> INSERT INTO EMP VALUES(1003,NULL,'CLERK',NULL,'18-JUN-82',4000,NULL,20);

INSERTING THE DATA USING VARIABLES:

SQL> INSERT INTO EMP


VALUES(&EMPNO,'&ENAME','&JOB',&MGR,'&HIREDATE',&SAL,&COMM,&DEPTNO);

Enter value for empno: 1004

Enter value for ename: RAJ

Enter value for job: CLERK

Enter value for mgr: 7788

Enter value for hiredate: 10-JAN-81

Enter value for sal: 2300

Enter value for comm: 250

90
Enter value for deptno: 10

old 1: INSERT INTO EMP


VALUES(&EMPNO,'&ENAME','&JOB',&MGR,'&HIREDATE',&SAL,&COMM,&DEPTNO)

new 1: INSERT INTO EMP VALUES(1004,'RAJ','CLERK',7788,'10-JAN-81',2300,250,10)

1 row created.

SQL> /

Enter value for empno: 1005

Enter value for ename: KIRAN

Enter value for job: MANAGER

Enter value for mgr: 7839

Enter value for hiredate: 17-DEC-82

Enter value for sal: 4500

Enter value for comm: NULL

Enter value for deptno: 30

old 1: INSERT INTO EMP


VALUES(&EMPNO,'&ENAME','&JOB',&MGR,'&HIREDATE',&SAL,&COMM,&DEPTNO)

new 1: INSERT INTO EMP VALUES(1005,'KIRAN','MANAGER',7839,'17-DEC-82',4500,NULL,30)

1 row created.

INSERTING PARTIAL VALUES:

INSERT INTO EMP(EMPNO,ENAME,SAL) VALUES(1007,'SUNIL',6500);

INSERT INTO EMP(EMPNO,ENAME,SAL) VALUES(&EMPNO,'&ENAME',&SAL);

Enter value for empno : 1008

Enter value for ename : RAKESH

Enter value for sal : 4500

INSERTING MULTIPLE ROWS IN A TABLE (Writing a sub query under INSERT query):

To store multiple rows at a time in a single table, it is essential that INSERT query is associated
with SELECT statement.

syntax:

91
INSERT INTO table_name[(list_of_cols)] SELECT query;

SQL> INSERT INTO BONUS SELECT ENAME,JOB,SAL,COMM FROM EMP;

14 rows created.

SQL> INSERT INTO BONUS(ENAME,SAL) SELECT ENAME,SAL FROM EMP;

14 rows created.

SQL> INSERT INTO BONUS SELECT ENAME,JOB,SAL,COMM FROM EMP WHERE DEPTNO=20;

5 rows created.

INSERTING MULTIPLE ROWS IN MULTIPLE TABLES:

INSERT ALL:

This command is often called as ETL command(E-Extraction,

T-Transformation,L-Loading).

This command is provided to with 2 syntaxes to insert multiple rows in multiple tables.

1. Conditional syntax

2. Unconditional syntax

1. INSERT ALL (with conditional syntax)

SYNTAX: INSERT ALL

WHEN condition1 THEN INTO table1[(list_of_cols)]

[ WHEN condition2 THEN INTO table2[(list_of_cols)]

...................

ELSE

INTO table[(list_of_cols)] ]

SELECT query;

example:

insert the rows of emp table distributing the data according to condition in different tables.
deptno=10-----emp1

deptno=20-----emp2

and other departments---emp3

92
SQL> INSERT ALL

2 WHEN DEPTNO=10 THEN INTO EMP1

3 WHEN DEPTNO=20 THEN INTO EMP2

4 ELSE

5 INTO EMP3

6 SELECT * FROM EMP;

14 rows created.

SQL> INSERT ALL

2 WHEN DEPTNO=10 THEN INTO EMP1(EMPNO,ENAME,SAL,DEPTNO)

3 WHEN DEPTNO=20 THEN INTO EMP2(EMPNO,ENAME,SAL,DEPTNO)

4 ELSE

5 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)

6 SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP;

14 rows created.

SQL> INSERT ALL

2 WHEN DEPTNO=10 THEN INTO EMP1(EMPNO,ENAME,SAL,DEPTNO)

3 WHEN DEPTNO=20 THEN INTO EMP2(EMPNO,ENAME,SAL,DEPTNO)

4 ELSE

5 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)

6 SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP WHERE DEPTNO=20;

5 rows created.

INSERT ALL (UNCONDITIONAL SYNTAX):

INSERT ALL

INTO table1[(list_of_cols)] [VALUES(list_of_values)]

INTO table2[(list_of_cols)] [VALUES(list_of_values)]

............

SELECT query;
93
SQL> INSERT ALL

2 INTO EMP1

3 INTO EMP2

4 INTO EMP3

5 SELECT * FROM EMP;

42 rows created.

SQL> INSERT ALL

2 INTO EMP1(EMPNO,ENAME,SAL)

3 INTO EMP2(EMPNO,ENAME,SAL)

4 INTO EMP3(EMPNO,ENAME,SAL)

5 SELECT EMPNO,ENAME,SAL FROM EMP;

42 rows created.

SQL> INSERT ALL

2 INTO EMP1(EMPNO,ENAME,SAL,DEPTNO)

3 INTO EMP2(EMPNO,ENAME,SAL,DEPTNO)

4 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)

5 SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP WHERE DEPTNO=20;

15 rows created.

SQL> INSERT ALL

2 INTO EMP1(EMPNO,ENAME,SAL,DEPTNO)

3 INTO EMP2(EMPNO,ENAME,SAL,DEPTNO) VALUES(1001,'XYZ',1000,20)

4 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)

5 SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP;

42 rows created.

UPDATE:

This DML command is used to modify the existing rows of a table.

It supports to modify single or multiple cols w.r.to single or multiple rows.


94
It supports to modify the data with values or with mathematical expressions.

It does not support to use the same column for modification with different data for more than
once.

syntax:

UPDATE table_name SET col1=value/expr[,col2=value/expr,col3=value/expr,........] [WHERE


condition(s)];

1. modify the salary of SMITH from 800 to 1800?

SQL> UPDATE EMP SET SAL=1800 WHERE ENAME='SMITH';

1 row updated.

2. modify the job of SCOTT from ANALYST to MANAGER and SALARY from 3000 to 4500?

SQL> UPDATE EMP SET JOB='MANAGER',SAL=4500 WHERE ENAME='SCOTT';

1 row updated.

3. update the salaries of deptno 20 with an increment of 8%?

SQL> UPDATE EMP SET SAL=SAL+SAL*8/100 WHERE DEPTNO=20;

5 rows updated.

4. update the salary of BLAKE with an increment of 1000 and

prvide the comm with 12% of salary?

SQL> UPDATE EMP SET SAL=SAL+1000,COMM=SAL*12/100 WHERE ENAME='BLAKE';

1 row updated.

NOTE: comm has been calculated with 12% on the previous salary,since UPDATE command will
modify the columns at a time.

SQL> UPDATE EMP SET SAL=SAL+1000,COMM=(SAL+1000)*12/100 WHERE ENAME='BLAKE';

5. update the salary of MANAGERS with 12% increment,

the salary of CLERKS with 10% increment,

and others with 8%?

SQL> UPDATE EMP SET


SAL=DECODE(JOB,'MANAGER',SAL+SAL*12/100,'CLERK',SAL+SAL*10/100,SAL+SAL*8/100);

Writing a sub query under UPDATE command:

95
A sub query can be written in UPDATE command,

where the data returned by subquery will be updated with outer query.

SYNTAX:

UPDATE table_name SET col1=(SELECT query) [,col2=(SELECT query),......]

[WHERE condition(s)];

1. update the job of SMITH with the job of SCOTT?

SQL> UPDATE EMP SET JOB=(SELECT JOB FROM EMP WHERE ENAME='SCOTT') WHERE
ENAME='SMITH';

1 row updated.

2. update the job of FORD with the job of CLARK and salary with the salary of KING?

SQL> UPDATE EMP SET JOB=(SELECT JOB FROM EMP WHERE ENAME='CLARK'),

2 SAL=(SELECT SAL FROM EMP WHERE ENAME='KING') WHERE ENAME='FORD';

3. update the salaries of deptno 20 with average salary of deptno 30?

SQL> UPDATE EMP SET SAL=(SELECT AVG(SAL) FROM EMP WHERE DEPTNO=30) WHERE
DEPTNO=20;

5 rows updated.

DELETE :

This DML command is used to remove unwanted rows from a table.

It will support to delete all the rows or supports to delete the rows on conditional basis. It deletes
the rows for temporary.

syntax:

DELETE FROM table_name [WHERE condition(s)];

1. delete all the rows of dept table?

SQL> DELETE FROM DEPT;

2. delete all those rows of emp table who are working as CLERK,ANALYST?

SQL> DELETE FROM EMP WHERE JOB IN('CLERK','ANALYST');

5 rows deleted.

96
3. delete all those employees who have been hired in the year 81 and they do not earn
commission?

SQL> DELETE FROM EMP WHERE HIREDATE LIKE '%81' AND COMM IS NULL;

6 rows deleted.

WRITING A SUB QUERY UNDER DELETE COMMAND:

A subquery can be written under DELETE command, where the output returned by sub query can
be used to make the condition at outer query, where outer query deletes all those rows that gets
match with condition.

syntax:

DELETE FROM table_name WHERE expr operator(SELECT query);

1. delete all those employees who are working on a same job as of SMITH?

SQL> DELETE FROM EMP WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME='SMITH');

4 rows deleted.

2. delete all those employee whose salary is more than the average salary of deptno 20?

SQL> DELETE FROM EMP WHERE SAL>(SELECT AVG(SAL) FROM EMP WHERE DEPTNO=20);

3. delete all those employees who are working in SALES,RESEARCH departments?

SQL> DELETE FROM EMP WHERE DEPTNO IN(SELECT DEPTNO FROM DEPT WHERE DNAME
IN('RESEARCH','SALES'));

11 rows deleted.

MERGE :

It is introduced thru Oracle 12c.

This command is used to join the data from 2 tables into a single table.

This command is also called as ETL command.

This command is often called as UPSERT, which means it is a combination of UPDATE+INSERT.

This command works with the help of 4 Clauses.

1. USING clause

2. ON clause

3. WHEN MATCHED clause

97
4. WHEN NOT MATCHED clause

syntax:

MERGE INTO table1 [table1_alias]

USING table2 [table2_alias]/SELECT query

ON (condition)

WHEN MATCHED THEN

UPDATE query

WHEN NOT MATCHED THEN

INSERT query;

example:

SQL> CREATE TABLE EMPB

2 AS

3 SELECT EMPNO,ENAME,SAL FROM EMP WHERE 1=2;

Table created.

SQL> SELECT * FROM EMPB;

no rows selected

SQL> INSERT INTO EMPB VALUES(7788,'SCOTT',1000);

1 row created.

SQL> INSERT INTO EMPB VALUES(7369,'SMITH',2000);

1 row created.

SQL> SELECT * FROM EMPB;

EMPNO ENAME SAL

-------- ---------- --------

7788 SCOTT 1000

7369 SMITH 2000

SQL> MERGE INTO EMPB E1

2 USING (SELECT EMPNO,ENAME,SAL,SAL*12 AN_SAL FROM EMP) E2


98
3 ON (E1.EMPNO=E2.EMPNO)

4 WHEN MATCHED THEN

5 UPDATE SET E1.SAL=E2.SAL

6 WHEN NOT MATCHED THEN

7 INSERT VALUES(E2.EMPNO,E2.ENAME,E2.AN_SAL);

14 rows merged.

TRANSACTION CONTROL LANGUAGE (TCL):

This language is used to make the transactions that are made on 1 or more tables either for
permanent or supports to cancel those transactions.

This language supports to work with the following commands;

COMMIT

ROLLBACK

SAVEPOINT

COMMIT : This TCL command is used to make the transactions that are made on 1 or more tables
for permanent. Inserted rows, updated rows becomes permanent in a table and deleted rows are
permanently gets removed from tables.

Syntax:

COMMIT;

ROLLBACK [TO save_point] : This TCL command is used to cancel the transactions that are made
on 1 or more tables. It also supports to cancel the partial transactions. Inserted rows, updated
rows will get cancel from tables and deleted rows gets recalled back into table.

Syntax:

ROLLBACK [ TO save_point_name ];

SAVEPOINT save_point_name : This TCL command is used to create blocks for transactions,
where those block names can be used to cancel partial transactions. Random selection of
Savepoints cant be made for cancel of transactions.

Syntax:

SAVEPOINT save_point_name;

Save points are temporary i.e. when transactions gets rollback it even removes the savepoint
names from memory.

99
NOTE:

SET AUTOCOMMIT ON/OFF/n : Default this enviroment variable is OFF.

If it is turned to ON then after each transaction it will automatically make the transaction
permanent. If n value is specified then it will automatically make the transactions permanent after
every n transactions.

SET TRANSACTION READ ONLY/WRITE; : This environment variable should be applied as 1st
statement, which means before applying any DML command the transaction should be set. Once
the transaction is set to READ ONLY then it will not allow a user to perform DML operations into
any table until and unless the transaction is not READ WRITE.

REPRESENTATION OF DATA:

Data in Oracle gets represented based on the following 3 keypoints;

1. Data Name

2. Data Type

3. Data Size

1. Data Name : It is often called as "Column name" or "Identifier" or "field" or "Attribute".

Data name is used to store the data.

Rules to be followed before using column name in a table:

1. Col Name can be min of 1 char and max of 30 chars

2. Col Name cant have blank spaces, spl characters (except underscore)

3. Col Name should not start with numbers.

4. Col Name should not be a reserved of Oracle.

5. Cols in a table should always be unique.

6. Cols which are created in 1 table, the same can be created in other table.

2. Data Type & Data Size :

Data type explains regarding type of data to be stored in a dataname.

i. NUMBER[(size)] :

This data type will support to store the data which is purely of numerics.

Size to this data type is optional.


100
When size is not specified then it assigns the Max size as 38, from which 16 are reserved for
decimals or scale and 22 are reserved for precision.

ii. CHAR(size):

This datatype will support to store any type of data.

This datatype provides fixed memory i.e. static memory, which results to wastage of memory.

This datatype will support to specify the size with min of 1 and max of 2000 bytes.

iii. VARCHAR or VARCHAR2(size):

This datatype will support to store any type of data.

This datatype provides variable length memory i.e. Dynamic memory which results to
saving of memory.

This dataype will support to specify the size with min of 1 character and max of 4000 chars.

iv. DATE :

This datatype will support to store date type data, with a format of DD-MON-YY.

v. TIMESTAMP:

This datatype will support to store date and time.

When this datatype is provided and if time is not mentioned then it will provide the time as 12am

DATA DEFINITION LANGUAGE (DDL):

This language will support to create,alter,drop the database objects like


TABLES,VIEWS,SYNONYMS,CLUSTERS,INDEXES,PROCEDURES,FUNCTIONS,PACKAGES etc.

This language includes the following Commands;

CREATE,ALTER,TRUNCATE,RENAME,DROP

*** All DDL commands are auto commit;

CREATING A TABLE:

Table is defined as logical structure which contains data in the form of rows and columns.

1. A Table name can be with min of 1 char and max of 30 chars.

2. A Table can have min of 1 col and max of 1000 cols.

3. Tables names should always be unique.

4. No limit for rows.

101
5. A record is stored in the form of block, where capacity of block is between 4kb to 8kb.

6. To create a table, object type TABLE should be used.

syntax:

CREATE TABLE <table_name>

(col1 col1_def,col2 col2_def,

col3 col3_def,col4 col4_def,

.....................)

Examples:

create a table called student which stores rollno,sname,addr,cno.

CREATE TABLE student

(rollno NUMBER(4),sname VARCHAR2(12),addr VARCHAR2(15),cno NUMBER(10));

DEFAULT:

This keyword is used to specify the default value to a column.

If data is not provided by a user then it stores default value.

If data is provided then it gives priority to user defined value.

create a table called bank which stores acno,ahn,addr,doa and amount?

CREATE TABLE bank

(acno NUMBER(4),ahn VARCHAR2(12),addr VARCHAR2(15),

amount NUMBER(8) DEFAULT 500,doa DATE DEFAULT SYSDATE);

CREATE TABLE bank1

(acno NUMBER(4),ahn VARCHAR2(12),addr VARCHAR2(15),

amount NUMBER(8) DEFAULT 500,doa TIMESTAMP DEFAULT SYSDATE);

Practice:

1. Create a table called stud that stores rno,sname,mm,pm,cm.

calculate for total and average marks?

2. create a table called employ that stores eno,en,gender?

eno en gender
102
1001 x Male

1009 y Male

1003 z FEMALE

1012 a Male

1004 b FEMALE

update the gender from male to female and vice versa.

3. create a table called product which stores pcode, pname,qty,price. Calculate for gbill,disc,nbill?

calculate for disc based on different products,

if product is PENS then provide the disc of 14%

if product is ERASERS then provide the disc of 10%

and other products with 8%?

4. Student Marks

Rno Sname M P C Rno TM AM

10 x 78 56 89 12 -- --

19 y 56 34 78 15 -- --

12 z 44 89 65 19 -- --

17 a 45 67 82 10 -- --

15 b 45 89 67 17 -- --

ALTER :

This ddl command is used to add new column,modify and drop existing columns. To work with
this command ALTER TABLE command provides the following options;

ADD --- To add the columns

MODIFY --- to modify the columns

DROP --- to drop the columns

To ADD/MODIFY single column:

ALTER TABLE table_name ADD/MODIFY col_name data_type[(size)];

To ADD/MODIFY multiple columns:

103
ALTER TABLE table_name ADD/MODIFY (col_name1 data_type[(size)],col_name2
data_type[(size)],........);

To Drop single column:

ALTER TABLE table_name DROP COLUMN col_name;

To Drop Multiple Columns:

ALTER TABLE table_name DROP (col1[,col2,col3,....]);

ALTER TABLE table_name SET UNUSED(col1[,col2,col3,....]);

TRUNCATE:

This DDL command is used to delete all the rows from a specified table for permanent.

TRUNCATE TABLE table_name;

Differences between DELETE and TRUNCATE commands;

-------------------------------------------------------------

DELETE | TRUNCATE

-------------------------------------------------------------

1. It is DML command |1. It is DDL command.

2. Deletes all rows |2. Deletes all rows

3. Rows can be deleted |3. No conditional deletion

on condition |

4. Deletes rows for |4. Deletes all rows for permanent

temporary |

RENAME src_table TO target_table;

This DDL command is used to rename a table.

Example:

RENAME emp TO employ;

104
DROP : This DDL command is used to drop the objects like tables, views, synonyms, indexes,
procedures, functions,...etc

To drop a table the following syntax is used:

Syntax:

DROP TABLE table_name;

Example:

DROP TABLE emp;

Data Dictionary

Data Dictionary store meta data.

Meta data refers to Data about data.

Oracle 12c supports to work with the 444 predefined tables available in data dictionary.

All the predefined tables are read only tables, which means a user cant perform DML operations
manually.

All the dictionary tables are automatically gets updated.

All the predefined tables are stored as rows to the other predefined table and it is called
dict(dictionary).

TAB : This predefined table stores the information about the following objects.

TAB = TABLES + VIEWS + SYNONYMS + CLUSTERS

USER_CATALOG (synonym is CAT) : This predefined table stores the information about the
following objects.

CAT = TABLES + VIEWS + SYNONYMS + SEQUENCES

USER_TABLES (synonym is TABS)

USER_TAB_COLUMNS (synonym is COLS)

USER_OBJECTS : This dictionary table will store the information about different objects which are
created in Oracle like TABLES,VIEWS,PROCEDURES,FUNCTIONS....etc

DATA CONSTRAINTS

Constraint is defined as rule or condition.

Constraints will make Oracle to prevent invalid data entry into a table.

Constraints can be specified at the creation of table or after the creation of table.
105
Constraints which are created for columns can be provided with unique constraint names, which
can be of user defined name or predefined name.

When constraint name is not defined by a user, Oracle provides the constraint name as
SYS_Cn(where n is a unique integer).

To specify user defined constraint name, it is essential that CONSTRAINT keyword is used
followed by constraint name.

Constraint names should always be unique.

Data constraints are classified into 3 types;

1. Domain Integrity Constraints

2. Entity Integrity Constraints

3. Referential Integrity Constraints

1. Domain Integrity Constraints: These constraints are created only at column level. These
constraints can be used in a table for any number of times. It includes the following constraints.

NOT NULL, CHECK

NOT NULL : Normally a column in a table will support to store null values. When this constraint is
specified then it will

not allow a user to store null values, but it supports to store duplicates.

CHECK : This constraint will support to specify user defined condition. If data is stored beyond
the condition then it is rejected.

EXAMPLE:

CREATE TABLE EMPLOY

(ENO NUMBER(4) NOT NULL,EN VARCHAR2(12) CONSTRAINT EN_NN NOT NULL,DESIG


VARCHAR2(14) CHECK(DESIG IN('CLERK','ANALYST','OPERATOR')),PAY NUMBER(8)
CONSTRAINT PAY_CHK CHECK(PAY BETWEEN 17000 AND 22000));

2. ENTITY INTEGRITY CONSTRAINTS:

These constaints can be created at 2 levels.

1. Column Level

2. Table Level

These constraints include;

1. UNIQUE

106
2. PRIMARY KEY

1. UNIQUE :

This constraint can be used for any number of columns.

This constraint will not allow a user to store duplicates but will allow to store null values.

Creating UNIQUE constraint at Column level:

SQL> CREATE TABLE EMPLOY1

2 (ENO NUMBER(3) UNIQUE,

3 EN VARCHAR2(12) CONSTRAINT EN_UK UNIQUE);

Table created.

Creating UNIQUE constraint at Table Level:

SQL> CREATE TABLE EMPLOY2

2 (ENO NUMBER(3),

3 EN VARCHAR2(12),

4 UNIQUE(ENO),CONSTRAINT EN_UK1 UNIQUE(EN));

Table created.

COMPOSITE UNIQUE KEY:

Multiple columns set with 1 UNIQUE constraint refers to Composite Unique key.

Composite UNIQUE key can be created only at table level.

Behaviour of Composite UNIQUE key, is that one column can have duplicates and its
corresponding column should contain unique values(which means if all the columns contain
duplicates then the data is rejected).

SQL> CREATE TABLE STUD

2 (RNO NUMBER(3),

3 SN VARCHAR2(12),

4 CLASS NUMBER(2),UNIQUE(RNO,CLASS));

Table created.

SQL> SELECT * FROM STUD;

RNO SN CLASS
107
-------- ------------ --------

1X 7

1Y 8

2Z 7

2A 8

3B

4C

D 7

8 rows selected.

PRIMARY KEY:

It is a combination of NOT NULL + UNIQUE, which means this constraint will not allow a user to
store duplicates and null values.

A table can have max of only 1 primary key.

A table can have any number of columns associated with indirect primary keys i.e. a column will
be set with 2 constraints NOT NULL UNIQUE. Indirect primary keys can be for any number of
columns in a table.

Creating PRIMARY KEY at column level:

CREATE TABLE employ3

(eno NUMBER(3) CONSTRAINT eno_pk PRIMARY KEY,

en VARCHAR2(12));

Creating PRIMARY KEY at table level:

CREATE TABLE employ4

(eno NUMBER(3),

en VARCHAR2(12),

CONSTRAINT eno_pk1 PRIMARY KEY(eno));

Creating Direct And Indirect Primary keys at column level:

CREATE TABLE employ5

108
(eno NUMBER(3) PRIMARY KEY,

en VARCHAR2(12) NOT NULL UNIQUE,

job VARCHAR2(14) NOT NULL UNIQUE);

Creating Direct and Indirect Primary keys at Table Level:

CREATE TABLE employ6

(eno NUMBER(3),

en VARCHAR2(12) NOT NULL,

job VARCHAR2(14) NOT NULL,

PRIMARY KEY(eno),UNIQUE(en),UNIQUE(job));

Composite Primary Key:

Multiple columns set with 1 primary key refers to composite primary key.

Composite primary key is also created only at table level.

Behaviour of composite primary key will not allow a user to store null values into any columns,
but will allow to store duplicates only when its corresponding column contains unique data.

SQL> CREATE TABLE STUD1

2 (RNO NUMBER(3),

3 SN VARCHAR2(12),

4 CLASS NUMBER(2),PRIMARY KEY(RNO,CLASS));

SQL> SELECT * FROM STUD1;

RNO SN CLASS

-------- ------------ --------

1X 7

1Y 8

2Z 7

2A 8

3.REFERENTIAL INTEGRITY CONSTRAINTS:

This constraint is used to create relationships between the tables.

109
Oracle supports to implement the following relationships

between tables

one to one direct implementation

one to many direct implementation

many to many indirect implementation

This constraint includes FOREIGN KEY.

FOREIGN KEY:

This constraint will support to store null values and duplicates.

This constraint will support to store valid values that are present in another column, which should
be set with PRIMARY KEY or UNIQUE key.

FOREIGN KEY and reference key column can be with same names or with different names, but it
is essential that there data types and data size should be same.

FOREIGN KEY is called bi-directional key, since it interacts between the tables in the following
way;

i. at insertion it works from child to parent and

ii. at deletion it works from parent to child.

FOREIGN KEY and reference key can be in different table or they can be in same table. if they are
in same table then it is called SELF REFERENCED TABLE or Reflexive relation.

FOREIGN KEY can be created at column level or can be created at table level.

FOREIGN KEY column is referred valid values of other column using REFERENCES clause
followed by 2 options;

1. ON DELETE CASCADE -- When data from parent table is deleted it automatically


deletes the same record from child table. This process of updating data is called Data
Consistency.

2. ON DELETE SET NULL -- When data from parent table is deleted it automatically
makes the foreign key column at child table with null values.

Creating 1 to 1 relationship:

CREATE TABLE REGISTRATION

(REGNO NUMBER(4) PRIMARY KEY,SNAME VARCHAR2(12),

SUBJECT VARCHAR2(12),FEE NUMBER(7,2));

110
CREATE TABLE RESULTS

(HTNO NUMBER(4) PRIMARY KEY,RES VARCHAR2(5),RNK NUMBER(7),MARKS NUMBER(3),


FOREIGN KEY(HTNO) REFERENCES REGISTRATION(REGNO) ON DELETE CASCADE);

Creating 1 to Many relationship:

CREATE TABLE DEPTS

(DNO NUMBER(2) PRIMARY KEY,DNAME VARCHAR2(12) UNIQUE);

CREATE TABLE EMPS

(ENO NUMBER(4) PRIMARY KEY,EN VARCHAR2(12),

DESIG VARCHAR2(14),DEPTNO NUMBER(2),

FOREIGN KEY(DEPTNO) REFERENCES DEPTS(DNO) ON DELETE SET NULL);

SELF REFERENCED TABLE (REFLEXIVE RELATION)

CREATE TABLE EMP1

(ENO NUMBER(4) PRIMARY KEY,

EN VARCHAR2(12),MCODE NUMBER(4),

FOREIGN KEY(MCODE) REFERENCES EMP1(ENO) ON DELETE SET NULL);

DEFERRED CONSTRAINTS

These constraints will get check when the transaction is committed.

By default a constraint will get check immediately after the transaction related to Insert,Update
transaction.

When these constraints are created and if any data is beyond the constraints then it will make the
transactions Rolled back. If data is found to be according to the rule of a constraint then it makes
that data for permanent.

To create these constraints DEFERRABLE clause is used, which is followed by INITIALLY


IMMEDIATE / INITIALLY DEFERRED.

By default it is set with INITIALLY IMMEDIATE.

Example:

CREATE TABLE EMPLOY2

(ENO NUMBER(4) CONSTRAINT EMPNO_UK UNIQUE DEFERRABLE INITIALLY DEFERRED,

EN VARCHAR2(12));
111
CREATING CONSTRAINTS ON EXISTING TABLE:

Constraints can be created on the columns of existing table, using ALTER TABLE command.

NOT NULL : This constraint is to be created on the column of existing table using MODIFY option
of ALTER TABLE command.

ALTER TABLE table_name MODIFY col_name data_type[(size)] [CONSTRAINT constraint_name]


NOT NULL [DISABLE];

CHECK,UNIQUE,PRIMARY KEY,FOREIGN KEY are the constraints which can be created on


columns of existing table using ADD option of ALTER TABLE command.

ALTER TABLE table_name ADD [CONSTRAINT constraint_name]

constraint_type(col1[,col2,....]) [DISABLE];

EXAMPLE:

CREATE TABLE EMP2

(ENO NUMBER(4),

EN VARCHAR2(12),JOB VARCHAR2(14),SAL NUMBER(8,2));

ALTER TABLE EMP2 MODIFY ENO NUMBER(4) NOT NULL;

ALTER TABLE EMP2 ADD CHECK(JOB IN('CLERK','ANALYST'));

ALTER TABLE EMP2 ADD UNIQUE(EN);

DROPING THE CONSTRAINTS:

The constraints which are created on the columns of 1 or more tables can be dropped in the
following way;

ALTER TABLE table_name DROP PRIMARY KEY / UNIQUE(col1[,col2,....]) / CONSTRAINT


constraint_name [CASCADE];

NOTE:

CASCADE option is to be specified when primary key referred column is to be dropped.

ALTER TABLE employ DROP CONSTRAINT EN_NN;

ALTER TABLE employ3 DROP PRIMARY KEY;

ALTER TABLE REGISTRATION DROP PRIMARY KEY CASCADE;

ALTER TABLE employ1 DROP UNIQUE(ENO);

DISABLE / ENABLE THE CONSTRAINTS:


112
The constraints which are created on different columns of a table can be disabled or can be
enabled.

When constraint is disabled then data in that column can be stored beyond the rule of a
constraint. The disabled constraint cannot

be enabled until the data beyond the constraint is not deleted.

ALTER TABLE table_name DISABLE/ENABLE PRIMARY KEY / UNIQUE (col1[,col2,col3,......]) /


CONSTRAINT constraint_name;

VIEWING THE CONSTRAINTS INFORMATION:

USER_CONSTRAINTS:

This predefined table will provide the detail information about the constraints created on different
columns and at different tables.

It provides CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME etc.

CONSTRAINT_TYPE REPRESENTATION

NOT NULL C

CHECK C

PRIMARY KEY P

UNIQUE U

FOREIGN KEY R

SELECT TABLE_NAME,CONSTRAINT_NAME,CONSTRAINT_TYPE FROM USER_CONSTRAINTS;

USER_CONS_COLUMNS:

This predefined table will provide the information about the constraints created on different
columns like CONSTRAINT_NAME,TABLE_NAME, COLUMN_NAME etc

SELECT TABLE_NAME,CONSTRAINT_NAME,COLUMN_NAME FROM USER_CONS_COLUMNS;

SELECT T1.TABLE_NAME,T1.CONSTRAINT_NAME,T1.CONSTRAINT_TYPE,T2.COLUMN_NAME

FROM USER_CONSTRAINTS T1,USER_CONS_COLUMNS T2

WHERE T1.TABLE_NAME=T2.TABLE_NAME;

NORMALIZATION

113
It is a process of splitting a single table into 2 or more tables to avoid redundancy and promote
integrity.

OR

It is a process of deciding tables required in a database, columns in each table and relationship
between tables is known as Normalization.

Normalization is used to store the data in simple forms

Advantages of Normalization:

1. Minimizes Redundancy

2. Reduces Complexity

3. Easy maintainance

4. Making Tables ready to perform joins and sub queries.

A table can be normalized in different ways often called Normal Forms;

1. First Normal Form (1NF)

2. Second Normal Form (2NF)

3. Third Normal Form (3NF)

4. Boyce Codd Normal Form (BCNF)

5. Fourth Normal Form (4NF)

6. Fifth Normal Form (5NF)

First Normal Form (1NF)

Tables are said to be in First normal form when it satisfies the following rules.

1. Isolate the repeating groups by adding a common column.

2. Every column should be atomic.

Unnormalized table

order_no order_date cno cname caddr cphone items

1 11-JUL-09 A15 xyz AMRPT1234 p10 pens 120

e18 erasers 134

b15 books 163

2 11-JUL-09 F17 abc SRNGR 6543 e18 erasers 78


114
s13 scales 200

3 19-JUL-09 A15 xyz AMRPT1234 S13 scales 150

p10 pens 110

The above unnormalized table can be normalized with 1st rule of first normal form in the following
procedure;

CUSTOMER (p)

p/k

cno cname caddr cphone

A15 xyz AMRPT1234

F17 abc SRNGR 6543

ORDERS (c)

p/k f/k

order_no order_date items cno

1 11-JUL-09 p10 pens 120 A15

e18 erasers 134

b15 books 163

2 11-JUL-09 e18 erasers 78 F17

s13 scales 200

3 19-JUL-09 S13 scales 150 A15

p10 pens 110

In the above table, there is a difficulty in accessing the items column, hence it should be
normalized with 2nd rule of first normal form.

2. Every Column should be atomic.

ITEMS_ORDERED

(order_no and item_no -- p/k)

f/k

order_no order_date item_no item_name qty cno

1 11-JUL-09 p10 pens 120 A15


115
1 11-JUL-09 e18 erasers 134 A15

1 11-JUL-09 b15 books 163 A15

2 11-JUL-09 e18 erasers 78 F17

2 11-JUL-09 s13 scales 200 F17

2. SECOND NORMAL FORM (2NF)

The tables are said to be in second normal form when it satisfies the following rules.

1. Tables should be in 1NF

2. Non key columns should be made to depend on whole key but not part of a key.

Orders1

p/k f/k

Order_no Order_date cno

1 05-JUN-09 A15

2 12-JUN-09 F17

Items

f/k

item_no item_name qty order_no

p10 pens 120 1

e18 erasers 134 1

b15 books 163 1

e18 erasers 78 2

s13 scales 200 2

3. THIRD NORMAL FORM (3NF)

The tables are said to be in third normal form when it satisfies the following rules.

1. Tables should be in 2NF

2. no transitive dependency

Unnormalized table:

WORKERS
116
p/k

wid skill bonus

e15 Elect 1400

m13 Mech 2000

c18 Comp ---

p12 --- 1500

In this table there are 2 functional dependencies;

Fd : wid----->skill..............1

Fd : wid----->bonus..............2

So the above table can be normalized in the following way;

Workers1

p/k

skill bonus

Elect 1400

Mech 2000

Workers2

p/k f/k

wid skill

e15 Elect

m13 Mech

CREATING PARTITIONS

Partitioning addresses key issues in supporting very large tables and indexes by letting them to
decompose into small manageable pieces called Partitions.

SQL queries and DML statements need not be changed in order to access partitioned tables.

After creating the partitions DDL statements can access individual partitions rather than on entire
table.

117
Each partition of a table have same logical structure such as Column Names, Data Types and
Constraints.

Advantages Of Partitions:

1. Partitioning enables data management operations like Index Creation, Backup / Recovery at the
partition level rather than on entire table. This will result in reducing time for these operations.

2. Partitioning improves query performance.

3. Partitioning can reduce maintainance operations.

4. Partitioning can be implemented into Existing table without making changes in the existing
application.

Partition key:

Partition key is a column, which specifies the row to a related partition.

Partition key can be on minimum of 1 column and maximum of 16 Columns.

Oracle 12c automatically directs INSERT,UPDATE and DELETE operations to related partitions.

Partition key cant be created on Pseudo Columns like ROWID, LEVEL etc.

Partition key will not allow a user to store NULL values.

Types of Partitions:

Partitions are classified into the following types;

1. Range Partition

2. List Partition

3. Hash Partition

4. Composite Partition

1. Range Partition : It is the most common type of partitioning used that will map the data to
partitions based on Range of values.

This partition will allow each partition with a non inclusive upper bound for a partition.

Upper bound of 1st partition will become lower bound of next partition.

The 1st partition will be provided with automatic lower bound.

This partition uses "VALUES LESS THAN" clause to specify the partition range.

CREATE TABLE student

118
(rno NUMBER(3),sname VARCHAR2(12),age NUMBER(3))PARTITION BY RANGE (age)

(PARTITION P1 VALUES LESS THAN(10),

PARTITION P2 VALUES LESS THAN(20),

PARTITION P3 VALUES LESS THAN(30));

TO ADD A NEW PARTITION

ALTER TABLE student ADD PARTITION P4 VALUES LESS THAN(40);

TO TRUNCATE A PARTITION

ALTER TABLE student TRUNCATE PARTITION P2;

TO DROP A PARTITION

ALTER TABLE student DROP PARTITION P2;

TO RENAME A PARTITION

ALTER TABLE student RENAME PARTITION P2 TO P9;

RETRIEVING THE DATA FROM PARTITIONS:

SELECT * FROM STUDENT;

SELECT * FROM STUDENT PARTITION (P1);

SELECT * FROM STUDENT PARTITION (P3);

NOTE: PARTITIONS CANT BE ADDED WITH VALUES OF ALREADY EXISTING RANGE.

LIST PARTITION:

This partition will allow to store rows that are ungrouped and unrelated data in each partition.

This partition will use VALUES clause to specify list of values to each partition.

CREATE TABLE SALES

(SNO NUMBER(3),SNAME VARCHAR2(12),STATE VARCHAR2(15))

PARTITION BY LIST(STATE)

(PARTITION P1 VALUES('AP','HP'),

PARTITION P2 VALUES('UP','KERALA'));

VIEWING THE PARTITION INFORMATION

USER_TAB_PARTITIONS
119
USER_PART_TABLES

USER_PART_KEY_COLUMNS

USER CREATION

To create a user, modify the password of existing user and to drop a user it is essential that the
existing user in Oracle should have DBA privileges.

Oracle provides a user with DBA privileges to perform some special operations in a database
(SYSTEM/MANAGER)

Syntax for creating a new user:

CREATE USER <user_name> IDENTIFIED BY <password>;

Syntax for changing the password of existing user:

ALTER USER <user_name> IDENTIFIED BY <new_password>;

PASSWORD [user_name] : This command is used to change the password being in current login
or can change the password from administration.

User name specification will have only when password is being changed from administration.

If a password is being changed from current logged in user, then it confirms for old password.

Syntax for droping a user:

DROP USER <user_name> [CASCADE];

VIEWING USERS INFORMATION

ALL_USERS : This predefined table will provide the user names, user ids, date and time on which
user is created.

SELECT * FROM ALL_USERS;

SELECT USERNAME FROM ALL_USERS;

NOTE:

CONN[ECT] [USER_NAME[/PASSWORD]] : This command is used to switch between users.

DISCONN[ECT] : This command is used to disconnect from a user.

SHOW USER : This command is used to display user name of currently logged in user.

PREDEFINED ROLES:

Role is defined as one through which set of permissions are granted.

120
Oracle supports to work with the following Roles.

CONNECT

RESOURCE

DBA

When a new user is created, it will not be provided with any of the following privileges;

like connecting to that user, using resources and performing special operations.

To provide the permissions for a newly created user or existing users, the above mentioned Roles
should be granted.

GRANT role_name TO user1[,user2,user3,.....]/PUBLIC;

To cancel the granted permissions;

REVOKE role_name FROM user1[,user2,user3,......]/PUBLIC;

examples:

SQL> CONN SYSTEM/MANAGER

SQL> CREATE USER SHAREEF IDENTIFIED BY SQLSCHOOL;

SQL> CREATE USER SWATHI IDENTIFIED BY STUDENT;

SQL> CREATE USER NIKHIL IDENTIFIED BY STUDENT;

SQL> CRAETE USER INFY IDENTIFIED BY MNC;

SQL> ALTER USER SHAREEF IDENTIFIED BY INST;

SQL> DROP USER INFY;

SQL> DROP USER SCOTT CASCADE;

SQL> GRANT CONNECT,RESOURCE TO SHAREEF,SWATHI,NIKHIL;

SQL> GRANT DBA TO SWATHI;

SQL> REVOKE DBA FROM SWATHI;

SQL> REVOKE CONNECT,RESOURCE FROM SHAREEF;

DATA CONTROL LANGUAGE (DCL)

This language is used to give the rights on database objects to get them access from user to
other user. It also supports to cancel those granted rights.

It includes GRANT,REVOKE commands;


121
GRANT : This DCL command is used to grant the privileges on different database objects existing
in one user to get them access from other users.

Syntax:

GRANT privilege[(list_of_cols)] / ALL ON <object_name>

TO user1[,user2,user3,........] / PUBLIC [ WITH GRANT OPTION];

privilege refers to the operations that are to be performed on a granted objects.

ALL refers to granting all the privileges.

PUBLIC refers to granting all the privileges to all the valid users existing in Oracle database.

WITH GRANT OPTION refers to the granting of privilege to other users from a user who has been
received with the permission from other users.

REVOKE : This DCL command is used to cancel the privileges from different database objects
that are granted to the other users.

Syntax:

REVOKE privilege[(list_of_cols)] / ALL ON <object_name>

FROM user1[,user2,user3,.......] / PUBLIC;

SCOTT SHAREEF SWATHI NIKHIL

select

EMP----------------------->

select,insert

DEPT------------------------------------->

select,insert(grade,losal)

SALGRADE--------------------------------->

ALL

BONUS--------------------> ALL

---------------------------------------> ALL

------------------------------------------------------->

select select

DUMMY-------------------->------------------------------->

122
example:

SQL> CONN SCOTT/TIGER

SQL> GRANT SELECT ON EMP TO SHAREEF;

SQL> GRANT SELECT,INSERT ON DEPT TO SWATHI;

SQL> GRANT SELECT,INSERT(GRADE,LOSAL) ON SALGRADE TO SWATHI;

SQL> GRANT ALL ON BONUS TO SHAREEF,SWATHI,NIKHIL;

SQL> GRANT SELECT ON DUMMY TO SHAREEF WITH GRANT OPTION;

SQL> CONN SHAREEF/INST

SQL> SELECT * FROM SCOTT.EMP;

SQL> SELECT * FROM SCOTT.DUMMY;

SQL> GRANT SELECT ON SCOTT.DUMMY TO NIKHIL;

SQL> CONN SWATHI/STUDENT

SQL> SELECT * FROM SCOTT.DEPT;

SQL> INSERT INTO SCOTT.DEPT VALUES(50,'MARKETING','CALIFORNIA');

SQL> SELECT * FROM SCOTT.SALGRADE;

SQL> CONN NIKHIL/STUDENT

SQL> SELECT * FROM SCOTT.BONUS;

SQL> INSERT INTO SCOTT.BONUS VALUES('RAJ','CLERK',1200,NULL);

SQL> SELECT * FROM SCOTT.DUMMY;

SQL> CONN SCOTT/TIGER

SQL> REVOKE SELECT ON EMP FROM SHAREEF;

SQL> REVOKE ALL ON BONUS FROM SHAREEF,SWATHI,NIKHIL;

SQL> REVOKE SELECT,INSERT ON SALGRADE FROM SWATHI;

VIEWING THE PERMISSIONS GRANTED ON DIFFERENT OBJECTS TO DIFFERENT USERS;

USER_TAB_PRIVS_MADE

USER_TAB_PRIVS_RECD

USER_COL_PRIVS_MADE
123
USER_COL_PRIVS_RECD

CREATING USER DEFINED ROLES:

Role is defined as the one thru which set of permissions are granted.

To create a role it is essential that the user should have DBA privileges.

Syntax:

CREATE ROLE <role_name>;

After storing all the privileges in a role, this role can be granted to different users.

SQL> CONN SYSTEM/MANAGER

SQL> CREATE ROLE MYROLE;

SQL> CONN SCOTT/TIGER

SQL> GRANT SELECT,INSERT ON DEPT TO MYROLE;

SQL> GRANT SELECT,INSERT(GRADE,LOSAL) ON SALGRADE TO MYROLE;

SQL> CONN SWATHI/STUDENT

SQL> GRANT SELECT,INSERT,UPDATE ON STUD TO MYROLE;

SQL> CONN SYSTEM/MANAGER

SQL> CREATE USER SUNIL IDENTIFIED BY SQLSCHOOL;

SQL> GRANT CONNECT,RESOURCE TO SUNIL;

SQL> GRANT MYROLE TO SUNIL;

SQL> CONN SUNIL/SQLSCHOOL

SQL> SELECT * FROM SCOTT.DEPT;

SQL> SELECT * FROM SWATHI.STUD;

DROPING A ROLE:

To drop a role it is essential that a user should have DBA privileges.

Syntax:

DROP ROLE role_name;

Example:

SQL> CONN SYSTEM/MANAGER


124
SQL> DROP ROLE MYROLE;

VIEWING THE ROLES INFORMATION:

USER_ROLE_PRIVS --------> Roles granted to current user

ROLE_ROLE_PRIVS --------> Roles which are granted to Roles

ROLE_SYS_PRIVS --------> System privileges granted to roles

ROLE_TAB_PRIVS --------> Table privileges granted to roles

SESSION_ROLES ---------> Roles which the user currently has enabled.

CREATING SYNONYMS

Synonym is a database object, which can be created for table or view, where from they can be
referred with that name.

Synonym is a dependent object whereas table is independent object, which means if a table is
dropped then synonym stops its working. If a table is recalled back then synonym will start its
working.

Synonym is like creating a permanent alias name for a table or view.

It provides its advantage when object has a frequent usage with different queries.

Synonym is classified into 2 types;

1. Private Synonym : It is created being in a user, which provides its working within that user,
hence it is named as private synonym.

2. Public Synonym : This synonym is created from a user, which has got DBA privileges. When
public synonym is created and if the same object gets accessed from other user, table name
should not be used as qualifier.

Syntax:

CREATE [PUBLIC] SYNONYM synonyn_name FOR [user.]object;

Creating private synonyms:

SQL> CONN SCOTT/TIGER

SQL> CREATE SYNONYM sg FOR salgrade;

SQL> SELECT * FROM sg;

SQL> SELECT * FROM salgrade;

SQL> DELETE FROM sg WHERE GRADE=5;

125
Creating public synonyms:

SQL> CONN SYSTEM/MANAGER

SQL> CREATE PUBLIC SYNONYM s1 FOR scott.salgrade;

SQL> CONN SCOTT/TIGER

SQL> GRANT SELECT ON salgrade TO NIKHIL;

SQL> CONN NIKHIL/STUDENT

SQL> SELECT * FROM scott.salgrade;

SQL> SELECT * FROM s1;

VIEWING SYNONYM INFORMATION:

TAB & CAT : These predefined tables will store only about private synonym names with their type
of object.

USER_SYNONYMS : This predefined table will provide the detail information about the user
created private synonyms.

SELECT SYNONYM_NAME,TABLE_NAME FROM USER_SYNONYMS;

ALL_SYNONYMS : This predefined table will provide the detail information about the private &
public synonyms.

SELECT OWNER,TABLE_OWNER,SYNONYM_NAME,TABLE_NAME FROM ALL_SYNONYMS


WHERE TABLE_NAME='SALGRADE';

DROPING A SYNONYM:

DROP [PUBLIC] SYNONYM synonym_name;

PUBLIC synonyms can be dropped from a user, which has got DBA privileges.

SQL> CONN SYSTEM/MANAGER

SQL> DROP PUBLIC SYNONYM s1;

SQL> CONN SCOTT/TIGER

SQL> DROP SYNONYM sg;

NOTE:

Private synonyms created in one user can be provided with privileges to get access from other
users, where synonym name should also be preceeded with user name as qualifier.

SQL> CONN SCOTT/TIGER


126
SQL> GRANT SELECT ON SG TO NIKHIL;

SQL> CONN NIKHIL/STUDENT

SQL> SELECT * FROM SCOTT.SG;

CREATING SEQUENCES

Sequence is a database object, which is stored in database server and it is used to


generate the sequence of numbers.

Syntax:

CREATE SEQUENCE seq_name

[INCREMENT BY 1 / n]

[START WITH n]

[NOMINVALUE / MINVALUE n]

[NOMAXVALUE / MAXVALUE n]

[NOCYCLE / CYCLE]

[NOCACHE / CACHE n];

When a sequence is created with no user specified values then sequence will start generating the
numbers from 1 and ends with 10 power 27.

INCREMENT BY 1 / n : By default a sequence is incremented by 1. When this clause is used it will


allow a user to specify the increment either with +ve or -ve value. Any interval can be specified for
increment. If +ve value is specified it generates the sequence of numbers in Ascending order. If
-ve values is specified it generates the sequence of numbers in Descending order.

START WITH n : This clause is used to specify the start value of a sequence.

It gets executed only for once. Start value should be >=minvalue and <=maxvalue.

NOMINVALUE : It is a default minvalue which gets set for a sequence.

If a sequence is in ascending order min value is 1.

If a sequence is in descending order min value is 10 power -26

NOMAXVALUE : It is a default maxvalue which gets set for a sequence.

If a sequence is in ascending order max value is 10 power 27

If a sequence is in descending order max value is -1

MINVALUE n : It is used to specify min value of a sequence.


127
MAXVALUE n : It is used to specify max value of a sequence.

NOCYCLE : It is a default option which is set for a sequence and that sequence will be not
reusable.

CYCLE : It is used to make a sequence repeat with respect to gerarating the numbers between min
value to max value and vice versa.

CACHE n : It will support to create a buffer to store n number of values

To interact with the sequence to generate the numbers, 2 pseudo columns plays and important
role.

NEXTVAL ---- generates next value of a sequence

CURRVAL ---- displays current value of a sequence

NEXTVAL & CURRVAL can be used;

1. at SELECT statement

2. at INSERT,UPDATE statement

3. at Outer most queries

Restriction on NEXTVAL & CURRVAL;

1. Cant be used at DELETE command

2. Cant be used at Inner queries

3. Cant be used with DISTINCT operator

4. Cant be used at Group By Clause

EXAMPLE 1:

SQL> CREATE SEQUENCE sn1;

SQL> SELECT sn1.NEXTVAL FROM DUAL;

SQL> /

SQL> /

SQL> SELECT sn1.NEXTVAL FROM EMP;

EXAMPLE 2:

SQL> CREATE SEQUENCE sn2

START WITH 100

128
INCREMENT BY 5

MINVALUE 50

MAXVALUE 150;

SQL> SELECT sn2.NEXTVAL FROM DUAL;

SQL> /

SQL> /

EXAMPLE 3:

SQL> CREATE SEQUENCE sn3

START WITH 100

INCREMENT BY -5

MINVALUE 50

MAXVALUE 150;

SQL> SELECT sn3.NEXTVAL FROM DUAL;

Populating the Sequence to a table:

SQL> CREATE TABLE emps

(eno NUMBER(4),en VARCHAR2(12));

SQL> CREATE SEQUENCE sn4

START WITH 1001

INCREMENT BY 3

MINVALUE 1000

MAXVALUE 1050

CYCLE

CACHE 3;

SQL> INSERT INTO emps VALUES(sn4.NEXTVAL,'&en');

ALTERING A SEQUENCE:

Sequence which is created can be altered w.r.to minvalue, maxvalue, increment by value... etc. It
does not support to change the START value.

129
Syntax:

ALTER SEQUENCE sequence_name

INCREMENT BY n

MINVALUE n

MAXVALUE n ......;

DROPING A SEQUENCE:

A sequence which is created can be dropped using DROP SEQUENCE command.

DROP SEQUENCE seq_name;

DROP SEQUENCE sn1;

VIEWING THE SEQUENCES INFORMATION:

USER_SEQUENCES : This predefined table provides the detail information about the sequences
which are created in a database, which includes Sequence name,start value, min value,
maxvalue,........ etc.

SQL> SELECT SEQUENCE_NAME,MIN_VALUE,MAX_VALUE,INCREMENT_BY,LAST_NUMBER


FROM USER_SEQUENCES;

CREATING VIEWS

It is a virtual table or creates a window like structure through which we can allow related users to
view or modify related data.

Any modifications made through a view automatically updates the base table.

View is a database object , which will store a query in compiled format, hence it is called "Stored
Query".

Advantages of views:

1. Provides high security

2. Improves performance

3. Network traffic gets reduces

4. Shortens SQL queries

5. Supports to perform summarized calculation fastly

6. Supports to INSERT/UPDATE/DELETE related data

7. We can retrieve the data from many tables


130
Differences between Tables and views:

---------------------------------------------------------------------------

Tables | Views

-----------------------------------------------------------------------------

1. Contains data |1. No data

2. Independent Object |2. Dependent Object

3. No. Of Tables are limited |3. No Limit

4. Supports to Insert/Update/Delete |4. Supports to Insert/Update/Delete

any data | related data

5. Can have any trigger |5. It creates only Insteadof trigger

Types of Views:

1. Simple views

2. Read only views

3. Check option views

4. Complex views

5. Force views

6. Materialized views

1. Simple views:

A view which is created in a single table refers to simple view.

These views will support to modify only when it contains all mandatory columns of base table.

These views will not contain group functions, mathematical expressions....etc.


131
Syntax:

CREATE [ OR REPLACE ] [ FORCE / NOFORCE ] VIEW view_name

AS

SELECT query

[WITH READ ONLY / WITH CHECK OPTION];

note:

1. When base table is dropped, view will stop its working.

2. When base table is back in database, view will start its working.

Examples:

Create a view v1 that stores a query on emp table for empno,ename,job,sal?

CREATE VIEW V1

AS

SELECT EMPNO,ENAME,JOB,SAL FROM EMP;

SELECT * FROM V1;

INSERT INTO V1 VALUES(1001,'X','CLERK',2000);

MODIFY THE EXISTING VIEW V1 ADD DEPTNO INTO IT?

CREATE OR REPLACE VIEW V1

AS

SELECT EMPNO,ENAME,JOB,SAL,DEPTNO FROM EMP;

SELECT * FROM V1;

Create view v2 that stores a query for empno,ename,sal,deptno of all those employees related to 2
dept?

CREATE VIEW V2

AS

SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP WHERE DEPTNO=20;

SELECT * FROM V2;

INSERT INTO V2 VALUES (1002,'Y',2000,20);

132
INSERT INTO V2 VALUES (1003,'Z',3000,30);

READ ONLY VIEWS:

When a view is created as Read only view, it will not allow a user to perform DML operations
through a view. A keyword called "WITH READ ONLY" should be associated.

Create a read only view v3 that stores a query for empno,ename,sal,deptno of emp table?

CREATE VIEW V3

AS

SELECT EMPNO,ENAME,SAL,DEPTNO FROM EMP

WITH READ ONLY;

SELECT * FROM V3;

CHECK OPTION VIEWS:

These views will support to insert the data into base table only for those records that get match
with the condition mentioned at SELECT query.

An option called "WITH CHECK OPTION" is used.

create a check option view v4 that stores a query on emp table for empno,ename,deptno of 20
dept employees?

CREATE VIEW V4

AS

SELECT EMPNO,ENAME,DEPTNO FROM EMP WHERE DEPTNO=20

WITH CHECK OPTION;

INSERT INTO V4 VALUES(2001,'A',20);

INSERT INTO V4 VALUES(2002,'B',30); INVALID RECORD SINCE DEPTNO IF BEYOND THE


CONDITION OF SELECT QUERY.

SELECT * FROM V4;

COMPLEX VIEWS:

A view is said to be complex view, when it contains any of the following;

1. Group Functions

2. Group By clause

133
3. Joins

4. Mathematical Expressions

5. DISTINCT operator

By default complex view is not updatable view.

CREATE VIEW V5

AS

SELECT deptno,SUM(sal) TS FROM emp GROUP BY deptno;

SELECT * FROM V5;

CREATE VIEW V6

AS

SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC FROM EMP,DEPT WHERE


EMP.DEPTNO=DEPT.DEPTNO;

SELECT * FROM V6;

CREATE VIEW V7

AS

SELECT EMPNO,ENAME,SAL,SAL*12 A_SAL FROM EMP;

SELECT * FROM V7;

CREATE VIEW V8

AS

SELECT DISTINCT DEPTNO FROM EMP;

SELECT * FROM V8;

FORCE VIEWS:

By default view is NOFORCE view.

Force views are created on a table and column that which does not exist.

CREATE FORCE VIEW V9

AS

SELECT * FROM STUDENT;

134
CREATE FORCE VIEW V10

AS

SELECT EMPNO,ENAME,JOB,SAL,TAX FROM EMP;

To view the errors occured at the creation of Force view;

SHOW ERRORS VIEW <view_name>

SHOW ERRORS VIEW V9

VIEWING THE INFORMATION ABOUT VIEWS:

TAB & CAT : These predefined tables will provide object names i.e. view names and object type as
view.

USER_VIEWS : This table will provide the view name & the query which is stored in a view.

SELECT VIEW_NAME,TEXT FROM USER_VIEWS;

MATERIALIZED VIEW:

These views will store the compiled query and its output.

These views are created from SYS user.

These views are created using MATERIALIZED VIEW option.

Prior to Oracle 12c it was called SNAPSHOT.

When materialized view is created on a table, where table should contain PRIMARY KEY.

Example:

SELECT DEPTNO,COUNT(*) NOE FROM EMP GROUP BY DEPTNO;

When this query gets executed, it includes the following steps;

1. Checks the syntax

2. Compiles the query

3. Execution plan is generated

4. Executed

i. It takes the rows into buffer

ii. It sorts the data

iii. It will create a group on each deptno

135
iv. COUNT function will count number of employees in each group

v. output is displayed.

All the above steps are avoided when materialized views are created, whereas 1st 3 steps are
avoided when standard views are created.

Syntax:

CREATE MATERIALIZED VIEW <view_name>

AS

SELECT .......... FROM user_name.object_name......;

OR

CREATE SNAPSHOT <view_name>

AS

SELECT ......... FROM user_name.object_name.......;

SQL> CONN SCOTT/TIGER

SQL> CREATE TABLE EMPT

AS

SELECT * FROM EMP;

SQL> CONN / AS SYSDBA

SQL> ALTER TABLE SCOTT.EMPT ADD PRIMARY KEY(EMPNO);

SQL> CREATE MATERIALIZED VIEW mv1

AS

SELECT * FROM SCOTT.EMPT;

SQL> INSERT INTO SCOTT.EMPT VALUES(1001,'XYZ','ANALYST',......,30);

SQL> SELECT * FROM SCOTT.EMPT; (15 ROWS)

SQL> SELECT * FROM SCOTT.MV1; (14 ROWS)

To update a materialized view w.r.to the original table or base table, the following package is used,
with a procedure REFRESH();

Syntax:

EXECUTE DBMS_MVIEW.REFRESH('materialized view name');


136
Ex:

EXECUTE DBMS_MVIEW.REFRESH('mv1');

SELECT * FROM mv1;

VIEWING MATERIALIZED INFORMATION:

USER_MVIEWS : This predefined table provides the information of materialized view.

CREATING INDEXES

CREATING CLUSTERS

BACKUP AND RECOVERY

LARGE OBJECTS

137

You might also like