Professional Documents
Culture Documents
Database Systems Laboratory 1: Introduction To SQL
Database Systems Laboratory 1: Introduction To SQL
Chittaranjan Pradhan
Client/Server
Laboratory 1 Database
SQL
SQL Statements
Data Types
Table Creation
Viewing Table
Structure
Record Insertion
Inserting Time
Querying Data
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
1.1
Introduction To SQL
Introduction To SQL
Chittaranjan Pradhan
1 RDBMS
RDBMS
Client/Server
2 Client/Server Database Database
SQL
Data Types
SQL*PLUS
Table Creation
Naming Conventions
Viewing Table
Structure
4 Data Types Record Insertion
Inserting Time
7 Record Insertion
Inserting Time
8 Querying Data
1.2
Introduction To SQL
RDBMS
Chittaranjan Pradhan
RDBMS
Client/Server
• Relational database is a collection of related information Database
that has been organized into tables. Each table contains SQL
SQL Statements
rows and columns SQL*PLUS
Naming Conventions
• The tables are stored in the database in structures known Data Types
as schemas Table Creation
Viewing Table
Structure
• Each row is called an entity, thus table as entity set
Record Insertion
• Row is known as Tuple Inserting Time
Querying Data
• Columns are the properties called Attributes
• The facts describing an entity are known as data
1.3
Introduction To SQL
Employee Table
Chittaranjan Pradhan
RDBMS
Client/Server
Database
SQL
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO SQL Statements
SQL*PLUS
7369 SMITH CLERK 7902 17-DEC-80 800 20
Naming Conventions
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 Data Types
1.4
Introduction To SQL
Examples of RDBMS
Chittaranjan Pradhan
• Oracle
RDBMS
• DB2 Client/Server
Database
• Microsoft SQL-Server
SQL
• SQLite
• Vertica
• IBM Informix
• Ingres
• IBM Lotus
• SQL Anywhere
1.5
Introduction To SQL
Client/Server Database
Chittaranjan Pradhan
RDBMS
Client/Server
Database
SQL
• Client/Server databases run the DBMS as a process on SQL Statements
SQL*PLUS
the server and run a client database application on each Naming Conventions
Table Creation
• The client application sends a request for data over the
Viewing Table
network to the server Structure
Record Insertion
• When the server receives the client request, the DBMS Inserting Time
retrieves data from the database, performs the required Querying Data
1.6
Introduction To SQL
SQL
Chittaranjan Pradhan
RDBMS
• SQL( Structured Query Language) is the standard Client/Server
language for relational database Database
SQL
• IBM developed the original version of SQL in early 1970s, SQL Statements
SQL*PLUS
with name Sequel Naming Conventions
• In 1986, the ANSI & ISO published the SQL standard, Data Types
Table Creation
SQL-86
Viewing Table
• ANSI published extended standard, SQL-89 in 1989 Structure
Record Insertion
• Next versions are SQL-92, SQL-1999, SQL-2003, Inserting Time
1.7
Introduction To SQL
SQL Statements
Chittaranjan Pradhan
RDBMS
Data Definition Language(DDL)
Client/Server
Database
Defines the data structure that make up a database
SQL
• CREATE statement SQL Statements
SQL*PLUS
Data Types
• DROP statement Table Creation
Querying Data
Data Manipulation Language(DML)
Modifies the contents of tables
• INSERT statement
• UPDATE statement
• DELETE statement
1.8
Introduction To SQL
SQL Statements...
Chittaranjan Pradhan
Query Statement
RDBMS
Retrieves data from the database Client/Server
Database
• SELECT statement SQL
SQL Statements
SQL*PLUS
Naming Conventions
Transaction Control Language(TCL)
Data Types
Permanently records the changes made to the rows stored in a Table Creation
• SAVEPOINT statement
1.9
Introduction To SQL
SQL*PLUS
Chittaranjan Pradhan
RDBMS
Client/Server
Database
Table Creation
• Two versions of SQL*PLUS Viewing Table
Structure
• Graphical version
Record Insertion
• Start->All Programs->Oracle Database 10g Express Inserting Time
Edition->Go to Database home page(SQL->SQL Commands) Querying Data
• Command-Line version
• Start->All Programs->Oracle Database 10g Express
Edition->Run SQL Command Line(Connect)
1.10
Introduction To SQL
Naming Conventions
Chittaranjan Pradhan
RDBMS
Client/Server
Database
• When you create a table, you must specify the table name, SQL*PLUS
Naming Conventions
name of each column, data type of each column, and size Data Types
of each column Table Creation
1.11
Introduction To SQL
Data Types
Chittaranjan Pradhan
RDBMS
Data type specifies the type of data that will be stored in the
Client/Server
column. Data types also help to optimize storage space Database
SQL
• CHAR(n) SQL Statements
SQL*PLUS
• Stores fixed-length alphanumeric data in a column Naming Conventions
• Default and minimum size is one character Data Types
• Maximum allowable size is 2000 characters (previously 255) Table Creation
• If a string of a smaller length is stored, it is padded with Viewing Table
Structure
spaces at the end
Record Insertion
Inserting Time
• VARCHAR(n)/VARCHAR2(n) Querying Data
• Stores variable-length alphanumeric data in a column
• Default and minimum size is one character
• Maximum allowable size is 4000 characters (previously
2000)
• If the data are smaller than the specified size, only the data
value is stored; no padding is done
1.12
Introduction To SQL
Data Types...
Chittaranjan Pradhan
RDBMS
• DATE
Client/Server
• Stores date and time values Database
Table Creation
Querying Data
number; scale is the total number of digits to the right of the
decimal point(if used). The precision can range from 1 to 38
• If neither precision nor scale is specified, any number may
be stored up to a precision of 38 digits
• INTEGER
• Stores integer number
1.13
Introduction To SQL
Data Types...
Chittaranjan Pradhan
• NUMERIC(p,d)
RDBMS
• Stores fixed-point number with user specified precision Client/Server
Database
• Similar to NUMBER data type
SQL
SQL Statements
• LONG SQL*PLUS
Naming Conventions
• Stores variable length character strings containing up to
Data Types
2GB Table Creation
• Similar to VARCHAR
Viewing Table
• There can be one LONG data type per table Structure
Record Insertion
Querying Data
• Stores binary data such as digitized picture or image
• Maximum allowable size is 2000 Bytes (previously 255
Bytes)
• LONG RAW
• It is the higher range of RAW
• There can be one LONG data type per table
• Maximum allowable size id 2GB
1.14
Introduction To SQL
Data Types...
Chittaranjan Pradhan
RDBMS
Client/Server
Database
SQL
• LOB(Large Object) SQL Statements
SQL*PLUS
• Stores large volume of data Naming Conventions
• BLOB Data Types
• Used for binary data such as graphics, video clips and audio Table Creation
files up to 4GB Viewing Table
• CLOB Structure
1.15
Introduction To SQL
Table Creation
Chittaranjan Pradhan
RDBMS
Client/Server
Database
CREATE TABLE statement SQL
SQL Statements
CREATE statement is used for table creation. The syntax is: SQL*PLUS
Naming Conventions
Data Types
CREATE TABLE table_name( column datatype, Table Creation
column datatype, ... column datatype); Viewing Table
Structure
For example, create a table for STUDENT ( Roll, Name, Record Insertion
Inserting Time
Gender, Age, CGPA) Querying Data
1.16
Introduction To SQL
Viewing Table Structure
Chittaranjan Pradhan
RDBMS
DESCRIBE statement
Client/Server
DESCRIBE statement is used for viewing table structure. The Database
SQL
syntax is: SQL Statements
SQL*PLUS
Naming Conventions
DESCRIBE table_name; or Data Types
DESC table_name; Table Creation
Viewing Table
For example: DESCRIBE STUDENT; Structure
Querying Data
Name Null? Type
Roll NUMBER(6)
Name VARCHAR2(20)
Gender CHAR(1)
Age NUMBER(3)
CGPA NUMBER(4,2)
1.17
Introduction To SQL
Record Insertion
Chittaranjan Pradhan
INSERT statement
INSERT statement is used to insert a new row/record into a RDBMS
SQL
INSERT INTO table_name (column1, column2,..) VALUES SQL Statements
SQL*PLUS
(value1, value2,..); Naming Conventions
Data Types
Table Creation
• Column names are optional
Viewing Table
• Numeric data is not enclosed within quotes; while Structure
Record Insertion
character and date values are enclosed within single Inserting Time
RDBMS
Substitution variables
Client/Server
Database
• Substitution variables enable you to create an interactive SQL
SQL script, which prompts you to enter a value for the SQL Statements
SQL*PLUS
substitution variable Naming Conventions
Data Types
• In command line version, & character is used before the
Table Creation
substitution variable in the query; whereas : character is Viewing Table
used in graphical version Structure
Record Insertion
• Substitution variables for character and date columns are Inserting Time
1.19
Introduction To SQL
Record Insertion...
Chittaranjan Pradhan
RDBMS
• INSERT INTO STUDENT(Roll, Name, Gender, Age, Client/Server
Database
CGPA) VALUES (705129, ’Uday’, ’M’, 19, 9.2);
SQL
SQL Statements
SQL*PLUS
• INSERT INTO STUDENT VALUES (705129, ’Uday’, ’M’, Naming Conventions
Table Creation
Viewing Table
• INSERT INTO STUDENT(Roll, Name, CGPA) VALUES Structure
Querying Data
1.20
Introduction To SQL
Record Insertion...
Chittaranjan Pradhan
Customized Prompts
RDBMS
• ACCEPT Roll PROMPT ’Please enter the Roll of Student:’ Naming Conventions
Data Types
• ACCEPT Name PROMPT ’Please enter the Name of
Table Creation
Student:’ Viewing Table
Structure
• ACCEPT Gender PROMPT ’Please enter the Gender of
Record Insertion
Student:’ Inserting Time
Querying Data
• ACCEPT Age PROMPT ’Please enter the Age of Student:’
• ACCEPT CGPA PROMPT ’Please enter the CGPA of
Student:’
INSERT INTO STUDENT VALUES (&Roll, ’&Name’,
’&Gender’, &Age, &CGPA);
RDBMS
Client/Server
Database
Data Types
INSERT INTO STUDENT(dob) VALUES (TO_DATE( Table Creation
’12-JAN-1990 10:34:45 P.M.’, ’DD-MON-YYYY HH:MI:SS Viewing Table
Structure
P.M.’));
Record Insertion
Inserting Time
• If only the date value is entered in a date-type column, the Querying Data
1.22
Introduction To SQL
Querying Data
Chittaranjan Pradhan
RDBMS
SELECT statement Client/Server
Database
SELECT statement is used to retrieve data from the underlying
SQL
table. The syntax is: SQL Statements
Data Types
If the user wants to see all the columns in a table, * can be Table Creation
Record Insertion
SELECT * FROM STUDENT; Inserting Time
Querying Data
Roll Name Gender Age CGPA
705129 Uday M 19 9.2
705170 Ram M 20
705171 Kim F 19 8.6
705172 Raji 20 7.5
1.23
Introduction To SQL
Querying Data...
Chittaranjan Pradhan
RDBMS
Client/Server
Database
SQL
SQL Statements
Data Types
Roll Name CGPA
Table Creation
705129 Uday 9.2 Viewing Table
705170 Ram Structure
Record Insertion
705171 Kim 8.6 Inserting Time
1.24
SQL Fundamentals
Chittaranjan Pradhan
Laboratory 2
condition
Sorting
ALTER Statement
DROP Statement
TRUNCATE Statement
DELETE Statement
RENAME Statement
ROWID
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
2.1
SQL Fundamentals
SQL Fundamentals
Chittaranjan Pradhan
1 SELECT Statement
Operators used in WHERE condition SELECT Statement
Operators used in WHERE
Sorting condition
Sorting
UPDATE Statement
TRUNCATE Statement
4 DROP Statement DELETE Statement
RENAME Statement
5 TRUNCATE Statement Viewing User Tables
11 ROWID
2.2
SQL Fundamentals
Student table
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
Roll Name City Age CGPA condition
Sorting
RENAME Statement
106 Yogesh Rajastan 18 7.9
Viewing User Tables
210 Smriti Delhi 20 8.99
Creating Table from
211 Sudam Cuttack 21 8.6 another Table
ROWID
2.3
SQL Fundamentals
SELECT Statement
Chittaranjan Pradhan
SELECT statement
SELECT Statement
SELECT statement is used to retrieve data from the underlying Operators used in WHERE
condition
table. The syntax is: Sorting
UPDATE Statement
DROP Statement
If the user wants to see all the columns in a table, * can be
TRUNCATE Statement
used in place of columns DELETE Statement
RENAME Statement
SELECT Roll, CGPA FROM Student;
Viewing User Tables
2.4
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan
DROP Statement
DELETE Statement
City RENAME Statement
2.5
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan
DROP Statement
DELETE Statement
Name Age Age+3 RENAME Statement
2.6
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan
The column aliases are used to rename a table’s columns for condition
Sorting
the purpose of a particular SQL query. The syntax is: ALTER Statement
SELECT column1, column2 [AS] Alias FROM tablename; UPDATE Statement
DROP Statement
SELECT Name, Age, Age+3 “Passing Age”FROM Student; TRUNCATE Statement
DELETE Statement
Name Age Passing Age RENAME Statement
Ram 19 22 Viewing User Tables
2.7
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan
Concatenation
SELECT Statement
ALTER Statement
SELECT column1||’ ’||column2 [AS] ALIAS FROM
UPDATE Statement
tablename; DROP Statement
TRUNCATE Statement
SELECT Name||’ ’||City FROM Student;
DELETE Statement
SELECT Name||’ ’||City AS “Address”FROM Student; RENAME Statement
2.8
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan
Displaying Time
SELECT Statement
Operators used in WHERE
Time of a date-type column can be displayed by using condition
Sorting
TO_CHAR(). The syntax is:
ALTER Statement
UPDATE Statement
DROP Statement
SELECT Roll, DOB FROM Student;
TRUNCATE Statement
SELECT Roll, TO_CHAR(DOB, ’DD-MON-YYYY HH:MI:SS
DELETE Statement
A.M.’) FROM Student; RENAME Statement
2.9
SQL Fundamentals
Operators used in WHERE condition
Chittaranjan Pradhan
DELETE Statement
<> or != ex: Name !=’Hari’
RENAME Statement
ANY ex: Age > ANY(20,23,19)
Viewing User Tables
ALL ex: Age > ALL(20,18) Creating Table from
another Table
2.10
SQL Fundamentals
Operators used in WHERE condition...
Chittaranjan Pradhan
LIKE Operator
SELECT Statement
LIKE operator uses wild cards for matching as: Operators used in WHERE
condition
%: represents zero or more characters Sorting
UPDATE Statement
DELETE Statement
ex: Name LIKE ’%i%’
RENAME Statement
ex: Name LIKE ’_i%’ Viewing User Tables
Name Age
Hari
2.11
SQL Fundamentals
Sorting
Chittaranjan Pradhan
SELECT Statement
ORDER BY clause using column name Operators used in WHERE
condition
UPDATE Statement
ORDER BY column [ASC/DESC]; DROP Statement
TRUNCATE Statement
SELECT * FROM Student ORDER BY Age; DELETE Statement
NULL values come at the end of the table in case of ORDER Viewing User Tables
ROWID
Records can be sorted by using the column number
SELECT columns FROM tablename [WHERE cond n ]
ORDER BY columnno [ASC/DESC];
SELECT * FROM Student ORDER BY 3;
2.12
SQL Fundamentals
ALTER Statement
Chittaranjan Pradhan
TRUNCATE Statement
DELETE Statement
2.13
SQL Fundamentals
ALTER Statement...
Chittaranjan Pradhan
UPDATE Statement
Column NULL? Datatype
DROP Statement
ROLL NUMBER(6)
TRUNCATE Statement
NAME VARCHAR2(20)
DELETE Statement
AGE NUMBER(2)
RENAME Statement
ADDRESS VARCHAR2(20)
Viewing User Tables
ROWID
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
Renaming a Column
UPDATE Statement
DELETE Statement
2.15
SQL Fundamentals
UPDATE Statement
Chittaranjan Pradhan
TRUNCATE Statement
DELETE Statement
UPDATE Statement RENAME Statement
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Stud SET Branch=’CSE’; UPDATE Statement
DROP Statement
Roll Name Age Branch TRUNCATE Statement
101 Vikas 19 CSE DELETE Statement
ROWID
2.17
SQL Fundamentals
DROP Statement
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Statement
DROP Statement
TRUNCATE Statement
DROP command
DELETE Statement
DROP TABLE tablename; RENAME Statement
ROWID
2.18
SQL Fundamentals
TRUNCATE Statement
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Statement
DROP Statement
TRUNCATE Statement
TRUNCATE command
DELETE Statement
TRUNCATE TABLE tablename; RENAME Statement
ROWID
2.19
SQL Fundamentals
DELETE Statement
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Statement
DROP Statement
DELETE command
TRUNCATE Statement
DELETE FROM tablename [WHERE cond n ]; DELETE Statement
RENAME Statement
DELETE FROM Stud WHERE Roll=101; Viewing User Tables
ROWID
2.20
SQL Fundamentals
RENAME Statement
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Statement
DROP Statement
TRUNCATE Statement
RENAME command
DELETE Statement
RENAME oldname TO newname; RENAME Statement
ROWID
2.21
SQL Fundamentals
Viewing User Tables
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Statement
TRUNCATE Statement
SELECT * FROM TAB; DELETE Statement
RENAME Statement
ROWID
2.22
SQL Fundamentals
Creating Table from another Table
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
DROP Statement
CREATE TABLE tablename(column1,column2) AS SELECT TRUNCATE Statement
column1,column2 FROM tablename; DELETE Statement
RENAME Statement
CREATE TABLE Person(Roll, Name, Age) AS SELECT Roll, Viewing User Tables
Name, Age FROM Stud; Creating Table from
another Table
2.23
SQL Fundamentals
Inserting data into a Table from another Table
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
ALTER Statement
UPDATE Statement
Inserting data into a Table from another Table
DROP Statement
RENAME Statement
INSERT INTO Person SELECT Roll, Name, Age FROM Stud Viewing User Tables
ROWID
2.24
SQL Fundamentals
ROWID
Chittaranjan Pradhan
ALTER Statement
• It is an 18-bit number and represented as a base-64
UPDATE Statement
number DROP Statement
DELETE Statement
RENAME Statement
In case user has inputted same records more than one time, Viewing User Tables
ROWID is used to distinguish each record Creating Table from
another Table
1 Akash BBS
2 Amir BBS
2 Amir BBS
3 Ashok CTC
2.25
SQL Fundamentals
ROWID...
Chittaranjan Pradhan
SELECT Statement
Operators used in WHERE
condition
Sorting
If the user wants to delete the duplicate copies of the same ALTER Statement
DROP Statement
DELETE Statement
ROWID Cid RENAME Statement
AAAF4YAABAAAHCKAAA 1 Viewing User Tables
AAAF4YAABAAAHCKAAB 2
Creating Table from
AAAF4YAABAAAHCKAAC 2 another Table
AAAF4YAABAAAHCKAAD 3
Inserting data into a
Table from another
DELETE FROM Customer WHERE ROWID= Table
’AAAF4YAABAAAHCKAAC’; ROWID
2.26
Constraints
Chittaranjan Pradhan
Constraints table
PRIMARY Key
Constraint
Dealing with PRIMARY
KEY Constraint in an
existing table
FOREIGN Key
Constraint
Dealing with FOREIGN
KEY Constraint in an
existing table
CHECK Constraint
Dealing with Check
Constraint in an existing
table
DEFAULT Value
Viewing USER
Constraints
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
3.1
Constraints
Constraints
Chittaranjan Pradhan
1 Constraints
Constraints
7 DEFAULT Value
3.2
Constraints
Constraints
Chittaranjan Pradhan
SQL Constraints
Constraints
Constraints enforce rules on tables. Constraints can be NOT NULL Constraint
imposed to the database tables either with the CREATE or Unique Constraint
ALTER command. Whenever a DML operation is to be Dealing with UNIQUE
Constraint in an existing
PRIMARY Key
for the operation to succeed Constraint
Dealing with PRIMARY
KEY Constraint in an
existing table
name. For a user’s account, each constraint name must be existing table
CHECK Constraint
unique. The standard convention for naming constraint is : Dealing with Check
Constraint in an existing
<table name>_<column name>_<constraint type> table
DEFAULT Value
The abbreviation for different constraint types are: pk for Viewing USER
Constraints
PRIMARY Key, fk for FOREIGN Key, uk for UNIQUE, chk or ck
for CHECK and nn for NOT NULL constraint
If you do not name a constraint, then the server will generate a
name for it by using SYS_Cn format
3.3
Constraints
Constraints...
Chittaranjan Pradhan
Defining a Constraint
Constraints
Constraint can be defined in either of the two ways: NOT NULL Constraint
Unique Constraint
• Column level: Dealing with UNIQUE
Constraint in an existing
• A column- level constraint references a single column and is table
PRIMARY Key
defined along with the definition of the column Constraint
• This type of constraint is applied to the current column only Dealing with PRIMARY
KEY Constraint in an
• column datatype [CONSTRAINT constraint_name] existing table
Constraints
It ensures that the column has a value and the value is not a Constraint in an existing
table
CHECK Constraint
NOT NULL Dealing with Check
Constraint in an existing
It can only be applied at column level table
DEFAULT Value
3.5
Constraints
NOT NULL Constraint...
Chittaranjan Pradhan
Unique Constraint
Item_no NUMBER 4 Dealing with UNIQUE
CHECK Constraint
Dealing with Check
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4), Name Constraint in an existing
table
VARCHAR2(20), Qty_on_hand NUMBER(5), Category DEFAULT Value
CHAR(1), Unit_measure CHAR(4), Reorder_Lvl NUMBER(5), Viewing USER
Reorder_qty NUMBER(5), Rate NUMBER(8,2)); Constraints
3.6
Constraints
NOT NULL Constraint...
Chittaranjan Pradhan
PRIMARY Key
Constraint
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) Dealing with PRIMARY
KEY Constraint in an
CONSTRAINT c1 NOT NULL, Name VARCHAR2(20), existing table
FOREIGN Key
Qty_on_hand NUMBER(5), Category CHAR(1), Unit_measure Constraint
Viewing USER
A NOT NULL constraint can be dropped by executing Constraints
FOREIGN Key
UNIQUE Constraint
Dealing with FOREIGN
KEY Constraint in an
existing table
Table level: CONSTRAINT constraintname
CHECK Constraint
UNIQUE(columns) Dealing with Check
Constraint in an existing
table
3.8
Constraints
Unique Constraint...
Chittaranjan Pradhan
FOREIGN Key
Constraint
Dealing with FOREIGN
KEY Constraint in an
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) NOT existing table
CHECK Constraint
NULL, Name VARCHAR2(20) , Qty_on_hand NUMBER(5), Dealing with Check
3.9
Constraints
Unique Constraint...
Chittaranjan Pradhan
Constraints
PRIMARY Key
Constraint
Dealing with PRIMARY
CONSTRAINT student_name_city_uk UNIQUE(name, city) KEY Constraint in an
existing table
FOREIGN Key
Constraint
Dealing with FOREIGN
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) NOT KEY Constraint in an
existing table
3.10
Constraints
Dealing with UNIQUE Constraint in an existing table
Chittaranjan Pradhan
Constraints
DEFAULT Value
3.11
Constraints
Primary Key Constraint
Chittaranjan Pradhan
PRIMARY Key
constraint and UNIQUE constraint Constraint
Dealing with PRIMARY
KEY Constraint in an
existing table
Column level: Columnname datatype(size) PRIMARY KEY or
FOREIGN Key
Constraint
Dealing with FOREIGN
Columnname datatype(size) CONSTRAINT constraintname KEY Constraint in an
existing table
PRIMARY KEY CHECK Constraint
Dealing with Check
Constraint in an existing
DEFAULT Value
KEY(columns)
Viewing USER
Constraints
roll number(6) CONSTRAINT student_roll_pk PRIMARY KEY
3.12
Constraints
Primary Key Constraint...
Chittaranjan Pradhan
Constraints
Let the Item_no column in ITEM_MASTER table is primary key: NOT NULL Constraint
Unique Constraint
Dealing with UNIQUE
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) Constraint in an existing
table
PRIMARY KEY, Name VARCHAR2(20) UNIQUE, PRIMARY Key
Qty_on_hand NUMBER(5), Category CHAR(1), Unit_measure Constraint
Dealing with PRIMARY
CHAR(4), Reorder_Lvl NUMBER(5) NOT NULL, Reorder_qty KEY Constraint in an
existing table
3.13
Constraints
Dealing with Primary Key Constraint in an existing table
Chittaranjan Pradhan
Constraints
The syntax for adding Primary key constraint is: NOT NULL Constraint
Unique Constraint
ALTER TABLE tablename ADD CONSTRAINT Dealing with UNIQUE
PRIMARY Key
Constraint
ALTER TABLE ITEM_MASTER ADD CONSTRAINT C5 Dealing with PRIMARY
KEY Constraint in an
PRIMARY KEY(Item_no); existing table
FOREIGN Key
Constraint
The syntax for dropping Primary key constraint is: Dealing with FOREIGN
KEY Constraint in an
CHECK Constraint
[CASCADE]; Dealing with Check
Constraint in an existing
table
Viewing USER
Constraints
ALTER TABLE ITEM_MASTER DROP CONSTRAINT C5;
3.14
Constraints
Foreign Key Constraint
Chittaranjan Pradhan
Foreign Key Constraint
It is also known as the referential integrity constraint. It Constraints
establishes a relationship with the primary key of the same or NOT NULL Constraint
Unique Constraint
another table. Foreign key and the referenced primary key Dealing with UNIQUE
columns need not have the same name, but the data type, size Constraint in an existing
table
CHECK Constraint
Dealing with Check
Constraint in an existing
Table level: CONSTRAINT constraintname FOREIGN table
Viewing USER
Constraints
fid VARCHAR(6) CONSTRAINT student_fid_fk REFERENCES
faculty(fid)
ON DELETE CASCADE
Constraints
This option can be added to allow deletion of a record in the
NOT NULL Constraint
parent table and deletion of the dependent records in the child
Unique Constraint
table implicitly Dealing with UNIQUE
Constraint in an existing
table
FOREIGN Key
Constraint
Dealing with FOREIGN
Table level: CONSTRAINT constraintname FOREIGN KEY Constraint in an
existing table
KEY(columns) REFERENCES tablename(columns) [ON CHECK Constraint
DELETE CASCADE] Dealing with Check
Constraint in an existing
table
3.16
Constraints
Foreign Key Constraint...
Chittaranjan Pradhan
Constraints
Unique Constraint
Let ITEM_TRANS be the table where It_no references to the Dealing with UNIQUE
Constraint in an existing
PRIMARY Key
Constraint
Column Type Size Dealing with PRIMARY
KEY Constraint in an
FOREIGN Key
Trans_date DATE Constraint
CHECK Constraint
CREATE TABLE ITEM_TRANS(It_no NUMBER(4) Dealing with Check
Constraint in an existing
REFERENCES ITEM_MASTER(Item_no), trans_date DATE, table
Viewing USER
Constraints
3.17
Constraints
Dealing with Foreign Key Constraint in an existing table
Chittaranjan Pradhan
Constraints
The syntax for adding Foreign key constraint is: NOT NULL Constraint
Unique Constraint
ALTER TABLE tablename ADD CONSTRAINT Dealing with UNIQUE
CHECK Constraint
The syntax for dropping Foreign key constraint is: Dealing with Check
Constraint in an existing
ALTER TABLE tablename DROP CONSTRAINT table
Viewing USER
Constraints
ALTER TABLE ITEM_TRANS DROP CONSTRAINT C7;
3.18
Constraints
Check Constraint
Chittaranjan Pradhan
It defines a condition that every row must satisfy. There can be NOT NULL Constraint
DEFAULT Value
Constraints
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4)
NOT NULL Constraint
PRIMARY KEY, Name VARCHAR2(20) UNIQUE,
Unique Constraint
Qty_on_hand NUMBER(5), Category CHAR(1) Dealing with UNIQUE
Constraint in an existing
CHECK(Category in(’A’, ’B’, ’C’), Unit_measure CHAR(4), table
FOREIGN Key
Constraint
Dealing with FOREIGN
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) KEY Constraint in an
existing table
PRIMARY KEY, Name VARCHAR2(20) UNIQUE, CHECK Constraint
Qty_on_hand NUMBER(5), Category CHAR(1) NOT NULL, Dealing with Check
Constraint in an existing
Unit_measure CHAR(4), Reorder_Lvl NUMBER(5) NOT NULL, table
DEFAULT Value
Reorder_qty NUMBER(5) NOT NULL, Rate NUMBER(8,2)
Viewing USER
NOT NULL, CHECK((Category=’A’ AND Rate<=1000) OR Constraints
3.20
Constraints
Dealing with Check Constraint in an existing table
Chittaranjan Pradhan
Constraints
DEFAULT Value
3.21
Constraints
DEFAULT Value
Chittaranjan Pradhan
Constraints
DEFAULT Value NOT NULL Constraint
It ensures that a particular column will always have a value Unique Constraint
Dealing with UNIQUE
when a new record is inserted. The default value gets Constraint in an existing
table
overwritten if a user enters another value. The default value is PRIMARY Key
Constraint
used if a NULL value is inserted. The DEFAULT value is Dealing with PRIMARY
FOREIGN Key
Constraint
Columnname datatype(size) DEFAULT value Dealing with FOREIGN
KEY Constraint in an
existing table
CHECK Constraint
CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) Dealing with Check
Constraint in an existing
table
PRIMARY KEY, Name VARCHAR2(20) UNIQUE,
DEFAULT Value
Qty_on_hand NUMBER(5) DEFAULT 100, Category CHAR(1), Viewing USER
Unit_measure CHAR(4), Reorder_Lvl NUMBER(5) NOT NULL, Constraints
3.22
Constraints
DEFAULT Value...
Chittaranjan Pradhan
Constraints
Unique Constraint
Dealing with UNIQUE
If a column level constraint is defined on the column with a Constraint in an existing
table
default value, then the default value must precede the PRIMARY Key
constraint. The syntax is: Constraint
Dealing with PRIMARY
KEY Constraint in an
existing table
CHECK Constraint
Dealing with Check
Qty_on_hand NUMBER(5) DEFAULT 100 CHECK Constraint in an existing
table
(Qty_on_hand>=100), DEFAULT Value
Viewing USER
Constraints
3.23
Constraints
Viewing USER Constraints
Chittaranjan Pradhan
Constraints
FOREIGN Key
If the user wants to view all the constraints applied to a single Constraint
DEFAULT Value
3.24
Built-in Functions
Chittaranjan Pradhan
Employee Table
Group Functions
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
4.1
Built-in Functions
Built-in Functions
Chittaranjan Pradhan
DUAL Table
1 DUAL Table Employee Table
Built-in Functions
Group Functions
2 Employee Table
Scalar Functions
Date Functions
Numeric Functions
3 Built-in Functions Character Functions
Conversion Functions
Misc. Functions
4 Group Functions
5 Scalar Functions
Date Functions
Numeric Functions
Character Functions
Conversion Functions
Misc. Functions
4.2
Built-in Functions
DUAL Table
Chittaranjan Pradhan
DUAL Table
Employee Table
Built-in Functions
DUAL Table
Group Functions
DUAL table is a small worktable, which consists of only one Scalar Functions
Date Functions
column DUMMY and a single row with value X of VARCHAR2 Numeric Functions
4.3
Built-in Functions
Employee Table
Chittaranjan Pradhan
DUAL Table
Employee Table
Built-in Functions
Group Functions
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20 Scalar Functions
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 Date Functions
Numeric Functions
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 Character Functions
7566 JONES MANAGER 7839 02-APR-81 2975 20 Conversion Functions
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 Misc. Functions
4.4
Built-in Functions
Built-in Functions
Chittaranjan Pradhan
DUAL Table
Employee Table
Built-in Functions
Built-in Functions
Group Functions
The built-in functions provide a powerful tool for the Scalar Functions
enhancement of a basic query. They serve the purpose of Date Functions
Numeric Functions
manipulating data items and returning a result. Functions are Character Functions
Conversion Functions
of two types: Misc. Functions
4.5
Built-in Functions
Group Functions
Chittaranjan Pradhan
The group or aggregate functions perform an operation on a
group of rows and return one result. The different aggregate
DUAL Table
functions are:
Employee Table
Group Functions
This function counts the number of rows without considering Scalar Functions
NULL values Date Functions
Numeric Functions
Character Functions
SELECT COUNT(MGR) FROM EMP; Conversion Functions
Misc. Functions
SELECT COUNT(DISTINCT MGR) FROM EMP;
COUNT(MGR) COUNT(DISTINCT MGR)
13 6
COUNT(*)
It counts the number of rows including NULL values
Employee Table
It finds the sum of all values in a column ignoring the NULL
Built-in Functions
values
Group Functions
AVG([DISTINCT] column)
It finds the average of all values in a column ignoring the NULL
values
SELECT AVG(SAL) FROM EMP;
AVG(SAL)
2075.35
4.7
Built-in Functions
Group Functions...
Chittaranjan Pradhan
Employee Table
It finds the maximum value in the column ignoring the NULL
Built-in Functions
values
Group Functions
MIN([DISTINCT] column)
It finds the minimum value in the column ignoring the NULL
values
SELECT MIN(SAL) FROM EMP;
MIN(SAL)
800
4.8
Built-in Functions
Scalar Functions
Chittaranjan Pradhan
Employee Table
These functions act on one value at a time. There are various Built-in Functions
types of scalar functions: Group Functions
4.9
Built-in Functions
Date Functions
Chittaranjan Pradhan
The date values are stored internally with day, month, year,
hour, minute and second information. The different date DUAL Table
Built-in Functions
SYSDATE Group Functions
It is the pseudo column that returns the system’s current date Scalar Functions
Date Functions
Numeric Functions
ADD_MONTHS(date, n)
It adds calendar months to a date
SELECT ADD_MONTHS(HIREDATE, 4) FROM EMP WHERE
EMP_NO=7369;
ADD_MONTHS(HIREDATE,4)
17-APR-81
4.10
Built-in Functions
Date Functions...
Chittaranjan Pradhan
DUAL Table
LAST_DAY(date) Employee Table
Built-in Functions
It returns the last day of the month
Group Functions
Scalar Functions
SELECT LAST_DAY(SYSDATE) FROM DUAL; Date Functions
Numeric Functions
LAST_DAY(SYSDATE) Character Functions
Conversion Functions
31-JAN-13
Misc. Functions
MONTHS_BETWEEN(date1, date2)
It finds the number of months between two dates
SELECT MONTHS_BETWEEN(SYSDATE,’23-JAN-89’) FROM
DUAL;
MONTHS_BETWEEN(SYSDATE,’23-JAN-89’)
287.90
4.11
Built-in Functions
Date Functions...
Chittaranjan Pradhan
NEXT_DAY(date, ’day’)
DUAL Table
It finds the next occurrence of a day from the given date Employee Table
Built-in Functions
SELECT NEXT_DAY(SYSDATE, ’MONDAY’) FROM DUAL; Group Functions
Scalar Functions
NEXT_DAY(SYSDATE, ’MONDAY’) Date Functions
4.12
Built-in Functions
Numeric Functions
Chittaranjan Pradhan
Employee Table
ABS(n) Built-in Functions
Group Functions
It returns the absolute value of n
Scalar Functions
Date Functions
SELECT ABS(5), ABS(-100) FROM DUAL; Numeric Functions
Character Functions
Conversion Functions
ABS(5) ABS(-100) Misc. Functions
5 100
CEIL(n)
This returns the smallest integer greater than or equal to the
given value
4.13
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan
DUAL Table
FLOOR(n) Employee Table
This returns the largest integer less than or equal to the given Built-in Functions
Group Functions
value
Scalar Functions
Date Functions
SELECT FLOOR(-5.2), FLOOR(5.7) FROM DUAL; Numeric Functions
Character Functions
EXP(n)
It returns the exponent e raised to power n
4.14
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan
LN(n)
It returns the natural logarithm of n DUAL Table
Employee Table
Group Functions
LN(2)
0.693147181 Scalar Functions
Date Functions
Numeric Functions
Character Functions
LOG(b, n) Conversion Functions
Misc. Functions
It returns logb n value
MOD(n, m)
It returns the integer remainder of n/m
POWER(m, n)
DUAL Table
Built-in Functions
Scalar Functions
POWER(4,3) Date Functions
Numeric Functions
64 Character Functions
Conversion Functions
Misc. Functions
SQRT(n)
It returns the square root of the number n
4.16
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan
DUAL Table
ROUND(m, [n]) Employee Table
Group Functions
TRUNC(m, n)
It returns the truncated value of m up to n positions
4.17
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan
SIGN(n)
DUAL Table
It returns the sign of number n: -1 for negative, 0 for zero, 1 for Employee Table
Group Functions
SIN(n)
It returns sine of n, where n is in radian
Employee Table
CHR(n)
Built-in Functions
Scalar Functions
CONCAT(s1, s2)
It joins the first string to the second string. It is similar to the ||
operator
4.19
Built-in Functions
Character Functions...
Chittaranjan Pradhan
Employee Table
It pads the string s with the character c to the left to a total Built-in Functions
width of n Group Functions
Scalar Functions
SELECT LPAD(’ORACLE’,10,’*’) FROM DUAL; Date Functions
Numeric Functions
RPAD(s, n, c)
It pads the string s with the character c to the right to a total
width of n
SELECT RPAD(’ORACLE’,10,’*’) FROM DUAL;
RPAD(’ORACLE’,10,’*’)
ORACLE****
4.20
Built-in Functions
Character Functions...
Chittaranjan Pradhan
Employee Table
It returns the string with capitalization of the first letter in each Built-in Functions
word Group Functions
Scalar Functions
SELECT INITCAP(’HELLO’) FROM DUAL; Date Functions
Numeric Functions
Character Functions
INITCAP(’HELLO’) Conversion Functions
4.21
Built-in Functions
Character Functions...
Chittaranjan Pradhan
UPPER(s)
DUAL Table
Built-in Functions
Scalar Functions
UPPER(’HeLLo’) Date Functions
HELLO Numeric Functions
Character Functions
Conversion Functions
Misc. Functions
LTRIM(s, c)
It trims the string s from the left when the characters specified,
c, is present in s
DUAL Table
REPLACE(s, s1, s2) Employee Table
Group Functions
SUBSTR(s, n, m)
It returns a substring, starting at character position n, and
returns m number of characters
SELECT SUBSTR(’DATABASE’,3,2) FROM DUAL;
SUBSTR(’DATABASE’,3,2)
TA
4.23
Built-in Functions
Character Functions...
Chittaranjan Pradhan
DUAL Table
LENGTH(s)
Employee Table
Group Functions
SOUNDEX(s)
It compares words that are spell differently, but sound alike
4.24
Built-in Functions
Conversion Functions
Chittaranjan Pradhan
Employee Table
TO_NUMBER(char [,format]) Built-in Functions
Group Functions
It converts a character value with valid digits to a number using
Scalar Functions
the given format Date Functions
Numeric Functions
Character Functions
SELECT SUM(SAL) FROM EMP; Conversion Functions
TO_DATE(char [,format])
It converts a character value to date value based on the format
provided
4.25
Built-in Functions
Conversion Functions...
Chittaranjan Pradhan
DUAL Table
Employee Table
TO_CHAR(number [,format])
Built-in Functions
provided. 0 is used for compulsory purpose and 9 is used for Scalar Functions
Date Functions
optional purpose Numeric Functions
Character Functions
Conversion Functions
TO_CHAR(17145,’$999,999’)
$17,145
4.26
Built-in Functions
Conversion Functions...
Chittaranjan Pradhan
TO_CHAR(date [,format])
DUAL Table
It converts a date to a VARCHAR value based on the format Employee Table
provided Built-in Functions
Group Functions
SELECT TO_CHAR(HIREDATE,’MONTH DD, YYYY’) FROM Scalar Functions
EMP WHERE EMP_NO=7566; Date Functions
Numeric Functions
Character Functions
TO_CHAR(HIREDATE,’MONTH DD, YYYY’) Conversion Functions
Group Functions
WHERE DEPT_NO=10;
Scalar Functions
Date Functions
TO_CHAR(HIREDATE,’DDSP-MON-YY’) Numeric Functions
NINE-JUN-81 Character Functions
SEVENTEEN-NOV-81 Conversion Functions
Misc. Functions
TWENTY-THREE-JAN-82
Built-in Functions
It converts a NULL value to an actual value supplied as an Group Functions
argument. For numerical values, it accepts 0; whereas for Scalar Functions
character values, it accepts a fixed string Date Functions
Numeric Functions
Character Functions
COMMISSIONFROM EMP;
SELECT E_NAME, SALARY+NVL(COMMISSION, 0) Total
SalaryFROM EMP;
NVL2(column, notnullvalue, nullvalue)
It checks for NULL as well as not NULL values. If the column
has a not NULL value, the second parameter is displayed. If
the column has a NULL value, the third parameter is displayed
Chittaranjan Pradhan
Data Control
Transaction Control
Language (TCL)
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
5.1
Grouping, DCL & TCL
Grouping, DCL & TCL
Chittaranjan Pradhan
Grouping Data
Data Control
Language (DCL)
Transaction Control
1 Grouping Data Language (TCL)
SQL*PLUS
Commands
4 SQL*PLUS Commands
5.2
Grouping, DCL & TCL
Grouping Data
Chittaranjan Pradhan
GROUP BY clause
GROUP BY clause is used for grouping data. The column Grouping Data
SQL*PLUS
GROUP BY column; Commands
DEPT_NO AVG(SAL)
30 1566.66666666666666666666666666666666667
20 2175
10 2926.66666666666666666666666666666666667
5.3
Grouping, DCL & TCL
Grouping Data...
Chittaranjan Pradhan
Grouping Data
Data Control
Language (DCL)
HAVING Clause
Transaction Control
HAVING clause can restrict groups. The syntax of this is: Language (TCL)
SQL*PLUS
Commands
SELECT column, groupfunction(column) FROM tablename
GROUP BY column [HAVING groupcondition];
DEPT_NO AVG(SAL)
20 2175
10 2926.66666666666666666666666666666666667
5.4
Grouping, DCL & TCL
Grouping Data...
Chittaranjan Pradhan
Grouping Data
DEPT_NO AVG(SAL)
30 2850
20 2991.66666666666666666666666666666666667
10 3740
5.5
Grouping, DCL & TCL
Grouping Data...
Chittaranjan Pradhan
Grouping Data
WHERE, GROUP BY and HAVING Clause
Data Control
Language (DCL)
WHERE clause is used to filter the unwanted records, while the
Transaction Control
HAVING clause is used to filter the unwanted groups. The Language (TCL)
DEPT_NO AVG(SAL)
30 2850
20 2991.66666666666666666666666666666666667
5.6
Grouping, DCL & TCL
Data Control Language
Chittaranjan Pradhan
Transaction Control
and SELECT Language (TCL)
SQL*PLUS
Granting Privileges Commands
5.7
Grouping, DCL & TCL
Data Control Language...
Chittaranjan Pradhan
Grouping Data
SELECT * FROM SYSTEM.Employee;
Data Control
Language (DCL)
SQL*PLUS
Revoking Privileges Commands
5.8
Grouping, DCL & TCL
Transaction Control Language
Chittaranjan Pradhan
SQL*PLUS
Commands
Committing a transaction
COMMIT statement is used to end the current transaction and
makes permanent any changes made during transaction. The
general syntax is:
COMMIT;
5.9
Grouping, DCL & TCL
Transaction Control Language...
Chittaranjan Pradhan
Grouping Data
Data Control
Language (DCL)
Transaction Control
Roll backing the operations to a particular position Language (TCL)
SQL*PLUS
SAVEPOINT allows the user to create logical marking in the Commands
5.10
Grouping, DCL & TCL
SQL*PLUS Commands
Chittaranjan Pradhan
Grouping Data
SAVE filename.sql [REPLACE/ APPEND] Data Control
Language (DCL)
It saves current buffer contents to a file Transaction Control
Language (TCL)
SQL*PLUS
GET filename.sql Commands
START filename.sql
It runs a previously saved command from file
@filename.sql
Same as START command
The filename in the file-related commands requires entire file
path
5.11
Grouping, DCL & TCL
SQL*PLUS Commands...
Chittaranjan Pradhan
Transaction Control
Language (TCL)
EDIT filename.sql SQL*PLUS
Commands
It allows to edit a saved file
PASSWORD
It allows to change the password
EXIT
It leaves SQL *PLUS environment & commits current
transaction
5.12
Join & Set Operators
Chittaranjan Pradhan
Join
Outer Join
Set Operators
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
6.1
Join & Set Operators
Join & Set Operators
Chittaranjan Pradhan
CROSS JOIN
Inner Join
Outer Join
Set Operators
3 Inner Join
4 Outer Join
5 Self Join
6 Set Operators
6.2
Join & Set Operators
Cross Join
Chittaranjan Pradhan
CROSS JOIN
Join
Inner Join
Self Join
Cross join is used to combine information from any two
Set Operators
relations
SELECT Department.deptno, location, ename, eid FROM
Employee, Department;
6.3
Join & Set Operators
Join
Chittaranjan Pradhan
CROSS JOIN
Join
Join
When the required data are present in more than one table, Inner Join
related tables are joined using a join condition. The join Outer Join
condition combines a row in one table with a row in another Self Join
table based on the same values in the common columns Set Operators
Tables are joined on columns that have the same datatype and
data width in the tables. Join operation joins two relations by
merging those tuples from two relations that satisfy a given
condition
6.4
Join & Set Operators
Inner Join
Chittaranjan Pradhan
CROSS JOIN
In the Inner Join, tuples with NULL valued join attributes do not Join
appear in the result. Tuples with NULL values in the join Inner Join
attributes are also eliminated. The different types of inner join Outer Join
Set Operators
Theta Join
Theta join is a join with a specified condition involving a column
from each table. The syntax of theta join is:
SELECT columns FROM tables WHERE join_condition;
When columns are retrieved from more than one table, the use
of a table name qualifier in front of the column name tells the
server to retrieve that column from the specified table
6.5
Join & Set Operators
Inner Join...
Chittaranjan Pradhan
CROSS JOIN
Equi Join
Join
Equi join is a special kind of theta join where the join condition Inner Join
Self Join
6.6
Join & Set Operators
Outer Join
Chittaranjan Pradhan
are: Join
Inner Join
Left Outer Join Outer Join
Left outer join preserves all rows in left table even though there Self Join
is no matching tuples present in the right table. The syntax of Set Operators
CROSS JOIN
Right Outer Join Join
Right outer join preserves all rows in right table even though Inner Join
Outer Join
there is no matching tuples present in left table. The syntax of
Self Join
right outer join is:
Set Operators
SELECT columns FROM table1 RIGHT OUTER JOIN table2
USING(column); or
SELECT columns FROM table1 RIGHT OUTER JOIN table2
ON table1.column= table2.column;
6.8
Join & Set Operators
Outer Join...
Chittaranjan Pradhan
CROSS JOIN
Join
Full Outer Join Inner Join
Full outer join preserves all records in both tables. The syntax Outer Join
SELECT columns FROM table1 FULL OUTER JOIN table2 Set Operators
USING(column); or
6.9
Join & Set Operators
Self Join
Chittaranjan Pradhan
CROSS JOIN
Join
Inner Join
Self Join
Self join is similar to the theta join. It joins a relation to itself by
Set Operators
a condition. When a table is joined to itself, two copies of the
same table are used. The syntax for this is:
SELECT columns FROM table T1, table T2 WHERE
T1.column operator T2.column;
6.10
Join & Set Operators
Set Operators
Chittaranjan Pradhan
CROSS JOIN
Join
Inner Join
Self Join
and INTERSECTION, the relations need to be union
Set Operators
compatible for the result to be a valid relation. The different set
operators are:
UNION
Union is used to combine data from two relations
SELECT name, job FROM Employee WHERE dept=20 UNION
SELECT name, job FROM Employee WHERE dept=30;
6.11
Join & Set Operators
Set Operators...
Chittaranjan Pradhan
CROSS JOIN
Join
DIFFERENCE
Inner Join
Difference is used to identify the rows that are in one relation Outer Join
Set Operators
SELECT name, job FROM Employee WHERE dept=20 MINUS
SELECT name, job FROM Employee WHERE dept=30;
INTERSECTION
Intersection is used to identify the rows that are common to two
relations
SELECT name, job FROM Employee WHERE dept=20
INTERSECT SELECT name, job FROM Employee WHERE
dept=30;
6.12
Sub-Query
Chittaranjan Pradhan
Single-row Subquery
Multiple-column
Sub-Query Subquery
Correlated Subquery
Nested Subquery
UPDATE with
Subquery
DELETE with
Subquery
TOP- N Analysis
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
7.1
Sub-Query
Sub-Query
Chittaranjan Pradhan
Single-row Subquery
Multiple-column
Subquery
3 Multiple-row Subquery Correlated Subquery
Nested Subquery
DELETE with
5 Correlated Subquery Subquery
TOP- N Analysis
6 Nested Subquery
9 TOP- N Analysis
7.2
Sub-Query
Sub Query
Chittaranjan Pradhan
Single-row Subquery
Subquery is a SELECT statement that is nested within another Multiple-row Subquery
SELECT statement, which returns intermediate results Multiple-column
Subquery
Correlated Subquery
It is useful when you need to select rows from a table with a
Nested Subquery
condition that depends on the data in another table. Here, inner
UPDATE with
query evaluates first, generates values that are tested in the Subquery
condition of the outer query. Subqueries are of two types: DELETE with
Subquery
7.3
Sub-Query
Single-row Subquery
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-column
Single-row subquery returns zero or one row to the outer SQL Subquery
UPDATE with
(SELECT column FROM table2 WHERE condition); Subquery
DELETE with
Let, Student (roll,name,age, deptno) and Department (deptno, Subquery
dname, campus) be two schemas. If the user wants to find the TOP- N Analysis
7.4
Sub-Query
Single-row Subquery...
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
Multiple-column
Single-row Subquery used in HAVING clause Subquery
Correlated Subquery
Subquery can be used in place of the value in the HAVING
Nested Subquery
clause
UPDATE with
Subquery
Q. Find the department and the departmental average age DELETE with
which are less than the maximum departmental age Subquery
TOP- N Analysis
7.5
Sub-Query
Single-row Subquery...
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-column
The inner SELECT statement in the FROM clause is used as Subquery
the data source for the outer SELECT statement. This is also Correlated Subquery
UPDATE with
Subquery
SELECT age FROM (SELECT age FROM Student WHERE
DELETE with
age<20); Subquery
TOP- N Analysis
7.6
Sub-Query
Multiple-row Subquery
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
Multiple-row Subquery
Multiple-column
Subquery
Multiple-row subquery returns more than one row. It uses
Correlated Subquery
either IN, ALL or ANY operator Nested Subquery
UPDATE with
SELECT roll, name FROM Student WHERE age< Subquery
TOP- N Analysis
SELECT roll, name FROM Student WHERE age< IN(SELECT
age FROM Customer);
7.7
Sub-Query
Multiple-column Subquery
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
Multiple-column
Subquery
Nested Subquery
Multiple-column subquery returns more than one column as UPDATE with
result Subquery
DELETE with
Subquery
SELECT roll,deptno,age FROM Student WHERE (deptno,age)
TOP- N Analysis
IN (SELECT deptno,MIN(age) FROM Student Group BY
deptno);
7.8
Sub-Query
Correlated Subquery
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
Correlated Subquery
Multiple-column
Subquery
In a correlated subquery, the inner query can reference
Correlated Subquery
columns from the outer query. The inner query is executed Nested Subquery
once for each row in the outer query UPDATE with
Subquery
SELECT roll, deptno, name, age FROM Student s1 WHERE DELETE with
Subquery
age>(SELECT AVG(age) FROM Student s2 WHERE TOP- N Analysis
s1.deptno = s2.deptno);
7.9
Sub-Query
Nested Subquery
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
Nested Subquery
Multiple-column
Subquery
You can nest subqueries to a depth of 255
Correlated Subquery
Nested Subquery
SELECT empid, empname, salary, hiredate FROM Employee
UPDATE with
WHERE empid IN(SELECT empid FROM Employee WHERE Subquery
7.10
Sub-Query
UPDATE with Subquery
Chittaranjan Pradhan
Sub Query
UPDATE with Subquery Single-row Subquery
The column values can be updated with the help of a subquery Multiple-row Subquery
UPDATE with
Subquery
The value in the update statement can also be calculated by DELETE with
using a subquery. The general syntax for this is: Subquery
TOP- N Analysis
UPDATE tablename SET columnname = (SELECT
subquery) [WHERE condition];
Update the age of the student having roll no. 4 to the average
age of all the students
7.11
Sub-Query
DELETE with Subquery
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
DELETE with Subquery Multiple-column
Subquery
A row or rows from a table can be deleted based on a value Correlated Subquery
Delete all the student records whose ages are greater than the TOP- N Analysis
7.12
Sub-Query
TOP- N Analysis
Chittaranjan Pradhan
Sub Query
Single-row Subquery
Multiple-row Subquery
Multiple-column
TOP- N Analysis Subquery
Correlated Subquery
TOP-N queries are used to sort rows in a table and then to find Nested Subquery
the first- N largest or first- N smallest values UPDATE with
Subquery
DELETE with
TOP-N query uses an order by clause. The sorted rows are Subquery
7.13
View, Sequence,
Synonym & Index
Chittaranjan Pradhan
Sequence
Index
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
8.1
View, Sequence,
View, Sequence, Synonym & Index Synonym & Index
Chittaranjan Pradhan
View
Complex View
Advantages of Views
1 View Sequence
Complex View Synonym
Advantages of Views Index
2 Sequence
3 Synonym
4 Index
8.2
View, Sequence,
View Synonym & Index
Chittaranjan Pradhan
View
View is an object which gives the user a logical view of data View
Complex View
from an underlying table or tables Advantages of Views
Sequence
You can restrict what users can view by allowing them to see Synonym
When a view is created from more than one table, the user can
view data from the view without using join conditions and
complex conditions
Chittaranjan Pradhan
View
Synonym
• Simple view : It is based on one table. It allows data Index
manipulation
• Complex view : It is based on one or more tables. It
doesn’t allow data manipulation
View Creation
The syntax for creating a view is:
CREATE [OR REPLACE] VIEW viewname AS SELECT
statement;
8.4
View, Sequence,
View... Synonym & Index
Chittaranjan Pradhan
Synonym
CREATE VIEW Credit_dbt AS SELECT * FROM Debts
Index
WHERE account_id=4;
Displaying the content of a view
User can display the content from a view as:
SELECT * FROM viewname;
Chittaranjan Pradhan
Synonym
DESCRIBE Debts;
Index
Chittaranjan Pradhan
This constraint applies to the WHERE clause condition in the Complex View
Advantages of Views
Index
CREATE VIEW Asd AS SELECT * FROM Products WHERE
price < 15;
Chittaranjan Pradhan
View
Complex View
Advantages of Views
Sequence
Viewing all the user views Synonym
Index
All user created views can be displayed as:
SELECT * FROM USER_VIEWS;
Removing a View
A view can be removed as:
DROP VIEW viewname;
8.8
View, Sequence,
View... Synonym & Index
Chittaranjan Pradhan
View
Complex View
Advantages of Views
Synonym
When the underlying table is altered, the view becomes invalid. Index
Thus, the view requires the recompilation as:
ALTER VIEW viewname COMPILE;
8.9
View, Sequence,
View... Synonym & Index
Chittaranjan Pradhan
View
Complex View
Advantages of Views
Sequence
Use of GROUP BY clause Synonym
8.10
View, Sequence,
Complex View Synonym & Index
Chittaranjan Pradhan
View
Complex View
Advantages of Views
Sequence
Synonym
Complex View
Index
8.11
View, Sequence,
Advantages of Views Synonym & Index
Chittaranjan Pradhan
View
Complex View
Advantages of Views
Sequence
Advantages of Views Synonym
8.12
View, Sequence,
Sequence Synonym & Index
Chittaranjan Pradhan
Sequence View
Complex View
Advantages of Views
Sequence is used to generate a sequence of numbers. The Sequence
value generated can have a maximum of 38 digits Synonym
Index
The minimum information required to generate numbers using
a sequence are:
• The starting number
• The maximum number
• The increment value
The syntax for creating a sequence is:
CREATE SEQUENCE seqname INCREMENT BY n START
WITH s MAXVALUE m1 \ NOMAXVALUE MINVALUE m2 \
NOMINVALUE [CYCLE \ NOCYCLE] [CACHE c \
NOCACHE];
8.13
View, Sequence,
Sequence... Synonym & Index
Chittaranjan Pradhan
View
CREATE SEQUENCE sq INCREMENT BY 1 START WITH Complex View
Sequence
Index
NEXTVAL column returns the next available number in the
sequence
8.14
View, Sequence,
Sequence... Synonym & Index
Chittaranjan Pradhan
Sequence
Synonym
Modifying a Sequence Index
Dropping a Sequence
A sequence can be dropped as:
DROP SEQUENCE sequencename;
Chittaranjan Pradhan
Synonym
Synonyms are used to create alternate names for tables, View
Complex View
views, sequences ... etc. The syntax for this is: Advantages of Views
Synonym
Dropping a Synonym
A Synonym can be dropped as:
DROP SYNONYM synonymname;
Chittaranjan Pradhan
View
Index is used for faster retrieval of rows from a table. It can be Complex View
Advantages of Views
used implicitly or explicitly. Mainly, index is of two types:
Sequence
Synonym
8.17
View, Sequence,
Index... Synonym & Index
Chittaranjan Pradhan
View
Complex View
Advantages of Views
Viewing the details of a user-defined index
Sequence
Index
Rebuilding an Index
When a table goes through changes, it is advisable to rebuild
indexes based on that table. The syntax is:
ALTER INDEX indexname REBUILD;
8.18
PL/SQL
Chittaranjan Pradhan
Conditional Logic
CASE Statement
Looping Structure
Scope of variable in
nested block
DEFINE Statement
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
9.1
PL/SQL
PL/SQL
Chittaranjan Pradhan
PL/SQL Basics
1 PL/SQL Basics Advantages of PL/SQL
Conditional Logic
User Message CASE Statement
Looping Structure
3 Looping Structure
5 DEFINE Statement
9.2
PL/SQL
PL/SQL Basics
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Character Sets, Comments,
Conditional Logic
• It is a block - structured language that enables developers CASE Statement
9.3
PL/SQL
Advantages of PL/SQL
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Looping Structure
• It sends an entire block of statements to the oracle engine
Scope of variable in
at one time. Thus, reduces network traffic nested block
DEFINE Statement
• Permits dealing with errors
• It allows declaration & use of variables in blocks of code
• Applications written in PL/SQL are portable to any
computer hardware and operating system
9.4
PL/SQL
Structure of PL/SQL Block
Chittaranjan Pradhan
Structure of PL/SQL Block
PL/SQL Basics
• DECLARE: declaration and initialization of variables and Advantages of PL/SQL
Looping Structure
Scope of variable in
nested block
DEFINE Statement
9.5
PL/SQL
Character Sets, Comments, Special operators
Chittaranjan Pradhan
Character Sets
PL/SQL Basics
• Letters: A...Z, and a...z Advantages of PL/SQL
Structure of PL/SQL Block
Conditional Logic
CASE Statement
Comments
Looping Structure
Special operators
• Assignment operator: : =
• Comparison operator: =
• Concatenation symbol: ||
• Exponents: **
9.6
PL/SQL
Variables, Constant, BOOLEAN Datatype, %TYPE
Chittaranjan Pradhan
Variables
Variable name must begin with a character. Variable can hold PL/SQL Basics
Advantages of PL/SQL
at most 30 characters Structure of PL/SQL Block
Character Sets, Comments,
Varname datatype[size]; Special operators
Variables, Constant,
Ex:Input_no NUMBER(3); BOOLEAN Datatype,
%TYPE
User Message
Conditional Logic
Constant CASE Statement
BOOLEAN Datatype
Logical data type, either TRUE or FALSE or NULL only
%TYPE
Describes the data type of the table column
identifier tablename.columnname%TYPE;
Ex: name Employee.empname%TYPE;
9.7
PL/SQL
User Message
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Character Sets, Comments,
Special operators
User Message Variables, Constant,
BOOLEAN Datatype,
%TYPE
Oracle has a built-in package called DBMS_OUTPUT with the User Message
Looping Structure
DBMS_OUTPUT.PUT_LINE (message); Scope of variable in
Message is generally of varchar nested block
DEFINE Statement
9.8
PL/SQL
Conditional Logic
Chittaranjan Pradhan
PL/SQL Basics
Simple IF Advantages of PL/SQL
Structure of PL/SQL Block
Character Sets, Comments,
Special operators
IF condition THEN Variables, Constant,
BOOLEAN Datatype,
Statements %TYPE
User Message
END IF; Conditional Logic
CASE Statement
Looping Structure
Scope of variable in
Simple IF-ELSE nested block
DEFINE Statement
IF condition THEN
Statements
ELSE
Statements
END IF;
9.9
PL/SQL
Conditional Logic...
Chittaranjan Pradhan
IF-ELSE Ladder
PL/SQL Basics
IF condition THEN Advantages of PL/SQL
Structure of PL/SQL Block
Statements Character Sets, Comments,
Special operators
ELSIF condition THEN Variables, Constant,
BOOLEAN Datatype,
Statements %TYPE
User Message
ELSE Conditional Logic
Statements CASE Statement
Looping Structure
END IF;
Scope of variable in
nested block
DEFINE Statement
Nested IF-ELSE
IF condition THEN
IF condition THEN
Statements
END IF
ELSE
Statements
END IF;
9.10
PL/SQL
Conditional Logic...
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Input a number and check whether it is even or odd Character Sets, Comments,
Special operators
Variables, Constant,
BOOLEAN Datatype,
DECLARE %TYPE
User Message
n number(5); Conditional Logic
BEGIN CASE Statement
Scope of variable in
IF(MOD (n,2)=0) THEN nested block
ELSE
DBMS_OUTPUT.PUT_LINE(’odd’);
END IF;
END;
9.11
PL/SQL
Conditional Logic...
Chittaranjan Pradhan
Write a PL/SQL block that will accept a client_no from the user
and adds 500 rupees to the bal_due column if the bal_due PL/SQL Basics
Advantages of PL/SQL
column has a value less than 5000 rupees. The process is fired Structure of PL/SQL Block
DEFINE Statement
cno : =&cno;
SELECT bal_due INTO bal FROM Client_Master
WHERE client_no=cno;
IF bal<5000 THEN
UPDATE Client_Master SET bal_due=bal_due+addn
WHERE client_no=cno;
END IF;
END;
9.12
PL/SQL
CASE Statement
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Character Sets, Comments,
Special operators
CASE Statement Variables, Constant,
BOOLEAN Datatype,
%TYPE
User Message
Looping Structure
WHEN exp2 THEN Statement2
Scope of variable in
... nested block
ELSE Statementn+1
END CASE;
9.13
PL/SQL
CASE Statement...
Chittaranjan Pradhan
Input a 1-digit number and display the name
PL/SQL Basics
Looping Structure
WHEN 1 THEN DBMS_OUTPUT.PUT_LINE (’ONE’); Scope of variable in
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE (’TWO’); nested block
The EXIT statement provides a way to stop the iterative loop: Conditional Logic
CASE Statement
Scope of variable in
• IF i>10 THEN EXIT; nested block
WHILE LOOP
WHILE condition
LOOP
Statements
END LOOP;
9.15
PL/SQL
Looping Structure...
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Character Sets, Comments,
Special operators
Variables, Constant,
BOOLEAN Datatype,
%TYPE
FOR LOOP User Message
Conditional Logic
CASE Statement
FOR variable IN [REVERSE] low.. high Looping Structure
LOOP Scope of variable in
Statements nested block
DEFINE Statement
END LOOP;
9.16
PL/SQL
Scope of variable in nested block
Chittaranjan Pradhan
Scope of variable in nested block
PL/SQL statements can be nested wherever an executable PL/SQL Basics
Advantages of PL/SQL
statement is allowed. A nested block acts like a statement and Structure of PL/SQL Block
Character Sets, Comments,
executable statements can be broken into smaller blocks Special operators
Variables, Constant,
BOOLEAN Datatype,
DECLARE %TYPE
User Message
Looping Structure
BEGIN
Scope of variable in
DECLARE nested block
VB NUMBER(4) : = 111;
BEGIN
DBMS_OUTPUT.PUT_LINE(VA);
DBMS_OUTPUT.PUT_LINE(VB);
END;
DBMS_OUTPUT.PUT_LINE(’..................’);
DBMS_OUTPUT.PUT_LINE(VA);
DBMS_OUTPUT.PUT_LINE(VB);
END;
9.17
PL/SQL
DEFINE Statement
Chittaranjan Pradhan
PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block
Character Sets, Comments,
DEFINE Statement Special operators
Variables, Constant,
BOOLEAN Datatype,
It is used to enter different sets of values by using & symbol on %TYPE
User Message
substitution variables
Conditional Logic
CASE Statement
Scope of variable in
nested block
At the entry of each value, execute: DEFINE Statement
SET DEFINE OFF;
Later execute:
SET DEFINE ON;
9.18
CURSOR
Chittaranjan Pradhan
Implicit Cursor
Explicit Cursor
Parameterized Cursors
WHERE CURRENT
OF Clause
Disadvantages of
Cursors
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
10.1
CURSOR
CURSOR
Chittaranjan Pradhan
1 Cursor Cursor
Cursor Operations Cursor Operations
%TYPE and %ROWTYPE
%TYPE and %ROWTYPE Implicit Cursor
Explicit Cursor
2 Implicit Cursor Steps of Explicit Cursor
5 Parameterized Cursors
8 Disadvantages of Cursors
10.2
CURSOR
Cursor
Chittaranjan Pradhan
Cursor
Cursor is the work area which Oracle reserves for internal Cursor
Cursor Operations
processing of SQL statements. The data which is stored in the %TYPE and %ROWTYPE
Explicit Cursor
Steps of Explicit Cursor
Cursor is used when you have a SELECT statement that
Cursor FOR Loop
returns more than one row from the database Parameterized Cursors
Disadvantages of
A cursor acts logically as a pointer into a result set Cursors
Cursor Attributes
Attribute Description
%ISOPEN Returns TRUE if cursor is open
%FOUND Returns TRUE if record was fetched successfully
%NOTFOUND Returns TRUE if record was not fetched
%ROWCOUNT Returns the number of records processed from the cursor
10.3
CURSOR
Cursor Operations
Chittaranjan Pradhan
Cursor
Cursor Operations
Implicit Cursor
WHERE CURRENT
• Fetch the data rows: OF Clause
• LOOP Disadvantages of
Cursors
FETCH cursor_name INTO variable_name(s);
EXIT WHEN cursor_name%NOTFOUND;
END LOOP
• Close the cursor:
• CLOSE cursor_name;
10.4
CURSOR
%TYPE and %ROWTYPE
Chittaranjan Pradhan
Cursor
Cursor Operations
Implicit Cursor
It provides a column type Explicit Cursor
Steps of Explicit Cursor
Parameterized Cursors
Disadvantages of
%ROWTYPE Cursors
variablename tablename%ROWTYPE;
10.5
CURSOR
Implicit Cursor
Chittaranjan Pradhan
Cursor
Implicit Cursor Cursor Operations
%TYPE and %ROWTYPE
Implicit Cursor
• It is automatically created & handled by Oracle
Explicit Cursor
• It reserves an area in main memory to populate the data Steps of Explicit Cursor
• Implicit cursor handles all DMLs, i.e. INSERT, UPDATE & WHERE CURRENT
OF Clause
DELETE operations, which affect multiple rows and Disadvantages of
SELECT statement which returns exactly one row Cursors
10.6
CURSOR
Implicit Cursor...
Chittaranjan Pradhan
Cursor
An HRD manager has decided to raise the salary of employees Cursor Operations
by 15%. Write a PL/SQL block to accept an employee number and %TYPE and %ROWTYPE
update the salary of that employee. Display the appropriate Implicit Cursor
message based on the existence of the record in the EMP table Explicit Cursor
Steps of Explicit Cursor
WHERE CURRENT
WHERE emp_no=&emp_no; OF Clause
IF SQL%FOUND THEN Disadvantages of
Cursors
DBMS_OUTPUT.PUT_LINE(’MODIFIED’);
END IF;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE(’NOT MODIFIED’);
END IF;
END;
10.7
CURSOR
Implicit Cursor...
Chittaranjan Pradhan
Implicit Cursor
Explicit Cursor
DECLARE Steps of Explicit Cursor
Parameterized Cursors
BEGIN
FOR UPDATE Clause
UPDATE EMP SET salary=salary*1.15 WHERE DEPT=30;
WHERE CURRENT
rowaff : =SQL%ROWCOUNT; OF Clause
10.8
CURSOR
Explicit Cursor
Chittaranjan Pradhan
Cursor
Cursor Operations
Implicit Cursor
• The cursors which are declared by user are called Explicit Explicit Cursor
Steps of Explicit Cursor
Cursors Cursor FOR Loop
• When a SELECT statement returns more than one row of Parameterized Cursors
WHERE CURRENT
• We cannot use explicit cursor for DML statements OF Clause
Disadvantages of
Cursors
10.9
CURSOR
Steps of Explicit Cursor
Chittaranjan Pradhan
Cursor
Cursor Operations
%TYPE and %ROWTYPE
Implicit Cursor
Steps of Explicit Cursor
Explicit Cursor
Steps of Explicit Cursor
• Declare it: Cursor FOR Loop
• CURSOR cursorname IS SELECT statement; Parameterized Cursors
WHERE CURRENT
• OPEN cursorname; OF Clause
10.10
CURSOR
Explicit Cursor...
Chittaranjan Pradhan
Emp_raise table. Write a PL/SQL block to update the salary of Implicit Cursor
each employee & insert into the Emp_raise table Explicit Cursor
Steps of Explicit Cursor
10.11
CURSOR
Explicit Cursor...
Chittaranjan Pradhan
Cursor
Cursor Operations
%TYPE and %ROWTYPE
END LOOP;
COMMIT;
ELSE
DBMS_OUTPUT.PUT_LINE(’Unable to open the cursor’);
END IF;
CLOSE CSR;
END;
10.12
CURSOR
Explicit Cursor...
Chittaranjan Pradhan
Write a PL/SQL block that will displaying the name, dept and
salary of the first 3 employees getting the highest salary Cursor
Cursor Operations
%TYPE and %ROWTYPE
Implicit Cursor
DECLARE Explicit Cursor
CURSOR CSR IS SELECT e_name,dept,salary FROM EMP Steps of Explicit Cursor
Cursor FOR Loop
ORDER BY salary DESC;
Parameterized Cursors
vname EMP.e_name%TYPE;
FOR UPDATE Clause
vdept EMP.dept%TYPE; WHERE CURRENT
vsal EMP.salary%TYPE; OF Clause
BEGIN Disadvantages of
Cursors
OPEN CSR;
LOOP
FETCH CSR INTO vname,vdept,vsal;
EXIT WHEN CSR%ROWCOUNT=4 OR CSR%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(vname||’ ’||vdept||’ ’||vsal);
END LOOP;
CLOSE CSR;
END;
10.13
CURSOR
Cursor FOR Loop
Chittaranjan Pradhan
Cursor
Cursor Operations
%TYPE and %ROWTYPE
Implicit Cursor
Cursor FOR Loop
Explicit Cursor
In cursor FOR loop, you do not have to explicitly open and Steps of Explicit Cursor
WHERE CURRENT
FOR variable IN cursorname OF Clause
LOOP Disadvantages of
Cursors
Statements
END LOOP
10.14
CURSOR
Cursor FOR Loop...
Chittaranjan Pradhan
LOOP
UPDATE EMP SET salary=i.salary*1.05
WHERE e_id=i.e_id;
INSERT INTO Emp_raise VALUES(i.e_id, SYSDATE,
i.salary*0.05);
END LOOP;
COMMIT;
END;
10.15
CURSOR
Parameterized Cursors
Chittaranjan Pradhan
Cursor
Cursor Operations
%TYPE and %ROWTYPE
Parameterized Cursors
The parameter makes the cursor more reusable FOR UPDATE Clause
WHERE CURRENT
OF Clause
A cursor with parameter can be opened and closed several Disadvantages of
times. Each time a new active set is loaded in the memory and Cursors
10.16
CURSOR
Parameterized Cursors...
Chittaranjan Pradhan
Display the name and designation of employees corresponding
to the inputted deptno
Cursor
Cursor Operations
%TYPE and %ROWTYPE
DECLARE Implicit Cursor
vname EMPLOYEE.ename%TYPE; Explicit Cursor
vdesg EMPLOYEE.designation%TYPE; Steps of Explicit Cursor
Disadvantages of
did : =&did; Cursors
OPEN empcr(did);
DBMS_OUTPUT.PUT_LINE(’Employee in dept.’||did);
LOOP
FETCH empcr INTO vname, vdesg;
EXIT WHEN empcr%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(vname||’ ’||vdesg);
END LOOP;
CLOSE empcr;
END;
10.17
CURSOR
FOR UPDATE Clause
Chittaranjan Pradhan
Cursor
Cursor Operations
%TYPE and %ROWTYPE
FOR UPDATE Clause
Implicit Cursor
It is used to lock rows before updating or deleting of records Explicit Cursor
Steps of Explicit Cursor
WHERE CURRENT
Oracle server releases the lock at the end of the transaction OF Clause
Disadvantages of
Cursors
It is used to ensure that the record is not changed by another
user before the update or delete
10.18
CURSOR
WHERE CURRENT OF Clause
Chittaranjan Pradhan
Cursor
WHERE CURRENT OF Clause Cursor Operations
%TYPE and %ROWTYPE
It is used for referencing the current row of the active set Implicit Cursor
WHERE CURRENT
OF Clause
UPDATE tablename SET clause WHERE CURRENT OF
Disadvantages of
cursorname; Cursors
10.19
CURSOR
Explicit Cursor
Chittaranjan Pradhan
Implicit Cursor
DECLARE Explicit Cursor
vrec EMPLOYEE%ROWTYPE; Steps of Explicit Cursor
Cursor
Cursor Operations
%TYPE and %ROWTYPE
Implicit Cursor
Explicit Cursor
Steps of Explicit Cursor
Disadvantages of Cursors
Cursor FOR Loop
Disadvantages of
Cursors
If the cursor is not properly closed, the resources will not be
freed until the SQL session itself is closed
10.21
EXCEPTION HANDLER
Chittaranjan Pradhan
Built-in Errors
Laboratory 11 User-defined
Exceptions
Assigning name and error
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
11.1
EXCEPTION HANDLER
EXCEPTION HANDLER
Chittaranjan Pradhan
Exception Handler
Built-in Errors
User-defined
Exceptions
1 Exception Handler Assigning name and error
number to user-defined
exception
2 Built-in Errors
3 User-defined Exceptions
Assigning name and error number to user-defined
exception
11.2
EXCEPTION HANDLER
Exception Handler
Chittaranjan Pradhan
Exception Handler
When an exception occurs, the control is passed to the Exception Handler
User-defined
handler allows performing final action before it terminates Exceptions
Assigning name and error
number to user-defined
exception
It is an aid to develop program efficiently. Good PL/SQL
program traps the anticipated error using PL/SQL statements
and only unanticipated errors are diverted to exception handler
11.3
EXCEPTION HANDLER
Built-in Errors
Chittaranjan Pradhan
Built-in Errors
These errors are pre-defined and are automatically raised by User-defined
Oracle whenever an error is encountered. Each error is Exceptions
Assigning name and error
assigned a unique number and a message number to user-defined
exception
11.4
EXCEPTION HANDLER
Built-in Errors...
Chittaranjan Pradhan
no name. These are referred to by the general name OTHERS. Built-in Errors
User-defined
OTHERS stands for all other exceptions not explicitly named Exceptions
Assigning name and error
• SQLCODE: returns a negative error code number number to user-defined
exception
2 ORA-00000 to ORA-00830
3 ORA-00910 to ORA-01497
4 ORA-01500 to ORA-02098
5 ORA-02140 to ORA-04099
6 ORA-04930 to ORA-07499
7 ORA-07500 to ORA-09859
8 ORA-09870 to ORA-12100
9 ORA-12150 to ORA-12236
10 ORA-12315 to ORA-12354
11 ORA-12400 to ORA-12497
12 ORA-12500 to ORA-12699
13 ORA-12700 to ORA-19361
11.5
EXCEPTION HANDLER
Built-in Errors...
Chittaranjan Pradhan
Exception Handler
Built-in Errors
Display the employee working in the dept entered by the user User-defined
Exceptions
(Incorrect) Assigning name and error
number to user-defined
exception
DECLARE
vname EMPLOYEE.name%TYPE;
vd EMPLOYEE.deptno%TYPE;
BEGIN
vd : =&vd;
SELECT name INTO vname FROM EMPLOYEE WHERE
deptno=vd;
DBMS_OUTPUT.PUT_LINE(vname);
END;
11.6
EXCEPTION HANDLER
Built-in Errors...
Chittaranjan Pradhan
Exception Handler
Display the employee working in the dept entered by the user
Built-in Errors
(Partially Correct)
User-defined
Exceptions
Assigning name and error
number to user-defined
DECLARE exception
vname EMPLOYEE.name%TYPE;
vd EMPLOYEE.deptno%TYPE;
BEGIN
vd : =&vd;
SELECT name INTO vname FROM EMPLOYEE WHERE
deptno=vd;
DBMS_OUTPUT.PUT_LINE(vname);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(’No such dept with employee’);
END;
11.7
EXCEPTION HANDLER
Built-in Errors...
Chittaranjan Pradhan
User-defined
Exceptions
DECLARE Assigning name and error
number to user-defined
exception
vname EMPLOYEE.name%TYPE;
vd EMPLOYEE.deptno%TYPE;
BEGIN
vd : =&vd;
SELECT name INTO vname FROM EMPLOYEE WHERE
deptno=vd;
DBMS_OUTPUT.PUT_LINE(vname);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(’No such dept with employee’);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE||’ ’||SQLERRM);
END;
11.8
EXCEPTION HANDLER
User-defined Exceptions
Chittaranjan Pradhan
2. User-defined Exceptions
Exception Handler
User-defined
Exceptions
Assigning name and error
2.a. User-defined Named Exceptions number to user-defined
exception
11.9
EXCEPTION HANDLER
User-defined Exceptions...
Chittaranjan Pradhan
Write a PL/SQL block which will display the commission of the
inputted empno. Handle the exception for negative commission
Exception Handler
Built-in Errors
DECLARE User-defined
Exceptions
invalid_comm EXCEPTION; Assigning name and error
number to user-defined
vcomm Employee.comm%TYPE; exception
veno Employee.empno%TYPE;
BEGIN
veno : =&veno;
SELECT comm INTO vcomm FROM Employee WHERE empno=veno;
IF vcomm<0 THEN
RAISE invalid_comm;
ELSE
DBMS_OUTPUT.PUT_LINE(vcomm);
END IF;
EXCEPTION
WHEN invalid_comm THEN
DBMS_OUTPUT.PUT_LINE(’Commission is negative’);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(’No such id’);
11.10
EXCEPTION HANDLER
User-defined Exceptions...
Chittaranjan Pradhan
User-defined
Exceptions
Assigning name and error
DECLARE number to user-defined
exception
vcomm Employee.comm%TYPE;
veno Employee.empno%TYPE;
BEGIN
veno : =&veno;
SELECT comm INTO vcomm FROM Employee WHERE empno=veno;
IF vcomm<0 THEN
RAISE_APPLICATION_ERROR(-20000, ’Commission is negative’);
ELSE
DBMS_OUTPUT.PUT_LINE(vcomm);
END IF;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(’No such id’);
END;
11.11
EXCEPTION HANDLER
Assigning name and error number to user-defined exception
Chittaranjan Pradhan
Exception Handler
Built-in Errors
Assigning name and error number to user-defined exception
User-defined
Exceptions
A user-defined exception can be assigned a name and an error Assigning name and error
number to user-defined
number by using PRAGMA pre-compiler directive. This exception
exceptionname EXCEPTION;
PRAGMA EXCEPTION_INIT(exceptionname, errorcode);
11.12
EXCEPTION HANDLER
Assigning name & error number to user-defined exception...
Chittaranjan Pradhan
Exception Handler
DECLARE
Built-in Errors
vcomm Employee.comm%TYPE; User-defined
veno Employee.empno%TYPE; Exceptions
Assigning name and error
Invalid_comm EXCEPTION; number to user-defined
exception
Database Systems
Sub-Program
Package
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
12.1
STORED PROCEDURE
STORED PROCEDURE, STORED FUNCTION & PACKAGE STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Procedure
1 Sub-Program Parameter Passing
Stored Function
Package
2 Stored Procedure
Parameter Passing
3 Stored Function
4 Package
12.2
STORED PROCEDURE
Sub-Program STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program Sub-Program
Stored Procedure
• A subprogram is a named PL/SQL block that can accept Parameter Passing
Package
12.3
STORED PROCEDURE
Stored Procedure STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Stored Procedure
A procedure is a logically grouped set of SQL and PL/SQL Sub-Program
Stored Function
Oracle stores both the source and compiled code of Package
12.4
STORED PROCEDURE
Stored Procedure... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Write a procedure that accepts 2 numbers and print the sum
Sub-Program
Executing a procedure
EXECUTE psum(10, 20); or
Dropping a procedure
DROP PROCEDURE psum;
12.5
STORED PROCEDURE
Parameter Passing STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
a. IN Mode
Stored Procedure
Stored Function
into the program, it acts like a constant & can’t be assigned a
Package
value
12.6
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Stored Procedure
It is used to return values to the caller of a subprogram. The Parameter Passing
OUT parameter must be assigned some value in the called Stored Function
program Package
12.7
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Function
DECLARE Package
A NUMBER;
B NUMBER;
C NUMBER;
BEGIN
A : =&A;
B : =&B;
psum(A, B, C);
DBMS_OUTPUT.PUT_LINE(A||’+’||B||’=’||C);
END;
12.8
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
12.9
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Procedure
c. IN OUT Mode... Parameter Passing
Stored Function
Package
DECLARE
A NUMBER;
B NUMBER;
BEGIN
A : =&A;
B : =&B;
psum(A, B);
DBMS_OUTPUT.PUT_LINE(’Sum =’||A);
END;
12.10
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Write a procedure which takes the empid as input and displays Chittaranjan Pradhan
Like stored procedure, Oracle stores both the source code and Stored Function
Stored Procedure
BEGIN Parameter Passing
RETURN C; Package
END fsum;
Calling a function
SELECT fsum(10,15) FROM DUAL;
Showing Errors
SHOW ERRORS
Dropping a procedure
DROP FUNCTION fsum;
12.13
STORED PROCEDURE
Stored Function... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Procedure
Create a function which returns the deptname according to the Parameter Passing
Package
12.14
STORED PROCEDURE
Stored Function... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Write the PL/SQL block which takes the empid as input and
displays the deptid and dept name Sub-Program
Stored Procedure
Parameter Passing
vdeptname VARCHAR(12);
veid emp.empid%TYPE;
BEGIN
veid : =&veid;
SELECT deptno INTO vdid FROM emp WHERE empid=veid;
vdeptname : =get_deptname(vdid);
DBMS_OUTPUT.PUT_LINE(veid||’ ’||vdeptname);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE (veid||’not found);
END;
12.15
STORED PROCEDURE
Package STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Package
Sub-Program
A package is a collection of stored procedures, functions, Stored Procedure
cursors and exceptions. A package is compiled and stored in Parameter Passing
Package
Components of Packages
12.16
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Package Specification Chittaranjan Pradhan
Package Body
It contains actual programming code for the modules described
in the specification section
CREATE OR REPLACE PACKAGE BODY packname AS
Declaration
BEGIN
Executable statements
END packname;
12.17
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Stored Procedure
CREATE OR REPLACE PACKAGE calculator AS Parameter Passing
Sub-Program
Stored Procedure
FUNCTION fminus(A NUMBER, B NUMBER) RETURN NUMBER ISParameter Passing
BEGIN Package
C : =A-B;
RETURN C;
END fminus;
...
FUNCTION fmult(A NUMBER, B NUMBER) RETURN NUMBER IS
C NUMBER;
BEGIN
C : =A*B;
RETURN C;
END fmult;
12.19
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Procedure
Parameter Passing
Stored Function
FUNCTION fdivide(A NUMBER, B NUMBER) RETURN NUMBER IS
Package
C NUMBER;
BEGIN
IF B<>0 THEN
C : =A/B;
ELSE
C : =-1;
END IF;
RETURN C;
END fdivide;
12.20
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Procedure
PROCEDURE psum(A NUMBER, B NUMBER) IS Parameter Passing
BEGIN Package
C : =A+B;
DBMS_OUTPUT.PUT_LINE(A||’+’||B||’=’||C);
END Psum;
...
PROCEDURE pminus(A NUMBER, B NUMBER) IS
C NUMBER;
BEGIN
C : =A-B;
DBMS_OUTPUT.PUT_LINE(A||’-’||B||’=||C);
END Pminus;
END calculator;
12.21
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Sub-Program
Stored Procedure
Parameter Passing
Stored Function
12.22
DATABASE TRIGGER
Chittaranjan Pradhan
Types of Triggers
Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
13.1
DATABASE TRIGGER
DATABASE TRIGGER
Chittaranjan Pradhan
Database Trigger
Types of Triggers
INSTEAD OF Trigger
2 Types of Triggers
4 INSTEAD OF Trigger
13.2
DATABASE TRIGGER
Database Trigger
Chittaranjan Pradhan
Types of Triggers
• Trigger is a stored procedure that is fired when a DML : OLD and : NEW
Qualifiers
(INSERT, DELETE, UPDATE) statement is issued against INSTEAD OF Trigger
an associated table
• Trigger is mainly used to enforce checks, search and
backing up data
• A trigger can’t use a TCL statement like COMMIT,
ROLLBACK, or SAVEPOINT
• A variable in a trigger can’t be declared with LONG or
LONG RAW data type
• Components of Trigger:
• Triggering SQL statement
• Trigger action
• Trigger restriction
13.3
DATABASE TRIGGER
Types of Triggers
Chittaranjan Pradhan
Types of Triggers
• BEFORE Triggers: These triggers are fired before the
: OLD and : NEW
triggering SQL statement is executed Qualifiers
• AFTER Triggers: These triggers are fired after the INSTEAD OF Trigger
13.4
DATABASE TRIGGER
Database Trigger...
Chittaranjan Pradhan
Database Trigger
Types of Triggers
Database Trigger Syntax : OLD and : NEW
Qualifiers
INSTEAD OF Trigger
CREATE OR REPLACE TRIGGER triggername BEFORE/
AFTER/INSTEAD OF Triggerevent ON tablename/viewname
[FOR EACH ROW] [WHEN cond]
DECLARE
declaration
BEGIN
executable statements
EXCEPTION
exception handling statements
END;
13.5
DATABASE TRIGGER
: OLD and : NEW Qualifiers
Chittaranjan Pradhan
Database Trigger
Types of Triggers
INSTEAD OF Trigger
: OLD and : NEW Qualifiers
: OLD and : NEW qualifiers are related to ROW level triggers
13.6
DATABASE TRIGGER
Database Triggers...
Chittaranjan Pradhan
EMP_TRIG(ename, sal)
Database Trigger
Types of Triggers
EMP_BKUP(ename, sal, deletedate)
: OLD and : NEW
Qualifiers
INSTEAD OF Trigger
Create a trigger which checks the value of sal before INSERT or
UPDATE statement and ensures that sal below 500 is not inserted
............
INSERT INTO EMP_TRIG VALUES(’Prasant’,2000);
Types of Triggers
INSTEAD OF Trigger
............
DELETE FROM EMP_TRIG WHERE ENAME=’Prasant’;
13.8
DATABASE TRIGGER
Database Triggers...
Chittaranjan Pradhan
EMP_TRIG(ename, sal)
Database Trigger
EMP_BKUP(ename, sal, deletedate)
Types of Triggers
Database Trigger
Types of Triggers
.............
DELETE FROM stud_faculty WHERE facultyid=235;
13.10
DATABASE TRIGGER
INSTEAD OF Trigger...
Chittaranjan Pradhan
Database Trigger
Types of Triggers
.............
DELETE FROM stud_faculty WHERE facultyid=235;
13.11