Upload
satya-sharma
View
219
Download
0
Embed Size (px)
Citation preview
7/31/2019 sql note2003
1/62
7/31/2019 sql note2003
2/62
If database is categorized in 4 different types likewise DBMS is also categorized in
4 different types depending on its supports.
If DBMS supports to store retrieve and modify the data of network database then it
will be termed as NDBMS
Likewise if DBMS supports hierarchal, relational or object relational database to
manipulate them, then they will be termed as HDBMS, RDBMS, ORDBMS, respectively
.
RDBMS
Data : Attribute
Information : Tupple or Row
Datafile : Table
Database : Databank/Data warehouse
It is basically a concept which is developed by a scientist by John E.F.Cord in 1970
June . In his concept code prescribes 12 different rules known as 12 cord Rule.
If any database software fulfills 6 or more than 6 rules of cord rules of Cord that
will be termed as RDBMS types Software and if any database software fulfills less than 6
rules then they will termed as DBMS.
Greater Than 6(RDBMS) Lessthan 6(DBMS)
Oracale 6,7 Foxpro
Access Dbase
SQL Server Foxbase
DB2 Paradox
Informix
Ingiris
A relational Model of Data For Large Shared Databank It is book when 12 cord rules are
described and it is a foreign edition.
RDBMS
RDBMS is nothing but the collection of 2 dimensional table or relation.
Department
Dept No. 10 20 30
Dname Sales Purchase Admin
Loc CTC BBSR RKL
Employee
7/31/2019 sql note2003
3/62
Emp No 1 2 3
Name X Y Z
Sal 5000 6000 7000
Dept. No 10 10 20
The above graphics shows the relational model of architecture where both the tables are
related using a common attribute called Dept No.
In relational model of architecture always the data is represented in different
modules where each modules is known as table and each table has a relationship with
another one Data Modularity has 2 advantages.
1. Data Redundancy will be less
2. Data Security will be high
ORDBMS
It is the extended version of RDBMS. The extra feature is the object feature. Any thing
stored in Object relational Database will be treated as one object.
**Note : The advantages of Object Relational Database over a relational database is
memory management is proper and coding is less.
Feature of RDBMS
Class, Object, Abstraction, Encapsulation, Polymorphism. Inheritance
Class
Class is nothing but a template style of a blueprint which does not have its physically
existence. It is nothing but the collection of properties & behaviors of similar types of
object.
Object
It is nothing but instance of a class which has its physical existence having some properties
and behaviors.
Abstraction
This is a concept through which one object essential features will be represented hiding the
background details. It leads to data hiding which leads data security.
Encapsulation
This is a concept through which the data member and the member function will be rapped
up, under one module where each module is known as a class.
Polymorphism
This is a concept through which one object can act differently in different different
circumstances.
Inheritance
7/31/2019 sql note2003
4/62
This is a concept through which one object property and behavior can be reused in another
object .
Advantages of ORDBMS over RDBMS
1. Support for User Defined Datatype.
2. Supports for Multimedia.
3. High Quality Server Feature
4. Fully Relational
As because object relational database supports object features. It supports user
defined data type that means user can declare its own data type and used it inside the
programme.
Object relational database supports multimedia files such as Jpg file,Gif, Bmp,
Avi, etc. That means object relational database not only stress conventional types of data
rather than it stores multimedia data type.
Object relational database is popular for its high quality server features. Itsupports 3 level security
1. Client Level
2. Network Level
3. Server Level
Apart from that object related database supports 512 petabytes data.
As because object related database is based on relational database. It supports maximum
rules. So it is known as fully relational.
Eg:- Oracle 8, Oracle 8i, Oracle 9i
Oracle 9i
Oracle provides two different languages to manipulate its database.
(1) SQL (Structure Query Language)
(2) PL SQL (Procedural Language Extension of SQL)
Though oracle provides two different languages to manipulate its database but none of
these languages belongs to oracle because.
(1) SQL is an ANSI standard language which is required to manipulate the database
interactivity. Interactivity means one command can be extended at one point of time.
As because SQL is an ANSI Standard Language it is not only meant to manipulate
Oracle Database rather than it is meant to manipulate any type of database currently
available.
7/31/2019 sql note2003
5/62
(2) Where as through PL SQL is pronounced as a language rather than it is a mechanism or
technology implemented on ORACLE Server to manipulate the database programme
i.e using SQL commands.
SQL
It is not a single language of its own rather than it is a combination of 5 different Sub
languages . Namely
1. DQL (Data Query Language)
2. DDL (Data Definition Language)
3. DML (Data Manipulate Language)
4. TCL (Transaction Control Language)
5. DCL (Data Control Language)
DQL
This is a sub language which is helpful to retrieve the data from table and show to the
user. Otherwise it is known as Data Retrieval Language. It provides a statement Called
Select.
DDL
It is otherwise known as (OML) Object Manipulate Language , which is required to
create and manipulate the object in the Oracle Database. Oracle provides 5 different
types of Object for customized DBMS. Table, View, Synonyms, Sequence, Index. To
create and manipulate above object . DDL Provides five different statements , Create,
Alter, Drop, Truncate , Rename,.
DML
DML otherwise is known as Record Manipulate Language (RML), Which is
required to manipulate the record of tables. To accomplish the job DML provides different
statements. Insert, Update, Delete.
TCL
This sub language is required to control the transaction (Insert, Update , Delete)
made by the user. When ever any transaction is made in Oracle table those record will
never be permanent unless or until a save command is issued or discard command is
issued . To accomplish the job TCL provides 3 different statements.
1. Commit
2. Rollback
3. Savepoint
DCL
7/31/2019 sql note2003
6/62
Oracle supports user concept or schema concept to protect the object from invalid users .
To create and manipulate those users DCL provides different statements.
1. Grant
2. Revoke
*Note :- Schema :- It is nothing but logical area which holds some physical object
protected by a password.
Oracle provides a environment which acts as an interface between the user and the
database and the interface i.e. known as SQL * PLUS. Whenever a command is issued
from SQL * Plus , it goes to database and database will process the data command and
send the output back to SQL *Plus.
*Note : The difference between an editor and the environment is the editors are the
application which are require to edit the text and doesnt have its own command . Where as
an environment is an application which is required to manipulate other application as well
as has its own command itself.
When ever an user log on to Oracle . It shows a logon screen having 3 different options .
1. User name2. Password
3. Host String
Host string is an option which is required when ever an user working on multi Server
Architecture.
Select
It is a power full query statements which is helpful to extract the data from one
table or more than one table.
Syntax of Select Statement
Select [Distinct] from
Select Statement can perform 2 jobs .
1. Selection
2. Projection
Projection can be posed in two different manner.
SQL>
OUTPUT
SQL * PLUS
ORCALE 9I
b b b
7/31/2019 sql note2003
7/62
1. Column wise Projection / Column Restriction
2. Row wise Projection / Row Restrictions
Column Restriction is a concept through which , those column are displayed which
are specified in the column list.
Eg: - select empno, ename,sal from emp;
Where as row restriction is a concept through which those record are displayed when a
condition is satisfied.
*Note : - * represents for all column of a table and each individual SQL commands re
terminated by ; .
Working with Column Alias (Duplicate Name of an Object)
Column is a concept though which an user can provide a duplicate name to an existing
column. Column Alias can be given in three different manner.Consider the EMP table in Scott Login.
1. SELECT EMPNO NO,ENAME NAME,SAL SALARY FROM EMP
2. SELECT EMPNO AS NO,ENAME AS NAME,SAL AS SALARY FROM
EMP
3. SELECT EMPNO NO,ENAME NAME,SAL SALARY FROM EMP.
*Note :- When ever an alias is represented in multiple words it has to put in double
quotes ( ).
COLUMN CONCATENATION
1. SELECT EMPNO || JOB FROM EMP
2. SELECT EMPNO || JOB AS JOBPROFILE FROM EMP
3. SELECET EMPNO || IS WORKING AS || JOB AS JOBPROFILE FROM
EMP.
*Note:- In oracle string type of values and date type of values are always represented
through ( )single quote.
ARITHMETIC OPERATION THROUGH SELECT STATEMENT OR WORKING
WITH VIRTUAL COLUMN.
Select Statements supports arithmetic operators to implement formula concept .The
outcome of formula is basically known as a virtual column which does not have its
physical existence.
Eg. 1) SELECT EMPNO,ENAME,SAL,SAL*1,SAL*.11,SAL*.12 FROM EMP
What Where
7/31/2019 sql note2003
8/62
2) SELECT EMPNO,ENAME,SAL,SAL*1 AS TA,SAL*.11 AS DA,SAL*.12
AS HRA FROM EMP.
SQL*PLUS
When ever a valid SQL Statement is issued from SQl prompt, it never goes to database
directly rather than it passes through a temporary memory to database and the temporary
memory is known as a BUFFER.
BUFFER
Buffer is nothing but an active temporary memory in client side RAM, which holds a
statement for a temporary period unless or until another statement is issued by the user or
the memory is explicitly deleted by the user.
Editor or Ed
The above commands are required to open the buffer memory through default
editor called NOTEPAD.
RUN or /
SQL>
SQL *PLUS
CLIENT SITE
BUFFER(NOTEPAD)
(AFIEDT.BU
F)SERVERDatabase
7/31/2019 sql note2003
9/62
The above command is used to run buffer memory.
SAVE
To save a statement in a file permanently
Syntax :- SAVE
Eg.- SAVE END
An user can store statement for a permanent period in form file those filr a re
basically known as SCRIPTFILES . The extension of these type of files are known as
.SQL.
START
To execute the script file.
Syntax : - START
Or
@
The above command is used to run a script file.START command can perform 2 jobs.
1. Load the statement from the hard disk to buffer
2. RUN the buffer.
GET
The above command required to load the statement from the hard disk to the buffer
memory.
Syntax: Get
Clear
Clear the buffer
Syntax : Clear Buffer or Cl Buff
Show
Show the Current Username
Syntax : Show User.
Host
It is a SQL * Plus command required to jump from SQL * Plus to DOS Envirnmnet.
SAVE
Save a file in different location
Syntax : Save d:\aa.sql(Path Location)
Difference Between SQL and SQL * Plus
SQL SQL*PLUS
1. It is an Ansii Standard Language required
to manipulate the database
1.It is an environment proprietary of Oracle
b
b
b
b
7/31/2019 sql note2003
10/62
2. SQL Commands cannot be abbreviated 3.These commands can be abbreviated
Eg: Clear screen (Cl scr )
3.SQl Command always terminated by a ; 3. No optional character is used to terminate
SQL *PLUS Commands.
4. SQL Command always passes through
the buffer to database for execution.
4. No buffer memory is used fro SQL * Plus
commands
ROW RESTRICTION THROUGH SELECT STATEMENT
It is a concept implemented on select statement to restrict the record depending on a
condition . To implement condition select statement provides a clause called WHERE.
Syntax of SELECT using WHERE
Select
7/31/2019 sql note2003
11/62
From
[Where ];
To restrict records depending on a condition Oracle provides 3 different types of
operators.
1. Arithmetic Operator
2. Relational Or Comparison Operator.(>,=,2000 AND SAL
7/31/2019 sql note2003
12/62
WHERE JOB IN (SALESMAN,ANALYST,..,)
LIKE
It is a powerful query operator, which is required to extract the data from the table,
depending upon a character position. This operator is meant for character types of values or
date types of values. It provides the wild card character to accomplish the job.
Wild Card Character
% - It represents multiple characters
_(Underscore):- It represents a single character.
Eg : SELECT * FROM EMP
WHERE ENAME LIKE S%; (First Character)
2. SELECT * FROM EMP
WHERE ENAME LIKE %S (Last Character)
3. SELECT * FROM EMPWHERE ENAME LIKE S% OR ENAME LIKE %S
4. SELECT * FROM EMP
WHERE ENAME LIKE __ i %H (3rd character i and last character H
NOT LIKE
Eg : SELECT * FROM EMP
WHERE ENAME NOT LIKE S% AND ENAME LIKE %S
1. DATE LIKE %82
2. DATE LIKE %FEB
IS NULL
Null is a special kind of value which is Unassigned or Inapplicable To extract the
value from a table depending upon the NULL value . Oracle provides an operator called Is
Null.
Eg: SELECT * FROM EMP
WHERE COMM IS NULL;
JOIN
It is a mechanism or a technology implemented on select statement to extract the
data from multiple tables. To extract the data from multiple tables ,the tables must have a
7/31/2019 sql note2003
13/62
relationship depending upon the relationship of tables JOIN is categorized in 4 different
types.
1. Equi Join
2. Non Equi Join
3. Self Join/Inner Join
4. Outer Join
1. EQUI JOIN
It is a type of join , which will extract the data from multiple tables when a
common attribute is available.
TABLE EMP
(CHILD)
EMPNO NAME SAL DEPTNO
1 X - 20
2 Y - 10
3 Z - 204 A - 30
5 B - 10
TABLE DEPT
(MASTER)
DEPT NO DNAME LOC
10 SALES CTC
20 PUR BBSR
30 ADMIN RKL40 FIN BPD
The above graphic shows both the tables have a common attribute called
DEPTNO . To extract the data from above tables the user can use EQUI-JOIN.
Syntax
SELECT TBLE1.COL,TABLE1.COL,TABLE2.COL,TABLE 2.COL..N
FROM TABLE1,TABLE2
WHERE TABLE1.COL=TABLE2.COLEg: SELECT EMP.EMPNO,EMP.ENAME,EMP.SAL,
DEPT.DNAME,DEPT.LOC
FROM EMP ,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
**Note : A table name preferred with the column name is optional in nature , but is
mandatory when ever a common attribute is extracted.
Eg. SELECT EMPNO,ENAME,SAL,DANME,LOC,DEPT.DEPTNO,
7/31/2019 sql note2003
14/62
FROM EMP,DEPT
WHERE EMP.DEPT NO=DEPT.DEPTNO
OUTER JOIN
It is a type of join which will extracted the data from multiple tables weather the
condition is satisfied or not satisfied . In other words Outer Join is a type of join which will
extract all the data from multiple tables.
Eg. : Write a statement which will display empno,name ,sal , deptno, and location of
those who is working in a particular department as well as display those department
information under which no person are working.
SELECT EMPNO,ENAME,SAL,DNAME,LOC,
FROM EMP, DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
NON EQUI JOIN
It is type of join which will extract the data from multiple tables when ever nocommon attribute is available but there must be a relationship.
EMPNO NAME SAL DEPTNO GARDE LSAL HSAL
1 X 7500 1 700 1200
2 Y 2500 2 1201 2000
3 Z 950 3 2001 5000
4 A 3800 4 5001 8000
5 B 850 5 8001 9999
The above graphics shown both the tables have no common attributes but there is
an internal relationship using High salary and Low Salary . High salary of salgrade table to
extract the data from above tables the user can use non equi join.
Eg. Write a statement to display empno, ename, salary, grade
SELECT EMPNO,ENAME,SAL,GRADE,DNAME,LOC
FROM EMP ,SALGRADE,DEPT
WHERE SAL BETWEEN LOSAL AND HISAL
2. Write a statement which will display empname,salary,grade,deptname,and loc of
those employee whose job is salesman
SELECT EMPNO,ENAME,SAL,GRADE,DNAME,LOC
FROM EMP ,SALGRADE,DEPT
WHERE SAL BETWEEN LOSAL AND HISAL
AND EMP.DEPTNO = DEPT.DEPTNO
7/31/2019 sql note2003
15/62
AND JOB= SALESMAN;
WORKING WITH TABLE ALIAS
It is a concept or mechanism required to provide a duplicate name to an existing
table. Table alias is meant to provide short name instead of using object. This concept only
implemented for JOIN statement.
Eg: SELECT E.EMPNO,E.ENAME,E.SAL,D.DNAME,D.LOC
FROM EMP E,DEPT D
WHERE E.DEPTNO=D.DEPTNO;
SELF JOIN OR INNER JOIN
Self join is a concept or mechanism where a table is joined with itself to get the
output.
EMPNO NAME MGR(EMPNO) DEPTNO
1 X 2 -
2 Y 3 -
3 Z - -4 A 3 -
5 B 4 -
From this table
Y is the manger of X, Z is manager of Y, Z is manager of A, A is manager of B, Z has no
manager (Head)
Eg. 1. SELECT W.NAME || IS WORKING|| M.NAME
FROM EMP W, EMP M
WHERE W.MGR=E.EMPNO;
2. SELECT EMP.EMPNO, EMP.ENAME, EMP.SAL, EMP.DNAME, EMP.LOC
FROM EMP,DEPT
WHERE EMP.DEPTNO=DEPT.DEPTNO;
3. Deficiency (+) or Child table
SELECT EMPNO, ENAME,SAL,GRADE,DNAME,SAL
FROM EMP,SALGARDE,DEPT
WHERE SAL BETWEEN LOSAL AND HISAL
AND EMP.DEPTNO(+) = DEPT.DEPTNO;
Predefined Function In Oracle
Procedure Not value returned
Function Value Returned
SQL provides a series of predefined functions to enhance the capacity of SQL
statements these functions are categorized in 2 different types.
7/31/2019 sql note2003
16/62
1. SINGLE ROW
2. MULTI ROW
SINGLE ROW
It is a function which will accept one value as a argument & returns one value per
row.
MULTI ROW
Where as multi row function are those functions which will accepts multiple values
as an argument and returned one value per row.
CASE CONVERSION
This function are required to convert a character or a string from one cas to
another . The functions are
LOWER ( )
UPER ( )
INITCAP ( )
Eg. : SELECT LOWER(ENAME) FROM EMP;
**Note : The user can pass 2 types of values as an argument in a single row function
1. Column name
2. Static Value as an argument
**Note : When ever a static value is passed to single row function , the output will be
displayed that may no of times , the no of records available inside the table.
Eg : SELECT LOWER (ORISSA) FROM EMP;
FUNCTION
SINGLE ROW MULTI ROW
CHRACTER NUMBER DATE CONVERSION
CASE CONVERSION CHARACTER MANIPULATION
7/31/2019 sql note2003
17/62
Here the output will display 14 no of times. Test a single row function oracle
provides a predefined tba;e called dual , which is having one column DOMY one value as
X
Eg: SELECT LOWER(ORISSA) FROM DUAL;
CHARACTER MANIPULATION
These functions are required to manipulate the character type of values or string
type of values and the functions are
1. CONCAT ( )
2. SUBSTR ( )
3. INSTR ( )
4. LTRIM ( )
5. RTRIM ( )
6. LENGTH ( )
CONCAT ( )
This function is required to concatenation 2 strings or 2 columns.
Eg. : SELECT CONCAT (ENAME,JOB) FORM EMP
SELECT CONCAT (ENAME, CONCAT(WORKING AS,JOB)) FROM EMP;
SUBSTR
This function is required to extract the specific no of characters from a specified
string (String character include no of characters)
Syntax: SELECT (STRING |COLUMN ,STARING POINT OF STRING | [NO OF
CHARACTERS] );
Eg: SELECT SUBSTR(ORISSA,2,4) FORM DUAL;
INSTR (Inside the string)
This function is required to display a character position inside a specific string. If
the character is not available it will return 0 and if it is redundant, it will display first
character position.
Synatx : INSTR(STRING | COL, SINGLE CHARACTER)
LENGTH ( )
It will display the length of a string or length of a column values.
Eg : SELECT LENGTH (ORISSA) FROM DUAL;
7/31/2019 sql note2003
18/62
LTRIM ( ) /RTRIM ( )
This features are always require to truncate the blank space from left and right side
of the string.
Eg: SELECT LENGTH (LTRIM(ORISSA))FROM DUAL;
NUMBER FUNCTION
These functions are required to manipulate numeric values.
1. ROUND
2. TRUNCATE
3. MOD
ROUND
This is a function required to round a floating values.Eg: SELECT ROUND (45.378) FROM DUAL; 45,
IF THE NUMBER AFTER DECIMAL IS
7/31/2019 sql note2003
19/62
7. TRUNCATE ( )
ADD_MONTHS ( )
It is a function which is required to add a specific no of month to a specify date.
Eg: SELECT ADD_MONTHS (25-AUG-05,6 ) FROM DUAL;
MONTHS_BETWEEN ( )
This function is required to display approx month difference between two specify
dates.
Eg: SELECT MONTHS_BETWEEN (25-SEP-05,25-AUG-05) FROM DUAL;
LAST_DAY ( )
It is a function to view the last day of months date.
Eg: SELECT LAST_DAY(25-AUG-05)FROM DUAL;
NEXT_DAY
This is a function is required to display next day of the week date.
Eg: SELECT NEXT_DAY(25-AUG-05, FRIDAY) FROM DUAL;
SYSDATE
SELECT SYSDATE FROM DUAL;
SELECT CURRENT_ DATE FROM DUAL
ROUND
This function is required to round a date month wise or year wise. If the date is
rounded by month , it will check the day part. If the date is rounded by Year , it will check
the month part.
Eg: SELECT ROUND(TO_DATE(25-AUG-05), MONTH)FROM DUAL;
*Note : To_date is conversion function which is required to convert a string date to
actual date.
>=JULY 1ST DAY OF 1ST MONTH OF NEXT YEAR
=16- 1ST DAY OF NEXT MONTH
7/31/2019 sql note2003
20/62
Eg: SELECT TRUNC (TO_DATE( 25-AUG-05 ), MONTH)FROM DUAL;
SELECT TRUNC (TO_DATE( 25-AUG-05 ), YEAR)FROM DUAL;
CONVERSION FUNCTION
It is a type of function which is required to convert a value from one data type to
another data type.
TO_NUM ( ) TO_DATE ( )
NUMBER CHARACTER DATE
TO_CHAR( ) TO_CHAR( )
TO_CHAR ( )
This function is required to convert date to character or number to character.
Syntax : To_Char (Date | Number , FMT);Date to Character
Date to character formatting strings are :
DY : Abbreviated Character form of the Day of the Week.
DAY : Full character form of the day of the week
DD : Numeric representation of the day of the month between 1 to 31st
DDTH : Numeric representation of the day of the month in the period
DDTHSP : Character representation of the day of month dth format.
MM : Numeric representation of month between 1 to 12
MON : Abbreviated character of the month
MONTH : Full character form of the month
YY : Display the Year Part
YYYY : Display the year in centurion format.
Eg: SELECT TO_CHAR(TO_DATE(22-JAN-05),DDTH MON YY)FROM DUAL;
SELECT TO_CHAR (TO_DATE (22-JAN-05),DDTH-MON-YY)FROM DUAL;
Number to Character:
$ : Prefix $ as a symbol
9. : Represents the no in character format
, : Thousand separator
. : Decimal Notation
L : Prefix as a local currency style.
7/31/2019 sql note2003
21/62
TO_NUMBER
This function is required to convert string number to actual number
Eg: SELECT 10 FROM DUAL;
SELECT TO_NUMBER(10) FROM DUAL;
MULTI-ROW FUNCTION
This function is a type of function which will accept multiple values as an argument
& return one value per garoup & the functions are
1. SUM ( )
2. MAX ( )
3. MIN ( )
4. AVG ( )
5. COUNT ( )
Eg: SELECT SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP;
The above example will display sum(sal), max(sal), min(sal), and avg(sal) of
employee table where employee table is treated as a group.
WORKING WITH GROUP BY CLAUSE
Group by clause is a clause of select statement used to logically segregate the table
data in different different block. This clause is only implemented for group functions
(Multi-Row Functions).
Syntax of select using group by clause.
Select
From
[Where ]
[Group by [COL_NAME,N]
Eg: SELECT SUM(SAL), MAX(SAL), MIN(SAL), AVG(SAL) FROM EMP GROUP
BY DEPTNO;
The above example will display department wise sum(sal), max(Sal), min(sal),
avg(sal).
*Note : The user must use those columns in the group by clause the column which
have hugely duplicate values.
The user can use a column in the select list if the column is used in the group by
clause.
Eg: SELECT ENAME , SUM(SAL), MAX(SAL),AVG(SAL) FROM EMP GROUP
BY ENAME;
7/31/2019 sql note2003
22/62
The above example is an example of single column wise grouping
WORKING WITH MULTICOLUMN WISE GROUPING
Eg: SELECT DEPTNO, JOB, SUM(SAL), MAX(SAL), MIN(SAL) FROM EMP
GROUP BY DEPTNO, JOB.;
The above example will display sum(sal), max(sal) & min(sal).
COUNT ( )
This function is required to count the no of records of a group or no of values of a column.
Count function can accept 2 types of argument
(i) Count (*)
(ii) Count (Col.name)
Eg: Select count(*) from emp;
Select count(ename) from emp;
Question: Write a statement which will display department , job, sum (sal), min(sal),
max(sal) & the no of the persons working under each group.
Ans. SELECT DEPTNO,JOB,SUM(SAL),MIN(SAL), MAX(SAL),COUNT(*)
FROM EMP GROUP BY DEPTNO,JOB ;
WORKING WITH HAVING CLAUSE
HAVING clause is a clause of select statement which is required to restricted the
group depending on a condition. The difference between WHERE & HAVING is where
meant for row restriction where as HAVING is meant for group restriction.
SYNTAX OF SELECT USING HAVNING CLAUSE
SELECT
FROM
[WHERE ]
[GROUP BY ]
[HAVING < GROUP CONDITION>]
*Note : Select statement is nether case sensitive nor syntactical sensitive but select
statement is clause sensitive always.
Eg: SELECT DEPTNO , JOB, MAX(SAL), MIN(SAL), COUNT(*)
FROM EMP
WHERE DEPTNO 2000;
WORKING WITH ORDER BY CLAUSE
7/31/2019 sql note2003
23/62
ORDER BY clause is last of select statement which is required to arrange the
records in a proper manner either ascending or descending wise . To accomplish the job it
provides 2 pseudo columns. Ascending & Descending. The default order is ascending.
Eg: SELECT * FROM EMP ORDER BY DEPTNO;
SELECT * FROM EMP ORDER BY DEPTNO,SAL DESC;
The above example is an example of column wise ordering.
SYNTAX OF FULL FLEDGE SELECT STATEMENT
SELECT
FROM
[WHERE ]
[GROUP BY ]
[HAVING ]
[ORDER BY [ASC | DESC]];
SUB-QUERY
Sub query is a mechanism or technology implemented on select statement whenever a
condition value to an known to an user.
The advantage of sub query is to display the output whenever a condition value is
to known. Sub query has two different parts.
(i) Inner Query
(ii) Outer Query
Inner query is query which is always executed first to evaluate the condition value& provide the value to the outer query for the processing.
Where as outer query is a query which is responsible to accept the value from inner
query & display the output.
Depending on the value return from inner query to outer query sub query is
categorized in 2 different types.
1. Single Row Sub Query
2. Multi Row Sub Query
Single Row Sub Query
It is type of sub query where the inner query return one value to alter query
for processing.
Eg: Display those record whose salary is greater than Blakes Salary.
Where as multi row sub query is a sub query where inner query return more
than one value to outer query for processing.
7/31/2019 sql note2003
24/62
Eg: Display those record whose salary is greater than Blakes salaray
Where as multi row sub query is a sub query where inner query return more than one value
to outer query for processing.
Eg; Display those record whose salary is greater than all salary of department 30.
Syntax Of Subquery
SELECT
FROM
WHERE OPERATOR
(SELECT COL.NAME FROM WHERE );
*Note: The syntax of single row subquery and multi row subquery is same but the user
can identify the subquery from its operator . The single row subquery operators are >,
< , =, < >, =
Multi row subquery operators are :-
IN, >ANY, ALL, (SELECT SAL FROM EMP WHERE ENAME=BLAKE;
2. SELECT * FROM EMP
WHERE JOB=(SELECT JOB FROM EMP WHERE ENAME=ALEN)
AND ENAME ALEN;
3. Write a statement which will display those record whose salary is greater than
smiths salary & job must be same as ford.
SELECT * FROM EMP
WHERE SAL >(SELECT SAL FROM EMP WHERE ENAME=SMITH)
AND JOB = (SELECET JOB FROM EMP WHERE ENAME=FRD);
4. Write a statement which will display those records whose salary is greater than
SMITHs salary & less than BLAKE.
SELECT * FROM EMP
WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME =SMITH)
AND SAL < (SELECT SAL FROM EMP WHERE ENAME=BLAKE);
FOR MULTI ROW SUBQUERY
1. Write a statement which will display those records whose salary is greater than all
salary of department 30.
7/31/2019 sql note2003
25/62
SELECT * FROM EMP
WHERE SAL >ALL(SELECT SAL FROM EMP WHERE DEPTNO=30);
2. Write a statement which will display the records whose job is same as any job of
Deptno 30.
SELECT * FROM EMP
WHERE JOB =ANY(SELECT JOB FROM EMP WHERE DEPTNO=30)
AND DEPTNO30;
*Note Any operator is same as IN Operator
3. Write a statement which will display records whose salary is greater than ANY
salary of deptno 30.
SELECT * FROM EMP WHERE SAL >ANY(SELECT SAL FROM EMP `
WHERE DEPTNO=30)
**Note : >any means >(Minimum Value of List)
7/31/2019 sql note2003
26/62
1. SELECT * FROM EMP WHERE DEPTNO=&DEPTNO
ENTER VALUE FOR DEPTNO
SESSION TYPE SUBSTITUTION VARIABLE :
1. SELECT * FROM EMP WHERE DEPTNO=&&DEPNO
Once assigned cannot be changed
It can be changed by
UNDEFINE DNO
Reassign the session substitute variable
DEFINE DEPNO=20
**Note : Define and undefine are 2 SQL * PLUS command required to reassign and
destroy a session type substitution variable.
REPORTING THROUGH SELECT STATEMENT:-
Reporting is nothing but customized representation of data. In SQL reporting canbe possible in 2 different manners.
1. Column Wise Formatting
2. Table wise Formatting
Examples :
Column ename heading name
Column sal heading Salary
Column comm heading commission
DDL
ALTER
Syntax to Alter a Table (Add or Modify)
ALTER TABLE
ADD | MODIFY (COL_NAME DATATYPE (SIZE),[COL_NAME DATATYPE
(SIZE),..N]);
Example
1. ALTER TABLE MYEMP
ADD (JOB VRCHAR2(20));
3. ALTER TABLE MYEMP
MODIFY (NAME VARCHAR2(40));
7/31/2019 sql note2003
27/62
**Note :- To add a new column , to delete an existing column or to change the size
of a column the table may or ,may not contain the data, But to change the data type
of a column , the column must be blank.
DELETE
Syntax :
ALTER TABLE
DROP COLUMN ;
The above syntax required to delete a single column from the existing table
structure
Delete Multiple Column
ALTER TABLE
DROP (COL1,COL2,..N)Example
1. ALTER TABLE MYEMP
DROP COLUMN JOB;
2. ALTER TABLE MYEMP
DROP (NAME ,SAL);
Deleting a table from database physically :-
Syntax :
DROP TABLE ;
In Oracle 8i Once Table is deleted from system we can range the table in proper
manner by using the following statement.
@DEMO BLD
Deleting all records physically from a table remains structure using truncate.
Syntax :
TRUNCATE TABLE
Example :
Truncate table systab;
Renaming a table using Rename
7/31/2019 sql note2003
28/62
Syntax :
RENAME TO
Example :
Rename systab to myemp;
CONSTRAINT
Constraint are nothing but rules or restrictions imposed on individual column to
avoid invalid data entry.
Oracle provides 5 different types of constraints to avoid invalid data entry.
1. Primary Key
2. Not Null
3. Unique
4. Check
5. Foreign Key
Primary Key :
Enforces No Null and No Duplicate Value to a column
Not Null :
Enforces No Null value to column but it can accept duplicate Value.
Unique :
Enforces no duplicate value to a column but can accept Null Value.
Check :
This always checks a condition before entering value to a column.
Foreign Key :
The constraint which is helpful to make a relationship between two or more tables
using common attribute.
Foreign key always references to same tables primary key or another tables
primary key to make a relationship.
Foreign Key is just opposite of primary key i.e. it can accept duplicate values as
well as Null Values.
Foreign Key supports the concept ofReferential integrity.
Imposement Of Constraints
A constraint can be exposed to individual column during design in two different
levels
1. Column Level
7/31/2019 sql note2003
29/62
2. Table Level
Column Level :
Column Level constraints are those constraints which are imposed on those
columns just after the column defining.
Table Level :
It is those constraints which are imposed on individual column after all column
definition during table design.
**Note : The difference between column Level and Table Level constraints i.e
In column level maximum one constraint can be imposed to a single column and
not null can be used here. In Table Level multiple constraints can be imposed on a
single column. Here we cannot use the Not Null.
COLUMN LEVEL CONSTRAINT :-
Syntax :
CREATE TABLE
(COLUMN NAME DATATYPE(SIZE) [CONSTRAINT ] ,
COLUMN NAME DATATYPE(SIZE) [CONSTRAINT ] ,
-------------------------------------------N);
Example :
Q1. Design the following table having the following attribute and constraint.
T_NAME : MYEMPConstraints
EMPNO : NUMERIC(4) PRIMARY KEY
NAME : VARCHAR2(20) NOT NULL
SAL : NUMERIC(7,2) CHECK (SAL BETWEEN 2000 AND 5000)
JOB : VARCHAR2(20) UNIQUE
Ans.
CREATE TABLE MYEMP
(EMPNO NUMBER(4) CONSTRAINT MYEMP_EMPNO_PK PRIMARY KEY,
NAME VARCHAR2(20) CONSTRAINT MYEMP_NAME_NT NOT NULL,
SAL NUMBER (7,2) CONSTRAINT MYEMP_SAL_CHK CHECK (SAL BETWEEN 2000 AND 5000),
JOB VARCHAR2(20) CONSTRAINT MYEMP_JOB_UK UNIQUE );
TABLE LEVEL CONSTRAINT :
Syntax :
CREATE TABLE
(COL_NAME DATATYPE (SIZE),
COL_NAME DATATYPE (SIZE),
7/31/2019 sql note2003
30/62
N
CONSTRAINT (COL_NAME),
CONSTRAINT (COL_NAME);
.N;
Example :
T_NAME : MYEMP
CONSTRAINTS
EMPNO : NUMERIC(4) PRIMARY KEY
NAME : VARCHAR2(20) NOT NULL
SAL : NUMERIC(7,2) CHECK (SAL BETWEEN 2000 AND 5000)
JOB : VARCHAR2(20) UNIQUE
Q1. Design the above table with same attribute using table level.
CREATE TABLE MYEMP(EMPNO NUMBER(4),
NAME VARCHAR2(20) CONSTRAINT MYEMP_NAME_NT NOT NULL,
SAL NUMBER(7,2),
JOB VARCHAR2(20),
CONSTRAINT MYEMP_EMPNO_PK PRIMARY KEY(EMPNO),
CONSTRAINT MYEMP_SAL_CK CHECK(SAL BETWEEN 2000 AND 5000),
CONSTRAINT MYEMP_JOB_UK UNIQUE(JOB))
FOREIGN KEY
Syntax :
CREATE TABLE
(COL_NAME DATATYPE(SIZE),
COL_NAME DATATYPE(SIZE)
..(N)
CONSTRAINT FOREIGN KEY (COL_NAME)
REFERENCES (COL_NAME)),.;
Design The Following Tables :
T_NAME : MYDEPT
DEPTNO : NUMBER (4)
DNAME : VARCHAR2(20)
LOC : VARCHAR2(20)
2. T_NAME : MYEMP
EMPNO : NUMBER(4)
7/31/2019 sql note2003
31/62
NAME : VARCHAR2(20)
SAL : NUMBER(7,2)
MGR : NUMBER(4)
DEPTNO : NUMBER(4)
CONSTRAINTS
DEPTNO : PRIMARY KEY
DNAME : NOT NULL
CHECK (SALES,PURCAHSE,ADMIN)
LOC : NOT NULL
CHECK (CTC,BBSR,RKL)
2. EMPNO : PRIMARY KEY
NAME : NOT NULL
SAL : NOT NULL
CHECK (2000 -10,000)
MGR : FOREIGN REFERENCES MYEMP(EMPNO)
DEPTNO : FOREIGN REFERENCES MYDEPT(DEPTNO)
TABLE CREATION :
1. CREATE TABLE MYDEPT
(DEPTNO NUMBER(4),
DNAME VARCHAR2(20) CONSTRAINT MYDEPT_DNAME_NT NOT NULL,
LOC VARCHAR2(20) CONSTRAINT MYDEPT_LOC_NT NOT NULL,
CONSTRAINT MYDEPT_DEPTNO_PK PRIMARY KEY(DEPTNO),
CONSTRAINT MYDEPT_DNAME_CK CHECK(DNAME IN('SALES','PURCHASE','ADMIN')),
CONSTRAINT MYDEPT_LOC_CK CHECK(LOC IN('CUTTACK','BHUBANESWAR','ROURKELA')))
2. CREATE TABLE MYEMP
(EMPNO NUMBER(4),
NAME VARCHAR2(20) CONSTRAINT MYEMP_NAME_NT NOT NULL,
SAL NUMBER(7,2) CONSTRAINT MYEM_SAL_NT NOT NULL,
MGR NUMBER(4), DEPTNO NUMBER(4),
CONSTRAINT MYEMP_EMPNO_PK PRIMARY KEY(EMPNO),
CONSTRAINT MYEMP_SAL_CK CHECK(SAL BETWEEN 2000 AND 10000),
CONSTRAINT MYEMP_MGR_FK FOREIGN KEY (MGR) REFERENCES MYEMP(EMPNO),
CONSTRAINT MYEMP_DEPTNO_FK FOREIGN KEY(DEPTNO) REFERENCES MYDEPT(DEPTNO))
DATA DICTIONARY / SYSTEM CATALOG
1. To see the name of the existing tables in the current user login
SELECT TABLE _NAME FROM USER_TABLES
2. To see the structure of the existing tables
DESC USER_TABLES
7/31/2019 sql note2003
32/62
3. To see the name of the existing constraints in the current user login
SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS
4. To see the name of the constraints with the table name
SELECT CONSTRAINT_NAME,TABLE_NAME FROM
USER_CONSTRAINTS
5. To see the name of the constraints with the table name and status
SELECT CONSTRAINT_NAME,TABLE_NAME,STATUS FROM
USER_CONSTRAINTS
6. SELECT CONSTRAINT_NAME,TABLE_NAME,STATUS FROM
USER_CONSTRAINTS
WHERE TABLE_NAME='MYEMP'
7. Want to see the range of check constraint
SELECT CONSTRAINT_NAME,TABLE_NAME,SEARCH_CONDITION
FROM USER_CONSTRAINTSWHERE TABLE_NAME='MYEMP'
Implicit naming convention of a constraint
If no constraint name is given by a user at table design by default system will provide a
constraint name which look like SYS-C005001.
**Note : A constraint can be deleted by 2 different manner
(i) Explicitly using alter command.
(ii) Implicitly when ever a table is being dropped.
DML/RML
Required to manipulate records of a table to accomplish the job DML provides 3
statements
1. INSERT
2. UPDATE
3. DELETE
1. INSERT
Syntax :
INSERT INTO [OL1,COL2N]
VALUES(VALUE1,VALUE2,N);
The above example is a simple insertion where the user remember the column name and
their sequences.
7/31/2019 sql note2003
33/62
Date Insertion With Column List :
Example : INSERT INTO MYEMP(SAL,EMPNO,NAME) VALUES
(3000,2,'BBSR')
Insertion Of Null Value to a Column :
Null value can be entered to a column in two different manners.
1. Explicitly using NULL key word
2. Implicitly using column specification.
Explicitly :
INSERT INTO MYEMP VALUES(1,AAA,NULL);
Implicitly :
INSERT INTO MYEMP(EMPNO,NAME)VALUES (1,AAA);
INTERACTIVE INSERTION :
INSERT INTO MYEMP VALUES(&EMPNO,&NAME,&SAL);
UPDATING A RECORD USING UPDATE :
Syntax :
UPDATE
SET COL_NAME =VALUE [,COL_NAME=VALUEN]
[WHERE ]
Example :
UPDATE MYEMP
SET SAL =500
WHERE SAL IS NULL;
**Note : If where clause is omitted from the update statement , it will update a the
values of specific columns.
Question :
Write a statement which will updated the employee salary of employee no 3
to Blake salary of employee table.
Answer :
UPDATE MYEMP
SET SAL= (SELECT SAL FROM EMP WHERE ENAME = BLAKE
WHERE EMPNO=3;
7/31/2019 sql note2003
34/62
UPDATING MULTIPLE COLUMN VALUE :-
Example :
UPDATE MYEMP
SET NAME= kkk, SAL =5000
WHERE EMPNO=4;
DELETE :
SYNTAX :
DELETE FROM
[WHERE ];
If where clause is omitted from delete statement , it will delete all the records from the
table.
Example :
DELETE FROM MYEMPWHERE EMPNO=4;
CREATING A TABLE USING QUERY STATEMENT
Example :
CREATE TABLE SYSTAB
AS SELECT * FROM EMP;
**Note : Whenever a table is copied using query statement only not null constraint is
copied to the destination table not all constraints.
COPY THE STRUCTURE OF TABLE EXCEPT DATA
Example :
Create table system
as select * from emp
where 1=2;
TCL
In oracle database whenever a transaction is made , the transaction will never be
save permanently unless and until a save command is issued or discard command is issued.
To do so TCL provides 3 statements.
1. Commit (Save)
7/31/2019 sql note2003
35/62
2. Roll Back (Discard)
3. Save Point
TCL MECHANISM
Whenever a DML command is issued from SQL prompt, just before the DMLoperation is made , automatically a temporary memory is created inside the server whihjc is
known as ROLLBACK SEGMENT and the table on which DML operation is going to be
made will be copied temporary to the roll back segment which is known as SNAPSHOT.
Whenever a commit command I issued in SQl prompt , the roll back segment along
with the snap shot will be deleted and records transacted t the main table will ve
permanent.
If a Roll Back command is issued from SQL prompt, the snapshot available in Roll
Back segment will again be copied to its original location with the old data by deleting the
Roll back Segment.
**Note : The data once committed cannot be Roll Back and once rolled back cannt be
committed.
Example :
INSERT INTO MYEMP
VALUES(..);
COMMIT;
INSERT INTO MYEMP
VALUES(..);
ROLLBACK;
ROWID :
Required to manipulate duplicate record.
Example :
SQL * PLUS ROLL BACK SEGEMNT TEMPORARY MEMORY (Snapshot)
7/31/2019 sql note2003
36/62
SELECT ROWID FROM EMP;
SAVE POINT
Savepoint is nothing but a logical pointer which is given to individual transaction or
group of transaction made by an user.
Savepoint is only applicable for rollback purpose. Rollback to a particular point
does not mean, the above transactions are committed.
Rollback to a particular point excluding of that point.
Example :
Empno Name Sal
1 AAA 7800
INSERT INTO MYEMPVALUES (2,BBB,5000)
SAVEPOINT A;
INSERT INTO MYEMP
VALUES (3,CCC,8000)
SAVEPOINT B;
INSERT INTO MYEMP
VALUES (4,DDD,6000)
SAVEPOINT C;
ROLLBACK TO B /*DISCARD C*/
ROLLBACK /*DISCRAD A & B*/
IMPLICIT COMMIT & IMPLICIT ROLLBACK
The above example shows explicit commit and explicit rollback of data. In sme
cases the data is automatically committed or automatically rolled bak by the servers itself
which is basically known as AUTO COMMIT & AUTO ROLLBACK.
In the following circumstances the data is automatically committed;
1. Whenever an user exit out of SQl * Plus normally after any transaction.
2. Whenever a DDL or DCL command is used after any DML operation.
In the following circumstances the data is automatically Rolled Back;
1. Whenever an user exit out of SQL *PLUS abnormally after any transaction.
2. During system Crash.
7/31/2019 sql note2003
37/62
SET AUTOCOMMIT ON :
Valid upto
1. Whenever user exit of SQL * plus
2. Set Autocommit Off
Difference Between Rollback Segment & Buffer :
Rollback Segment Buffer
1. Stores the table called snapshot Stores the SQl Statement
2. Server side Client side
OBJECT
VIEW :
1. View is nothing but a logical subset of a data which is based on one table or more
than one tables.
2. The advantages of view is to protect the table structure from invalid users.
3. View is otherwise known as virtual table
4. The table based on which the view is created is known as the Base table.
5. Depending on the base table view is categorized into 2 different types.
I. Simple View
II. Complex View
Simple View is a type of view which is based on a single table or whose base table is one.
Complex View is a type of view which is based on multiple table or whose base table is
multiple.
Syntax :
CREATE [OR REPLACE] [FORCE | NOFORCE] VIEW
AS
7/31/2019 sql note2003
38/62
[WITH CHECK OPTION]
[WITH READ ONLY];
**Note : View neither contains the structure nor data of a table rather than it contains
only select statement of the base table. But the structure cannot be manipulated by the
user.
Example :
CREATE OR REPLACE VIEW MY VIEW
AS SELECT * FROM MYEMP;
The above example create a simple view which is based on myemp table.
Any record can be inserted, updated, deleted or selected through the view to the base table.
View can be based on a condition
Example :
CREATE OR REPLACE VIEW MYVIEW
AS SELECT * FROM MYEMP
WHERE DEPTNO=20;
In the above example a view will be created based on condition. If a view is based
on condition and record can be inserted through the view to the base table.
But those records are updated deleted and selected on which condition the view is
created.
Restricting Insertion Depending on condition using with check option
Example :
CREATE OR REPLACE MYVIEW
AS SELECT * FROM MYEMP
WHERE DEPTNO=20
WITH CHECK OPTION ;
We cannot insert the values like these (1, AAA , 67000, 10);
Through the above example a view will be created which meant for deptno=20
Creating a readonly view using a readonly
7/31/2019 sql note2003
39/62
Readonly views are those views thorough which the data can be selected but no
DML operation is made through the view to the base table.
This type of view is basically meant for reporting purposes.
Example :
CREATE OR REPLACE MYVIEW
AS SELECT * FROM MYEMP
WITH READ ONLY;
Creating A View Without Having Base Table Forcible Option
Example :
CREATE OR REPLACE FORCE VIEW MYVIEW
AS SELECT * FROM A;
A= TABLE NOT EXIST
Display a message like bellow
Warning : view is created with compilation error
SYNONYM
Synonyms are nothing but a duplicate name of an existing object. The advantage of a
synonyms name is to provide a short object name. Synonyms name is a schema object it
doesnt hold the data of an object rather than holds the references of an object.
Synonym is basically 2 types
1. Private Synonym
2. Public Synonym
Private synonym is a type of synonym once it is given to an object, it can be
accessed in a specified user , where as public synonym is a type of synonym once it is
given to an object can be accessed in any user.
Syntax to create a public or private synonym
Syntax :
CREATE [PUBLIC] SYNONYM
FOR
Example :
CREATE SYNONYM ME
7/31/2019 sql note2003
40/62
FOR MYEMP;
The above example will create a private synonym which is only access in a particular user
where the synonym is created.
To see the names of existing synonyms
Syntax :
SELECT SYNONYM_NAME, TABLE_NAME
FROM USER_SYNONYMS;
PUBLIC SYNONYM
Example :
CREATE PUBLIC SYNONYM ME
FOR MYEMP
**Note : A public synonym can only be created being present in a super user. We can
create a synonym of a existing synonym.
INDEX
It is nothing but a schema object which is required to arrange the records in proper
manner using references.
The advantage of index is to make the query access faster. If no index is created for
a particular column, during data search the total table scan occurs.
In oracle index is categorized in 2 different types :
1. Unique Index / Implicit Index
2. Non-unique / Explicit Index
Unique Index is a type of index which is automatically created by the
oracle Server whenever primary key or unique key constraints are exposed on
particular columns.
Where as Non Unique indexes are those indexes which are explicitly
created by an user on those columns, the columns which have hugely duplicate values.
Syntax :
CREATE INDEX
ON (COL_NAME);
Example :
CREATE INDEX MYEMP_COPMIDX
7/31/2019 sql note2003
41/62
ON MYEMP(DEPTNO,ENAME)
Required whenever an user search the data multi condition wise.
To see the output
SELECT * FROM EMP
WHERE DEPTNO=20 AND ENAME= SMITH;
UNIQUE INDEX
Whenever an unique index will be created automatically by the system , the
name of the index will be same as the constraint name given by the user or given by the
system.
**Note : An index file can be deleted in 2 different manners.
1. Explicitly using drop command
2. Implicitly whenever a table is dropped.
SEQUENCE
It is nothing but a schema object required to generate a linear no . It may be in
ascending order or descending .
Syntax :
CREATE SEQUENCE
[INCREMENT BY ]
[START WITH ]
[MAXVALUE N | NO MAXVALUE]
[MINVALUE N | NO MINVALUE]
[CYCLE | NOCYCLE]
[CACHE N | NOCACHE]
Note : Sequence is schema object which is only meant for insert purpose
Example :
CREATE SEQUENCE MYLINE;
The above example will create a sequence whose initial value is 1, each
incremented by 1 and generate infinite values.
Creating A Cyclic Sequence
Example :
CREATE SEQUENCE MYLINE
MAXVALUE 5
7/31/2019 sql note2003
42/62
CYCLE
CACHE 3
The above example will create a sequence whose initial value will
be 1 each time incremented by 1 and generate 5 nos and do the same for thrice.
Descending Sequence
Example :
CREATE SEQUENCE MYLINE
INCREMENT BY -1
MAXVALUE 10
MINVALUE 1
Modification Of Sequence
Example :
CREATE SEQUENCE MYLINE
MAXVALUE 5;
ALTER SEQUENCE MYLINE
MAXVALUE 10;
ALTER SEQUENCE MYLINE
NOMAXVALUE;
**Note : Any clause of a sequence can be alter except start with clause
DCL
Oracle supports user concept and schema concept to protect the object from invalid
user.
To create and manipulate schema Oracle provides a super user called system
identifier by manager.
To Create A User :
Syntax :
CREATE USER
IDENTIFIED BY
Example :
CREATE USER ORISSA
IDENTIFIED BY BBSR;
7/31/2019 sql note2003
43/62
To Delete An Existing User
Syntax :
DROP USER ;
To Delete A Filled User
Syntax :
DROP USER CASCADE;
Example :
DROP USER ORISSA CASCADE;
To Change The Password Of An User
Syntax :
ALTER USER
IDENTIFIED BY
Example :
ALTER USER SCOTT
IDENTIFIED BY LION
To See The Name Of Current User
Syntax :
SHOW USER;
**Note : User creation and deletion can exclusively done from the super user but
to change the password of a user, the user can take the help of super user or by the
user won the password.
To Jump One User To Another
Syntax :
CONNECT /CONN USERNAME ;
ENTER PASSWORD : PASSWORD;
CONNECTED
Example :
CONNECT SCOTT;
ENTER PASSWORD : MANAGER
CONNECTED
**Note : Connect is a SQL * Plus command required to jump from one user to
another without existing out of SQL * Plus.
7/31/2019 sql note2003
44/62
To Show All User
Syntax :
SELECT USER_NAME FROM DBA_USERS;
Whenever an user created in oracle database it will never work unless and until
some rules are given to it, those rules are technically known as privileges.
Privileges are 2 types :
1. System Privileges
2. Object Privileges
SYSTEM PRIVILEGE
System privileges are those privileges which are given to individual user ,
what can be done and what cant be .
OBJECT PRIVILEGE
Object privileges are those privileges are given to object, what can be done
and what cant be.
System Privileges are
1. Create Session
2. Create Table
3. Create View
4. Create Synonym
5. Create Sequence
6. Create Index
7. Create Procedure
Object Privileges are
1. Select 2. Insert
3. Update
4. Delete
5. Execute
*Note : Among the above privileges Create Session privileges is the primary privilege
requires to activate n user by creating session Id.
7/31/2019 sql note2003
45/62
To impose or revoke the above privileges from an user or from object DCL
provides
1. Grant
2. Revoke
Grant System Privileges To User
Syntax :
GRANT SP1, SP2..,N
TO | ROLE;
Revoke System Privileges From User
Syntax :
REVOKE SP1, SP2..,N
FROM | ROLE;
Grant Object Privileges To User
Syntax :
GRANT OP1, OP2..,N
ON
TO ;
Revoke Object Privileges From User
Syntax :
REVOKE OP1, OP2..,N
ON
FROM ;
**Note : System privileges are those privileges granted or revoked from the super user
only.
Object privileges are granted or revoked by that user who won the user.
WORKING WITH ROLE
Role is nothing but a container, contains system privileges which can be granted to
one user or different users. Role can only created in the system user.
Example :
CONNECT SYSTEM/MANAGER
CREATE ROLE SYSROLE;
GRANT CREATE SESSION, CREATE TABLE, CREATE VIEW
7/31/2019 sql note2003
46/62
TO SYSROLE;
GRANT SYSROLE
TO ORISS;
Display Role Names
SELECT ROLE
FROM USER_ROLES;
**Note : The above example is the example of user defined role .Apart from that
Oracle provide some system defined role to activate the user.
1. Resources (Contains All General User Privileges)
2. DBA (Contains All Super User Privileges).
PL SQL
Though PL SQL is pronounced as a language, but it is not a language typically rather
than it is a mechanism ortechnology implemented on Oracle Server to manipulate the
Database programmatically using SQL Commands .
Every Programming Language uses four different Blocks to develop an application
and those are :
1. Declare
2. Input
3. Process
4. Output
In some programming language the above blocks are physically in nature and they
are identified by some keywords. Those types of languages are basically known as Block
Structure Language. Eg: COBOL.
Where as in some programming language the above blocks are logical in nature and
only they follow rule. Those types of languages are Unblock Structure Language. Eg.
C, C++, etc.
PL SQL is an example of Block Structure Language, where the total program is
divided into 3 different Blocks.
1. Declare Optional
2. Begin Mandatory (Program Construct)
7/31/2019 sql note2003
47/62
Exception Optional
3. End ; Mandatory
DECLARATION
Declaration block is a block which is responsible for declaration of identifier types,
cursors to be used in PL SQL. This block is identified by declare keyword. This Block is
optional in nature.
BEGIN/END
This block is responsible for input, process and output in Pl SQL programme. Pl
SQl always starts execution from begin and end with end. This is mandatory.
EXCEPTION
This block is meant for error handling in PL SQL. Whenever an error occurs at PL
SQL automatically system control will navigate the exception block and thus the execute
the program normally, identified by the keyword exception. This is optional in nature.
The minimum requirement of a language is an identifier , and identifiers minimum
requirement is data types.
PL SQL provide 2 types of data type :
1. SCALAR DATA TYPE
2. COMPOSITE DATA TYPE
Scalar Data Type is a data type which can store one value at one point of
time in form of one variable.
Composite Data Type is a data type which can store multiple values at one
point of time in form of one variable.
SCALAR DATA TYPE
CHAR, VARCHAR2, NUMBER, DATE, BOOLEAN
Scalar Data Type provides an Attribute %type.
COMPOSITE DATA TYPE
User defined data type or type declaration. It provides an attribute called
%rowtype.
Declaring A Variable
Syntax :
DECLARE
V_NAME DATATYPE(SIZE);
A NUMBER (4);
V_NAME DATATYPE(SIZE):=
7/31/2019 sql note2003
48/62
A NUMBER(4):= 10;
Note : In PL SQL assignment operators is := .Each and individual statement in PL
SQL are to be terminated by ;.
To Display Output
DBMS_OUTPUT.PUT_LINE( );
It will work after declaring SET SERVEROUTPUT ON before declaration block.
*Note : To use DBMS_OUTPUT.PUT_LINE( ) a related SQL * PLUS command is
required known as SET SERVER OUTPUT ON, which allows the Server to display the
output in client console. The default behavior is OFF .
SQL Statement To Be Used In PL SQL
Though PL SQL advanced version of SQL, It only uses 3 sublanguages of SQL
1. DQL
2. DML
3. TCL
**Note : DDL & DCL are not allowed in PL SQL.
SELECT Statement in PL SQL
Syntax :
SELECT COL1, COL2, COL3.., N
INTO V1, V2, V3,., N
FROM
WHERE
DBMS_OUTPUT.PUT_LINE(V1)-------------------------------------------
------------------------------------------
DBMS_OUTPUT.PUT_LINE(N)
PL SQL is capable to develop 2 types of programme :
1. Anonymous Block
2. Sub Programme
7/31/2019 sql note2003
49/62
Anonymous Block is a type of programme whose programme code is stored inside
client hard diskin form of.SQL file .
Where as Sub Programme is a type of program whose program code is stored
inside Database server in form ofObject.
*Note : The job of anonymous block and sub programme is same to manipulate thedatabase programmatically, but divided into 2 category depending on their security.
To create a new file
Syntax :
Ed
Example :
Ed sysfile
The above example will create a file called sysfile .
Example :
SET SERVER OUTPUT ON
BEGIN
DBMS_OUTPUT.PUT_LINE (HELLO USER)
END;
O/P : HELLO USER
Example :
Write a programme which will display EMPNO, NAME, SAL, JOB of that
employee whose name is Blake.
SET SERVEROUTPUT ON
CLEAR SCREEN
SET VERIFY OFF
DECLARE
VEMPNO NUMBER(4);
VNAME VARCHAR2(20);
VSAL NUMBER(7,2);
VJOB VARCHAR2 (20);
BEGIN
SELECT EMPNO,ENAME, SAL ,JOB
7/31/2019 sql note2003
50/62
INTO VEMPNO, VNAME,VSAL, VJOB
FROM EMP
WHERE ENAME= BLAKE;
DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.NO : || VEMPNO)
DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.NAME : || VNAME)
DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.SAL : || VSAL)
DBMS_OUTPUT.PUT_LINE ( EMPLOYEE.JOB : || VJOB)
END;
/
Dynamic Input
Where Ename = &name ;
Working with Scalar Attribute (% Type)
% type is a scalar attribute which is required to declare a variable as a particular
table columns type or another variable type.
The advantage of this attribute is for proper memory management .
Example :
SET SERVEROUTPUT ON
CLEAR SCREEN
SET VERIFY OFF
DECLARE
VEMPNO EMP.EMPNO%TYPE;
A VEMPNO%TYPE
VNAME EMP.ENAME%TYPE;
VSAL EMP.SAL%TYPE ;
VJOB EMP.JOB%TYPE;
BEGIN
SELECT EMPNO,ENAME,SAL,JOB
INTO VEMPNO,VNAME,VSAL,VJOB
FROM EMP WHERE ENAME='BLAKE';
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO : ' || VEMPNO);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO : ' || VNAME);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO : ' || VSAL);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO : ' || VJOB);
END;
/
7/31/2019 sql note2003
51/62
In the above exampleVempno is a variable which is employee no type where as A
is variable which is Vempno type
Working With Composite Attribute (%rowtype)
%row type is a composite attribute which is required to declare a variable as a
particular table structure type. The advantage of % row type is it reduces the programme
coding.
Example :
SET SERVEROUTPUT ON
CLEAR SCREEN
SET VERIFY OFF
DECLARE
A EMP %ROWTYPE;
BEGIN
SELECT * INTO A
FROM EMP WHERE ENAME='&NAME';
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.EMPNO);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.ENAME);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.SAL);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.JOB);
END;
/
The disadvantage of % row type is , It uses unnecessary memory spaces. To avoid the
above loophole the user can declare its own data type known as TYPE DECLARATION.
Declaring User defined Data type
Syntax :
DECLARE
TYPE IS RECORD
( V_NAME DATATYPE (SIZE),
V_NAME DATATYPE (SIZE),
V_NAME DATATYPE (SIZE),
.N);
V_NAME
Example :
7/31/2019 sql note2003
52/62
SET SERVEROUTPUT ON
CLEAR SCREEN
SET VERIFY OFF
DECLARE
TYPE MYTYPE IS RECORD
(VEMPNO EMP.EMPNO%TYPE,
VNAME EMP.ENAME%TYPE,
VSAL EMP.SAL%TYPE,
VJOB EMP. JOB%TYPE);
A MYTYPE;
BEGIN
SELECT EMPNO,ENAME,SAL,JOB
INTO AFROM EMP WHERE ENAME='&NAME';
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VEMPNO);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VNAME);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VSAL);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :' || A.VJOB);
END;
/
In the above example MYTYPE is a structure where as A is a Variable of Mytype.
WORKING WITH CONTROL STATEMENT
Control statement is a block of executable statement which will perform a specify
task once or no of times unless and until a condition is satisfied.
Those are :
1. IF.ELSE ..ENDIF
2. BASIC LOOP
3. WHILE LOOP
4. FOR LOOP
Syntax of IF :
IF THEN
STATEMENT;
7/31/2019 sql note2003
53/62
STATEMENT;
ELSE
STATEMENT;
ENDIF;
Syntax of Nested IF :
IF THEN
STATEMENT;
STATEMENT;
ELSIF THEN
STATEMENT;
STATEMENT;
ELSIF THEN
STATEMENT;STATEMENT;
ELSE
STATEMENT;
END IF;.
OR
IF THEN
STATEMENT;
STATEMENT;
ELSE
IF THEN
STATEMENT;
STATEMENT;
ELSE
IF THEN
STATEMENT;
STATEMENT;
ELSE
ENDIF;
ENDIF;
ENDIF;
7/31/2019 sql note2003
54/62
Syntax Of Basic LOOP :
Basic lop is type of looping where the statement is executed
first then it checks the condition . In this type of looping the statement must be executed
once.
Syntax :
LOOP
STATEMENT;
STATEMENT;
STATEMENT;
EXIT [WHEN ];
END LOOP;
Example :
DECLARE
I NUMBER(4):=1;BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(I);
I:=I+1;
EXIT WHEN I>10;
END LOOP;
END;
/
Syntax Of While LOOP :
This is a type of looping where the condition is checked first
then it will execute the statement. If the condition is set to false the system control will
move to the very next statement after looping.
Syntax :
WHILE LOOP
STATEMENT;
STATEMENT;
------------------;
------------------;
END LOOP;
Example :
SET SERVEROUTPUT ON
7/31/2019 sql note2003
55/62
DECLARE
I NUMBER(4):=1;
BEGIN
WHILE I
7/31/2019 sql note2003
56/62
and once the execution is done automatically cursor memory will be deleted from the
SERVER.
Cursor is basically categorized in 2 different types
1. Implicit Cursor (Automatically)
2. Explicit (Create By Own)
Cursor ha s4 different stages namely
1. DECLARE
2. OPEN3. FETCH
4. CLOSE
DECLARATION of a cursor means the memory will be declared inside the srver
and the statement will be dumped inside the memory.
OPENING of a cursor means the statement available inside the temporary memory
starts execution and the output returned by the statement will be stored inside the same
memory.
FETCHING of a cursor means the output available inside the temporary memory
will be transport one by one to the respective variable.
CLOSING of a cursor means the memory will be deallocated once the processing
is over.
7/31/2019 sql note2003
57/62
IMPLICIT CURSORis a type of cursor where all the above jobs are being dump
implicitly by the system itself but the disadvantages of implicit cursor is it can store one
record at one point of time.
Where as EXPLICIT CURSOR is a type of cursor where all the above jobs are
done by explicitly by the user itself but the advantage of an explicit cursor is it can store
multiple records at one point of time for the processing purpose.
Cursor has four different attributes to manipulate itself.
1. %FOUND
2. %NOTFOUND
3. %ISOPEN
4. %ROWCOUNT
The above attributes are always suffixed with the cursor name either given by the user or
given by the system.
Declaring An Explicit Cursor
Syntax :
DECLARE
CURSOR IS
;
Opening Explicit Cursor
Syntax :
BEGIN
OPEN ;
Fetching An Explicit Cursor
Syntax :
FETCH INTO ;
Closing An Explicit Cursor
Syntax :
CLOSE
END;
/
Simple Cursor Using Basic Loop
Example :
7/31/2019 sql note2003
58/62
SET SERVEROUTPUT ON
DECLARE
CURSOR C1 IS
SELECT EMPNO,ENAME,SAL,JOB FROM EMP
WHERE JOB='MANAGER';
A C1%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO A;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :'|| A.EMPNO);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME :'|| A.ENAME);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARAY :'|| A.SAL);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE JOB :'|| A.JOB);
DBMS_OUTPUT.PUT_LINE('----------------------');
END LOOP;
CLOSE C1;
END;
/
The above example is an example ofsimple cursor using basic loop.
**Note : Open is a key word which can perform 2 jobs
1. Execute the statement and stores the output inside the same memory
2. Set the pointer to the 1strecord of the record set.
Likewise Fetch is a keyword which can perform 2 jobs
1. Fetch the current record into the variable
2. Skip the pointer to the nest record of the record set.
Simple Cursor Using For LoopThe advantage of cursor for loop over cursor basic loop is , in cursor loop the
cursor is explicitly declared by the user but opening , fetching, closing is done by the
system itself.
In another words, the advantage of cursor for loop is the coding will be less.
Syntax :
DECLARE
CURSOR IS
7/31/2019 sql note2003
59/62
;
BEGIN
FOR IN LOOP
STATEMENT;
STATEMENT;
-----------------;
END LOOP;
END;
/
Example :
SET SERVEROUTPUT ON
DECLARE
CURSOR C1 ISSELECT EMPNO,ENAME,SAL,JOB FROM EMP
WHERE JOB='MANAGER';
BEGIN
FOR A IN C1 LOOP
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :'|| A.EMPNO);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME :'|| A.ENAME);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARAY :'|| A.SAL);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE JOB :'|| A.JOB);
DBMS_OUTPUT.PUT_LINE('----------------------');
END LOOP;
END;
/
Advance Cursor Or Cursor With Parameter
Advance cursor is otherwise known as dynamic cursor. The advantage of dynamic
cursor is each time. It will ask for the value and depending upon the value the cursor will
be opened.
Declaring Advance Cursor
Syntax :
DECLARE
CURSOR (ARG DATATYPE) IS
SELECT STATEMENT;
7/31/2019 sql note2003
60/62
WHERE COL_NAME=ARG;
BEGIN
OPEN (VALUE/EXPRESSION)
Example :
Advance Cursor In For Loop
Syntax :
Example :
SET SERVEROUTPUT ON
DECLARE
CURSOR C1(VJOB VARCHAR2) IS
SELECT EMPNO, ENAME, SAL , JOB FROM EMP
WHERE JOB=VJOB;
BEGIN
FOR A IN C1('&VJOB')LOOP
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NO :'|| A.EMPNO);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE NAME :'|| A.ENAME);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE SALARAY :'|| A.SAL);
DBMS_OUTPUT.PUT_LINE('EMPLOYEE JOB :'|| A.JOB);
DBMS_OUTPUT.PUT_LINE('----------------------');
END LOOP;
END;
/
7/31/2019 sql note2003
61/62
SUBPROGRAMS
Subprograms has to be physical existence inside the server inform of object . Subprograms
are otherwise known as NAME BLOCK when any other block otherwise known as
UNAME BLOCK.
The advantages of subprograms, it is more secured than anonymous block.
Subprograms is categorized in 2 different types.
1. STORED PROCEDURE
2. STORED FUNCTION
Creating A Procedure
Syntax :
CREATE [OR REPLACE] PROCEDURE [(ARG DATATYPE)]
IS/AS
IDENTIFIER DECLARATION
TYPE DECLARATION
CURSOR DECLARATION
BEGIN
STATEMENT;
STATEMENT;
;
END
Example :
PACKAGE
Package is nothing but a container which contains related procedure and function to be
used by one user or different users. The advantage of a package is to make the procedure
& function execution faster.
Package has 2 different parts or blocks.
7/31/2019 sql note2003
62/62
1. PACKAGE SPECIFICATION
2. PACKAGE BODY
Package Specificationblock is a block where all procedure & functions are to be declared
or specified to be used inside a package where as Package Body is a block where all the
procedure and function are to be designed which are developed in the
Specification block.
**Note : Procedure & Function specified in the specification block may or
may not be designed in the body block but the procedures & functions designed in the
body block have to be specified in the specification block.
Syntax Of Package Specification :
Syntax :
CREATE [OR REPLACE] PACKAGE
IS / AS
PROCEDURE [(ARG DATATYPE)];
PROCEDURE [(ARG DATATYPE)];
PROCEDURE [(ARG DATATYPE)];
-------------------------------------------------------------N;
END ;
/
Syntax Of Package Body :