You are on page 1of 243

Introduction To SQL

Chittaranjan Pradhan

Database Systems RDBMS

Client/Server

Laboratory 1 Database

SQL
SQL Statements

Introduction To SQL SQL*PLUS


Naming Conventions

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

3 SQL SQL Statements


SQL*PLUS

SQL Statements Naming Conventions

Data Types
SQL*PLUS
Table Creation
Naming Conventions
Viewing Table
Structure
4 Data Types Record Insertion
Inserting Time

5 Table Creation Querying Data

6 Viewing Table Structure

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

• For an attribute, the set of permitted values is called


domain of that attribute

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

7566 JONES MANAGER 7839 02-APR-81 2975 20 Table Creation


7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30 Viewing Table
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30 Structure
7782 CLARK MANAGER 7839 09-JUN-81 2450 10 Record Insertion
7788 SCOTT ANALYST 7566 09-NOV-81 3000 20 Inserting Time
7839 KING PRESIDENT 17-NOV-81 5000 10
Querying Data
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-SEP-81 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

1.4
Introduction To SQL
Examples of RDBMS
Chittaranjan Pradhan

• Oracle
RDBMS
• DB2 Client/Server
Database
• Microsoft SQL-Server
SQL

• MySQL SQL Statements


SQL*PLUS
Naming Conventions
• Microsoft Access
Data Types
• Apache Derby Table Creation

• Visual FoxPro Viewing Table


Structure

• OpenBase Record Insertion


Inserting Time

• PostgreSQL Querying Data

• 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

client Data Types

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

processing on the data, and sends only the requested


data back to the client over the network

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

SQL-2006, SQL-2008, SQL-2011 Querying Data

• SQL is the ideal database language to


• create database and table structures
• perform basic data management operation
• perform complex queries to transform data into useful
information

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

• ALTER statement Naming Conventions

Data Types
• DROP statement Table Creation

• RENAME statement Viewing Table


Structure
• TRUNCATE statement Record Insertion
Inserting Time

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

table or undoes those changes affected by DML statements Viewing Table


Structure
• COMMIT statement Record Insertion
Inserting Time
• ROLLBACK statement Querying Data

• SAVEPOINT statement

Data Control Language(DCL)


Gives and removes permissions on database structure
• GRANT statement
• REVOKE statement

1.9
Introduction To SQL
SQL*PLUS
Chittaranjan Pradhan

RDBMS

Client/Server
Database

• It is a tool to manipulate data & perform queries against SQL


SQL Statements
the database SQL*PLUS
Naming Conventions

• It enables you to conduct a conversation with the database Data Types

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

• A table is an object that can store data in a database SQL


SQL Statements

• 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

• The table and column names can be up to 30 characters Viewing Table


Structure
long Record Insertion
Inserting Time
• Table or column name must begin with a letter
Querying Data
• The names are not case sensitive
• Spaces and hyphens are not allowed in a table or a
column name; but $, _ and # are allowed

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

• The range of allowable dates is between January 1, SQL


SQL Statements
4712B.C. and December 31, 9999A.D. SQL*PLUS

• The default date format is DD-MON-YY. The Naming Conventions

DD-MON-YYYY format also works Data Types

Table Creation

• NUMBER(precision, scale) Viewing Table


Structure
• Stores floating point numbers as well as integer numbers. Record Insertion
Precision is the total number of significant digits in the Inserting Time

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

• RAW Inserting Time

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

• Used for character data up to 4GB Record Insertion


Inserting Time
• BFILE Querying Data
• Stores references to a binary file that is external to the
database and is maintained by the operating system’s file
system

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

Solution: CREATE TABLE STUDENT(Roll NUMBER(6), Name


VARCHAR2(20), Gender CHAR(1), Age NUMBER(3), CGPA
NUMBER(4,2));

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

Solution: Record Insertion


Inserting Time

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

table. The syntax is: Client/Server


Database

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

quotes Querying Data

Entering NULL values:

• Implicit method: Here, column name is omitted from the


column list in the INSERT statement
• Explicit method: Here, the null value is used as a value for
a numeric column, and an empty string (”) is used for date
or character columns
1.18
Introduction To SQL
Record Insertion...
Chittaranjan Pradhan

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

enclosed within a pair of single quotation marks Querying Data

• For more records, press /


• If an INSERT statement contains a value containing &
character, it is treated as a substitution variable. In such
cases, SET DEFINE OFF; and SET DEFINE ON;
commands are used

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

19, 9.2); Data Types

Table Creation

Viewing Table
• INSERT INTO STUDENT(Roll, Name, CGPA) VALUES Structure

(705129, ’Uday’, 9.2); Record Insertion


Inserting Time

Querying Data

• INSERT INTO STUDENT VALUES (&Roll, ’&Name’,


’&Gender’, &Age, &CGPA);

• INSERT INTO STUDENT (Roll, Name, Gender, Age)


VALUES(&Roll, ’&Name’, ’&Gender’, &Age);

1.20
Introduction To SQL
Record Insertion...
Chittaranjan Pradhan

Customized Prompts
RDBMS

ACCEPT command is used for customized prompts. The Client/Server


Database
syntax is: SQL
ACCEPT variablename PROMPT ’prompt message’ SQL Statements
SQL*PLUS

• 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);

Once a variable is defined with substitution variable or


ACCEPT, its value is known throughout that session
1.21
Introduction To SQL
Inserting Time
Chittaranjan Pradhan

RDBMS

Client/Server
Database

Time insertion SQL


SQL Statements
Time can be inserted by using TO_DATE() SQL*PLUS
Naming Conventions

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

time value is set to the midnight (12:00A.M.)


• If only the time value is entered in a date-type column, the
date is set to first of the current month

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

SELECT column1,column2 FROM table_name; SQL*PLUS


Naming Conventions

Data Types

If the user wants to see all the columns in a table, * can be Table Creation

used in place of columns Viewing Table


Structure

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

NULL value means the value is unknown or doesn’t exist

1.23
Introduction To SQL
Querying Data...
Chittaranjan Pradhan

RDBMS

Client/Server
Database

SQL
SQL Statements

SELECT Roll, Name, CGPA FROM STUDENT; SQL*PLUS


Naming Conventions

Data Types
Roll Name CGPA
Table Creation
705129 Uday 9.2 Viewing Table
705170 Ram Structure

Record Insertion
705171 Kim 8.6 Inserting Time

705172 Raji 7.5 Querying Data

1.24
SQL Fundamentals

Chittaranjan Pradhan

Database Systems SELECT Statement


Operators used in WHERE

Laboratory 2
condition
Sorting

ALTER Statement

SQL Fundamentals UPDATE Statement

DROP Statement

TRUNCATE Statement

DELETE Statement

RENAME Statement

Viewing User Tables

Creating Table from


another Table

Inserting data into a


Table from another
Table

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

2 ALTER Statement ALTER Statement

UPDATE Statement

3 UPDATE Statement DROP Statement

TRUNCATE Statement
4 DROP Statement DELETE Statement

RENAME Statement
5 TRUNCATE Statement Viewing User Tables

Creating Table from


6 DELETE Statement another Table

Inserting data into a


7 RENAME Statement Table from another
Table

8 Viewing User Tables ROWID

9 Creating Table from another Table

10 Inserting data into a Table from another Table

11 ROWID
2.2
SQL Fundamentals
Student table
Chittaranjan Pradhan

SELECT Statement
Operators used in WHERE
Roll Name City Age CGPA condition
Sorting

101 Ram Bhubaneswar 19 9.0 ALTER Statement


102 Hari Bhubaneswar 6.7 UPDATE Statement

103 Uday Jharkhand 20 8.97 DROP Statement

104 Vikas Uttar Pradesh 19 8.5 TRUNCATE Statement

105 Sweta Ranchi 19 9.2 DELETE Statement

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

212 Vikas Kolkota 23 5.98 Inserting data into a


Table from another
165 Manish 19 9.15 Table

ROWID

• The character data is displayed with left justification, while


numeric data with right justification

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

SELECT columns FROM tablename; ALTER Statement

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

Roll CGPA Creating Table from


another Table
101 9.0
Inserting data into a
102 6.7 Table from another
103 8.97 Table

104 8.5 ROWID


105 9.2
106 7.9
210 8.99
211 8.6
212 5.98
165 9.15

2.4
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan

Displaying Distinct Rows SELECT Statement


Operators used in WHERE
condition
The DISTINCT keyword is used to suppress duplicate values. Sorting

The syntax is: ALTER Statement

SELECT DISTINCT column FROM tablename; UPDATE Statement

DROP Statement

SELECT DISTINCT City FROM Student; TRUNCATE Statement

DELETE Statement
City RENAME Statement

Bhubaneswar Viewing User Tables

Jharkhand Creating Table from


another Table
Uttar Pradesh Inserting data into a
Ranchi Table from another
Table
Rajastan ROWID
Delhi
Cuttack
Kolkota

2.5
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan

Use of Arithmetic Expressions SELECT Statement


Operators used in WHERE

The arithmetic expressions are used to display mathematically condition


Sorting

calculated data. The syntax is: ALTER Statement

SELECT column, expression FROM tablename; UPDATE Statement

DROP Statement

SELECT Name, Age, Age+3 FROM Student; TRUNCATE Statement

DELETE Statement
Name Age Age+3 RENAME Statement

Ram 19 22 Viewing User Tables

Uday 20 23 Creating Table from


another Table
Vikas 19 22 Inserting data into a
Sweta 19 22 Table from another
Table
Yogesh 18 21 ROWID
Smriti 20 23
Sudam 21 24
Vikas 23 26
Manish 19 22

2.6
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan

Use of Alias SELECT Statement


Operators used in WHERE

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

Uday 20 23 Creating Table from


another Table
Vikas 19 22 Inserting data into a
Sweta 19 22 Table from another
Table
Yogesh 18 21 ROWID
Smriti 20 23
Sudam 21 24
Vikas 23 26
Manish 19 22

2.7
SQL Fundamentals
SELECT Statement...
Chittaranjan Pradhan

Concatenation
SELECT Statement

Concatenation joins a column or a character string to another Operators used in WHERE


condition

column. The syntax is: Sorting

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

Viewing User Tables


Name||’ ’||City Address
Creating Table from
Ram Bhubaneswar Ram Bhubaneswar another Table
Hari Bhubaneswar Hari Bhubaneswar Inserting data into a
Uday Jharkhand Uday Jharkhand Table from another
Table
Vikas Uttar Pradesh Vikas Uttar Pradesh
ROWID
Sweta Ranchi Sweta Ranchi
Yogesh Rajastan Yogesh Rajastan
Smriti Delhi Smriti Delhi
Sudam Cuttack Sudam Cuttack
Vikas Kolkota Vikas Kolkota
Manish Manish

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

Viewing User Tables


Selecting Specific Records
Creating Table from
another Table
Specific records can be selected by using a WHERE clause
Inserting data into a
with the SELECT statement. The syntax is: Table from another
Table
SELECT columns FROM tablename WHERE cond n ; ROWID

SELECT * FROM Student WHERE city= ’Bhubaneswar’;


Roll Name City Age CGPA
101 Ram Bhubaneswar 19 9.0
102 Hari Bhubaneswar 6.7

2.9
SQL Fundamentals
Operators used in WHERE condition
Chittaranjan Pradhan

Relational Operators SELECT Statement


Operators used in WHERE

= ex: CGPA=9.0 condition


Sorting

> ex: Age>20 ALTER Statement

< ex: Age<20 UPDATE Statement

>= ex: Age>=20 DROP Statement

<= ex: Age<=20 TRUNCATE Statement

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

Inserting data into a


Logical Operators Table from another
Table

AND ex: City=’Bhubaneswar’ AND Age=20 ROWID

OR ex: City =’Bhubaneswar’ OR Age=20


NOT ex: NOT(Age=20 OR Age=21)

AND has more precedence than OR

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

_: represents any one character ALTER Statement

UPDATE Statement

ex: Name LIKE ’S%’ DROP Statement

ex: Name LIKE ’S__’ TRUNCATE Statement

DELETE Statement
ex: Name LIKE ’%i%’
RENAME Statement
ex: Name LIKE ’_i%’ Viewing User Tables

Creating Table from


another Table
Special Operators
Inserting data into a
Table from another
IN ex: City IN(’Delhi’,’Cuttack’,’Ranchi’) Table

BETWEEN ex: Age BETWEEN 20 AND 22 ROWID

IS NULL ex: SELECT Name FROM Student WHERE Age is


NULL;

Name Age
Hari
2.11
SQL Fundamentals
Sorting
Chittaranjan Pradhan

SELECT Statement
ORDER BY clause using column name Operators used in WHERE
condition

ORDER BY clause is used to sort records in a table Sorting

SELECT columns FROM tablename [WHERE cond n ] ALTER Statement

UPDATE Statement
ORDER BY column [ASC/DESC]; DROP Statement

TRUNCATE Statement
SELECT * FROM Student ORDER BY Age; DELETE Statement

SELECT * FROM Student ORDER By CGPA, Age DESC; RENAME Statement

NULL values come at the end of the table in case of ORDER Viewing User Tables

BY clause Creating Table from


another Table

Inserting data into a


Table from another
ORDER BY clause using column number Table

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

Stud (roll, name, age) SELECT Statement


Operators used in WHERE
condition
Column NULL? Datatype Sorting

ROLL NUMBER(6) ALTER Statement

NAME VARCHAR2(20) UPDATE Statement

AGE NUMBER(2) DROP Statement

TRUNCATE Statement

DELETE Statement

Adding a New Column RENAME Statement

Viewing User Tables


ALTER TABLE tablename ADD(column definition); Creating Table from
another Table

ALTER TABLE Stud ADD (address number(20)); Inserting data into a


Table from another
Table
Column NULL? Datatype ROWID
ROLL NUMBER(6)
NAME VARCHAR2(20)
AGE NUMBER(2)
ADDRESS NUMBER(20)

2.13
SQL Fundamentals
ALTER Statement...
Chittaranjan Pradhan

Modifying an Existing Column


SELECT Statement
ALTER TABLE tablename MODIFY(column definition); Operators used in WHERE
condition
Sorting
ALTER TABLE Stud MODIFY(address varchar2(20)); ALTER Statement

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

Creating Table from


another Table
Dropping a Column
Inserting data into a
Table from another
ALTER TABLE tablename DROP COLUMN columnname; Table

ROWID

ALTER TABLE Stud DROP COLUMN address;


Column NULL? Datatype
ROLL NUMBER(6)
NAME VARCHAR2(20)
AGE NUMBER(2)
2.14
SQL Fundamentals
ALTER Statement...
Chittaranjan Pradhan

SELECT Statement
Operators used in WHERE
condition
Sorting

ALTER Statement
Renaming a Column
UPDATE Statement

ALTER TABLE tablename RENAME COLUMN oldname to DROP Statement

newname; TRUNCATE Statement

DELETE Statement

ALTER TABLE Stud RENAME COLUMN roll to id; RENAME Statement

Viewing User Tables


Column NULL? Datatype Creating Table from
another Table
ID NUMBER(6)
Inserting data into a
NAME VARCHAR2(20) Table from another
Table
AGE NUMBER(2)
ROWID

2.15
SQL Fundamentals
UPDATE Statement
Chittaranjan Pradhan

Roll Name Age Branch


101 Vikas 19 SELECT Statement
Operators used in WHERE
102 Soheb 20 condition
Sorting
103 Gita 18 ALTER Statement
104 Monalisa 19 UPDATE Statement

105 Ganesh 20 DROP Statement

TRUNCATE Statement

DELETE Statement
UPDATE Statement RENAME Statement

UPDATE tablename SET columnname=value [WHERE Viewing User Tables

cond n ]; Creating Table from


another Table

Inserting data into a


UPDATE Stud SET Branch=’CSE’ WHERE Roll=101; Table from another
Table

Roll Name Age Branch ROWID

101 Vikas 19 CSE


102 Soheb 20
103 Gita 18
104 Monalisa 19
105 Ganesh 20
2.16
SQL Fundamentals
UPDATE Statement...
Chittaranjan Pradhan

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

102 Soheb 20 CSE RENAME Statement

103 Gita 18 CSE Viewing User Tables

Creating Table from


104 Monalisa 19 CSE another Table

105 Ganesh 20 CSE Inserting data into a


Table from another
Table

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

Viewing User Tables


DROP TABLE Stud; Creating Table from
another Table

Inserting data into a


Table from another
Table

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

Viewing User Tables


TRUNCATE TABLE Stud; Creating Table from
another Table

Inserting data into a


Table from another
Table

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

Creating Table from


another Table
DELETE FROM Stud;
Inserting data into a
Table from another
Table

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

Viewing User Tables


RENAME Stud TO Student; Creating Table from
another Table

Inserting data into a


Table from another
Table

ROWID

2.21
SQL Fundamentals
Viewing User Tables
Chittaranjan Pradhan

SELECT Statement
Operators used in WHERE
condition
Sorting

ALTER Statement

UPDATE Statement

Viewing all user Objects DROP Statement

TRUNCATE Statement
SELECT * FROM TAB; DELETE Statement

RENAME Statement

Viewing all user Tables Viewing User Tables

Creating Table from


SELECT table_name FROM user_tables; another Table

Inserting data into a


Table from another
Table

ROWID

2.22
SQL Fundamentals
Creating Table from another Table
Chittaranjan Pradhan

SELECT Statement
Operators used in WHERE
condition
Sorting

ALTER Statement

Creating Table from another Table UPDATE 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

Inserting data into a


The SQL statement populates the target table with data from Table from another
Table
the source table ROWID

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

INSERT INTO tablename SELECT column1, column2 TRUNCATE Statement

FROM tablename[WHERE cond n ]; DELETE Statement

RENAME Statement

INSERT INTO Person SELECT Roll, Name, Age FROM Stud Viewing User Tables

WHERE Roll=101; Creating Table from


another Table

Inserting data into a


Table from another
INSERT INTO Person SELECT Roll, Name, Age FROM Stud; Table

ROWID

2.24
SQL Fundamentals
ROWID
Chittaranjan Pradhan

ROWID SELECT Statement


Operators used in WHERE
condition

• Each row has a unique ROWID Sorting

ALTER Statement
• It is an 18-bit number and represented as a base-64
UPDATE Statement
number DROP Statement

• It contains the physical address of a row in a database TRUNCATE 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

Inserting data into a


For example, consider Customer table Table from another
Table

Cid CName Address ROWID

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

record, then ROWID is used UPDATE Statement

DROP Statement

SELECT ROWID, Cid FROM Customer; TRUNCATE 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

Database Systems Constraints

NOT NULL Constraint

Laboratory 3 Unique Constraint


Dealing with UNIQUE
Constraint in an existing

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

NOT NULL Constraint


2 NOT NULL Constraint
Unique Constraint
Dealing with UNIQUE
Constraint in an existing
3 Unique Constraint table

Dealing with UNIQUE Constraint in an existing table PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
4 PRIMARY Key Constraint existing table

Dealing with PRIMARY KEY Constraint in an existing table FOREIGN Key


Constraint
Dealing with FOREIGN
KEY Constraint in an
5 FOREIGN Key Constraint existing table

Dealing with FOREIGN KEY Constraint in an existing table CHECK Constraint


Dealing with Check
Constraint in an existing
table
6 CHECK Constraint DEFAULT Value
Dealing with Check Constraint in an existing table Viewing USER
Constraints

7 DEFAULT Value

8 Viewing USER Constraints

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

performed on a table, the specified constraint must be satisfied table

PRIMARY Key
for the operation to succeed Constraint
Dealing with PRIMARY
KEY Constraint in an
existing table

Naming a Constraint FOREIGN Key


Constraint
A constraint can be identified by an internal or user-defined Dealing with FOREIGN
KEY Constraint in an

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

constraint_type FOREIGN Key


Constraint

• Table level: Dealing with FOREIGN


KEY Constraint in an
existing table
• A table- level constraint references one or more columns
CHECK Constraint
and is defined separately from the definitions of the columns Dealing with Check
Constraint in an existing
• Except the NOT NULL constraint, all other constraints can table

be defined at the table level DEFAULT Value

• [CONSTRAINT constraint_name] constraint_type Viewing USER


Constraints
(column,..)

Normally, simple keys are defined at the column level and


composite keys are defined at the table level
3.4
Constraints
NOT NULL Constraint
Chittaranjan Pradhan

Constraints

NOT NULL Constraint

NOT NULL Constraint Unique Constraint


Dealing with UNIQUE

It ensures that the column has a value and the value is not a Constraint in an existing
table

NULL value PRIMARY Key


Constraint
It prevents a column from accepting NULL values. The syntax Dealing with PRIMARY
KEY Constraint in an
is: existing table

columnname datatype(size) NOT NULL or FOREIGN Key


Constraint
Dealing with FOREIGN
KEY Constraint in an

columnname datatype(size) CONSTRAINT constraintname existing table

CHECK Constraint
NOT NULL Dealing with Check
Constraint in an existing
It can only be applied at column level table

DEFAULT Value

name VARCHAR(20) CONSTRAINT student_name_nn NOT Viewing USER


Constraints
NULL

3.5
Constraints
NOT NULL Constraint...
Chittaranjan Pradhan

Let the structure of ITEM_MASTER table is:


Constraints

Column Type Size NOT NULL Constraint

Unique Constraint
Item_no NUMBER 4 Dealing with UNIQUE

Name VARCHAR2 20 Constraint in an existing


table

Qty_on_hand NUMBER 5 PRIMARY Key


Constraint
Category CHAR 1 Dealing with PRIMARY
KEY Constraint in an
Unit_measure CHAR 4 existing table

Reorder_Lvl NUMBER 5 FOREIGN Key


Constraint
Reorder_qty NUMBER 5 Dealing with FOREIGN
KEY Constraint in an
Rate NUMBER 8,2 existing table

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

Let the Item_no,Reorder_lvl, Reorder_qty and Rate columns


are NOT NULL

3.6
Constraints
NOT NULL Constraint...
Chittaranjan Pradhan

CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) NOT


NULL, Name VARCHAR2(20), Qty_on_hand NUMBER(5), Constraints

NOT NULL Constraint


Category CHAR(1), Unit_measure CHAR(4), Reorder_Lvl
Unique Constraint
NUMBER(5) NOT NULL, Reorder_qty NUMBER(5) NOT Dealing with UNIQUE
Constraint in an existing
NULL, Rate NUMBER(8,2) NOT NULL); table

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

CHAR(4), Reorder_Lvl NUMBER(5) CONSTRAINT c2 NOT Dealing with FOREIGN


KEY Constraint in an
existing table
NULL, Reorder_qty NUMBER(5) CONSTRAINT c3 NOT
CHECK Constraint
NULL, Rate NUMBER(8,2) CONSTRAINT c4 NOT NULL); Dealing with Check
Constraint in an existing
table

Dropping NOT NULL Constraint DEFAULT Value

Viewing USER
A NOT NULL constraint can be dropped by executing Constraints

ALTER TABLE tablename DROP CONSTRAINT


constraintname;

ALTER TABLE ITEM_MASTER DROP CONSTRAINT c4;


3.7
Constraints
Unique Constraint
Chittaranjan Pradhan

Unique Constraint Constraints

NOT NULL Constraint


It ensures every value in a column or set of columns be unique
Unique Constraint
The unique constraint allows NULL values. The syntax is: Dealing with UNIQUE
Constraint in an existing
table

Column level: Columnname datatype(size) UNIQUE or PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
Columnname datatype(size) CONSTRAINT constraintname existing table

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

mob_no NUMBER(10) CONSTRAINT student_mob_uk DEFAULT Value

UNIQUE Viewing USER


Constraints

CONSTRAINT student_mob_uk UNIQUE(mob_no)

3.8
Constraints
Unique Constraint...
Chittaranjan Pradhan

Let the Name column in ITEM_MASTER table is unique: Constraints

NOT NULL Constraint

CREATE TABLE ITEM_MASTER(Item_no NUMBER(4) NOT Unique Constraint


Dealing with UNIQUE
NULL, Name VARCHAR2(20) UNIQUE, Qty_on_hand Constraint in an existing
table

NUMBER(5), Category CHAR(1), Unit_measure CHAR(4), PRIMARY Key


Constraint
Reorder_Lvl NUMBER(5) NOT NULL, Reorder_qty Dealing with PRIMARY
KEY Constraint in an
NUMBER(5) NOT NULL, Rate NUMBER(8,2) NOT NULL); existing table

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

Category CHAR(1), Unit_measure CHAR(4), Reorder_Lvl Constraint in an existing


table

NUMBER(5) NOT NULL, Reorder_qty NUMBER(5) NOT DEFAULT Value

NULL, Rate NUMBER(8,2) NOT NULL), CONSTRAINT ce3 Viewing USER


Constraints
UNIQUE(Name) ;

3.9
Constraints
Unique Constraint...
Chittaranjan Pradhan

Constraints

NOT NULL Constraint


The composite unique key constraint can be defined only at the Unique Constraint
table level by specifying column names separated by a comma Dealing with UNIQUE
Constraint in an existing

within parentheses table

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

NULL, Name VARCHAR2(20) , Qty_on_hand NUMBER(5), CHECK Constraint

Category CHAR(1), Unit_measure CHAR(4), Reorder_Lvl Dealing with Check


Constraint in an existing
table
NUMBER(5) NOT NULL, Reorder_qty NUMBER(5) NOT
DEFAULT Value
NULL, Rate NUMBER(8,2) NOT NULL), CONSTRAINT ce4 Viewing USER
UNIQUE(Item_no,Name) ; Constraints

3.10
Constraints
Dealing with UNIQUE Constraint in an existing table
Chittaranjan Pradhan

Constraints

NOT NULL Constraint

The syntax for adding unique constraint is: Unique Constraint


Dealing with UNIQUE
ALTER TABLE tablename ADD CONSTRAINT Constraint in an existing
table

constraintname UNIQUE(columns); PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
ALTER TABLE ITEM_MASTER ADD CONSTRAINT C4 existing table

UNIQUE(Name); FOREIGN Key


Constraint
Dealing with FOREIGN
KEY Constraint in an
The syntax for dropping unique constraint is: existing table

ALTER TABLE tablename DROP CONSTRAINT CHECK Constraint


Dealing with Check

constraintname; Constraint in an existing


table

DEFAULT Value

ALTER TABLE ITEM_MASTER DROP CONSTRAINT C4; Viewing USER


Constraints

3.11
Constraints
Primary Key Constraint
Chittaranjan Pradhan

Primary Key Constraint


Constraints
Primary key constraint is also known as the entity integrity
NOT NULL Constraint
constraint Unique Constraint
A table can have at most one primary key constraint Dealing with UNIQUE
Constraint in an existing
PRIMARY key is equivalent to the combination of NOT NULL table

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

Table level: CONSTRAINT constraintname PRIMARY table

DEFAULT Value
KEY(columns)
Viewing USER
Constraints
roll number(6) CONSTRAINT student_roll_pk PRIMARY KEY

CONSTRAINT student_roll_pk PRIMARY KEY(roll)

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

NUMBER(5) NOT NULL, Rate NUMBER(8,2) NOT NULL); FOREIGN Key


Constraint
Dealing with FOREIGN
KEY Constraint in an
existing table

CREATE TABLE ITEM_MASTER(Item_no NUMBER(4), Name CHECK Constraint


Dealing with Check
VARCHAR2(20) UNIQUE, Qty_on_hand NUMBER(5), Constraint in an existing
table
Category CHAR(1), Unit_measure CHAR(4), Reorder_Lvl DEFAULT Value
NUMBER(5) NOT NULL, Reorder_qty NUMBER(5) NOT Viewing USER
Constraints
NULL, Rate NUMBER(8,2) NOT NULL, CONSTRAINT C7
PRIMARY KEY(Item_no));

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

constraintname PRIMARY KEY(columns); Constraint in an existing


table

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

ALTER TABLE tablename DROP PRIMARY KEY existing table

CHECK Constraint
[CASCADE]; Dealing with Check
Constraint in an existing
table

ALTER TABLE ITEM_MASTER DROP PRIMARY KEY; or DEFAULT Value

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

and domain must match PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
Column level: Columnname datatype(size) [CONSTRAINT existing table

constraintname] REFERENCES tablename(columns) or FOREIGN Key


Constraint
Columnname datatype(size) [CONSTRAINT Dealing with FOREIGN
KEY Constraint in an

constraintname] REFERENCES tablename existing table

CHECK Constraint
Dealing with Check
Constraint in an existing
Table level: CONSTRAINT constraintname FOREIGN table

KEY(columns) REFERENCES tablename(columns) DEFAULT Value

Viewing USER
Constraints
fid VARCHAR(6) CONSTRAINT student_fid_fk REFERENCES
faculty(fid)

CONSTRAINT student_fid_fk FOREIGN KEY(fid)


REFERENCES faculty(fid)
3.15
Constraints
Foreign Key Constraint...
Chittaranjan Pradhan

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

Coulmn level: Columnname datatype(size) [CONSTRAINT PRIMARY Key


Constraint
constraintname] REFERENCES tablename(columns) [ON Dealing with PRIMARY
KEY Constraint in an

DELETE CASCADE] 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

fid VARCHAR(6) CONSTRAINT student_fid_fk REFERENCES DEFAULT Value

faculty(fid) ON DELETE CASCADE Viewing USER


Constraints

CONSTRAINT student_fid_fk FOREIGN KEY(fid)


REFERENCES faculty(fid) ON DELETE CASCADE

3.16
Constraints
Foreign Key Constraint...
Chittaranjan Pradhan

Constraints

NOT NULL Constraint

Unique Constraint
Let ITEM_TRANS be the table where It_no references to the Dealing with UNIQUE
Constraint in an existing

Item_no column in ITEM_MASTER table table

PRIMARY Key
Constraint
Column Type Size Dealing with PRIMARY
KEY Constraint in an

It_no NUMBER 4 existing table

FOREIGN Key
Trans_date DATE Constraint

qty NUMBER 5 Dealing with FOREIGN


KEY Constraint in an
existing table

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

qty NUMBER(5)); DEFAULT Value

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

constraintname FOREIGN KEY(columns) REFERENCES Constraint in an existing


table

tablename(columns); PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
ALTER TABLE ITEM_TRANS ADD CONSTRAINT C7 existing table

FOREIGN KEY(Item_no) REFERENCES FOREIGN Key


Constraint
ITEM_MASTER(Item_no); Dealing with FOREIGN
KEY Constraint in an
existing table

CHECK Constraint
The syntax for dropping Foreign key constraint is: Dealing with Check
Constraint in an existing
ALTER TABLE tablename DROP CONSTRAINT table

constraintname; DEFAULT Value

Viewing USER
Constraints
ALTER TABLE ITEM_TRANS DROP CONSTRAINT C7;

3.18
Constraints
Check Constraint
Chittaranjan Pradhan

Check Constraint Constraints

It defines a condition that every row must satisfy. There can be NOT NULL Constraint

more than one CHECK constraint on a column Unique Constraint


Dealing with UNIQUE
Constraint in an existing
table

Column level: Columnname datatype(size) CONSTRAINT PRIMARY Key


Constraint
constraintname CHECK(condition) Dealing with PRIMARY
KEY Constraint in an
existing table

Table level: CONSTRAINT constraintname FOREIGN Key


Constraint
CHECK(condition) Dealing with FOREIGN
KEY Constraint in an
existing table

age NUMBER(2) CONSTRAINT student_age_chk CHECK Constraint


Dealing with Check
CHECK((age>=15) AND (age<=50)) Constraint in an existing
table

DEFAULT Value

CONSTRAINT student_age_chk CHECK((age>=15) AND Viewing USER


Constraints
(age<=50))

name VARCHAR(20) CONSTRAINT student_name_nn


CHECK(name is NOT NULL)
3.19
Constraints
Check Constraint...
Chittaranjan Pradhan

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

Reorder_Lvl NUMBER(5) NOT NULL, Reorder_qty PRIMARY Key


Constraint
NUMBER(5) NOT NULL, Rate NUMBER(8,2) NOT NULL); Dealing with PRIMARY
KEY Constraint in an
existing 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

(Category=’B’ AND Rate<=4500) OR (Category=’C’ AND


Rate>=4500)));

3.20
Constraints
Dealing with Check Constraint in an existing table
Chittaranjan Pradhan

Constraints

NOT NULL Constraint

The syntax for adding Check constraint is: Unique Constraint


Dealing with UNIQUE
ALTER TABLE tablename ADD CONSTRAINT Constraint in an existing
table

constraintname CHECK (condition); PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
ALTER TABLE ITEM_TRANS ADD CONSTRAINT C8 existing table

CHECK(Category in(’A’, ’B’, ’C’)); FOREIGN Key


Constraint
Dealing with FOREIGN
KEY Constraint in an
The syntax for dropping Check constraint is: existing table

ALTER TABLE tablename DROP CONSTRAINT CHECK Constraint


Dealing with Check

constraintname; Constraint in an existing


table

DEFAULT Value

ALTER TABLE ITEM_TRANS DROP CONSTRAINT C8; Viewing USER


Constraints

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

defined in the column level. The syntax is: KEY Constraint in an


existing table

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

Reorder_qty NUMBER(5) NOT NULL, Rate NUMBER(8,2)


NOT NULL);

3.22
Constraints
DEFAULT Value...
Chittaranjan Pradhan

Constraints

NOT NULL Constraint

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

Columnname datatype(size) DEFAULT value constraint FOREIGN Key


Constraint
definition Dealing with FOREIGN
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

NOT NULL Constraint

Viewing USER Constraints Unique Constraint


Dealing with UNIQUE
Constraint in an existing
User can view all the constraints by excuting table

SELECT * FROM USER_CONSTRAINTS; PRIMARY Key


Constraint
Dealing with PRIMARY
KEY Constraint in an
existing table

FOREIGN Key
If the user wants to view all the constraints applied to a single Constraint

table, the syntax is: Dealing with FOREIGN


KEY Constraint in an
existing table
SELECT * FROM USER_CONSTRAINTS WHERE
CHECK Constraint
TABLE_NAME= tablename; Dealing with Check
Constraint in an existing
table

DEFAULT Value

SELECT * FROM USER_CONSTRAINTS WHERE Viewing USER


Constraints
TABLE_NAME=’ITEM_MASTER’;

3.24
Built-in Functions

Chittaranjan Pradhan

Database Systems DUAL Table

Employee Table

Laboratory 4 Built-in Functions

Group Functions

Built-in Functions Scalar Functions


Date Functions
Numeric Functions
Character Functions
Conversion Functions
Misc. 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

type Character Functions


Conversion Functions
Misc. Functions

This table is owned by user SYS and is available to all users

It is used for Arithmetic calculations and Date retrieval


SELECT 2*5 FROM DUAL;

SELECT SYSDATE FROM DUAL;

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

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30


7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 09-NOV-81 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-SEP-81 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10

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

• Single-row or Scalar functions:


• They work on columns from each row and return one result
per row
• Group functions or Aggregate functions:
• They manipulate data in a group of rows and return single
result

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

COUNT([DISTINCT] column) Built-in Functions

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

SELECT COUNT(*) FROM EMP;


COUNT(*)
14
4.6
Built-in Functions
Group Functions...
Chittaranjan Pradhan

SUM([DISTINCT] column) DUAL Table

Employee Table
It finds the sum of all values in a column ignoring the NULL
Built-in Functions
values
Group Functions

SELECT SUM(SAL) FROM EMP; Scalar Functions


Date Functions
Numeric Functions

SUM(SAL) Character Functions


Conversion Functions
29055 Misc. 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

MAX([DISTINCT] column) DUAL Table

Employee Table
It finds the maximum value in the column ignoring the NULL
Built-in Functions
values
Group Functions

SELECT MAX(SAL) FROM EMP; Scalar Functions


Date Functions
Numeric Functions

MAX(SAL) Character Functions


Conversion Functions
5000 Misc. 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

Scalar Functions DUAL Table

Employee Table
These functions act on one value at a time. There are various Built-in Functions
types of scalar functions: Group Functions

• Date functions: These functions take a date value or Scalar Functions


Date Functions
date-type column as argument and return date-type data Numeric Functions
Character Functions
• Numeric functions: These functions take a number or Conversion Functions
Misc. Functions
number-type column as argument and return a numeric
value
• Character functions: These functions take a character
string or character-type column as argument and return a
character or numeric value
• Conversion functions: These functions are used to
convert value from one data type to another
• Misc. functions: These functions perform some specific
tasks

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

functions are: Employee 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

SELECT SYSDATE FROM DUAL; Character Functions


Conversion Functions
Misc. Functions
SYSDATE
21-JAN-13

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

28-JAN-13 Numeric Functions


Character Functions
Conversion Functions
Misc. Functions

EXTRACT(YEAR/MONTH/DAY FROM date)


This extracts the year, month, or day from a date value

SELECT EXTRACT(MONTH FROM SYSDATE) FROM DUAL;


EXTRACT(MONTH FROM SYSDATE)
1

SELECT EXTRACT(YEAR FROM SYSDATE) FROM DUAL;


EXTRACT(YEAR FROM SYSDATE)
2013

4.12
Built-in Functions
Numeric Functions
Chittaranjan Pradhan

These functions take numeric values and return a numeric


value. The different functions in this category are: DUAL Table

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

SELECT CEIL(-5.2), CEIL(5.7) FROM DUAL;


CEIL(-5.2) CEIL(5.7)
-5 6

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

FLOOR(-5.2) FLOOR(5.7) Conversion Functions


Misc. Functions
-6 5

EXP(n)
It returns the exponent e raised to power n

SELECT EXP(5) FROM DUAL;


EXP(5)
148.413159

4.14
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan
LN(n)
It returns the natural logarithm of n DUAL Table

Employee Table

SELECT LN(2) FROM DUAL; Built-in Functions

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

SELECT LOG(4,10) FROM DUAL;


LOG(4,10)
1.66096405

MOD(n, m)
It returns the integer remainder of n/m

SELECT MOD(15,4) FROM DUAL;


MOD(15,4)
3
4.15
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan

POWER(m, n)
DUAL Table

It returns m raised to power n Employee Table

Built-in Functions

SELECT POWER(4,3) FROM DUAL; Group 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

SELECT SQRT(25) FROM DUAL;


SQRT(25)
5

SELECT SQRT(-25) FROM DUAL;


ORA-01428: argument ’-25’ is out of range

4.16
Built-in Functions
Numeric Functions...
Chittaranjan Pradhan

DUAL Table
ROUND(m, [n]) Employee Table

It returns m, rounded to n places to the right of a decimal point Built-in Functions

Group Functions

SELECT ROUND(15.19,1), ROUND(15.19) FROM DUAL; Scalar Functions


Date Functions
Numeric Functions

ROUND(15.19,1) ROUND(15.19) Character Functions


Conversion Functions
15.2 15 Misc. Functions

TRUNC(m, n)
It returns the truncated value of m up to n positions

SELECT TRUNC(15.19,1) FROM DUAL;


TRUNC(15.19,1)
15.1

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

positive Built-in Functions

Group Functions

SELECT SIGN(-8.5) FROM DUAL; Scalar Functions


Date Functions
Numeric Functions
SIGN(-8.5) Character Functions
Conversion Functions
-1 Misc. Functions

SIN(n)
It returns sine of n, where n is in radian

SELECT SIN(60), SIN(1.047167) FROM DUAL;


SIN(60) SIN(1.047167)
-0.3048106 0.8660

Other trigonometric functions are: COS(n), TAN(n), SINH(n),


COSH(n), TANH(n)
4.18
Built-in Functions
Character Functions
Chittaranjan Pradhan

These functions work on character values. The different types


of character functions are: DUAL Table

Employee Table
CHR(n)
Built-in Functions

It returns the ASCII character corresponding to the integer n Group Functions

Scalar Functions

SELECT CHR(70) FROM DUAL; Date Functions


Numeric Functions
Character Functions

CHR(70) Conversion Functions


Misc. Functions

CONCAT(s1, s2)
It joins the first string to the second string. It is similar to the ||
operator

SELECT CONCAT(’RAM’,’KRISHNA’), ’RAM’||’KRISHNA’


FROM DUAL;
CONCAT(’RAM’,’KRISHNA’) ’RAM’||’KRISHNA’
RAMKRISHNA RAMKRISHNA

4.19
Built-in Functions
Character Functions...
Chittaranjan Pradhan

LPAD(s, n, c) DUAL Table

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

LPAD(’ORACLE’,10,’*’) Character Functions


Conversion Functions

****ORACLE Misc. 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

INITCAP(s) DUAL Table

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

Hello Misc. Functions

SELECT INITCAP(E_NAME) FROM EMP;


LOWER(s)
It converts each letter to lowercase
SELECT LOWER(’HELLO’) FROM DUAL;
LOWER(’HELLO’)
hello

4.21
Built-in Functions
Character Functions...
Chittaranjan Pradhan

UPPER(s)
DUAL Table

It converts each letter to uppercase Employee Table

Built-in Functions

SELECT UPPER(’HeLLo’) FROM DUAL; Group 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

SELECT LTRIM(E_NAME,’S’) FROM EMP;


RTRIM(s, c)
It trims the string s from the right when the characters
specified, c, is present in s

SELECT RTRIM(E_NAME,’I’) FROM EMP;


4.22
Built-in Functions
Character Functions...
Chittaranjan Pradhan

DUAL Table
REPLACE(s, s1, s2) Employee Table

It returns the string s with the replacement of s2 in place of s1 Built-in Functions

Group Functions

SELECT REPLACE(’ORACLE’,’RAC’,’V’) FROM DUAL; Scalar Functions


Date Functions
Numeric Functions
REPLACE(’ORACLE’,’RAC’,’V’) Character Functions

OVLE Conversion Functions


Misc. 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

It returns the number of characters present in the string s Built-in Functions

Group Functions

SELECT LENGTH(’ORACLE’) FROM DUAL; Scalar Functions


Date Functions
Numeric Functions
LENGTH(’ORACLE’) Character Functions
6 Conversion Functions
Misc. Functions

SOUNDEX(s)
It compares words that are spell differently, but sound alike

SELECT E_NAME FROM EMP WHERE


SOUNDEX(E_NAME)=SOUNDEX(’KEEING’);
E_NAME
KING

4.24
Built-in Functions
Conversion Functions
Chittaranjan Pradhan

These functions convert data from one data type to another.


The different conversion functions are: DUAL Table

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

SELECT SUM(TO_NUMBER(SAL)) FROM EMP; Misc. Functions

TO_DATE(char [,format])
It converts a character value to date value based on the format
provided

SELECT TO_DATE(’January 7, 1988’,’month dd, yyyy’) FROM


DUAL;
TO_DATE(’January 7, 1988’,’month dd, yyyy’)
07-JAN-88

4.25
Built-in Functions
Conversion Functions...
Chittaranjan Pradhan

DUAL Table

Employee Table
TO_CHAR(number [,format])
Built-in Functions

It converts a number to a VARCHAR value based on the format Group 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

SELECT TO_CHAR(17145,’$999,999’) FROM DUAL; Misc. Functions

TO_CHAR(17145,’$999,999’)
$17,145

SELECT TO_CHAR(17145,’$000,000’) FROM DUAL;


TO_CHAR(17145,’$000,000’)
$017,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

APRIL 02, 1981 Misc. Functions

Use of TH in Date formatting


It converts a date to a VARCHAR value based on TH format
SELECT HIREDATE, TO_CHAR(HIREDATE,’DDTH-MON-YY’)
FROM EMP WHERE DEPT_NO=10;
HIREDATE TO_CHAR(HIREDATE,’DDTH-MON-YY’)
09-JUN-81 09TH-JUN-81
17-NOV-81 17TH-NOV-81
23-JAN-82 23RD-JAN-82
4.27
Built-in Functions
Conversion Functions...
Chittaranjan Pradhan

Use of SP in Date formatting


DUAL Table
It converts a date to a VARCHAR value with the spelling
Employee Table

SELECT TO_CHAR(HIREDATE,’DDSP-MON-YY’) FROM EMP Built-in 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

Use of SPTH in Date formatting


It converts a date to a VARCHAR value with the spelling and
TH format
SELECT TO_CHAR(HIREDATE,’DDSPTH-MON-YY’) FROM
EMP WHERE DEPT_NO=10;
TO_CHAR(HIREDATE,’DDSPTH-MON-YY’)
NINTH-JUN-81
SEVENTEENTH-NOV-81
TWENTY-THIRD-JAN-82
4.28
Built-in Functions
Misc. Functions
Chittaranjan Pradhan

Two important functions to deal with NULL value are:


DUAL Table

NVL(column, value) Employee Table

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

SELECT E_NAME, NVL(COMMISSION, 0) Conversion Functions


Misc. 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

SELECT E_NAME, NVL2(COMMISSION, ’YES’, ’NO’) FROM


EMP;
4.29
Grouping, DCL & TCL

Chittaranjan Pradhan

Database Systems Grouping Data

Data Control

Laboratory 5 Language (DCL)

Transaction Control
Language (TCL)

Grouping, DCL & TCL SQL*PLUS


Commands

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

2 Data Control Language (DCL)

3 Transaction Control Language (TCL)

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

appearing in SELECT statement must also appear in GROUP Data Control


Language (DCL)
BY clause. The syntax of this is: Transaction Control
SELECT column, groupfunction(column) FROM tablename Language (TCL)

SQL*PLUS
GROUP BY column; Commands

SELECT DEPT_NO FROM EMP GROUP BY DEPT_NO;


DEPT_NO
30
20
10
SELECT DEPT_NO, AVG(SAL) FROM EMP GROUP BY
DEPT_NO;

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];

SELECT DEPT_NO, AVG(SAL) FROM EMP GROUP BY


DEPT_NO HAVING AVG(SAL)>2000;

DEPT_NO AVG(SAL)
20 2175
10 2926.66666666666666666666666666666666667

5.4
Grouping, DCL & TCL
Grouping Data...
Chittaranjan Pradhan

Grouping Data

WHERE and GROUP BY Clause Data Control


Language (DCL)
The data can be restricted before the grouping by using Transaction Control
Language (TCL)
WHERE clause. The syntax of this is:
SQL*PLUS
Commands

SELECT column, groupfunction(column) FROM tablename


[WHERE condition] GROUP BY column;

SELECT DEPT_NO, AVG(SAL) FROM EMP WHERE


SAL>2000 GROUP BY DEPT_NO;

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)

syntax for it is: SQL*PLUS


Commands

SELECT column, groupfunction(column) FROM tablename


[WHERE condition] GROUP BY column [HAVING
groupcondition];

SELECT DEPT_NO, AVG(SAL) FROM EMP WHERE


SAL>2000 GROUP BY DEPT_NO HAVING AVG(SAL)<3000;

DEPT_NO AVG(SAL)
30 2850
20 2991.66666666666666666666666666666666667

5.6
Grouping, DCL & TCL
Data Control Language
Chittaranjan Pradhan

An object privilege specifies what a user can do with a Grouping Data


database object, such as a table or a view. The different Data Control
privileges for table are: ALTER, INSERT, UPDATE, DELETE, Language (DCL)

Transaction Control
and SELECT Language (TCL)

SQL*PLUS
Granting Privileges Commands

A user can grant privileges on objects from own schema to


other users or roles by using GRANT command. The syntax of
providing a privilege is:
GRANT privileges/ ALL ON objectname TO username/
PUBLIC [WITH GRANT OPTION];
WITH GRANT OPTION clause allows the grantee to grant
privileges to other users and roles

GRANT SELECT, INSERT ON Employee TO Mita;

GRANT SELECT, INSERT ON Employee TO Mita WITH


GRANT OPTION;

5.7
Grouping, DCL & TCL
Data Control Language...
Chittaranjan Pradhan

Grouping Data
SELECT * FROM SYSTEM.Employee;
Data Control
Language (DCL)

GRANT SELECT ON SYSTEM.Employee TO Mithun; Transaction Control


Language (TCL)

SQL*PLUS
Revoking Privileges Commands

If a user granted privileges by a WITH GRANT OPTION to


another user and that second user passed on those privileges,
the REVOKE statement takes privileges not only from the
grantee but also from the users granted privileges by the
grantee. The general syntax is:
REVOKE privileges/ALL ON objectname FROM username/
PUBLIC;

REVOKE INSERT ON Employee FROM Mita;

REVOKE ALL ON Employee FROM Mita;

5.8
Grouping, DCL & TCL
Transaction Control Language
Chittaranjan Pradhan

A transaction consists of a sequence of query and update Grouping Data

statements. Transaction Control Language gives you flexibility Data Control


Language (DCL)
to undo transactions or write transactions to the disk.
Transaction Control
Transactions provide consistency in case of a system failure Language (TCL)

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;

Roll backing the operations


ROLLBACK statement is used to discard parts or all of the
work the user has done in the current transaction. The syntax
for this is:
ROLLBACK;

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

whole transaction, so that the system will discard all the


changes up to a point. The syntax for creating a SAVEPOINT
is:
SAVEPOINT savepointname;

The syntax for roll backing to a particular savepoint is:


ROLLBACK TO SAVEPOINT savepointname;

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

It retrieves previously saved file to the buffer

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

EDIT Grouping Data

It opens the current buffer named afiedt.buf Data Control


Language (DCL)

Transaction Control
Language (TCL)
EDIT filename.sql SQL*PLUS
Commands
It allows to edit a saved file

PASSWORD
It allows to change the password

CREATE USER username IDENTIFIED BY password


It creates a new user with respective password

EXIT
It leaves SQL *PLUS environment & commits current
transaction

5.12
Join & Set Operators

Chittaranjan Pradhan

Database Systems CROSS JOIN

Join

Laboratory 6 Inner Join

Outer Join

Join & Set Operators Self Join

Set Operators

Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
6.1
Join & Set Operators
Join & Set Operators
Chittaranjan Pradhan

CROSS JOIN

1 CROSS JOIN Join

Inner Join

Outer Join

2 Join Self 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

Cross Join Outer 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;

SELECT d.deptno, d.location, e.ename, e.eid FROM Employee


e, Department d;

SELECT * FROM Employee CROSS JOIN 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

In broad level, Joins are of three categories:


• Inner Join
• Outer Join
• Self Join

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

are: Self 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

SELECT e.eid, e.ename, e.sal, s.bonus FROM Employee e,


Salgrades s WHERE e.comm>s.bonus;

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

is based on the equality operation Outer Join

Self Join

SELECT empno, ename, Employee.deptno, dname FROM Set Operators

Employee, Department WHERE Employee.deptno =


Department.deptno;
Natural Join
Natural join is possible between two tables only when they
contain at least one common attribute. It is just like the equi
join with the elimination of the common attributes. The syntax
of natural join is:
SELECT columns FROM table1 NATURAL JOIN table2;

SELECT ename, sal, deptno FROM Employee NATURAL JOIN


Department;

6.6
Join & Set Operators
Outer Join
Chittaranjan Pradhan

Outer join is an extension of the natural join operation to deal


with the missing information. The different types of outer join CROSS JOIN

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

left outer join is:


SELECT columns FROM table1 LEFT OUTER JOIN table2
USING(column); or
SELECT columns FROM table1 LEFT OUTER JOIN table2
ON table1.column= table2.column;

SELECT * FROM Employee LEFT OUTER JOIN Department


USING(deptno);
SELECT * FROM Employee LEFT OUTER JOIN Department
ON Employee.deptno= Department.deptno;
SELECT deptno, location, ename * FROM Employee,
Department WHERE Employee.deptno=
Department.deptno(+);
6.7
Join & Set Operators
Outer Join...
Chittaranjan Pradhan

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;

SELECT * FROM Employee RIGHT OUTER JOIN Department


USING(deptno);
SELECT * FROM Employee RIGHT OUTER JOIN Department
ON Employee.deptno= Department.deptno;
SELECT deptno, location, ename * FROM Employee,
Department WHERE Employee.deptno(+)=
Department.deptno;

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

of full outer join is: Self Join

SELECT columns FROM table1 FULL OUTER JOIN table2 Set Operators

USING(column); or

SELECT columns FROM table1 FULL OUTER JOIN table2


ON table1.column= table2.column;

SELECT * FROM Employee FULL OUTER JOIN Department


USING(deptno);

SELECT * FROM Employee FULL OUTER JOIN Department


ON Employee.deptno= Department.deptno;

6.9
Join & Set Operators
Self Join
Chittaranjan Pradhan

CROSS JOIN

Join

Inner Join

Self Join Outer 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;

SELECT e.ename AS ëmployee", m.ename AS


managerFROM Employee m, Employee e WHERE
e.mgr=m.empno;

6.10
Join & Set Operators
Set Operators
Chittaranjan Pradhan

CROSS JOIN

Join

Inner Join

To perform the set operations such as UNION, DIFFERENCE Outer 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

and not in another Self 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

Database Systems Sub Query

Single-row Subquery

Laboratory 7 Multiple-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

1 Sub Query Sub Query

Single-row Subquery

2 Single-row Subquery Multiple-row Subquery

Multiple-column
Subquery
3 Multiple-row Subquery Correlated Subquery

Nested Subquery

4 Multiple-column Subquery UPDATE with


Subquery

DELETE with
5 Correlated Subquery Subquery

TOP- N Analysis

6 Nested Subquery

7 UPDATE with Subquery

8 DELETE with Subquery

9 TOP- N Analysis

7.2
Sub-Query
Sub Query
Chittaranjan Pradhan

Sub Query Sub Query

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

• Single-row subquery: It is a subquery that returns only TOP- N Analysis

one row of data


• Multiple-row subquery: It is a subquery that returns
more than one row of data

The subtypes of subqueries are:


• Multiple column Subqueries
• Correlated subqueries

7.3
Sub-Query
Single-row Subquery
Chittaranjan Pradhan

Sub Query

Single-row Subquery

Single-row Subquery Multiple-row Subquery

Multiple-column
Single-row subquery returns zero or one row to the outer SQL Subquery

statement. The general syntax of this is: Correlated Subquery

SELECT columns FROM table1 WHERE column operator Nested 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

roll and name of students belongs to ’CSE’ department, the


query is:

SELECT roll, name FROM Student WHERE deptno=(SELECT


deptno FROM Department WHERE dname=’CSE’);

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

SELECT deptno, AVG(age) FROM Student GROUP BY deptno


HAVING AVG(age)<(SELECT MAX(AVG(age)) FROM Student
GROUP BY deptno);

7.5
Sub-Query
Single-row Subquery...
Chittaranjan Pradhan

Sub Query

Single-row Subquery

Single-row Subquery used in FROM clause Multiple-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

called as Inline View Nested Subquery

UPDATE with
Subquery
SELECT age FROM (SELECT age FROM Student WHERE
DELETE with
age<20); Subquery

TOP- N Analysis

A subquery may not use the ORDER BY clause, but an inline


view may

SELECT age FROM (SELECT age FROM Student ORDER BY


age DESC) WHERE ROWNUM<=2;

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

ANY(SELECT age FROM Customer); DELETE with


Subquery

TOP- N Analysis
SELECT roll, name FROM Student WHERE age< IN(SELECT
age FROM Customer);

SELECT roll, name FROM Student WHERE age<


ALL(SELECT age FROM Customer);

7.7
Sub-Query
Multiple-column Subquery
Chittaranjan Pradhan

Sub Query

Single-row Subquery

Multiple-row Subquery

Multiple-column
Subquery

Multiple-column Subquery Correlated 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);

SELECT * FROM Catalog WHERE Catalog.bookid IN(SELECT


bookid FROM Order_Details WHERE Catalog.bookid=
Order_Details.bookid);

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

mgrid = (SELECT empid FROM Employee WHERE empname DELETE with


Subquery
= ’Paresh’)); TOP- N Analysis

SELECT deptno,AVG(age) FROM Student GROUP BY deptno


HAVING AVG(age)<( SELECT MAX(AVG(age)) FROM Student
WHERE deptno IN (SELECT deptno FROM Staff WHERE
qty>10) GROUP BY deptno);

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

statement. The general syntax is: Multiple-column


Subquery
UPDATE tablename SET columnname = value WHERE Correlated Subquery

columnnane operator (SELECT subquery); Nested 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

UPDATE Student SET age=(SELECT AVG(age) FROM


Student) WHERE roll=4;

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

returned by a subquery. The general syntax is: Nested Subquery

DELETE FROM tablename WHERE columnname = UPDATE with


Subquery
(SELECT subquery); DELETE with
Subquery

Delete all the student records whose ages are greater than the TOP- N Analysis

average age of the students

DELETE FROM Student WHERE age>(SELECT AVG(age)


FROM Student);

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

numbered with a pseudocolumn named ROWNUM TOP- N Analysis

SELECT roll, name FROM (SELECT roll, name FROM student


ORDER BY roll DESC) WHERE ROWNUM<= 4;

7.13
View, Sequence,
Synonym & Index

Chittaranjan Pradhan

Database Systems View


Complex View

Laboratory 8 Advantages of Views

Sequence

View, Sequence, Synonym & Index Synonym

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

only a few columns from a table Index

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

Views also hide the names of the underlying tables

View is stored as a SELECT statement in the Data Dictionary


View contains no data of its own Any updation of rows in the
table will automatically reflect in the views

A query fired on a view will run slower than a query fired on a


base table
8.3
View, Sequence,
View... Synonym & Index

Chittaranjan Pradhan

View

View Types Complex View


Advantages of Views

Views are of two types: Sequence

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;

CREATE VIEW Debts AS SELECT * FROM BILLS;

8.4
View, Sequence,
View... Synonym & Index

Chittaranjan Pradhan

Creating View from another View


View
Similar to the view creation from tables, a view can be created Complex View
Advantages of Views
from a previously created view
Sequence

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;

SELECT * FROM Debts;


Inserting into table through view
User can insert records into the underlying table through the
view as:
INSERT INTO viewname VALUES(val1, val2..);

INSERT INTO Debts VALUES(val1,val2,..);


8.5
View, Sequence,
View... Synonym & Index

Chittaranjan Pradhan

Describing a view structure


View
View structure can be described as: Complex View
Advantages of Views
DESCRIBE viewname;
Sequence

Synonym
DESCRIBE Debts;
Index

Updating table data through view


User can update the records of a table through the view as:
UPDATE viewname SET columnname=newvalue[WHERE
cond n ];

UPDATE Debts SET PRICE=PRICE*1.1 WHERE


PUBLISHER=’MGH’;
Deleting records from table through view
User can delete records from table through view as:
DELETE FROM viewname [WHERE cond n ];

DELETE FROM Debts WHERE condn;


8.6
View, Sequence,
View... Synonym & Index

Chittaranjan Pradhan

Creating a View WITH CHECK OPTION Constraint


View

This constraint applies to the WHERE clause condition in the Complex View
Advantages of Views

subquery. It allows insertion and updation of rows based on the Sequence

condition that satisfies the view Synonym

Index
CREATE VIEW Asd AS SELECT * FROM Products WHERE
price < 15;

CREATE VIEW Psd AS SELECT * FROM Products WHERE


price < 15 WITH CHECK OPTION CONSTRAINT con1;
Creating a View WITH READ ONLY Constraint
This option is used to make sure that the data in the underlying
table are not changed through the view

CREATE VIEW Cheap_products_view3 AS SELECT * FROM


Products WHERE price < 15 WITH READ ONLY
CONSTRAINT cheap_products_view3_read_only;
8.7
View, Sequence,
View... Synonym & Index

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;

DROP VIEW Debts;

8.8
View, Sequence,
View... Synonym & Index

Chittaranjan Pradhan

View
Complex View
Advantages of Views

Altering a View Sequence

Synonym
When the underlying table is altered, the view becomes invalid. Index
Thus, the view requires the recompilation as:
ALTER VIEW viewname COMPILE;

ALTER VIEW Debts COMPILE;

ALTER VIEW statement lets you add or remove constraints to


or from a view

ALTER VIEW Psd DROP CONSTRAINT con1;

8.9
View, Sequence,
View... Synonym & Index

Chittaranjan Pradhan

View
Complex View
Advantages of Views

Sequence
Use of GROUP BY clause Synonym

GROUP By clause can be used with view creation Index

CREATE OR REPLACE VIEW Vn (empno, noincr, amount) AS


SELECT emp_no, COUNT(*), SUM(amt) FROM INCR GROUP
BY emp_no;

CREATE VIEW Pr AS SELECT product_type_id, AVG(price)


average_price FROM Products WHERE price < 15 GROUP BY
product_type_id HAVING AVG(price) > 13;

8.10
View, Sequence,
Complex View Synonym & Index

Chittaranjan Pradhan

View
Complex View
Advantages of Views

Sequence

Synonym
Complex View
Index

It is based on one or more tables. It doesn’t allow data


manipulation

In complex view, you can use only SELECT statement

CREATE VIEW Vw AS SELECT P.name, PT.type,P.price


FROM PRODUCTS P NATURAL JOIN PRODUCTTYPE PT;

8.11
View, Sequence,
Advantages of Views Synonym & Index

Chittaranjan Pradhan

View
Complex View
Advantages of Views

Sequence
Advantages of Views Synonym

Some of the major advantages of using views are: Index

• Views allow in setting up different security levels for the


same base table, thus protecting certain data from people
who do not have proper authority
• The views allow the same data to be seen by different
users in different ways at the same time
• Views can be used to hide complex queries

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

100 MAXVALUE 999 NOCACHE; Advantages of Views

Sequence

CURRVAL & NEXTVAL pseudocolumns Synonym

Index
NEXTVAL column returns the next available number in the
sequence

CURRVAL column gives the current sequence value

NEXTVAL must be used at least once to get the value from


CURRVAL
SELECT sq.CURRVAL FROM DUAL;
SELECT sq.NEXTVAL FROM DUAL;
INSERT INTO emp(eid) VALUES (sq.NEXTVAL);

8.14
View, Sequence,
Sequence... Synonym & Index

Chittaranjan Pradhan

Viewing the details of a user sequences


SELECT sequence_name, last_number, max_value, View
Complex View

min_value, increment_by FROM USER_SEQUENCES; Advantages of Views

Sequence

Synonym
Modifying a Sequence Index

Modification of a sequence does not allow you to change the


START WITH option. Similarly, the maximum value cannot be
set to a number less than the current number
ALTER SEQUENCE seqname INCREMENT BY n
MAXVALUE m1 \ NOMAXVALUE MINVALUE m2 \
NOMINVALUE [CYCLE \ NOCYCLE] [CACHE c \
NOCACHE];

Dropping a Sequence
A sequence can be dropped as:
DROP SEQUENCE sequencename;

DROP SEQUENCE sq;


8.15
View, Sequence,
Synonym Synonym & Index

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

CREATE [PUBLIC] SYNONYM synname FOR objectname; Sequence

Synonym

CREATE SYNONYM Emp FOR Employee; Index

CREATE SYNONYM Cstd FOR Customer_Details;


SELECT * FROM Cstd;
Viewing the details of a user synonyms
SELECT synonym_name, table_name, table_owner FROM
USER_SYNONYMS;

Dropping a Synonym
A Synonym can be dropped as:
DROP SYNONYM synonymname;

DROP SYNONYM Emp;


8.16
View, Sequence,
Index Synonym & Index

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

Simple Index Index

It is created on a single column. The syntax is:


CREATE INDEX indexname ON tablename(column);

CREATE INDEX idx ON Student (cgpa);


Complex Index
It is created on more than one column. The syntax is:
CREATE INDEX indexname ON tablename(columns);

CREATE INDEX ids ON Student (first, last);

8.17
View, Sequence,
Index... Synonym & Index

Chittaranjan Pradhan

View
Complex View
Advantages of Views
Viewing the details of a user-defined index
Sequence

SELECT index_name, table_name FROM USER_INDEXES; Synonym

Index

SELECT index_name, table_name FROM USER_INDEXES


WHERE table_name= ’Student’;

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;

ALTER INDEX ids REBUILD;

8.18
PL/SQL

Chittaranjan Pradhan

Database Systems PL/SQL Basics


Advantages of PL/SQL

Laboratory 9 Structure of PL/SQL Block


Character Sets, Comments,
Special operators
Variables, Constant,

PL/SQL BOOLEAN Datatype,


%TYPE
User Message

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

Advantages of PL/SQL Structure of PL/SQL Block


Character Sets, Comments,

Structure of PL/SQL Block Special operators


Variables, Constant,

Character Sets, Comments, Special operators BOOLEAN Datatype,


%TYPE

Variables, Constant, BOOLEAN Datatype, %TYPE User Message

Conditional Logic
User Message CASE Statement

Looping Structure

2 Conditional Logic Scope of variable in


nested block
CASE Statement DEFINE Statement

3 Looping Structure

4 Scope of variable in nested block

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,

PL/SQL Basics Special operators


Variables, Constant,
BOOLEAN Datatype,
%TYPE
• It is the procedural language extension of SQL User Message

Conditional Logic
• It is a block - structured language that enables developers CASE Statement

to combine the power of SQL with procedural statements Looping Structure

• It bridges the gap between database technology and Scope of variable in


nested block
procedural programming languages DEFINE Statement

• PL/SQL also possesses features of object oriented


languages like: Data encapsulation, Error handling, Data
hiding and Object oriented programming

9.3
PL/SQL
Advantages of PL/SQL
Chittaranjan Pradhan

PL/SQL Basics
Advantages of PL/SQL
Structure of PL/SQL Block

Advantages of PL/SQL Character Sets, Comments,


Special operators
Variables, Constant,
BOOLEAN Datatype,
• It not only supports SQL data manipulation, but also %TYPE
User Message
provides facilities of conditional checking, branching & Conditional Logic
looping CASE Statement

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

constants Structure of PL/SQL Block


Character Sets, Comments,
Special operators
• BEGIN: implementation of actual programming logic Variables, Constant,
BOOLEAN Datatype,

• EXCEPTION: deals with runtime errors %TYPE


User Message

• END: end of PL/SQL block Conditional Logic


CASE Statement

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

• Numbers: 0...9 Character Sets, Comments,


Special operators
Variables, Constant,
• Symbols: ∼ ! @ # $ % ∧ & * ( ) - + { [ } ] | : ; « , > . ? / etc BOOLEAN Datatype,
%TYPE
User Message

Conditional Logic
CASE Statement
Comments
Looping Structure

• Single line: - - Scope of variable in


nested block

• Multi line: /* ... */ DEFINE Statement

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

Varname CONSTANT datatype[size]:=value; Looping Structure

Ex: Input_no NUMBER(3) :=16; Scope of variable in


nested block
Ex: Input_no CONSTANT NUMBER(3) :=16; DEFINE 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

procedure PUT_LINE to print Conditional Logic


CASE Statement

Looping Structure
DBMS_OUTPUT.PUT_LINE (message); Scope of variable in
Message is generally of varchar nested block

DEFINE Statement

Before using PUT_LINE(), you should switch ON the output


buffer as:
SET SERVEROUTPUT ON;

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

n : =&n; Looping Structure

Scope of variable in
IF(MOD (n,2)=0) THEN nested block

DBMS_OUTPUT.PUT_LINE(’even’); DEFINE Statement

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

on the Client_Master table Character Sets, Comments,


Special operators
Variables, Constant,
BOOLEAN Datatype,
%TYPE
DECLARE User Message

bal Client_Master.bal_due%TYPE; Conditional Logic


CASE Statement
cno Client_Master.client_no%TYPE; Looping Structure
addn number(4) : =500; Scope of variable in
BEGIN nested 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

CASE selector Conditional Logic

WHEN exp1 THEN Statement1 CASE Statement

Looping Structure
WHEN exp2 THEN Statement2
Scope of variable in
... nested block

WHEN expn THEN Statementn DEFINE Statement

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

DECLARE Advantages of PL/SQL


Structure of PL/SQL Block

vdigit NUMBER(1); Character Sets, Comments,


Special operators

BEGIN Variables, Constant,


BOOLEAN Datatype,
%TYPE
vdigit : =&vdigit; User Message

CASE vdigit Conditional Logic

WHEN 0 THEN DBMS_OUTPUT.PUT_LINE (’ZERO’); CASE Statement

Looping Structure
WHEN 1 THEN DBMS_OUTPUT.PUT_LINE (’ONE’); Scope of variable in
WHEN 2 THEN DBMS_OUTPUT.PUT_LINE (’TWO’); nested block

WHEN 3 THEN DBMS_OUTPUT.PUT_LINE (’THREE’); DEFINE Statement

WHEN 4 THEN DBMS_OUTPUT.PUT_LINE (’FOUR’);


WHEN 5 THEN DBMS_OUTPUT.PUT_LINE (’FIVE’);
WHEN 6 THEN DBMS_OUTPUT.PUT_LINE (’SIX’);
WHEN 7 THEN DBMS_OUTPUT.PUT_LINE (’SEVEN’);
WHEN 8 THEN DBMS_OUTPUT.PUT_LINE (’EIGHT’);
WHEN 9 THEN DBMS_OUTPUT.PUT_LINE (’NINE’);
ELSE DBMS_OUTPUT.PUT_LINE (vdigit||’ is wrong input’);
END CASE;
END;
9.14
PL/SQL
Looping Structure
Chittaranjan Pradhan

Basic Loop/Simple LOOP


PL/SQL Basics
Advantages of PL/SQL

LOOP Structure of PL/SQL Block


Character Sets, Comments,

Statements Special operators


Variables, Constant,

END LOOP; BOOLEAN Datatype,


%TYPE
User Message

The EXIT statement provides a way to stop the iterative loop: Conditional Logic
CASE Statement

• EXIT WHEN i>10; Looping Structure

Scope of variable in
• IF i>10 THEN EXIT; nested block

END IF; DEFINE Statement

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

VA NUMBER(4) : =10; Conditional Logic

VB NUMBER(4) : =11; CASE Statement

Looping Structure
BEGIN
Scope of variable in
DECLARE nested block

VA NUMBER(4) : =100; DEFINE Statement

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

It is done by setting the DEFINE ON and OFF Looping Structure

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

Database Systems Cursor


Cursor Operations

Laboratory 10 %TYPE and %ROWTYPE

Implicit Cursor

Explicit Cursor

CURSOR Steps of Explicit Cursor

Cursor FOR Loop

Parameterized Cursors

FOR UPDATE Clause

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

Cursor FOR Loop

3 Explicit Cursor Parameterized Cursors

FOR UPDATE Clause


Steps of Explicit Cursor
WHERE CURRENT
OF Clause

4 Cursor FOR Loop Disadvantages of


Cursors

5 Parameterized Cursors

6 FOR UPDATE Clause

7 WHERE CURRENT OF Clause

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

cursor is called Active Data Set Implicit Cursor

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

FOR UPDATE Clause


A cursor is basically a set of rows that you access one at a time WHERE CURRENT
OF Clause

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

Cursor Operations %TYPE and %ROWTYPE

Implicit Cursor

• Declare the cursor: Explicit Cursor


Steps of Explicit Cursor
• CURSOR cursor_name IS select_query; Cursor FOR Loop

• Open the cursor: Parameterized Cursors

• OPEN cursor_name; FOR UPDATE Clause

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

%TYPE %TYPE and %ROWTYPE

Implicit Cursor
It provides a column type Explicit Cursor
Steps of Explicit Cursor

Variablename tablename.column%TYPE; Cursor FOR Loop

Parameterized Cursors

FOR UPDATE Clause


Ex: cno Customer.custno%TYPE;
WHERE CURRENT
OF Clause

Disadvantages of
%ROWTYPE Cursors

It provides a record type

variablename tablename%ROWTYPE;

Ex: vcust Customer%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

Cursor FOR Loop


• It releases the memory area after the processing
Parameterized Cursors

FOR UPDATE Clause

• 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

• You have no control over an implicit cursor

• Implicit cursor attributes are: SQL%ISOPEN,


SQL%FOUND, SQL%NOTFOUND, SQL%ROWCOUNT

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

Cursor FOR Loop

BEGIN Parameterized Cursors

UPDATE EMP SET salary=salary*1.15 FOR UPDATE Clause

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

An HRD manager has decided to raise the salary of employees


Cursor
working in department 30 by 15%. Write the PL/SQL block to Cursor Operations

display the number of records updated %TYPE and %ROWTYPE

Implicit Cursor

Explicit Cursor
DECLARE Steps of Explicit Cursor

rowaff NUMBER(4); Cursor FOR Loop

Parameterized Cursors
BEGIN
FOR UPDATE Clause
UPDATE EMP SET salary=salary*1.15 WHERE DEPT=30;
WHERE CURRENT
rowaff : =SQL%ROWCOUNT; OF Clause

IF rowaff>0 THEN Disadvantages of


Cursors
DBMS_OUTPUT.PUT_LINE(rowaff||’ Employee
records modified’);
ELSE
DBMS_OUTPUT.PUT_LINE(’There is no employee
working for dept. 30’);
END IF;
END;

10.8
CURSOR
Explicit Cursor
Chittaranjan Pradhan

Cursor
Cursor Operations

Explicit Cursor %TYPE and %ROWTYPE

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

results, we have to use explicit cursor FOR UPDATE Clause

WHERE CURRENT
• We cannot use explicit cursor for DML statements OF Clause

Disadvantages of
Cursors

• Different attributes of explicit cursors are:


• Cursorname%ROWCOUNT
• Cursorname%FOUND
• Cursorname%NOTFOUND
• Cursorname%ISOPEN

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

• Open it: FOR UPDATE Clause

WHERE CURRENT
• OPEN cursorname; OF Clause

• Fetch rows from it: Disadvantages of


Cursors
• FETCH cursorname INTO variableset/ recordname;
• Close it:
• CLOSE cursorname;

10.10
CURSOR
Explicit Cursor...
Chittaranjan Pradhan

An HRD manager has decided to raise the salary of all the


employees in department 30 by 5%. Whenever any such raise is Cursor
Cursor Operations
given to the employee, a record for the same is maintained in the %TYPE and %ROWTYPE

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

Cursor FOR Loop

DECLARE Parameterized Cursors

FOR UPDATE Clause


CURSOR CSR IS SELECT e_id, salary FROM EMP
WHERE CURRENT
WHERE dept=30; OF Clause

eid1 EMP.e_id%TYPE; Disadvantages of


Cursors
sal1 EMP.salary%TYPE;
BEGIN
OPEN CSR;
IFCSR%ISOPEN THEN
LOOP
FETCH CSR INTO eid1,sal1;
EXIT WHEN CSR%NOTFOUND;

10.11
CURSOR
Explicit Cursor...
Chittaranjan Pradhan

Cursor
Cursor Operations
%TYPE and %ROWTYPE

... Implicit Cursor

... Explicit Cursor


Steps of Explicit Cursor
...
Cursor FOR Loop
IFCSR%FOUND THEN Parameterized Cursors
UPDATE EMP SET salary=salary*1.05 WHERE e_id=eid1; FOR UPDATE Clause
INSERT INTO Emp_raise VALUES(eid1, SYSDATE, WHERE CURRENT
OF Clause
sal1*0.05);
Disadvantages of
END IF; Cursors

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

Cursor FOR Loop


close the cursor. It is automatically done by FOR loop
Parameterized Cursors

FOR UPDATE Clause

WHERE CURRENT
FOR variable IN cursorname OF Clause

LOOP Disadvantages of
Cursors
Statements
END LOOP

10.14
CURSOR
Cursor FOR Loop...
Chittaranjan Pradhan

An HRD manager has decided to raise the salary of all the


employees in department 30 by 5%. Whenever any such raise is Cursor
given to the employee, a record for the same is maintained in the Cursor Operations
%TYPE and %ROWTYPE
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

Cursor FOR Loop


DECLARE Parameterized Cursors

CURSOR CSR IS SELECT e_id,salary FROM EMP FOR UPDATE Clause

WHERE dept=30; WHERE CURRENT


OF Clause
BEGIN Disadvantages of
FOR i IN CSR Cursors

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 Implicit Cursor

Parameters in cursors are useful when a cursor is required to Explicit Cursor


Steps of Explicit Cursor
be opened based on different set of parameter values Cursor FOR Loop

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

the pointer is placed at first

CURSOR cursorname (parametername type,


parametername type) IS SELECT statement;

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

Cursor FOR Loop


did NUMBER(2);
Parameterized Cursors
CURSOR empcr(deptno EMPLOYEE.dno%TYPE) IS SELECT FOR UPDATE Clause
ename, designation FROM EMPLOYEE WHERE dno=deptno;WHERE CURRENT
BEGIN OF Clause

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

Cursor FOR Loop


It is added in the cursor query to lock the affected records
Parameterized Cursors
when cursor is opened
FOR UPDATE Clause

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

CURSOR cursorname IS SELECT columns FROM tables


WHERE cond FOR UPDATE [OF columns] [NOWAIT];

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

retrieved by the explicit cursor Explicit Cursor


Steps of Explicit Cursor

Cursor FOR Loop


It allows to apply updates & deletes to the row currently being Parameterized Cursors
accessed without referencing ROWID FOR UPDATE Clause

WHERE CURRENT
OF Clause
UPDATE tablename SET clause WHERE CURRENT OF
Disadvantages of
cursorname; Cursors

DELETE FROM tablename WHERE CURRENT OF


cursorname;

WHERE CURRENT OF clause references the cursor and


changes only to the last fetched row

10.19
CURSOR
Explicit Cursor
Chittaranjan Pradhan

Write the PL/SQL block which increases the salary of the


employees of the dept 10 & 30 with the locking of the records Cursor
Cursor Operations
%TYPE and %ROWTYPE

Implicit Cursor
DECLARE Explicit Cursor
vrec EMPLOYEE%ROWTYPE; Steps of Explicit Cursor

Cursor FOR Loop


CURSOR cremp IS SELECT * FROM EMPLOYEE WHERE
Parameterized Cursors
deptno IN (10,30) ORDER BY deptno FOR UPDATE OF
FOR UPDATE Clause
deptno, salary NOWAIT; WHERE CURRENT
BEGIN OF Clause

OPEN cremp; Disadvantages of


Cursors
LOOP
FETCH cremp INTO vrec;
EXIT WHEN cremp%NOTFOUND;
UPDATE EMPLOYEE SET salary=vrec.salary*1.1
WHERE CURRENT OF cremp;
END LOOP;
CLOSE cremp;
END;
10.20
CURSOR
Disadvantages of Cursors
Chittaranjan Pradhan

Cursor
Cursor Operations
%TYPE and %ROWTYPE

Implicit Cursor

Explicit Cursor
Steps of Explicit Cursor
Disadvantages of Cursors
Cursor FOR Loop

It uses much more network bandwidth Parameterized Cursors

FOR UPDATE Clause

It allocates resources at the server WHERE CURRENT


OF Clause

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

Database Systems Exception Handler

Built-in Errors

Laboratory 11 User-defined
Exceptions
Assigning name and error

EXCEPTION HANDLER number to user-defined


exception

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

exception handler and error handling is done. Exception Built-in Errors

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

1. Built-in Errors Exception Handler

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

1.a. Named Errors


These pre-defined errors have been assigned names by Oracle

Error No. Error Name Error No. Error Name


ORA-01403 NO_DATA_FOUND ORA-06501 PROGRAM_ERROR
ORA-01422 TOO_MANY_ROWS ORA-06530 ACCESS_INTO_NULL
ORA-01476 ZERO_DIVIDE ORA-06511 CURSOR_ALREADY_OPEN
ORA-06502 VALUE_ERROR ORA-00001 DUP_VAL_ON_INDEX
ORA-06500 STORAGE_ERROR ORA-01001 INVALID_CURSOR
ORA-01017 LOGIN_DENIED ORA-01722 INVALID_NUMBER
ORA-01012 NOT_LOGGED_ON ORA-06504 ROWTYPE_MISMATCH
ORA-00051 TIMEOUT_ON_RESOURCE

11.4
EXCEPTION HANDLER
Built-in Errors...
Chittaranjan Pradhan

1.b. Unnamed Errors


These pre-defined errors have been assigned error number but Exception Handler

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

• SQLERRM: returns the error message associated with the


error code

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

Display the employee working in the dept entered by the user


Exception Handler
(Correct) Built-in Errors

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

These are explicitly declared and raised by user Built-in Errors

User-defined
Exceptions
Assigning name and error
2.a. User-defined Named Exceptions number to user-defined
exception

• Step-1: declare the exception in the DECLARE section


• Step-2: raise the exception in the execution section of the
program with RAISE statement
• Step-3: write handler for the exception

2.b. User-defined Unnamed Exceptions


Oracle provides a feature wherein we can RAISE exceptions
by our own assigned error number and message without
specifying a name to it
Error numbers from -20000 to -20999 can be used for
user-defined exceptions

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

Write a PL/SQL block which will display the commission of the


inputted empno. Handle the exception for negative commission Exception Handler
(User-defined Unnamed Exceptions) Built-in Errors

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

directive binds the specified error number to a user-defined


exception name

You can use more than one PRAGMA EXCEPTION_INIT


directives

The syntax is:

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

PRAGMA EXCEPTION_INIT(Invalid_comm, -20000);


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(SQLERRM||’ ’||’Negative commission);
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(’No such id’);
END; 11.13
STORED PROCEDURE
STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan

Database Systems
Sub-Program

Laboratory 12 Stored Procedure


Parameter Passing

STORED PROCEDURE, STORED Stored Function

Package

FUNCTION & 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

parameters & can be used as per requirements Stored Function

Package

• A subprogram comprises of:


• Declarative section
• Executable section and
• Exceptional handling section
• Subprograms are frequently used because of its
reusability & ease of writing code in PL/SQL

• Two types of subprograms:


• Stored Procedure
• Stored Function

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

statements that perform a specific task Stored Procedure


Parameter Passing

Stored Function
Oracle stores both the source and compiled code of Package

procedures in database. Therefore, procedures are called


stored procedures

The syntax for procedural declaration is:

CREATE OR REPLACE PROCEDURE procname [(arg1, arg2)] IS


constatnt/variable declaration
BEGIN
executable statements
EXCEPTION
exception handler statements
END procname;

12.4
STORED PROCEDURE
Stored Procedure... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
Write a procedure that accepts 2 numbers and print the sum

Sub-Program

CREATE OR REPLACE PROCEDURE psum (A NUMBER, Stored Procedure


Parameter Passing
B NUMBER) IS
Stored Function
C NUMBER; Package
BEGIN
C : = A + B;
DBMS_OUTPUT.PUT_LINE(A||’+’||B||’=’||C);
END psum;

Executing a procedure
EXECUTE psum(10, 20); or

EXEC psum(10, 20);

Dropping a procedure
DROP PROCEDURE psum;
12.5
STORED PROCEDURE
Parameter Passing STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan

Sub-Program
a. IN Mode
Stored Procedure

It is the default mode of parameter passing. It passes a value Parameter Passing

Stored Function
into the program, it acts like a constant & can’t be assigned a
Package
value

CREATE OR REPLACE PROCEDURE psum (A IN NUMBER,


B IN NUMBER) IS
C NUMBER;
BEGIN
C : = A + B;
DBMS_OUTPUT.PUT_LINE(A||’+’||B||’=’||C);
END psum;

EXECUTE psum(10, 20);

12.6
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan

b. OUT Mode Sub-Program

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

Procedures with OUT parameter can’t be executed with


EXECUTE statement. It must be called from other PL/SQL
program

CREATE OR REPLACE PROCEDURE psum (A IN NUMBER,


B IN NUMBER, C OUT NUMBER) IS
BEGIN
C : = A + B;
END psum;

12.7
STORED PROCEDURE
Parameter Passing... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan

Sub-Program

b. OUT Mode... Stored Procedure


Parameter Passing

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

c. IN OUT Mode Stored Procedure


Parameter Passing
It is used to pass initial values to the subprograms when Stored Function
invoked & is also returns updated values to the caller Package

Procedures with IN OUT parameter can’t be executed using


EXECUTE statements

CREATE OR REPLACE PROCEDURE psum (A IN OUT NUMBER,


B NUMBER) IS
BEGIN
A : = A + B;
END psum;

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

the details of employee as the output


Sub-Program

CREATE OR REPLACE PROCEDURE searchemp(eid IN Stored Procedure


Parameter Passing
NUMBER, nm OUT VARCHAR, sl OUT NUMBER) IS Stored Function
BEGIN Package
SELECT ename, sal INTO nm, sl FROM emp WHERE empid=eid;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(eid||’does’t exist’);
END searchemp;
DECLARE
vname emp.ename%TYPE;
vsal emp.sal%TYPE;
veid emp.empid%TYPE;
BEGIN
veid : =&veid;
searchemp(veid, vname, vsal);
DBMS_OUTPUT.PUT_LINE(veid||’ ’||vname||’ ’||vsal);
END;
12.11
STORED PROCEDURE
Stored Function STORED FUNCTION &
PACKAGE

Stored Function Chittaranjan Pradhan

These are the PL/SQL blocks that take parameters, perform


Sub-Program
some action and return a single value to the calling program
Stored Procedure
Parameter Passing

Like stored procedure, Oracle stores both the source code and Stored Function

compiled code in its database Package

The syntax for procedural declaration is:


CREATE OR REPLACE FUNCTION funcname [(arg1, arg2)]
RETURN datatype IS
constatnt/variable declaration
BEGIN
executable statements
RETURN returnvalue
EXCEPTION
exception handler statements
RETURN returnvalue
END funcname;
12.12
STORED PROCEDURE
Stored Function... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan
CREATE OR REPLACE FUNCTION fsum(A NUMBER,
B NUMBER) RETURN NUMBER IS
C NUMBER; Sub-Program

Stored Procedure
BEGIN Parameter Passing

C : =A+B; Stored Function

RETURN C; Package

END fsum;

Calling a function
SELECT fsum(10,15) FROM DUAL;

SELECT ename, fsum(sal,1000) newsalary FROM emp;

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

inputted deptno Stored Function

Package

CREATE OR REPLACE FUNCTION get_deptname (did NUMBER)


RETURN VARCHAR IS
vdept VARCHAR(12);
BEGIN
SELECT deptname INTO vdept FROM dept WHERE deptid=did;
RETURN vdept;
END get_deptname;

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

DECLARE Stored Function

vdid emp.deptno%TYPE; Package

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

database as an object Stored Function

Package

Packages enable to perform overloading of functions and


procedures

Components of Packages

• Package Specification: contains the list of various


functions/ procedure names which will be a part of the
package
• Package Body: contains the actual code implementing
the logics of functions and procedures declared in the
specification

12.16
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Package Specification Chittaranjan Pradhan

It contains information about the package elements such as


Sub-Program
definitions of functions & procedures, declarations of variables
Stored Procedure
Parameter Passing
CREATE OR REPLACE PACKAGE packname AS Stored Function
Declarations Package
BEGIN
Executable statements
END packname;

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

Create a package calculator which contains different functions Chittaranjan Pradhan

and procedures for the different operations


Sub-Program

Stored Procedure
CREATE OR REPLACE PACKAGE calculator AS Parameter Passing

FUNCTION fsum(A NUMBER, B NUMBER) RETURN NUMBER; Stored Function


FUNCTION fminus(A NUMBER, B NUMBER) RETURN NUMBER;Package

FUNCTION fmult(A NUMBER, B NUMBER) RETURN NUMBER;


FUNCTION fdivide(A NUMBER, B NUMBER) RETURN NUMBER;
PROCEDURE psum(A NUMBER, B NUMBER);
PROCEDURE pminus(A NUMBER, B NUMBER);
END calculator;
...
CREATE OR REPLACE PACKAGE BODY calculator AS
FUNCTION fsum(A NUMBER, B NUMBER) RETURN NUMBER IS
C NUMBER;
BEGIN
C : =A+B;
RETURN C;
END fsum;
12.18
STORED PROCEDURE
Package... STORED FUNCTION &
PACKAGE
Chittaranjan Pradhan

Sub-Program

Stored Procedure
FUNCTION fminus(A NUMBER, B NUMBER) RETURN NUMBER ISParameter Passing

C NUMBER; Stored Function

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

C NUMBER; Stored Function

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

Executing Package Functions & Procedures Package

EXECUTE calculator.psum(10, 20);

SELECT calculator.fsum(10, 20) FROM DUAL;

SELECT empid,calculator.fmultiply(sal, 2) FROM emp;

12.22
DATABASE TRIGGER

Chittaranjan Pradhan

Database Systems Database Trigger

Types of Triggers

Laboratory 13 : OLD and : NEW


Qualifiers

DATABASE TRIGGER INSTEAD OF Trigger

Chittaranjan Pradhan
School of Computer Engineering,
KIIT University
13.1
DATABASE TRIGGER
DATABASE TRIGGER
Chittaranjan Pradhan

Database Trigger

Types of Triggers

: OLD and : NEW


1 Database Trigger Qualifiers

INSTEAD OF Trigger

2 Types of Triggers

3 : OLD and : NEW Qualifiers

4 INSTEAD OF Trigger

13.2
DATABASE TRIGGER
Database Trigger
Chittaranjan Pradhan

Database Trigger Database Trigger

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

BEFORE, AFTER & INSTEAD OF Triggers


Database Trigger

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

triggering SQL statement is executed


• INSTEAD OF Triggers: These triggers are used to make
the non-updateable views updateable

Statement level & Row level Triggers

• Statement level or Table level Triggers: These triggers


are fired for each DML operation being performed on a
table. This is the default type
• Row level Triggers: These triggers are fired for each and
every record which is inserted or deleted or updated from
a table. This is the common type

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

: OLD and : NEW


Qualifiers

INSTEAD OF Trigger
: OLD and : NEW Qualifiers
: OLD and : NEW qualifiers are related to ROW level triggers

Value of a column before the data change is referenced by


prefixing OLD

Value of a column after the data change is referenced by


prefixing NEW

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

CREATE OR REPLACE TRIGGER MIN_SAL_CHK BEFORE


INSERT OR UPDATE ON EMP_TRIG FOR EACH ROW
WHEN(NEW.sal<500)
BEGIN
RAISE_APPLICATION_ERROR(-20000,’sal must be above 500’);
END;

............
INSERT INTO EMP_TRIG VALUES(’Prasant’,2000);

INSERT INTO EMP_TRIG VALUES(’Jack’,300);


13.7
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 keeps backup of deleted records of


EMP_TRIG table. Deleted records are inserted in EMP_BKUP
table

CREATE OR REPLACE TRIGGER BKUP_REC AFTER


DELETE ON EMP_TRIG FOR EACH ROW
BEGIN
INSERT INTO EMP_BKUP VALUES( : OLD.ename,
: OLD.sal, SYSDATE);
END;

............
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

: OLD and : NEW


Qualifiers
Create a trigger which checks for any duplicate value and INSTEAD OF Trigger
disallow insertion

CREATE OR REPLACE TRIGGER UNIQUE_VAL BEFORE


INSERT ON EMP_TRIG FOR EACH ROW
DECLARE
vc NUMBER(2);
BEGIN
SELECT COUNT(*) INTO vc FROM EMP_TRIG
WHERE ename= : NEW.ename;
IF vc=1 THEN
RAISE_APPLICATION_ERROR(-20024,’You
have entered duplicate ename’);
END IF;
END;
13.9
DATABASE TRIGGER
INSTEAD OF Trigger
Chittaranjan Pradhan

Database Trigger

Types of Triggers

INSTEAD OF Trigger : OLD and : NEW


Qualifiers

Normally, we can’t perform any of the DML operations on INSTEAD OF Trigger

non-updateable views. But, INSTEAD OF Trigger can be used


to make the non-updateable views updateable

It is used to modify a table that can’t be modified through a view

CREATE OR REPLACE VIEW stud_faculty AS SELECT *


FROM student LEFT OUTER JOIN faculty ON
faculty.facultyid= student.facultyid;

.............
DELETE FROM stud_faculty WHERE facultyid=235;

13.10
DATABASE TRIGGER
INSTEAD OF Trigger...
Chittaranjan Pradhan

Database Trigger

Types of Triggers

: OLD and : NEW


Qualifiers
INSTEAD OF Trigger... INSTEAD OF Trigger

CREATE OR REPLACE TRIGGER fac_delete INSTEAD OF


DELETE ON stud_faculty FOR EACH ROW
BEGIN
DELETE FROM faculty WHERE facultyid= : OLD.facultyid;
END;

.............
DELETE FROM stud_faculty WHERE facultyid=235;

13.11

You might also like