SQL Material
SQL Material
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.
1. Data Query or Retrieval Language (DQL or DRL) : This language will support to retrieve the data
from a database in different procedures.
2. Data Manipulation Language (DML) : Insertion of new rows, Modification of existing rows,
Removing unwanted rows collectively known as DML.
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
DEMONSTRATION TABLES:
2
Oracle provides the following 5 demonstration tables.
c:\Oracle\Ora90\sqlplus\demo
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
This language is used to retrieve the data in different ways from a database.
3. Joins : It is a process of joining the data from 2 or more tables always producing a new
table.
Syntax:
[ 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.
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.
examples:
COLUMN ALIASES:
Column alias will provide its affect only in the output of a query.
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.
OR
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;
1. Magnitude 2. ASCII
| |
| |
| |
| |
comparision to string and date type date should be always in single quotes.
Operators:
IN,BETWEEN,IS,LIKE,DISTINCT,SOME/ANY
5
We can combine special operators with NOT logical operator.
OR
OR
OR
display ename,sal,deptno of all those employees who are working in 10,30 depts?
display ename,job,sal of all those employees who are not working as managers?
OR
display ename,sal and deptno of all those employees whose 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;
Literal is constant value, which does not get change at the execution of a query.
Row ------ X
DESC DUAL
12+19
---------
31
ADD_NO
---------
31
144 31 91
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;
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.
OR
display all those employees who are not earning the comm?
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.
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.
3. display all those employees whose names are starting with J and Ending with S?
6. display ename,sal of all those employees whose salary ends with 00?
7. display ename,job,sal,hiredate of all those employees who have been hired in those months
which starts with A?
9. display ename,deptno of all those employees whose names does not containt 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 '\';
SELECT ename FROM emp WHERE ename LIKE '%\_%' ESCAPE '\';
4. When multiple columns are used with DISTINCT operator, it eliminates the record only if all the
columns contain duplicates.
To eliminate NULL value the query can be written in the following way.
DEPTNO JOB
--------- ---------
10 CLERK
10 MANAGER
10 PRESIDENT
20 ANALYST
20 CLERK
20 MANAGER
30 CLERK
30 MANAGER
30 SALESMAN
11
9 rows selected.
To Arrange the data in descending order, option called DESC should be used.
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.
OR
display ename,job, sal of all the employees arranging job in ascending order.
display ename,job,sal,comm,deptno of all the employees arranging sal in ascending order using
column position?
1 2 3 4 5
12
display ename,job,sal of all the employees arranging job,sal in ascending order based on their
column positions?
display ename,job,sal,comm,deptno of all the employees arranging job is ascending order and sal
in descending order based on column positions?
display ename,job,sal,comm,deptno of all the employees arranging job is descending order and
sal in ascending order based on column positions?
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?
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".
OR OR
Predefined Functions are those functions which are provided by software. These functions are
classified into 2 types;
or or
13
These functions will process These functions will process
Functions)
3.Date Functions
or
6.General Functions
(NVL,NVL2,COALESCE,NULLIF,CASE expr,
DECODE)
These functions will take arguments of numeric type and returns value of numeric type.
ABS(-89)
--------
89
ABS(-19)
---------
19
19
14
19
19
ABS(78)
---------
78
SQRT(16)
---------
RES
---------
2.8284271
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.
ROUND(1234.5678,2)
15
------------------
1234.57
ROUND(1234.5638,2)
------------------
1234.56
ROUND(1234.5678,3)
------------------
1234.568
ROUND(1234.5678,1)
------------------
1234.6
ROUND(1234.5678,0)
------------------
1235
ROUND(1234.5678)
----------------
1235
ROUND(1234.3678)
----------------
1234
-------------------
1200
ROUND(5678.123,-2)
------------------
5700
ROUND(6758.123,-3)
------------------
7000
ROUND(6789.123,-4)
------------------
10000
ROUND(1234.567,-4)
------------------
ROUND(1234.7998,3)
------------------
1234.8
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.
TRUNC(1234.5678,2)
------------------
1234.56
TRUNC(1234.5678,3)
------------------
1234.567
TRUNC(1234.5678,0)
------------------
1234
TRUNC(1234.5678,-2)
-------------------
1200
TRUNC(5678.1234,-2)
-------------------
5600
18
SQL> SELECT TRUNC(5678.1234,-4) FROM DUAL;
TRUNC(5678.1234,-4)
-------------------
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.
SIN(30)
---------
-.9880316
SIN(30*3.14/180)
----------------
.4997701
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.
---------------
1235
CEIL(1234.5678)
---------------
1235
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.
FLOOR(1234.5678)
----------------
1234
FLOOR(-1234.0000)
------------------
-1234
FLOOR(-1234.0010)
-----------------
-1235
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.
LENGTH('COMPUTER')
-----------------
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.
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.
LOWER('C
--------
computer
3. UPPER(text) : This function will convert the text from lower case to upper case.
UPPER('C
--------
COMPUTER
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
LTRIM('C
--------
COMPUTER
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.
RTRIM('C
--------
COMPUTER
RTR
---
XYZ
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.
TRIM('CO
23
--------
COMPUTER
TRI
---
EVE
TRIM
----
EVEL
TRIM
----
LEVE
TRIM(LEAD
---------
123459999
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.
SUB
---
24
PUT
10. INITCAP(text) : This function will convert initial characters of a given string to Capital letters.
INITCAP('COMPUTERSOFTWAREHYDERABADTECHNO
----------------------------------------
11. REPLACE(text1,text2,text3) : This function will search for text2 in text1 and if it is found then
replaces text3.
REPLACE(
--------
COMPUTER
12. INSTR(text1,text2) : This function will search for text2 in text1 and returns position of that
string else returns with 0.
INSTR('COMPUTER','PUT')
-----------------------
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.
LPAD('COMP
----------
**COMPUTER
25
SQL> SELECT LPAD('COMPUTER',15,'*') FROM DUAL;
LPAD('COMPUTER'
---------------
*******COMPUTER
LPAD('CO
--------
COMPUTER
LPAD(
-----
COMPU
**
***
****
*****
LPAD('*',GRADE,'*')
-------------------------------------------------
**
***
****
*****
-------
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.
RPAD('COMP
----------
COMPUTER**
RPAD(LPAD('C
------------
**COMPUTER**
SYSDATE: This pseudo column will return server date and time, where time is hidden.
DD-MON-YY
SYSDATE
---------
23-JUN-09
27
Internally date type data is stored in the following format;
Internally Date type data is represented in numbers, so it can be performed with arithmetic
operations, which includes;
SYSDATE+1
---------
05-JUL-09
SYSDATE-3
---------
16-MAY-09
28
17-NOV-81 06-DEC-81 03-NOV-81
14 rows selected.
DAYS
---------
10415.723
10350.723
10348.723
10309.723
10130.723
10280.723
DAYS
---------
10416
10351
10349
10310
Display ename,job,sal and experience of those employees whose experience is more than 28
years?
2 WHERE ROUND((SYSDATE-HIREDATE)/365)>28;
These functions are used to perform operations over date type data.
ADD_MONTH
---------
23-SEP-09
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 whose exp is more than 27 years;
3. LAST_DAY(date) : This function will display last date based on a month specified in a given
date.
LAST_DAY(
---------
30-JUN-09
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.
NEXT_DAY(
---------
25-JUN-09
31
SQL> SELECT NEXT_DAY(SYSDATE,'MON') FROM DUAL;
NEXT_DAY(
---------
29-JUN-09
NEXT_DAY(
---------
30-JUN-09
NEXT_DAY(
---------
25-JUN-09
5. ROUND(date[,format]) : This function will round a given date based on a specified months and
years.
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.
It is a process of converting the data stored with one type to the other type.
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
DATE VARCHAR2
NUMBER VARCHAR2
'16'+'29'
---------
45
33
'28'+56
---------
84
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.
year 009
of year 9
number 06
day WED
format 05
format 17
TWENTY FOUR
(st,nd,rd,th) 24th
TO_CHAR(SYSDATE,'DD-
-------------------
4-JUN-2009 05:20:12
TO_CH
-----
17:20
TO_CHAR(SYSDATE,'DAYDD-MONT
---------------------------
TO_CHAR(SYS
-----------
175-06-2009
TO_CHAR(SYSDATE,'DYDDD-MON-YEAR')
36
-------------------------------------------------------
TO_CHAR(S
---------
JUNE
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.
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.
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.
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.
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.
$2,975.00
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.
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.
TO_NUMBER('28')
---------------
28
TO_DATE('date'[,format]) : This function will convert the date type data stored in text format into
date type.
SYSDATE-TO_DATE('10-FEB-09')
----------------------------
134.73708
TO_DATE('24-APR-09')-TO_DATE('10-FEB-09')
-----------------------------------------
73
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.
43
BLAKE MANAGER 2850 4
====>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.
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.
expr2 & expr3 can be substituted with any type of data i.e. numbers or text
====>COALESCE(expr1,expr2,expr3,expr4,...............) :
This function will search for null values in expr1, if finds substitutes expr2, if expr2 contains null
values substitutes expr3,.................etc.
====>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
44
====>CASE expr : Case expression will allow to compare the data with multiple conditions
providing different resultant values.
syntax:
CASE expr
.................
ELSE
default_result ]
END [alias_name]
examples:
display ename,job,sal,increment the sal with different percentages on the categories of job.
SELECT ENAME,JOB,SAL,
CASE job
ELSE
sal*8/100
display ename,job,sal,deptno increment the sal with different percentages on the categories of
deptno.
SELECT ENAME,JOB,SAL,deptno,
CASE DEPTNO
====>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.
example:
display ename,job,sal, increment the sal with different percentages on the categories of job.
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.
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,...........) :
====>LEAST(val1,val2,val3,..........) :
This function will find the least value among the set of values.
1 -1 0
These funtions will process multiple rows at a time and returns 1 value.
AGGREGATE FUNCTIONS:
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.
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.
47
OR
OR
SUM(SAL)
--------
29025
AVG(SAL)
--------
2073.214
display the total comm being paid among all the employees?
SUM(COMM)
---------
2200
AVG(COMM)
---------
550
MAX(SAL)
48
--------
5000
MIN(SAL)
--------
800
count the number of employees who are being paid with salary?
count the number of employees who are being paid with comm?
display total salary and avg salary of all those employees who are working in deptno 10,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?
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?
2 GROUP BY DEPTNO;
2 WHERE DEPTNO=20
3 GROUP BY DEPTNO;
DEPTNO SUM(SAL)
-------- --------
20 10875
50
2 GROUP BY JOB;
JOB SUM(SAL)
--------- --------
ANALYST 6000
CLERK 4150
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
display deptno,job,and total salary being paid on each deptno and job?
GROUP BY DEPTNO,JOB;
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:
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
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?
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?
GROUP BY DEPTNO
ROLLUP(expr1[,expr2,expr3,........]) :
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?
GROUP BY ROLLUP(DEPTNO,JOB);
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,........]) :
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.
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
2* GROUP BY CUBE(DEPTNO,JOB)
SQL> /
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
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.
1. UNION
2. UNION ALL
55
3. INTERSECT
4. MINUS
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:
JOB
---------
MANAGER
PRESIDENT
CLERK
JOB
---------
CLERK
MANAGER
56
ANALYST
CLERK
ANALYST
JOB
---------
SALESMAN
SALESMAN
SALESMAN
MANAGER
SALESMAN
CLERK
6 rows selected.
UNION
OUTPUT:
ANALYST
CLERK
MANAGER
PRESIDENT
UNION ALL
JOB
57
---------
MANAGER
PRESIDENT
CLERK
CLERK
MANAGER
ANALYST
CLERK
ANALYST
8 rows selected.
INTERSECT
JOB
---------
CLERK
MANAGER
MINUS
JOB
---------
PRESIDENT
UNION
OUTPUT:
CLERK
MANAGER
PRESIDENT
SALESMAN
UNION
JOB
-----------
ACCOUNTING
CLERK
MANAGER
OPERATIONS
PRESIDENT
RESEARCH
SALES
UNION ALL
JOB
59
---------
ANALYST
ANALYST
CLERK
CLERK
CLERK
MANAGER
MANAGER
PRESIDENT
2 UNION
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.
or
i. Equi Join
2. Outer Joins
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.
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?
2 FROM EMP,DEPT
3 WHERE EMP.DEPTNO=DEPT.DEPTNO;
OR
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
3 WHERE E.DEPTNO=D.DEPTNO;
OR
2 WHERE E.DEPTNO=D.DEPTNO;
OR
WHERE E.DEPTNO=D.DEPTNO;
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?
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
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.
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
WHERE E.DEPTNO=D.DEPTNO(+);
SELECT EMPNO,ENAME,JOB,DNAME,LOC
WHERE D.DEPTNO=E.DEPTNO(+);
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;
SELECT EMPNO,ENAME,JOB,DNAME,LOC
WHERE E.DEPTNO(+)=D.DEPTNO;
NOTE:
1. Outer join operator can be specified at left or right side of a joining condition.
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?
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?
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.
3 WHERE E.EMPNO=M.MGR;
13 rows selected.
65
ANSI JOINS
OR
These joins are introduced thru Oracle 12c, Which supports to join the data by using keywords
specifying them at FROM clause of SELECT statement.
1. NATURAL JOIN
2. CROSS JOIN
3. outer joins
Syntax:
SELECT .........................
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.
2. CROSS JOIN:
66
Display ename,job,sal,dname,loc,grade of all the employees using CROSS JOIN?
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.
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 and grade of all the employees using JOIN....ON clause?
SELECT M.EMPNO,M.ENAME,M.MGR,E.ENAME
outer joins:
67
SELECT EMPNO,ENAME,JOB,SAL,DNAME,LOC FROM EMP E RIGHT OUTER JOIN DEPT D
ON(E.DEPTNO=D.DEPTNO);
NESTED QUERIES
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.
--------------------------------------------------------
| |
1. at WHERE clause
2. at HAVING clause
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:
FROM table1
FROM table2
[WHERE condition]);
display empno,ename,job,sal and deptno of the employee who is earning the least salary?
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?
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);
UNION ALL
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 whose salary is more than the min salary of
Sales Department?
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?
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?
GROUP BY DEPTNO
GROUP BY DEPTNO
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 details of deptno 10 employees, from a data given by inner query?
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
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.
_________________________________________________________________
| |
| _________________________________ |
| |7369| Smith|CLERK|...........|20| |
| |
| |
| |
| |
|_________________________________________________________________|
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.
AAAH5SAABAAAPB4AAA 10 ACCOUNTING
72
AAAH5SAABAAAPB4AAB 20 RESEARCH
AAAH5SAABAAAPB4AAC 30 SALES
NOTE :
Temp01.dbf,Users01.dbf,Tools01.dbf,........etc
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.
REDO01.LOG
REDO02.LOG
REDO03.LOG
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:
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
ROWNUM is generated with sequence of numbers after the execution of SELECT statement
display all those employees whose row positions are more than 7?
display all those employees whose row positions are between 4 and 8?
display all those employees whose row positions are at odd positions?
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;
syntax:
SOME/ANY OPERATOR:
=ANY
>ANY
<ANY
>=ANY
<=ANY
!=ANY
75
ENAME JOB SAL DEPTNO
13 rows selected.
11 rows selected.
ALL operator:
This operator will also make a subquery to return more than 1 row.
=ALL
>ALL
<ALL
>=ALL
<=ALL
!=ALL
no rows selected
no rows selected
SAL
--------
1300
2450
5000
78
BLAKE MANAGER 2850 30
9 rows selected.
display ename,job,sal,deptno of all those employees who are working on a job and deptno as of
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?
6 rows selected.
NOTE: this query is getting executed based on multiple columns and multile rows.
These queries provide different execution to nested queries i.e. corelated queries "first executes
outer query and then executes
79
inner query."
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?
EXISTS operator:
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 :
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
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;
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)]
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.
2 FROM EMP
1 7839 KING
TREE
------------------------------------------------------------
KING
**JONES
****SCOTT
******ADAMS
82
****FORD
******SMITH
**BLAKE
****ALLEN
****WARD
****MARTIN
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:
AS
SELECT query;
EXAMPLE 1:
2 AS
Table created.
EXAMPLE 2:
2 AS
Table created.
EXAMPLE 3:
83
COPIES REQUIRED COLUMNS FROM EMP TO EMP3 TABLE.
2 AS
Table created.
EXAMPLE 4:
AS
SQL PLUS
5. DEL [n] --- used to delete the required lines from last qry
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.
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:
GET : This command is used to get the queries that are stored in a file into buffer.
Syntax:
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:
@ [drive:\] file1[.ext]
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.
Example:
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.
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.
& : 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 statement at different areas, like in expressions, for table
name, at condition, and at other clauses.
&& : 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.
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
86
SELECT * FROM EMP WHERE JOB='&K';
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
These variables will support to do environment settings, which will provides its effect only for
current working session.
Syntax:
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.
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.
SHOW variable/ALL : This command is used to get the changed or default settings of environment
variable.
87
Output of SQL queries can be generated in a formatted way, which includes providing headings,
footers, group calculations etc.
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:
NULL ---- used to substitute a required data at those rows of a column, where
null values are found.
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.
6. CLEAR COLUMN : This command is used to clear all the formats that are applied to different
columnns of a table.
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 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'
SQL> @TEST
-----------------------------------------------------------------------
-----------------------------------------------------------------------
Database Server. |
functions |
Insertion of new rows, modifications to existing rows and removing unwanted rows collectively
known as DML.
1. INSERT:
syntax:
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.
90
Enter value for deptno: 10
1 row created.
SQL> /
1 row created.
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;
14 rows created.
14 rows created.
SQL> INSERT INTO BONUS SELECT ENAME,JOB,SAL,COMM FROM EMP WHERE DEPTNO=20;
5 rows created.
INSERT ALL:
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
...................
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
92
SQL> INSERT ALL
4 ELSE
5 INTO EMP3
14 rows created.
4 ELSE
5 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)
14 rows created.
4 ELSE
5 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)
5 rows created.
INSERT ALL
............
SELECT query;
93
SQL> INSERT ALL
2 INTO EMP1
3 INTO EMP2
4 INTO EMP3
42 rows created.
2 INTO EMP1(EMPNO,ENAME,SAL)
3 INTO EMP2(EMPNO,ENAME,SAL)
4 INTO EMP3(EMPNO,ENAME,SAL)
42 rows created.
2 INTO EMP1(EMPNO,ENAME,SAL,DEPTNO)
3 INTO EMP2(EMPNO,ENAME,SAL,DEPTNO)
4 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)
15 rows created.
2 INTO EMP1(EMPNO,ENAME,SAL,DEPTNO)
4 INTO EMP3(EMPNO,ENAME,SAL,DEPTNO)
42 rows created.
UPDATE:
It does not support to use the same column for modification with different data for more than
once.
syntax:
1 row updated.
2. modify the job of SCOTT from ANALYST to MANAGER and SALARY from 3000 to 4500?
1 row updated.
5 rows updated.
1 row updated.
NOTE: comm has been calculated with 12% on the previous salary,since UPDATE command will
modify the columns at a time.
95
A sub query can be written in UPDATE command,
where the data returned by subquery will be updated with outer query.
SYNTAX:
[WHERE condition(s)];
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'),
SQL> UPDATE EMP SET SAL=(SELECT AVG(SAL) FROM EMP WHERE DEPTNO=30) WHERE
DEPTNO=20;
5 rows updated.
DELETE :
It will support to delete all the rows or supports to delete the rows on conditional basis. It deletes
the rows for temporary.
syntax:
2. delete all those rows of emp table who are working as 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.
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:
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);
SQL> DELETE FROM EMP WHERE DEPTNO IN(SELECT DEPTNO FROM DEPT WHERE DNAME
IN('RESEARCH','SALES'));
11 rows deleted.
MERGE :
This command is used to join the data from 2 tables into a single table.
1. USING clause
2. ON clause
97
4. WHEN NOT MATCHED clause
syntax:
ON (condition)
UPDATE query
INSERT query;
example:
2 AS
Table created.
no rows selected
1 row created.
1 row created.
7 INSERT VALUES(E2.EMPNO,E2.ENAME,E2.AN_SAL);
14 rows merged.
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.
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:
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:
1. Data Name
2. Data Type
3. Data Size
2. Col Name cant have blank spaces, spl characters (except underscore)
6. Cols which are created in 1 table, the same can be created in other table.
i. NUMBER[(size)] :
This data type will support to store the data which is purely of numerics.
ii. CHAR(size):
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.
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:
When this datatype is provided and if time is not mentioned then it will provide the time as 12am
CREATE,ALTER,TRUNCATE,RENAME,DROP
CREATING A TABLE:
Table is defined as logical structure which contains data in the form of rows and columns.
101
5. A record is stored in the form of block, where capacity of block is between 4kb to 8kb.
syntax:
.....................)
Examples:
DEFAULT:
Practice:
eno en gender
102
1001 x Male
1009 y Male
1003 z FEMALE
1012 a Male
1004 b FEMALE
3. create a table called product which stores pcode, pname,qty,price. Calculate for gbill,disc,nbill?
4. Student Marks
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;
103
ALTER TABLE table_name ADD/MODIFY (col_name1 data_type[(size)],col_name2
data_type[(size)],........);
TRUNCATE:
This DDL command is used to delete all the rows from a specified table for permanent.
-------------------------------------------------------------
DELETE | TRUNCATE
-------------------------------------------------------------
on condition |
temporary |
Example:
104
DROP : This DDL command is used to drop the objects like tables, views, synonyms, indexes,
procedures, functions,...etc
Syntax:
Example:
Data Dictionary
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 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.
USER_CATALOG (synonym is CAT) : This predefined table stores the information about the
following objects.
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
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.
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 : 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:
1. Column Level
2. Table Level
1. UNIQUE
106
2. PRIMARY KEY
1. UNIQUE :
This constraint will not allow a user to store duplicates but will allow to store null values.
Table created.
2 (ENO NUMBER(3),
3 EN VARCHAR2(12),
Table created.
Multiple columns set with 1 UNIQUE constraint refers to Composite Unique key.
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).
2 (RNO NUMBER(3),
3 SN VARCHAR2(12),
4 CLASS NUMBER(2),UNIQUE(RNO,CLASS));
Table created.
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 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.
en VARCHAR2(12));
(eno NUMBER(3),
en VARCHAR2(12),
108
(eno NUMBER(3) PRIMARY KEY,
(eno NUMBER(3),
PRIMARY KEY(eno),UNIQUE(en),UNIQUE(job));
Multiple columns set with 1 primary key refers to composite primary key.
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.
2 (RNO NUMBER(3),
3 SN VARCHAR2(12),
RNO SN CLASS
1X 7
1Y 8
2Z 7
2A 8
109
Oracle supports to implement the following relationships
between tables
FOREIGN KEY:
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;
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;
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:
110
CREATE TABLE RESULTS
EN VARCHAR2(12),MCODE NUMBER(4),
DEFERRED CONSTRAINTS
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.
Example:
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.
constraint_type(col1[,col2,....]) [DISABLE];
EXAMPLE:
(ENO NUMBER(4),
The constraints which are created on the columns of 1 or more tables can be dropped in the
following way;
NOTE:
When constraint is disabled then data in that column can be stored beyond the rule of a
constraint. The disabled constraint cannot
USER_CONSTRAINTS:
This predefined table will provide the detail information about the constraints created on different
columns and at different tables.
CONSTRAINT_TYPE REPRESENTATION
NOT NULL C
CHECK C
PRIMARY KEY P
UNIQUE U
FOREIGN KEY R
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 T1.TABLE_NAME,T1.CONSTRAINT_NAME,T1.CONSTRAINT_TYPE,T2.COLUMN_NAME
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.
Advantages of Normalization:
1. Minimizes Redundancy
2. Reduces Complexity
3. Easy maintainance
Tables are said to be in First normal form when it satisfies the following rules.
Unnormalized table
The above unnormalized table can be normalized with 1st rule of first normal form in the following
procedure;
CUSTOMER (p)
p/k
ORDERS (c)
p/k f/k
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.
ITEMS_ORDERED
f/k
The tables are said to be in second normal form when it satisfies the following rules.
2. Non key columns should be made to depend on whole key but not part of a key.
Orders1
p/k f/k
1 05-JUN-09 A15
2 12-JUN-09 F17
Items
f/k
e18 erasers 78 2
The tables are said to be in third normal form when it satisfies the following rules.
2. no transitive dependency
Unnormalized table:
WORKERS
116
p/k
Fd : wid----->skill..............1
Fd : wid----->bonus..............2
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.
4. Partitioning can be implemented into Existing table without making changes in the existing
application.
Partition key:
Oracle 12c automatically directs INSERT,UPDATE and DELETE operations to related partitions.
Partition key cant be created on Pseudo Columns like ROWID, LEVEL etc.
Types of Partitions:
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.
This partition uses "VALUES LESS THAN" clause to specify the partition range.
118
(rno NUMBER(3),sname VARCHAR2(12),age NUMBER(3))PARTITION BY RANGE (age)
TO TRUNCATE A PARTITION
TO DROP A PARTITION
TO RENAME A PARTITION
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.
PARTITION BY LIST(STATE)
(PARTITION P1 VALUES('AP','HP'),
PARTITION P2 VALUES('UP','KERALA'));
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)
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.
ALL_USERS : This predefined table will provide the user names, user ids, date and time on which
user is created.
NOTE:
SHOW USER : This command is used to display user name of currently logged in user.
PREDEFINED ROLES:
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.
examples:
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.
Syntax:
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:
select
EMP----------------------->
select,insert
DEPT------------------------------------->
select,insert(grade,losal)
SALGRADE--------------------------------->
ALL
BONUS--------------------> ALL
---------------------------------------> ALL
------------------------------------------------------->
select select
DUMMY-------------------->------------------------------->
122
example:
USER_TAB_PRIVS_MADE
USER_TAB_PRIVS_RECD
USER_COL_PRIVS_MADE
123
USER_COL_PRIVS_RECD
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:
After storing all the privileges in a role, this role can be granted to different users.
DROPING A ROLE:
Syntax:
Example:
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.
It provides its advantage when object has a frequent usage with different queries.
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:
125
Creating public synonyms:
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.
ALL_SYNONYMS : This predefined table will provide the detail information about the private &
public synonyms.
DROPING A SYNONYM:
PUBLIC synonyms can be dropped from a user, which has got DBA privileges.
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.
CREATING SEQUENCES
Syntax:
[INCREMENT BY 1 / n]
[START WITH n]
[NOMINVALUE / MINVALUE n]
[NOMAXVALUE / MAXVALUE n]
[NOCYCLE / CYCLE]
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.
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.
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.
To interact with the sequence to generate the numbers, 2 pseudo columns plays and important
role.
1. at SELECT statement
2. at INSERT,UPDATE statement
EXAMPLE 1:
SQL> /
SQL> /
EXAMPLE 2:
128
INCREMENT BY 5
MINVALUE 50
MAXVALUE 150;
SQL> /
SQL> /
EXAMPLE 3:
INCREMENT BY -5
MINVALUE 50
MAXVALUE 150;
INCREMENT BY 3
MINVALUE 1000
MAXVALUE 1050
CYCLE
CACHE 3;
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:
INCREMENT BY n
MINVALUE n
MAXVALUE n ......;
DROPING A SEQUENCE:
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.
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:
2. Improves performance
---------------------------------------------------------------------------
Tables | Views
-----------------------------------------------------------------------------
Types of Views:
1. Simple views
4. Complex views
5. Force views
6. Materialized views
1. Simple views:
These views will support to modify only when it contains all mandatory columns of base table.
AS
SELECT query
note:
2. When base table is back in database, view will start its working.
Examples:
CREATE VIEW V1
AS
AS
Create view v2 that stores a query for empno,ename,sal,deptno of all those employees related to 2
dept?
CREATE VIEW V2
AS
132
INSERT INTO V2 VALUES (1003,'Z',3000,30);
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
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.
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
COMPLEX VIEWS:
1. Group Functions
2. Group By clause
133
3. Joins
4. Mathematical Expressions
5. DISTINCT operator
CREATE VIEW V5
AS
CREATE VIEW V6
AS
CREATE VIEW V7
AS
CREATE VIEW V8
AS
FORCE VIEWS:
Force views are created on a table and column that which does not exist.
AS
134
CREATE FORCE VIEW V10
AS
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.
MATERIALIZED VIEW:
These views will store the compiled query and its output.
When materialized view is created on a table, where table should contain PRIMARY KEY.
Example:
4. Executed
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:
AS
OR
AS
AS
AS
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('mv1');
CREATING INDEXES
CREATING CLUSTERS
LARGE OBJECTS
137