You are on page 1of 80

Department of Computer Science and Engineering

PRACTICAL FILE:
DATA BASE MANAGEMENT SYSTEM LAB
5TH SEM

Submitted To:- Submitted By:-


Tanuja mam Yash Sharma
1903198
CSE- G2

Chandigarh Engineering College


Landran, Mohali – 140307

Page 1
INDEX

Sr. Name Of the Experiment Page Remarks


No. No.

1. Introduction to DBMS software and installation of 4-12


SQL server/ Oracle.

2. To study Datatypes of SQL. 13-20

3. To Create, Alter and Drop a Table. 21-23

4. To perform DML commands on a table 24-31

5. To make use of different clauses viz Where, Group 32-35


by, Having, Order by.
6. To perform aggregate functions like SUM, MAX, 36-40
MIN, AVG, COUNT on a table.

7. To Study Airthmetic and logical Operators. 41-44

8. To Perform Single Row Functions: String, Numeric, 45-49


Date And Conversion Functions.

9. To study Set Operators 50-52

10. To study & implement constraints on a table 53

11. To understand the use and working of Joins 54-55

12. To understand the use and working of Sub- 56-60


Queries.
13. To perform Data Security and Privileges Command: 61-64
Grant and Revoke, Rollback and Commit on a table.

14. To make Views of a table and to perform Insert, 65-67


Update, Select and Delete operations on View

15. To make indexes and sequences for a table. 68

16. Introduction To PL/SQL Architecture. 69

Page 2
17. Compute Addition,Subtraction,Product and 70
Division of given two numbers.
18. To Print Multiplication Table of a number. 71

19. For Loop – To Find Reverse of a given number 72

20. Implementation of Procedure 73-75

21. Implementation of Triggers. 76-80

Page 3
PRACTICAL - 1

AIM :-Introduction to DBMS software and installation of SQL server/ Oracle.

Introduction to DBMS software:-

A database management system (DBMS) refers to the technology for creating and managing
databases. DBMS is a software tool to organize (create, retrieve, update and manage) data in
a database.
The main aim of a DBMS is to supply a way to store up and retrieve database information that
is both convenient and efficient. By data, we mean known facts that can be recorded and that
have embedded meaning. Normally people use software such as DBASE IV or V, Microsoft
ACCESS, or EXCEL to store data in the form of database. A datum is a unit of data.
Meaningful data combined to form information. Hence, information is interpreted data - data
provided with semantics. MS. ACCESS is one of the most common examples of database
management software.

More on Data, Information, and Knowledge:-

Knowledge refers to the useful use of information. As you know, that information can be
transported, stored and shared without much problem and difficulties but the same cannot be
said about knowledge. Knowledge necessarily involves a personal experience and practice.
Database systems are meant to handle a large collection of information. Management of data
involves both defining structures for storage of information and providing mechanisms that
can do the manipulation of those stored information. Moreover, the database system must
ensure the safety of the information stored, despite system crashes or attempts at unauthorized
access.

Why Use DBMS?

 To develop software applications In less time.


 Data independence and efficient use of data.
 For uniform data administration.
 For data integrity and security.
 For concurrent access to data, and data recovery from crashes.
 To use user-friendly declarative query language.

Where is a Database Management System (DBMS) being used?

 Airlines: reservations, schedules, etc


 Telecom: calls made, customer details, network usage, etc
 Universities: registration, results, grades, etc
 Sales: products, purchases, customers, etc
 Banking: all transactions etc
Page 4
Advantages of DBMS:-

A DBMS manage data and has many advantages. These are:

 Data independence: Application programs should be as free or independent as possible from


details of data representation and storage. DBMS can supply an abstract view of the data for
insulating application code from such facts.
 Efficient data access: DBMS utilizes a mixture of sophisticated concepts and techniques for
storing and retrieving data competently, and this feature becomes important in cases where
the data is stored on external storage devices.
 Data integrity and security: If data is accessed through the DBMS, the DBMS can enforce
integrity constraints on the data.
 Data administration: When several users share the data, integrating the administration of data
can offer major improvements. Experienced professionals understand the nature of the data
being managed and can be responsible for organizing the data representation to reduce
redundancy and make the data to retrieve efficiently.

Components of DBMS:-

 Users: Users may be of any kind such as DB administrator, System developer or database
users.
 Database application: Database application may be Departmental, Personal, organization's
and / or Internal.
 DBMS: Software that allows users to create and manipulate database access,
 Database: Collection of logical data as a single unit.

Databases and Information Management :-

database server is the key to solving the problems of information management. In general, a
server must reliably manage a large amount of data in a multi-user environment so that many
users can concurrently access the same data. Database users do not suffer from slow processing
performance.

Page 5
DBMS
A database management system (DBMS)is system software for creating and managing
databases. The DBMS provides users and programmers with a systematic way to create,
retrieve, update and manage data .A DBMS makes it possible for end users to create, read,
update and delete data in a database.

Major DBMS Components

Database Structure
An Oracle database has both a physical and a logical structure. Because the physical and
logical server structure are separate, the physical storage of data can be managed without
affecting the access to logical storage structures.
Logical Database Structure: An Oracle database's logical structure is determined by
 one or more table space . (A table space is a logical area of storage explained later in
this chapter.)
 the database's schema objects. A schema is a collection of objects. Schema objects are
the logical structures that directly refer to the database's data. Schema objects include
such structures as tables, views, sequences, stored procedures, synonyms, indexes,
clusters, and database links.

Database query

A database query is a way of requesting information from the database. A database query can
be either a select query or an action queryFor example, a manager can perform a query to
select the employees who were hired 5 months ago. The results will be the basis for creating
performance evaluation.

Installation of ORACLE SERVER


FEATURES OF ORACLE

 Automated testing of query plans


 Workload isolation in the cloud
 Automatic indexing
 Data Guard DML redirection
 Easy Connect enhancements
 partitioned hybrid tables
 statistics-only queries
 encryption capabilities

SQL COMMANDS DESCRIPTION

o SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
Page 6
Types of SQL Commands

These functions include building database objects, manipulating objects, populating database
tables with data, updating existing data in tables, deleting data, performing database queries,
controlling database access, and overall database administration.

The main categories are: Types of SQL Commands


 DDL (Data Definition Language)
 DML (Data Manipulation Language)
 DQL (Data Query Language)
 DCL (Data Control Language)
 Data administration commands
 Transactional control commands

Defining Database Structures


Data Definition Language, DDL, is the part of SQL that allows a database user to create and
restructure database objects, such as the creation or the deletion of a table.

Manipulating Data
Data Manipulation Language, DML, is the part of SQL used to manipulate data within objects
of a relational database.

Selecting Data
Though comprised of only one command, Data Query Language (DQL) is the most
concentrated focus of SQL for modern relational database users. The base command is as
follows:

Data Control Language


Data control commands in SQL allow you to control access to data within the database. These
DCL commands are normally used to create objects related to user access and also control the
distribution of privileges among users.

Data Administration Commands


Data administration commands allow the user to perform audits and perform analyses on
operations within the database.

Transactional Control Commands


In addition to the previously introduced categories of commands, there are commands that
allow the user to manage database transactions.

Page 7
Defining Database Structures
Data Definition Language, DDL, is the part of SQL that allows a database user to create
and restructure database objects, such as the creation or the deletion of a table.

Manipulating Data
Data Manipulation Language, DML, is the part of SQL used to manipulate data within
objects of a relational database.Selecting DataThough comprised of only one command,
Data Query Language (DQL) is the most concentrated focus of SQL for modern relational
database users. The base command is as follows:

Data Control Language


Data control commands in SQL allow you to control access to data within the database.
These DCL commands are normally used to create objects related to user access and also
control the distribution of privileges among users. Some data control commands are as
follows:

Data Administration Commands


They can also be used to help analyze system performance. Two general data
administration commands are as follows:

Transactional Control Commands


In addition to the previously introduced categories of commands, there are commands that
allow the user to manage database transactions.

SQL Data Types

Page 8
INSTALLATION PROCESS OF ORACLE SERVER
The following picture shows the structure of the folder of the Oracle installation files after
extraction.

Step 1. The installer asks you to provide your email address to get the latest security issues
and updates. You can ignore it by clicking the Next button

Step 2. In step 2, Oracle installer ask you to whether you want to create and configure a
database, install database software only or just upgrade an existing database.

Step 3. The installer allows you to choose the system class. Because you install Oracle on your
computer, not a server, therefore, you choose the first option: desktop class and click the Next
button.

Page 9
Step 4. This step allows you to specify the Windows user account to install and configure
Oracle Home for enhanced security. Choose the third option: “Use Windows Built-in
Account”.

Step 5. In this step you can (1) choose the folder on which Oracle database will be installed,
(2) Global database name and password, (3) pluggable database name.

Step 6. The installer performs the prerequisite check.

Page 10
Step 7. The installer shows you the summary of the information such as global settings,
database information, etc. You need to review the information and click the install button if
everything is fine.

Step 8. The installer starts installing Oracle database. It will take a few minutes to complete,
depending on your computer.

Page 11
You will see the Database Configuration Assistant window. Click the Password
management… button to enter the password for Oracle database accounts.

Page 12
PRACTICAL NO.2

AIM-To study Datatypes of SQL

DATA TYPES OF SQL

 CHAR :

This data type is used to store character strings values of fixed length. The size in
brackets determines the number of characters the cell can hold. The maximum number
of characters (i.e. the size) this data type can hold is 255 characters. Syntax is
CHAR(SIZE)

Example is CHAR (20)

 VARCHAR :

This data type is used to store variable length alphanumeric data. The maximum this
data type can hold is 2000 characters. One difference between this data type and the
CHAR data type is ORACLE compares VARCHAR values using non-padded
comparison semantics i.e. the inserted values will not be padded with spaces. Syntax is
VARCHAR(SIZE)

Example is VARCHAR (20) OR VARCHAR2 (20)

 NUMBER :

The NUMBER data type is used to store numbers (fixed or floating point). Numbers
of virtually any magnitude maybe stored up to 38 digits of precision. Numbers as large
as 9.99 * 10 to the power of 124, i.e. followed by 125 zeros can be stored. The
precision, (P), determines the maximum length of the data, whereas the scale, (S),
determines the number of places to the right of the decimal. If scale is omitted then the
default is zero. If precision is omitted values are stored with their original precision up
to the maximum of 38 digits.

Syntax is NUMBER (P, S) Example is NUMBER (10, 2)

 LONG :

This data type is used to store variable length character strings containing up to 2GB.
LONG data can be used to store arrays of binary data in ASCII format. LONG values
cannot be indexed, and the normal character functions such as SUBSTR cannot be
applied to LONG values.

Syntax is LONG (SIZE) Example is LONG (20)

Page 13
 DATE :

This data type is used to represent data and time. The standard format id DD-MM-YY
as in 13-JUL-85. To enter dates other than the standard format, use the appropriate
functions. Date Time stores date in the 24-hour format. By default, the time in a date
field is 12:00:00 am, if no time portion is specified. The default date for a date field is
the first day of the current month. Syntax is DATE

 LONG RAW :

Enter the password for SYS and SYSTEM accounts and then click OK button.

Step 9. Once installation completes successfully, the installer will inform you as shown in the
following screenshot. Click the Close button to close the window

Page 14
LONG RAW data types are used to store binary data, such as Digitized picture or
image. Data loaded into columns of these data types are stored without any further
conversion. LONG RAW data type can contain up to 2GB. Values stored in columns
having LONG RAW data type cannot be indexed. Syntax is LONGRAW (SIZE)

 RAW :

It is used to hold strings of byte oriented data. Data type can have a maximum
length of 255 bytes. Syntax is RAW(SIZE)

The following is a list of datatypes available in Oracle/PLSQL, which includes


character, numeric, date/time, LOB and rowid datatypes.
Character Datatypes
The following are the Character Datatypes in Oracle/PLSQL:

Data Type
Oracle 9i Oracle 10g Oracle 11g Explanation
Syntax

Where size is the


Maximum Maximum Maximum
number of characters
char(size) size of 2000 size of 2000 size of 2000
to store. Fixed-length
bytes. bytes. bytes.
strings. Space padded.

Where size is the


Maximum Maximum Maximum number of characters
nchar(size) size of 2000 size of 2000 size of 2000 to store. Fixed-length
bytes. bytes. bytes. NLS string Space
padded.

Where size is the


Maximum Maximum Maximum
number of characters
nvarchar2(size) size of 4000 size of 4000 size of 4000
to store. Variable-
bytes. bytes. bytes.
length NLS string.

Maximum Maximum Maximum Where size is the


varchar2(size) size of 4000 size of 4000 size of 4000 number of characters
bytes. bytes. bytes. to store. Variable-
length string.

Page 15
Maximum Maximum Maximum
size of 32KB size of 32KB size of 32KB
in PLSQL. in PLSQL. in PLSQL.

Variable-length
Maximum Maximum Maximum
long strings. (backward
size of 2GB. size of 2GB. size of 2GB.
compatible)
Maximum Maximum Maximum
Variable-length binary
raw size of 2000 size of 2000 size of 2000
strings
bytes. bytes. bytes.
Variable-length binary
Maximum Maximum Maximum
long raw strings. (backward
size of 2GB. size of 2GB. size of 2GB.
compatible)

Numeric Datatypes
The following are the Numeric Datatypes in Oracle/PLSQL:

Data Type
Oracle 9i Oracle 10g Oracle 11g Explanation
Syntax

Precision Precision Precision Where p is the precision


can range can range can range and s is the scale.
from 1 to from 1 to from 1 to
For example, number(7,2)
number(p,s) 38. 38. 38.
is a number that has 5
Scale can Scale can Scale can
digits before the decimal
range from - range from - range from -
and 2 digits after the
84 to 127. 84 to 127. 84 to 127.
decimal.

Where p is the precision


and s is the scale.
Precision Precision Precision
For example, numeric(7,2)
can range can range can range
numeric(p,s) is a number that has 5
from 1 to from 1 to from 1 to
digits before the decimal
38. 38. 38.
and 2 digits after the
decimal.

float

Page 16
Where p is the precision
and s is the scale.
Precision Precision Precision
can range can range can range For example, dec(3,1) is a
dec(p,s)
from 1 to from 1 to from 1 to number that has 2 digits
38. 38. 38. before the decimal and 1
digit after the decimal.

Where p is the precision


and s is the scale.
Precision Precision Precision
For example, decimal(3,1)
can range can range can range
decimal(p,s) is a number that has 2
from 1 to from 1 to from 1 to
digits before the decimal
38. 38. 38.
and 1 digit after the
decimal.

integer
int
smallint
real
double
precision

Date/Time Datatypes
The following are the Date/Time Datatypes in Oracle/PLSQL:

Data Type
Oracle 9i Oracle 10g Oracle 11g Explanation
Syntax

A date between A date between A date between


Jan 1, 4712 BC Jan 1, 4712 BC Jan 1, 4712 BC
date
and Dec 31, and Dec 31, and Dec 31,
9999 AD. 9999 AD. 9999 AD.

fractional fractional fractional Includes year,


timestamp seconds seconds seconds month, day,
(fractional precision must precision must precision must hour, minute,
seconds be a number be a number be a number and seconds.
precision) between 0 and 9. between 0 and 9. between 0 and 9.
For example:
(default is 6) (default is 6) (default is 6)
timestamp(6)

Page 17
Includes year,
month, day,
hour, minute,
timestamp fractional fractional fractional and seconds;
(fractional seconds seconds seconds with a time
seconds precision must precision must precision must zone
precision) be a number be a number be a number displacement
with time between 0 and 9. between 0 and 9. between 0 and 9. value.
zone (default is 6) (default is 6) (default is 6)
For example:
timestamp(5)
with time zone

Includes year,
month, day,
hour, minute,
timestamp fractional fractional fractional and seconds;
(fractional seconds seconds seconds with a time
seconds precision must precision must precision must zone expressed
precision) be a number be a number be a number as the session
with local between 0 and 9. between 0 and 9. between 0 and 9. time zone.
time zone (default is 6) (default is 6) (default is 6) For example:
timestamp(4)
with local time
zone

Time period
interval year precision is year precision is year precision is stored in years
year the number of the number of the number of and months.
(year digits in the digits in the digits in the
For example:
precision) year. (default is year. (default is year. (default is
interval year(4)
to month 2) 2) 2)
to month

day day day


precision must precision must precision must
be a number be a number be a number Time period
interval day
between 0 and 9. between 0 and 9. between 0 and 9. stored in days,
(day
(default is 2) (default is 2) (default is 2) hours, minutes,
precision)
and seconds.
to second fractional fractional fractional
(fractional seconds seconds seconds For example:
seconds precision must precision must precision must interval day(2)
precision) be a number be a number be a number to second(6)
between 0 and 9. between 0 and 9. between 0 and 9.
(default is 6) (default is 6) (default is 6)

Page 18
Large Object (LOB) Datatypes
The following are the LOB Datatypes in Oracle/PLSQL:

Data
Type Oracle 9i Oracle 10g Oracle 11g Explanation
Syntax

File locators that point to


Maximum Maximum file Maximum file
a binary file on the
bfile file size of size of 232-1 size of 264-1
server file system
4GB. bytes. bytes.
(outside the database).

Store up to (4 Store up to (4
gigabytes -1) * gigabytes -1) *
Store up to
(the value of the (the value of the Stores unstructured
blob 4GB of
CHUNK CHUNK binary large objects.
binary data.
parameter of parameter of
LOB storage). LOB storage).

Store up to (4 Store up to (4
gigabytes -1) * gigabytes -1) *
Store up to
(the value of the (the value of the Stores single-byte and
4GB of
clob CHUNK CHUNK multi-byte character
character
parameter of parameter of data.
data.
LOB storage) of LOB storage) of
character data. character data.

Store up to (4 Store up to (4
gigabytes -1) * gigabytes -1) *
Store up to (the value of the (the value of the
4GB of CHUNK CHUNK
nclob Stores Unicode data.
character parameter of parameter of
text data. LOB storage) of LOB storage) of
character text character text
data. data.

Page 19
Rowid Datatypes
The following are the Rowid Datatypes in Oracle/PLSQL:

Data
Explanati
Type Oracle 9i Oracle 10g Oracle 11g
on
Syntax

The format of the The format of the The format of the Fixed-
rowid is: rowid is: rowid is: length
BBBBBBB.RRRR. BBBBBBB.RRRR. BBBBBBB.RRRR. binary
FFFFF FFFFF FFFFF data.
Every
Where BBBBBBB Where BBBBBBB Where BBBBBBB
rowid record in
is the block in the is the block in the is the block in the
the
database file; database file; database file;
database
RRRR is the row in RRRR is the row in RRRR is the row in
has a
the block; the block; the block;
physical
FFFFF is the FFFFF is the FFFFF is the
address
database file. database file. database file.
or rowid.
Universal
rowid.
urowid(s
Where siz
ize)
e is
optional.

Page 20
PRACTICAL NO.3

AIM-To Create, Alter and Drop a Table.

DESCRIPTION:

1. CREATE : This command is used to create a table.It is used to specify a new relation
by giving it a name and specifying attributes and initial constraints. This command is a
part of DDL (Data Definition Language) of SQL. The column names must be specified
along the data types. Each table must have atleast one column.Tables are the basic
structure where data is stored in the database. Tables are divided into rows and
columns.

create table HONEY_1802050(name varchar(20) , mobile_no integer(10), address


varchar(40));

2. ALTER:
ADDING a new column in a Table: We can ALTER the table by adding a new
column to the existing column.

COMMAND:-

alter table HONEY_1802050 add(fathers_namevarchar(30));


descHONEY_1802050;

Page 21
MODIFYING a column in a table: We can modify a column definition by using the
ALTER command with the Modify clause.

Command:-
alter table HONEY_1802050 modify column name varchar(30);
descHONEY_1802050;

DROPPING a column in a table: We can drop a column from a table by using the
ALTER command with the Drop column clause.

Command:-

ALTER TABLE HONEY_1802050DROP COLUMN mobile_no;


Desc1802050;

3. DROP:
The DROP command is used to Drop tables. This command not only deletes all the
records in the table, but also removes the definition of a table. When we Drop a table,

Page 22
the database loses all the data in the table and all the indexes associated with it. All
data is deleted from the table.

.
Command:

drop tableHONEY_1802050;
show tables;

Page 23
PRACTICAL -4
AIM-To perform DML commands on a table

Description:
Oracle DML INSERT Statement
The Oracle INSERT statement is used to add new rows to a table. Before you become
familiar with this statement, please take into account the following points:
 Default value – when creating a new table (DDL), it is possible to define a specific column
with a default value. This means that unless otherwise indicated, this is the value that you
would like to enter into the field of that column.

Basic Syntax

1 INSERT INTO table_name


2 VALUES (value, value, value …)

Inserting a new row into the table


CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCREMENT
`Product_name` TEXT NOT NULL , `product_price` INT NOT NULL , `expiration_date`
DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE = InnoDB;
INSERT INTO `product` VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product`VALUES (NULL, 'Coffee ', '3200', '2016-05-19');

The following table reflects the data in products table after the INSERT statement has
completed:

Output

Page 24
Important Points
 The order of the values must match the order of the columns in the table. In the case
above, the first value must be associated with the Id column, the second value must be
associated with the name column, and so on.
 The value type must match the type of columns in the table.
 The number of values – must match the number of values in the table. It is not possible to
enter more or less values than the number of values in the table (in this case, 4 values).
 To enter a NULL value into one of the fields of one of the columns, the NULL keyword
should be used.
CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCREME
NT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL DEFAULT
'200' , `expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE =
InnoDB;
INSERT INTO `product` VALUES (1, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` VALUES (2, NULL , '3200', '2016-05-19');
INSERT INTO `product` VALUES (3, 'Soda ', '400', SYSDATE());
INSERT INTO `product` VALUES (4, 'Lemonade ',DEFAULT, '2014-01-23');
Output

 To enter a DEFAULT value into one of the fields of one of the columns, the DEFAULT
keyword should be used.

CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCREME


NT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL DEFAULT
'200' ,
`expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE = InnoDB
;
INSERT INTO `product` VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` VALUES (NULL, 'Coffee ', '3200', '2016-05-19');

Page 25
INSERT INTO `product` VALUES (3, 'Soda ', '400', SYSDATE());
INSERT INTO `product` VALUES (4, 'Lemonade ',DEFAULT, '2014-01-23');
Output:

 SYSDATE – you can use the SYSDATE function instead of writing a date.
CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCREME
NT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL ,
`expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE = InnoDB
;
INSERT INTO `product` VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` VALUES (NULL, 'Coffee ', '3200', '2016-05-19');
INSERT INTO `product` VALUES (3, 'Soda ', '400', SYSDATE());

Output

Using a Column List

The following example uses a column list to explicitly specify the values that are inserted
into each column. This option provides us with additional flexibility:
Inserting a new row into the table
CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCREMENT
`Product_name` TEXT NOT NULL , `product_price` INT NOT NULL , `expiration_date`
DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE = InnoDB;
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Coffee ', '3200', '2016-05-19');

The following table reflects the data in products table after the INSERT statement has
completed:

Output
Page 26
 The order of the values must match the order of the columns in the column list. In the case
above, the first value must be associated with the product number; the second value must
be associated with the product name, and so on.
 The value type must match the type of columns in the column list. For example, it is not
possible to enter the value 37 into the expiration_date column.
 The number of values – must match the number of values in the column list. Therefore,
there is no need to enter a value into each column of the table.

A NULL value is entered into a column that was not specified in the column list, if no
default value exists; otherwise, the DEFAULT value is entered.
 To enter a NULL value explicitly into one of the fields of one of the columns, the NULL
value should be specified.

CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCREME


NT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL DEFAULT
'200' , `expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE =
InnoDB;
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (1, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (2, NULL , '3200', '2016-05-19');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (3, 'Soda ', '400', SYSDATE());
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (4, 'Lemonade ',DEFAULT, '2014-01-23');
Output

Page 27
 To enter a DEFAULT value explicitly into one of the fields of one of the columns, the
DEFAULT value should be specified.
CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCRE
MENT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL
DEFAULT
'200' , `expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE
= InnoDB;
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Coffee ', '3200', '2016-05-19');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (3, 'Soda ', '400', SYSDATE());
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (4, 'Lemonade ',DEFAULT, '2014-01-23');
Output:

 GETDATE – you can use the SYSDATE (SYSDATE in Oracle) function instead of
writing a date.

Oracle INSERT INTO SELECT


This method allows copying data items from another table into the requested target table.

1 INSERT INTO target_table_name (column_name, column_name, column_name ..)


2 SELECT …
3 FROM source_table_name
4 WHERE …

For example:

CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCRE


MENT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL
DEFAULT

Page 28
'200' , `expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE
= InnoDB;
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Tea ', '57', '2014-01-23');
SELECT `product_id`,`product_name` FROM `product` WHERE `product_id`=1

Output

 You can use the INSERT INTO SELECT statement either with or without the column list
 It is not mandatory to include a WHERE statement in the query; however, including such a
statement is advisable if you would like to avoid copying the entire table.

Oracle DML UPDATE Statement


The Oracle UPDATE statement is used to modify existing rows.

1 UPDATE table_name
2 SET column=value, column=value ..
3 WHERE condition

Example

CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCRE


MENT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL
DEFAULT
'200' , `expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE
= InnoDB;
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Coffee ', '3200', '2016-05-19');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (4, 'Lemonade ',DEFAULT, '2014-01-23');
UPDATE `product` SET `product_name`=`Shakes` WHERE `product_id`=2;

Output

Page 29
It is possible to update to a NULL or DEFAULT value.

1 UPDATE Names
2 SET Name = DEFAULT
3 WHERE Id = 5

4 UPDATE Names
5 SET Name = NULL
6 WHERE Id= 5

Executing the Oracle UPDATE statement without using the Oracle WHERE clause results in
updating all of the fields in a column.

Oracle DML DELETE Statement


The Oracle DELETE statement is used to remove existing rows from a table.

1 DELETE FROM table_name


2 WHERE condition

Example:
CREATE TABLE `products`.`product` ( `Product_id` INT NOT NULL AUTO_INCRE
MENT , `Product_name` TEXT NOT NULL , `product_price` INT NOT NULL
DEFAULT
'200' , `expiration_date` DATE NOT NULL , PRIMARY KEY (`Product_id`)) ENGINE
= InnoDB;
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Tea ', '57', '2014-01-23');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (NULL, 'Coffee ', '3200', '2016-05-19');
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (3, 'Soda ', '400', SYSDATE());
INSERT INTO `product` (`Product_id`, `Product_name`, `product_price`,
`expiration_date`) VALUES (4, 'Lemonade ',DEFAULT, '2014-01-23');
DELETE FROM `product` WHERE `product_id`=3;
Output

Page 30
 Executing the Oracle DELETE statement without using the Oracle WHERE clause, results
in the deletion of all of the rows in the table.
 It is not possible to delete only a single field by using the Oracle DELETE statement .The
Oracle DELETE statement deletes rows.
 You can write a Oracle DELETE statement either with or without the Oracle FROM
keyword.

1 DELETE FROM products


2 -- or
3 DELETE product.

Page 31
PRACTICAL 5
AIM- To make use of different clauses viz Where, Group by, Having, Order by.

I Where:
The WHERE clause is used to extract only those records that fulfill a specified criterion. It is
used to specify a condition while fetching the data from single table or joining with multiple
tables. If the given condition is satisfied then only it returns specific value from the table. We
would use WHERE clause to filter the records and fetching only necessary records.
SQL WHERE Syntax:
SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;

a)LIKE:The LIKE operator is used to search for a specified pattern in a column.

SQL LIKE Syntax:

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

Page 32
b) Between: The BETWEEN operator selects values within a range. The values can be
numbers, text, or dates.

SQL BETWEEN Syntax:

SELECT column_name(s)
FROM table_name
WHERE column_nameBETWEENvalue1 AND value2;

II Group by:

The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns. The GROUP BY clause must follow the conditions in the
WHERE clause and must precede the ORDER BY clause if one is used.

SQL GROUP BY Syntax:

Page 33
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;

III Having:

The HAVING clause enables us to specify conditions that filter which group results appear in
the final results. The WHERE clause places conditions on the selected columns, whereas the
HAVING clause places conditions on groups created by the GROUP BY clause.

SQL HAVING Syntax:

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value;

Page 34
IV Order by:

The ORDER BY keyword is used to sort the result-set by one or more columns. The ORDER
BY keyword sorts the records in ascending order by default. To sort the records in a descending
order, we can use the DESC keyword. We can use more than one column in the ORDER BY
clause.

SQL ORDER BY Syntax:

SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;

Page 35
PRACTICAL-6

AIM: To perform aggregate functions like SUM, MAX, MIN,AVG,COUNT on a table.

Description:

Aggregate Functions: An aggregate function is a function where the values of multiple rows
are grouped together as input on certain criteria to form a single value of more significant
meaning or measurement.

1. SUM: The SUM( ) function returns the total sum of a numeric column. SQL SUM( )
function to sum one or more columns against one or more conditions.

Syntax:

Select SUM(<column name>) from <table name>;

Example :

Output:

Page 36
2. MAX: This function returns the maximum of values for any column of a table for all
the rows.

Syntax:

Select MAX(<column name>) from <table name>;

Example :

Output :

Page 37
3. MIN: This function returns the minimum of values for any column of a table for all
the rows.

Syntax:

Select MIN(<column name>) from <table name>;

Example :

Output :

Page 38
4. AVG: This function returns the average of values for any column of a table. It ignores
the null values in the column.

Syntax:

Select AVG(<column name>) from <table name>;

Example :

Output :

5. COUNT: This function returns the number of rows or non-null values for any given
column in a table.
Syntax:

Select COUNT(<column name>) from <table name>;


Select COUNT(*) from <table name>;

Page 39
Example :

Output :

Page 40
PRACTICAL NO.-7
AIM-To perform arithematic and logical opertiors.

DESCRIPTION:

Arithematic operators: We can use various Arithmetic Operators on the data stored in the
tables.Arithmetic Operators are:

+ [Addition]
- [Subtraction]
/ [Division]
* [Multiplication]

1. Addition (+) :It is used to perform addition operation on the data items, items include
either single column or multiple columns

Syntax:
SELECT column1, column1+ column2,column3+100
AS " column1+ column2" FROM tablename;

Fig 7.1

2. Subtraction (-) :It is use to perform subtraction operation on the data items, items
include either single column or multiple colum
ns.

Syntax:
SELECT column1, column1- column2,column3-100
AS " column1- column2" FROM tablename;

Page 41
Fig 7.2

3. Multiplication (*) : It is use to perform multiplication of data items.

Syntax:
SELECT column1, column1* column2,column3*2
AS " column1* column2" FROM tablename;

4. Modulus ( % ) :It is use to get remainder when one data is divided by another.

Syntax:
SELECT column1, column1%column2,column3%2
AS " column1%column2" FROM tablename;

5. Divide (/) : It is use to get qoutient when one data is divided by another of data items.

Syntax:
SELECT column1, column1* column2,(column3*2)/100
AS " column1* column2" FROM tablename;

Fig 7.3

Defining a Null Value


• A null is a value that is unavailable, unassigned, unknown, or inapplicable.

Page 42
• A null is not the same as a zero or a blank space

Fig 7.4

Logical Operators: The Logical operators are those that are true or false. They return a true
or false values to combine one or more true or false values.The Logical operators are:
1: AND: Logical AND compares between two Booleans as expression and returns true when
both expressions are true.

Synatx:
SELECT column1, column1
FROM tablename
Where coloumn1…[condition] and column2…[condition]

Fig 7.5

2. OR: Logical OR compares between two Booleans as expression and returns true when
one of the expression is true.

Syntax:

SELECT column1, column1


FROM tablename
Where coloumn1…[condition] or column2…[condition]

Page 43
Fig 7.6

3.NOT:Not takes a single Boolean as an argument and changes its value from false to true or
from true to false.

Syntax:

SELECT column1, column1


FROM tablename
Where Not coloumn1…[condition]

Fig 7.7

Page 44
PRACTICAL NO.8

AIM - To Perform Single Row Functions: String, Numeric, Date And Conversion
Functions.
Description:
SQL Functions: SQL functions are simply sub-programs,which commonly used and re-
used throught SQL database applications for processing or manipulating data. All SQL
database systems have DDL and DML tools to support the creation and maintainance of
databases.

There are two types of functions in Oracle:


 Single Row Functions: Single row or Scalar functions return a value for every row
that is processed in a query.
 Group Functions: These functions group the rows of data based on the values
returned by the query. This is discussed in SQL GROUP Functions. The group
functions are used to calculate aggregate values like total or average, which return just
one total or one average value after processing a group of rows.
Types Of Single Row Functions:
There are four types of single row functions. They are:
 Numeric Functions: These are functions that accept numeric inputand return numeric
values.
 Character OR Text OR String Functions: These are functions thataccept character
input and can return both character and numbervalues.
 Date Functions: These are functions that take values that are of datatype DATE as
input and return values of datatype DATE, exceptfor the MONTHS_BETWEEN
function, which returns a number.
 Conversion Functions: These are functions that help us to convert avalue in one form
to another form. For Example: a null value into anactual value, or a value from one
datatype to another datatype likeNVL, TO_CHAR, TO_NUMBER, TO_DATE etc.
You can combine more than one function together in an expression.
This is known as nesting of functions.

Page 45
1. Numeric Functions:- Numeric functions are used to perform operations on numbers.
They accept numeric values as input and return numeric values as output. Few of the
Numeric functions are: ABS,CEIL,FLOOR, POWER, ROUND.
Function Name& Return Value
 ABS (x): Absolute value of the number 'x'.
 CEIL (x): Integer value that is Greater than or equal to the number 'x'.
 FLOOR (x): Integer value that is Less than or equal to the number 'x'.
 POWER (x, y):The POWER() function returns the value'x' of a number raised to
the power of another number'y'.
 ROUND (x, y):Rounded off value of the number 'x' up to the number 'y' decimal
places.
SYNTAX:SELECT Numeric_function(parameter) from table_name;

Output:

Fig: 8.1
2. Character or Text Functions:- Character or text functions are used tomanipulate text
strings. They accept strings orcharacters as input and can return bothcharacter and
number values as output.

Page 46
Function Name&Return Value
 LOWER (string_value): All the letters in 'string_value'is converted to lowercase.
 UPPER (string_value): All the letters in 'string_value'is converted to uppercase.
 LTRIM (string_value, trim_text): All occurrences of 'trim_text' is removed from the
left of'string_value'.
 RTRIM (string_value, trim_text): All occurrences of 'trim_text' is removed from the
right of'string_value' .
 TRIM (trim_text FROM string_value): All occurrences of 'trim_text'from the left
and rightof'string_value' , 'trim_text' can also be only one character long .
 LENGTH (string_value): Number of characters in'string_value' in returned.
 LPAD (string_value, n, pad_value): Returns 'string_value' left-padded with
'pad_value' . The length of the whole string will be of 'n' characters.
 RPAD (string_value, n, pad_value): Returns 'string_value' right-padded with
'pad_value' . The length of the whole string will be of 'n' characters.

Output:

FIG:8.2

3. Date Functions:-These are functions that take values that are of data type DATE as
input and return values of datatypes DATE, except for the MONTHS_BETWEEN
function, which returns a number as output.
Function Name& Return Value
Page 47
 ADD_MONTHS (date, n): Returns a date value after adding 'n' months to the date'x'.
 MONTHS_BETWEEN (x1, x2): Returns the number of months between dates x1
and x2.
 ROUND (x, date_format): Returns the date 'x' rounded off to the nearest century,
year, month,
 date, hour, minute, or second as specified by the'date_format'.
 TRUNC (x, date_format): Returns the date 'x' lesser than or equal to the nearest
century, year,month, date, hour, minute, or second as specified by the'date_format'.
 NEXT_DAY (x, week_day): Returns the next date of the'week_day' on or after the
date'x' occurs.
 LAST_DAY (x): It is used to determine the number of days remaining in a month
from the date 'x'specified.
 SYSDATE: Returns the systems current date and time.
 NEW_TIME (x, zone1, zone2): Returns the date and time in zone2 if date 'x'
represents the time in zone1.
SYNTAX:-SELECT Date_function(parameters) from table_name;

Output:

Fig: 8.3

4. Conversion Functions:- These are functions that help us to convert avalue in one form
to another form. For Ex: anull value into an actual value, or a value fromone datatype to
another datatype like NVL,TO_CHAR, TO_NUMBER, TO_DATE.
Function Name& Return Value
 TO_CHAR (x [,y]): Converts Numeric and Date values to a character string value. It
cannot be used for calculations since it is a string value.
 TO_DATE (x [,date_format]): Converts a valid Numeric and Character values to a
Date value.Date is formatted to the format specified by 'date_format'.
 NVL (x, y): If 'x' is NULL, replace it with 'y'. 'x'and 'y' must be of the same datatype.

Page 48
 DECODE (a, b, c, d, e, default_value): Checks the value of 'a', if a = b, then returns
'c'. If a = d, then returns 'e'. Else, returns default_value.
SYNTAX:SELECT Conversion_function(parameter) from table_name;

Output:

Fig: 8.4

Page 49
PRACTICAL NO. 9
AIM- To Study Set Operators.
DESCRIPTION:

Set Operators:-Set operators are used to join the results of two(or more) SELECT
statements.The SET operators available in Oracle 11g are UNION,UNION
ALL,INTERSECT,and MINUS.
 Union: The UNION operator is used to combine the result-set of two or more
SELECTstatements. Each SELECT statement within the UNION must have the same
number of columns. The columns must also have similar data types.
STNTAX:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

Fig: 9.1

 Intersection:The SQL INTERSECT clause/operator is used to combine two


SELECTstatements, but returns rows only from the first SELECT statement that are
Page 50
identical to a rowin the second SELECT statement. This means INTERSECT returns
only common rowsreturned by the two SELECT statements.
STNTAX:
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

Fig: 9.2

 Set Difference: The SQL MINUS query returns all rows in the first SQL SELECT
statementthat are not returned in the second SQL SELECT statement.Each SQL
SELECT Statement within the SQL MINUS query must have the same number
offields in the result sets with similar data types.
STNTAX:
SELECT field1, field2, ...field_n

Page 51
FROM tables
MINUS
SELECT field1, field2, ...field_n
FROM tables;

Fig: 9.3

Page 52
PRACTICAL-10

Aim: To study & implement constraints on a table

Constraints can be specified when the table is created with the CREATE TABLE statement,
or after the table is created with the ALTER TABLE statement.

Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);

The following constraints are commonly used in SQL:

NOT NULL - Ensures that a column cannot have a NULL value


UNIQUE - Ensures that all values in a column are different
PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
FOREIGN KEY - Uniquely identifies a row/record in another table
CHECK - Ensures that all values in a column satisfies a specific condition

Page 53
PRACTICAL-11

AIM-To understand the use and working of Joins

Join: SQL joins are used to relate information in different tables. Joins are used to combine
columns from different tables. The connection between tables is established through the
where clause. There are five types of Joins:
Equijoins.
Cartesian Joins.
Outer Joins.
Non-Equi Joins
Self Joins.
1. Equijoin: When two tables are joined together using equality of values in one or more
columns, they make an Equijoin. Table prefixes are utilized to prevent ambiguity and
the where clause specifies the columns being joined. Equijoins are also called Simple
Joins or Inner Joins.
Syntax of Equijoin is:
SELECT *
FROM table1
JOIN table2
[ON (join_condition)]

2. Cartesian Join: The Cartesian Product returns the number of rows equal to the product
of all rows in all the tables being joined. Cartesian product is useful in finding out all
the possible combination of columns from different tables.
Syntax of Cartesian Join is:
SELECT *
FROM table1
CROSS JOIN table2;

3. Outer Join: This SQL Join condition returns all rows from both tables which satisfy
the Join condition along with rows which do not satisfy the Join condition from one of
the tables. The Outer Join is used in such cases where any values in one table that do
not have corresponding value in other table. We have further three types of Outer
Join:
Left Outer Join.
Right Outer Join.
Full Outer Join.

Page 54
Syntax of Left Outer Join is:
SELECT *
FROM table1
LEFT [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;

Syntax of Right Outer Join is:


SELECT *
FROM table1
RIGHT [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;

Syntax of Full Outer Join is:


SELECT *
FROM table1
FULL [ OUTER ] JOIN table2
ON table1.column_name=table2.column_name;

4. Non-Equi Join: When two or more tables are joined together using non-equality of
values in one or more columns, they make a Non-Equi Join.
Syntax of Non-Equi Join is:
SELECT *
FROM table_name1, table_name2
WHERE table_name1.column [> | < | >= | <= ] table_name2.column;

5. Self Join: Self Join is to join a table to itself means that each row of the table is
combined with itself and with every other row of the table. This type of join is used
when a table has a foreign key that references its own primary key. The self join can
be viewed as join of two copies of the same table.
Syntax:
SELECT a.column_name, b.column_name...
FROM table1 a, table1 b
WHERE a.common_filed = b.common_field;

Page 55
PRACTICAL NO: 12

AIM: To understand the use and working of Sub-Queries.

A sub query is a SQL query within a query. They are nested queries that provide data to
the enclosing query. Sub queries can return individual values or a list of records. A Sub
query or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause. A sub query is used to return data that will be
used in the main query as a condition to further restrict the data to be retrieved. Sub
queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc.

Note: that sub query statements are enclosed between parentheses.

SYNTAX:

1. SELECT column-names
2. FROM table-name1
3. WHERE value IN (SELECT column-name
4. FROM table-name2
5. WHERE condition)

Sub queries can also assign column values for each record:

1. SELECT column1 = (SELECT column-name FROM table-name WHERE


condition),
2. column-names
3. FROM table-name
4. WHERE condition

1) Sub queries with the SELECT Statement:


Sub queries are most frequently used with the SELECT statement. The basic syntax is
as follows –
SYNTAX:
SELECT column name [, column name]
FROM table1 [, table2]
WHERE column name OPERATOR
(SELECT column name [, column name]
Page 56
FROM table1 [, table2]
[WHERE]

SQL> SELECT *
FROM CUSTOMERS
WHERE ID IN (SELECT ID
FROM CUSTOMERS
WHERE SALARY >4500);

2) Sub queries with the INSERT Statement:


Sub queries also can be used with INSERT statements. The INSERT statement uses the
data returned from the sub query to insert into another table. The selected data in the
sub query can be modified with any of the character, date or number functions.
The basic syntax is as follows.
SYNTAX:
INSERT INTO table name [(column1 [, column2])]
SELECT [*|column1 [, column2]
FROM table1 [, table2]
[WHERE VALUE OPERATOR]

Page 57
3) Sub queries with the UPDATE Statement:
The sub query can be used in conjunction with the UPDATE statement. Either single or
multiple columns in a table can be updated when using a sub query with the UPDATE
statement.
The basic syntax is as follows.
UPDATE table
SET column name = new value
[WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[WHERE)]

SQL> UPDATE CUSTOMERS


SET SALARY = SALARY *0.25
WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >=15);

Page 58
4) Sub queries with the DELETE Statement:
The sub query can be used in conjunction with the DELETE statement like with any
other statements mentioned above. The basic syntax is as follows.
DELETE FROM TABLE_NAME
[WHERE OPERATOR [VALUE]
(SELECT COLUMN_NAME
FROM TABLE_NAME)
[WHERE)]

SQL> DELETE FROM CUSTOMERS


WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >=15);

Page 59
Page 60
PRACTICAL NO. 13

AIM-To perform Data Security and Privileges Command: Grant and Revoke, Rollback
and Commit on a table.

DESCRIPTION:

1. Grant: SQL GRANT is a command used to provide access or privileges on the database
objects to the users.
Syntax:

GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];

Example :

The following SQL grants the CONNECT privilege to a user named Deepansh with
the password welcome1 and a user named splashy with the password user123

Output:-

GRANT CONNECT TO Deepansh welcome1, splashy user123;

2) Revoke: The REVOKE command removes user access rights or privileges to the
database objects.

The Syntax for the REVOKE command is:

Example:-

if we wanted to revoke DELETE privileges on a table called employees from a user


named anderson,

output:-

Page 61
3) Rollback: The ROLLBACK command is the transactional command used to undo
transactions that have not already been saved to the database.The ROLLBACK command
can only be used to undo transactions since the last COMMIT or ROLLBACK command
was issued.

Syntax:-

Example :-

Output:-

Page 62
4) Commit: The COMMIT command is the transactional command used to save changes
invoked by a transaction to the database.The COMMIT command saves all transactions to
the database since the last COMMIT or ROLLBACK command.

Syntax:

Example :-

Page 63
Page 64
PRACTICAL 14

AIM: To make Views of a table and to perform Insert, Update, Select and Delete
operations on View.
1. Views: To reduce redundant data to the minimum possible, Oracle allows the creation of
an object called a view. A View is mapped, to a Select sentence. This technique offers a
simple, effective way of hiding columns of a table.
Syntax:
Create view <view_name> AS select <column_list> from <table_name>;
OUTPUT OF VIEWS:

2. Insertion in Views: It is used to Insert rows in views. We must specify a list of values for
a particular row.
Syntax:

Insert into <view_name> values<list of values>;


OUTPUT OF INSERT:

Page 65
3. Updation in Views: Columns in a view can be updated. It is used to modify attribute
values of one or more selected rows. Values of a single column or group of columns can be
updated.
Syntax:
Update <view_name> set <column name> = <value> where <condition>;
OUTPUT OF UPDATE VIEW:

4. Selection in Views: SELECT is used to retrieves information from the view.


Syntax:
Select <column list> from <view_name>;
OUTPUT OF SELECTION FROM VIEW:

Page 66
5. Deletion in Views: It is used to remove existing rows from a view. The entire row is
deleted from the view. A set of rows can also be deleted from the table by specifying the
condition.
Syntax:
Delete from <view_name> where <condition>;
OUTPUT OF DELETION FROM VIEW:

Page 67
PRACTICAL-15

AIM- To make indexes and sequences for a table.

DESCRIPTION:
Indexes: An Index is a database object that is used by the server to find a row in a table
quickly. Indexing a table is an access strategy, that is , a way to sort and search records in the
table. Indexes are essential to improve the speed with which the records can be located and
retrieved from a table.

Indexes are of two types:


1. Simple Index.
2. Composite Index.
I. Simple Index: An Index created on a Single Column of a table is called a simple
Index.
Syntax:
CREATE INDEX index_name
ON table_name (column_name);

II. Composite Index: An Index Created on more than one column is called a Composite
Index.

Sequences: Sequence is a database object from which multiple users may generate unique
integers. We can use sequences to automatically generate primary key values.
Syntax:
Create Sequence <Sequece name> by 1 <conditions>;

Page 68
PRACTICAL-16

Aim- Introduction To PL/SQL Architecture.

DESCRIPTION:

PL/SQL:
PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of programming
languages.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.

EXECUTION OF PL/SQL BLOCK:


The PL/SQL statements written on the client side are passed to the PL/SQL engine at server
side and all the SQL statements are send to the SQL executer. After the execution of whole
block the result is send back to the client side. The execution of the whole block is done in
one go.

Page 69
PRACTICAL-17

Aim: Compute Addition,Subtraction,Product and Division of given two numbers.

DESCRIPTION:
SQL>
declare
a number :=&amp;a;
b number:=&amp;b;
r1 number;
r2 number;
r3 number;
r4 number;
begin
r1:=a+b;
r2:=a-b;
r3:=a*b;
r4:=a/b;
dbms_output.put_line(‘RESULT=’||r1);
dbms_output.put_line(‘RESULT=’||r2);
dbms_output.put_line(‘RESULT=’||r3);
dbms_output.put_line(‘RESULT=’||r4);
end;
Output:

Page 70
PRACTICAL-18

Aim: To Print Multiplication Table of a number.

DESCRIPTION:
Text Editor
1. Type your code in a text editor, like Notepad, Notepad+, or EditPlus, etc.
2. Save the file with the . sql extension in the home directory.
3. Launch the SQL*Plus command prompt from the directory where you created
your PL/SQL file.
4. Type @file_name at the SQL*Plus command prompt to execute your program.
SQL>
Declare
table_ofnumber := &amp;enter_table_of;
cntnumber := 1;
Result number;
Begin
while (cnt&lt;= 10)
loop
Result :=table_of number * cnt;
DBMS_output.put_line(table_of number|| &#39;*&#39; || &#39;=&#39; || Result);
cnt := cnt + 1;
end loop;
end;
Output:

Page 71
PRACTICAL-19

Aim: For Loop – To Find Reverse of a given number.

DESCRIPTION:
Declare
n number;
i number;
rev number:=0;
r number;
begin
n:=&n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is '||rev);
end;

Page 72
PRACTICAL NO.20

AIM:Implementation of Procedure
THEORY:
Procedures: Procedures are named PL/SQL blocks that can take parameters, perform an
action and can be invoked. A procedure is generally used to perform an action and to pass
values. Procedures are made up of:
1.A declarative part
2.An executable part
3.An optional exception handling part
Declarative Part: The declarative part may contain declaration of cursors, constants, variables,
exceptions and subprograms. These objects are local to the procedure. The objects become
invalid once you exit from it.
Executable Part: This part contains PL/SQL block consisting of statements that assign values,
control execution and manipulate ORACLE data.
Exception Handling Part: This part contains code that performs action to deal with exceptions
raised during the execution of the program.
Syntax:
CREATE OR REPLACE
PROCEDURE [.schema] procedure_name
(argument {IN, OUT, IN OUT} datatype,){IS, AS}
Variable declarations;
Constant declarations;
BEGIN
PL/SQL subprogram body;
EXCEPTION
Exception PL/SQL block;

Page 73
END;

Types of Procedures:
1.Local Procedure
2.Stored Procedure

LOCAL PROCEDURE:These procedures are declared within the PL/SQL block and called
from the begin section of the PL/SQL block.
The following is a simple example of a procedure:
PROGRAM:
declare
a number;
b number;
c number;
d number;
e number;
f number;
procedure process ( a in number, b in number, c out number, d out number, e out number, f
out number) is
begin
c:=a+b;
d:=a-b;
e:=a*b;
f:=a/b;
end;
begin
a:=&firstnumber;
b:=&secondnumber;

Page 74
process(a, b, c, d, e, f);
DBMS_output.put_line(‘addition is’ || c);
DBMS_output.put_line(‘subtraction is’ || d);
DBMS_output.put_line(‘multiplication is’ || e);
DBMS_output.put_line(‘division is’ || f);
end;

OUTPUT:

Page 75
PRACTICAL NO.21

AIM:Implementation of Triggers.
THEORY:
Triggers:A trigger is a special kind of stored procedure that is invoked whenever an attempt
is made tomodify the data in the table it protects. Triggers are automatically executed or
firedwhensome events occur. Modifications to the table are made using INSERT,
UPDATE,ORDELETE statements. Triggers are used to enforce data integrity and business
rules such asautomatically updating summary data. It allows performing cascading delete or
updatingoperations. If constraints exist on the trigger table, they are checked prior to the
triggerexecution. If constraints are violated statement will not be executed and trigger will not
run.Triggers are associated with tables and they are automatic. Triggers are
automaticallyinvoked by SQL SERVER. Triggers prevent incorrect, unauthorized, or
inconsistent changesto data.

Uses of Triggers:
1) A trigger can permit DML statements against a table only if they are issued,
during regular business hours or on predetermined weekdays.
2) A trigger can also be used to keep an audit trail of a table.
3) It can be used to prevent invalid transactions.
4) Enforce complex security authorizations.
5) Exception handling.
6) Generation of primary key and foreign key.

How to apply Triggers:


A trigger has three basic parts:
1. Triggering Event or Statement:It is a SQL statement that causes a trigger to be fired. It can
be an INSERT, UPDATEor DELETE statement for a specific table.

Page 76
2. Trigger Restriction:A trigger restriction specifies a Boolean expression that must be TRUE
for thetrigger to fire. It is an option available for triggers that are fired for each row. Atrigger
restriction is specified using a WHEN clause.
3. Trigger Action:A trigger action is the PL/SQL code to be executed when a triggering
statement isencountered and any trigger restriction evaluates to TRUE.

Types of Triggers:
 Row Triggers: A row trigger is fired each time the table is affected by the triggering
statement, for example, if an UPDATE statement update multiple rows of a table, a row
trigger is fired once for eachrow affected by the UPDATE statement.
 Statement Triggers: A row trigger is fired once on behalf of the triggering statement,
independent of the numberof rows the triggering statement affects.
 Before Triggers: Before triggers execute the trigger action before the triggering
statement. These types oftriggers are commonly used in the following situations:
1. BEFORE triggers are used when the trigger action should determinewhether or not
the triggering statement should be allowed to complete. Byusing BEFORE trigger, user
can eliminate unnecessary processing of thetriggering statement.
2. BEFORE triggers are used to derive specific column values beforecompleting a
triggering INSERT or UPDATE statement.
 After Triggers: After triggers execute the trigger after the triggering statement is
executed. These types of triggers are commonly used in the following situations:
1. AFTER triggers are used when the triggering statement should complete before
executing the trigger action.
2. If a BEFORE trigger is already present, an AFTER trigger can perform different
actions on the same triggering statement.

Combinations Triggers: Using the above triggers, four types of triggers could be created.
There are twelve combinations of triggers.

Before Statement Trigger: Before executing the triggering statement, the trigger action is
executed.

Before Row Trigger: Before modifying each row affected by the triggering statement and
BEFORE applying appropriate integrity constraints, the trigger is executed.

Page 77
After Statement Trigger: After executing the triggering statement and applying and deferred
integrity constraints, the trigger action is executed.

After Row Trigger: After modifying each row affected by the triggering statement and
applying appropriate integrity constraints, the trigger action is executed for the current row.
Unlike BEFORE row triggers, AFTER row triggers have rows locked.

Creation of Triggers: Triggers are created with the CREATE TRIGGER statement. This
statement specifies that the on which table trigger is defined and on which events trigger will
be invoked.
Syntax:
CREATE OR REPLACE TRIGGER [Schema.] &lt;TriggerName&gt;
{BEFORE, AFTER, Instead of}
{DELETE,INSERT,UPDATE [OF Column,…]}
ON[Schema.] &lt;Tablename&gt;
[REFERENCING {OLD AS old, NEW as new}]
[FOR EACH ROW [WHEN condition]]
DECLARE
&lt;Variable declarations&gt;;
&lt;Constant declarations&gt;;
BEGIN
&lt;PL/SQL subprogram body&gt;;
EXCEPTION
&lt;Exception PL/SQL block&gt;;
END;

Deleting a Trigger: To drop Trigger one can use DROP TRIGGER statement.
Syntax:

DROP TRIGGER &lt;TriggerName&gt;

Example

Page 78
To start with, using the CUSTOMERS table
Select * from customers;
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +

The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.
This trigger will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID &gt; 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line(&#39;Old salary: &#39; || :OLD.salary);
dbms_output.put_line(&#39;New salary: &#39; || :NEW.salary);
dbms_output.put_line(&#39;Salary difference: &#39; || sal_diff);
END;
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.

Page 79
The following points need to be considered here −
 OLD and NEW references are not available for table-level triggers, rather use them
for record-level triggers.
 To query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial changes
are applied and the table is back in a consistent state.
 The above trigger has been written in such a way that it will fire before any DELETE
or INSERT or UPDATE operation on the table, but a trigger can be written on a
single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on the table.

Triggering a Trigger:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, &#39;Kriti&#39;, 22, &#39;HP&#39;, 7500.00 );
When a record is created in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary:
New salary: 7500
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null.

The UPDATE statement will update an existing record in the table −


UPDATE customers
SET salary = salary + 500
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create
trigger, display_salary_changes will be fired and it will display the following result −
Old salary: 1500
New salary: 2000
Salary difference: 500

Page 80

You might also like