Sunteți pe pagina 1din 148

i

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY

(Regulation 2017)

Lab Learning Material Academic

Year 2018-2019 (Even Semester)

Prepared By

Mr.Raguvaran.S AP/CSE
Mr.Karthic.S AP/CSE
Ms.Dhivya.R AP/CSE

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
ii

TABLE OF CONTENTS

Page
Ex.No Content No.

- Authenticated Syllabus Copy 1


- List of Exercises 2

- Student’s slot & Batch details 3


- Lab plan 4
Data Definition Commands, Data Manipulation Commands for
1 inserting, deleting, updating and retrieving Tables and Transaction 5-43
Control statements
Database Querying – Simple queries, Nested queries, Sub queries
2 and Joins 44-83

3 Views, Sequences, Synonyms 84-95


4 Database Programming: Implicit and Explicit Cursors 96-102
5 Procedures and Functions 103-111

6 Triggers 112-116
7 Exception Handling 117-123
Database Design using ER modeling, normalization and
8 124-130
Implementation for any application
9 Database Connectivity with Front End Tools 131-137

10 Case Study using real life database applications 138-144

11 PL SQL Block 145-148

12 Creating Index 149-150

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
1

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
2

CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY

AIM:

The aim of this laboratory is to inculcate the abilities of applying the principles of the database management
systems. This course aims to prepare the students for projects where a proper implementation of databases will
be required.

OBJECTIVES:

• To understand data definitions and data manipulation commands


• To learn the use of nested and join queries
• To understand functions, procedures and procedural extensions of data bases
• To be familiar with the use of a front end tool
• To understand design and implementation of typical database applications

LIST OF EXERCISES

1. Data Definition Commands, Data Manipulation Commands for inserting, deleting, updating and retrieving
Tables and Transaction Control statements
2. Database Querying – Simple queries, Nested queries, Sub queries and Joins
3. Views, Sequences, Synonyms
4. Database Programming: Implicit and Explicit Cursors
5. Procedures and Functions
6. Triggers
7. Exception Handling
8. Database Design using ER modeling, normalization and Implementation for any application
9. Database Connectivity with Front End Tools
10. Case Study using real life database applications

AUGUMENTED EXERCISES

11. PL-SQL Block


12 Creating Views

OUTCOMES:

Upon completion of the course, the students will be able to:

• Use typical data definitions and manipulation commands.


• Design applications to test Nested and Join Queries
• Implement simple applications that use Views
• Implement applications that require a Front-end Tool
• Critically analyze the use of Tables, Views, Functions and Procedures

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
3

Student’s slot & Batch details

II – A

Batches
Slots
Batch 1 Batch 2 Batch 3 Batch 4

711317104001- 711317104015-
Slot 1 711317104014 711317104029 - -

711317104044-
711317104030- 711317104058
Slot 2 - - 711317104301
711317104043
711317104701

II – B

711317104059- 711317104074-
Slot 1 711317104073 711317104089 - -

711317104090- 711317104104-
Slot 2 - - 711317104103 711317104117

II – C

711317104119- 711317104134-
Slot 1 711317104133 711317104148 - -

711317104165-
711317104149-
711317104178,
Slot 2 - - 711317104164
711317104302

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
4

LAB PLAN

CLASS : II Year/IV Sem- A, B & C Section


SUBJECT : CS8481 DATABASE MANAGEMENT SYSTEMS LABORATORY
STAFF IN-CHARGE : Mr.S.Raguvaran, Mr.S.Karthic and Ms.R.Dhivya

Exp. Periods to complete the experiments


No
4 8 12 16 20 24 28 32 36 40 44 48 52 56 60
B-
1 I.I
I
B-
1 I.II

B-
2 I.II
B-
2 I.II
B-
3 I.II
B-
4 I.II
B-
5 I.II

6 B-
I.II
B-
7 I.II
B-
8 I.II
B-
9 I.II
B-
10 I.II
B-
11 I.II
B-
12 I.II
B-
Model I.II

Total Hours Planned: 60 Hours

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
5

Ex.No:1: DATA DEFINITION COMMANDS, DATA MANIPULATION COMMANDS FOR


INSERTING, DELETING, UPDATING AND RETRIEVING TABLES AND TRANSACTION
CONTROL STATEMENTS
LEARNING MATERIAL
SQL:

Structured query language pronounced as (SEQUEL). This language is used to communicate to oracle
database.

Database Management System (DBMS):

DBMS is software it helps to manage the database. It performs the following activities very easily.
• Inserting the new data.

• Updating the exiting data.

• Deleting unnecessary data.

• Retrieving the required data.

Examples of RDBMS:
• ORACLE

• SQL SERVER

• DB2

• MYSQL

• SYBASE

• TERA DATA

• MS ACCESS
Structured Query Language (SQL)

The SQL language is subdivided according to their functions as follows

DDL Data Definition Language

DML Data Manipulation Language

DRL/DQL Data Retrieval Language / Data Query Language

DCL Data Control Language

TCL Transaction Control

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
6

Data Definition Language (DDL):

Data Definition Language (DDL) or Schema Definition Language, statements are used to define the
database structure or schema.

CREATE - to create objects in the database

ALTER - alters the structure of the database

DROP - delete objects from the database

TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed

COMMENT - add comments to the data dictionary

RENAME - rename an object

Transaction Control (TCL):

Transaction Control (TCL) statements are used to manage the changes made by DML statements.
It allows statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Data Types

SQL data type is an attribute that specifies type of data of any object. Each column, variable and expression has
related data type in SQL.
You would use these data types while creating your tables. You would choose a particular data type for a
table column based on your requirement.
SQL Server offers six categories of data types for your use.

Exact Numeric Data Types

DATA TYPE FROM TO

bigint - 9,223,372,036,854,775,808 9,223,372,036,854,775,807

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
7

int -2,147,483,648 2,147,483,647

smallint -32,768 32,767

tinyint 0 255

bit 0 1

decimal -10^38 +1 10^38 -1

numeric -10^38 +1 10^38 -1

money -922,337,203,685,477.5808 +922,337,203,685,477.5807

smallmoney -214,748.3648 +214,748.3647

Approximate Numeric Data Types

DATA TYPE FROM TO

float -1.79E + 308 1.79E + 308

real -3.40E + 38 3.40E + 38

Date and Time Data Types

DATA TYPE FROM TO

datetime Jan 1, 1753 Dec 31, 9999

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
8

smalldatetime Jan 1, 1900 Jun 6, 2079

date Stores a date like June 30, 1991

time Stores a time of day like 12:30 P.M.

Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.

Character Strings Data Types

DATA TYPE Description

Maximum length of 8,000 characters.( Fixed length non-


char
Unicode characters)

Maximum of 8,000 characters.(Variable-length non- Unicode


varchar
data).

Maximum length of 231characters, Variable-length non-


varchar(max)
Unicode data (SQL Server 2005 only).

Variable-length non-Unicode data with a maximum length of


text
2,147,483,647 characters.

Unicode Character Strings Data Types

DATA TYPE Description

Maximum length of 4,000 characters.( Fixed length


nchar
Unicode)

nvarchar Maximum length of 4,000 characters.(Variable length Unicode)

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
9

Maximum length of 231characters (SQL Server 2005 only).(


nvarchar(max)
Variable length Unicode)

Maximum length of 1,073,741,823 characters. ( Variable length


ntext
Unicode )

Binary Data Types

DATA TYPE Description

Maximum length of 8,000 bytes(Fixed-length binary data


binary
)

varbinary Maximum length of 8,000 bytes.(Variable length binary data)

Maximum length of 231 bytes (SQL Server 2005 only). ( Variable


varbinary(max)
length Binary data)

Maximum length of
image 2,147,483,647 bytes. ( Variable
length Binary Data)

Misc Data Types

DATA TYPE Description

Stores values of various SQL Server-supported data types, except


sql_variant
text, ntext, and timestamp.

Stores a database-wide unique number that gets updated every time


timestamp
a row gets updated

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
10

uniqueidentifier Stores a globally unique identifier (GUID)

Stores XML data. You can store xml instances in a column or a


xml
variable (SQL Server 2005 only).

cursor Reference to a cursor object

table Stores a result set for later processing

Operators
An operator is a reserved word or a character used primarily in an SQL statement's WHERE clause to
perform operation(s), such as comparisons and arithmetic operations.

Operators are used to specify conditions in an SQL statement and to serve as conjunctions for multiple
conditions in a statement.

• Arithmetic operators
• Comparison operators
• Logical operators
• Operators used to negate conditions

SQL Arithmetic Operators:

Operator Description Example

Addition - Adds values on either side of the a + b will


+
operator give 30

Subtraction - Subtracts right hand operand from a - b will


-
left hand operand give -10

Multiplication - Multiplies values on either side of a * b will


*
the operator give 200

Division - Divides left hand operand by right hand b / a will


/
operand give 2

b%a
Modulus - Divides left hand operand by right hand
% will give
operand and returns remainder
0

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
11

SQL Comparison Operators:

Operator Description Example

(a = b)
Checks if the values of two operands are equal or
= is not
not, if yes then condition becomes true.
true.

Checks if the values of two operands are equal or


(a != b)
!= not, if values are not equal then condition
is true.
becomes true.

Checks if the values of two operands are equal or


(a <> b)
<> not, if values are not equal then condition
is true.
becomes true.

Checks if the value of left operand is greater than (a > b)


> the value of right operand, if yes then condition is not
becomes true. true.

Checks if the value of left operand is less than the


(a < b)
< value of right operand, if yes then condition
is true.
becomes true.

Checks if the value of left operand is greater than (a >= b)


>= or equal to the value of right operand, if yes then is not
condition becomes true. true.

Checks if the value of left operand is less than or


(a <= b)
<= equal to the value of right operand, if yes then
is true.
condition becomes true.

Checks if the value of left operand is not less than


(a !< b)
!< the value of right operand, if yes then condition
is false.
becomes true.

Checks if the value of left operand is not greater


(a !> b)
!> than the value of right operand, if yes then
is true.
condition becomes true.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
12

SQL Logical Operators:

Operator Description

The ALL operator is used to compare a value to all values in


ALL
another value set.

The AND operator allows the existence of multiple conditions in


AND
an SQL statement's WHERE clause.

The ANY operator is used to compare a value to any applicable


ANY
value in the list according to the condition.

The BETWEEN operator is used to search for values that are


BETWEEN within a set of values, given the minimum value and the
maximum value.

The EXISTS operator is used to search for the presence of a


EXISTS
row in a specified table that meets certain criteria.

The IN operator is used to compare a value to a list of literal


IN
values that have been specified.

The LIKE operator is used to compare a value to similar values


LIKE
using wildcard operators.

The NOT operator reverses the meaning of the logical operator


NOT with which it is used. Eg: NOT EXISTS, NOT BETWEEN, NOT IN,
etc. This is a negate operator.

The OR operator is used to combine multiple conditions in an


OR
SQL statement's WHERE clause.

The NULL operator is used to compare a value with a NULL


IS NULL
value.

The UNIQUE operator searches every row of a specified table


UNIQUE
for uniqueness (no duplicates).

SQL - CREATE Table

Creating a basic table involves naming the table and defining its columns and each column's data type.

The SQL CREATE TABLE statement is used to create a new table.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
13

Syntax:
Basic syntax of CREATE TABLE statement is as follows:
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
CONSTRAINT CONSTRAINTNAME CONSTRAINTKEYWORD1( one or more columns ),
CONSTRAINT CONSTRAINTNAME CONSTRAINTKEYWORD2( one or more columns ),
.
.
.);

CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to
create a new table. The unique name or identifier for the table follows the CREATE TABLE statement.

Then in brackets comes the list defining each column in the table and what sort of data type it is. The syntax
becomes clearer with an example below.

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the
SELECT statement.
Example:

SQL> CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
CONSTRAINT PK1 PRIMARY KEY (ID)
);

Following is an example, which creates a CUSTOMERS table with ID as primary key and NOT NULL are
the constraints showing that these fields can not be NULL while creating records in this table:
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
14

You can verify if your table has been created successfully by looking at the message displayed by the SQL
server, otherwise you can use DESC command as follows:

SQL> DESC CUSTOMERS;


+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

Now, you have CUSTOMERS table available in your database which you can use to store required
information related to customers.

SQL - ALTER TABLE Command


The SQL ALTER TABLE command is used to add, delete or modify columns in an existing table.You
would also use ALTER TABLE command to add and drop various constraints on a an existing table.
Syntax:
The basic syntax of ALTER TABLE to add a new column in an existing table is as follows:

ALTER TABLE table_name ADD column_name datatype;

The basic syntax of ALTER TABLE to DROP COLUMN in an existing table is as follows:

ALTER TABLE table_name DROP COLUMN column_name;

The basic syntax of ALTER TABLE to change the DATA TYPE of a column in a table is as follows:

ALTER TABLE table_name MODIFY COLUMN column_name datatype;

The basic syntax of ALTER TABLE to add a NOT NULL constraint to a column in a table is as follows:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
15

ALTER TABLE table_name MODIFY column_name datatype NOT NULL;

The basic syntax of ALTER TABLE to ADD UNIQUE CONSTRAINT to a table is as follows:

ALTER TABLE table_name


ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);

The basic syntax of ALTER TABLE to ADD CHECK CONSTRAINT to a table is as follows:

ALTER TABLE table_name


ADD CONSTRAINT MyUniqueConstraint CHECK (CONDITION);

The basic syntax of ALTER TABLE to ADD PRIMARY KEY constraint to a table is as follows:

ALTER TABLE table_name


ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);

The basic syntax of ALTER TABLE to DROP CONSTRAINT from a table is as follows:

ALTER TABLE table_name


DROP CONSTRAINT MyUniqueConstraint;

If you're using MySQL, the code is as follows:

ALTER TABLE table_name


DROP INDEX MyUniqueConstraint;

The basic syntax of ALTER TABLE to DROP PRIMARY KEY constraint from a table is as follows:

ALTER TABLE table_name


DROP CONSTRAINT MyPrimaryKey;

If you're using MySQL, the code is as follows:

ALTER TABLE table_name

DROP PRIMARY KEY;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
16

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is the example to ADD a new column in an existing table:

ALTER TABLE CUSTOMERS ADD SEX char(1);

Now, CUSTOMERS table is changed and following would be output from SELECT statement:

+----+---------+-----+-----------+----------+------+
| ID | NAME | AGE | ADDRESS | SALARY | SEX |
+----+---------+-----+-----------+----------+------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 | NULL |
| 2 | Ramesh | 25 | Delhi | 1500.00 | NULL |
| 3 | kaushik | 23 | Kota | 2000.00 | NULL |
| 4 | kaushik | 25 | Mumbai | 6500.00 | NULL |
| 5 | Hardik | 27 | Bhopal | 8500.00 | NULL |
| 6 | Komal | 22 | MP | 4500.00 | NULL |
| 7 | Muffy | 24 | Indore | 10000.00 | NULL |

Following is the example to DROP sex column from existing table:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
17

ALTER TABLE CUSTOMERS DROP SEX;

Now, CUSTOMERS table is changed and following would be output from SELECT statement:

+----+---------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+---------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+---------+-----+-----------+----------+

You can also use DROP TABLE command to delete complete table but it would remove complete table
structure form the database and you would need to re-create this table once again if you wish you store some
data.
Syntax:
The basic syntax of TRUNCATE TABLE is as follows:

TRUNCATE TABLE table_name;

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
18

| 4 | Chaitali | 25 | Mumbai | 6500.00 |


| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is the example to truncate:

SQL > TRUNCATE TABLE CUSTOMERS;

Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:

SQL> SELECT * FROM CUSTOMERS;


Empty set (0.00 sec)

SQL - DROP or DELETE Table

The SQL DROP TABLE statement is used to remove a table definition and all data, indexes, triggers,
constraints, and permission specifications for that table.

NOTE: You have to be careful while using this command because once a table is deleted then all the
information available in the table would also be lost forever.

Syntax:
Basic syntax of DROP TABLE statement is as follows:

DROP TABLE table_name;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
19

Example:
Let us first verify CUSTOMERS table and then we would delete it from the database:

SQL> DESC CUSTOMERS;


+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |

+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)

This means CUSTOMERS table is available in the database, so let us drop it as follows:

SQL> DROP TABLE CUSTOMERS;


Query OK, 0 rows affected (0.01 sec)

Now, if you would try DESC command, then you would get error as follows:

SQL> DESC CUSTOMERS;


ERROR 1146 (42S02): Table 'TEST.CUSTOMERS' doesn't exist

Here, TEST is database name which we are using for our examples.

SQL – Constraints
Constraints are the rules enforced on data columns on table. These are used to limit the type of data that can go
into a table. This ensures the accuracy and reliability of the data in the database. Constraints could be column
level or table level. Column level constraints are applied only to one column, whereas table level constraints
are applied to the whole table.

Following are commonly used constraints available in SQL.


These constraints have already been discussed in SQL - RDBMS Concepts chapter but it’s worth to revise
them at this point.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
20

• NOT NULL Constraint: Ensures that a column cannot have NULL value.

• DEFAULT Constraint: Provides a default value for a column when none is specified.

• UNIQUE Constraint: Ensures that all values in a column are different.

• PRIMARY Key: Uniquely identified each rows/records in a database table.

• FOREIGN Key: Uniquely identified a rows/records in any another database table.

• CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy certain
conditions.

• INDEX: Use to create and retrieve data from the database very quickly.

Constraints can be specified when a table is created with the CREATE TABLE statement or you can use
ALTER TABLE statement to create constraints even after the table is created.

Dropping Constraints:
Any constraint that you have defined can be dropped using the ALTER TABLE command with the DROP
CONSTRAINT option.

For example, to drop the primary key constraint in the EMPLOYEES table, you can use the following
command:

ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;

Some implementations may provide shortcuts for dropping certain constraints. For example, to drop the
primary key constraint for a table in Oracle, you can use the following command:

ALTER TABLE EMPLOYEES DROP PRIMARY KEY;

Some implementations allow you to disable constraints. Instead of permanently dropping a constraint from
the database, you may want to temporarily disable the constraint and then enable it later.
Integrity Constraints:
Integrity constraints are used to ensure accuracy and consistency of data in a relational database. Data
integrity is handled in a relational database through the concept of referential integrity.

There are many types of integrity constraints that play a role in referential integrity (RI). These constraints
include Primary Key, Foreign Key, Unique Constraints and other constraints mentioned above.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
21

SQL RENAME Statement

With RENAME statement you can rename a table

Some of the relational database management system (RDBMS) does not support this command, because this
is not standardizing statement.

For example renaming a table through MS SQL Server you must use storage procedure SP_RENAME.
Syntax for SQL RENAME is:

RENAME TABLE {tbl_name} TO {new_tbl_name};

Where {tbl_name} table that exists in the current database, and


{new_tbl_name} is new table name.

As for Oracle may also be use the following option: ALTER TABLE

{tbl_name} RENAME TO {new_tbl_name};

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.
Syntax:

There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


VALUES (value1, value2, value3,...valueN);

Here, column1, column2,...columnN are the names of the columns in the table into which you want to insert
data.

You may not need to specify the column(s) name in the SQL query if you are adding values for all the columns
of the table. But make sure the order of the values is in the same order as the columns in the table.

The SQL INSERT INTO syntax would be as follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example:
Following statements would create six records in CUSTOMERS table:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
22

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

You can create a record in CUSTOMERS table using second syntax as follows:

INSERT INTO CUSTOMERS


VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

All the above statements would produce the following records in CUSTOMERS table:

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

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
23

| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Populate one table using another table:


You can populate data into a table through select statement over another table provided another table
has a set of fields, which are required to populate first table. Here is the syntax:

INSERT INTO first_table_name [(column1, column2, ... columnN)]


SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition]

Pre Lab Questions:

1. Define SQL
2. What is DDL?
3. Give the create table syntax.
4. What is a key?
5. Explain NULL values.
6. Define ACID properties.
7. Give syntax for dynamic data insertion.
8. What is primary key?
9. What are null values?
10. How do define check constraints?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
24

DATA DEFINITION LANGUAGE (DDL)

EXERCISES
SET I

Consider the Library schema shown in figure, perform the following operations.

1. Use DDL to create the above mentioned tables and implement the following constraints.
Primary Keys

i. BOOK(Book_id)
ii. BOOK_AUTHORS(Book_id,Author_name)
iii. PUBLISHER(Name)
iv. BOOK_COPIES(Book_id,Branch_id)
v. BOOK_LOANS(Book_id,Branch_id,Card_no)
vi. LIBRARY_BRANCH(Branch_id)
vii. BORROWER(Card_no)

Referential Integrity Constraints


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
25

*Use appropriate on delete cascade, on update cascade, on delete set null clauses

i. BOOK_AUTHORS(Book_id) --→ BOOK(Book_id)


ii. BOOK_COPIES(Book_id) -→ BOOK(Book_id)
iii. BOOK_LOANS(Book_id)-→ BOOK(Book_id)
iv. BOOK(Publisher_Name) → PUBLISHER(Name)
v. BOOK_COPIES(Branch_id)-→LIBRARY_BRANCH(Branch_id)
vi. BOOK_LOANS(Branch_id)→ LIBRARY_BRANCH(Branch_id)
vii. BOOK_LOANS(Card_no)-→ BORROWER(Card_no)

*Use appropriate on delete cascade,on update cascade,on delete set null clauses.

2. Display the structure of the any three tables.


3. Add EmailId Column to the borrower table with not null constraint.
4. Create a constraint that due_date always greater than Date_out.
5. Disable the primary key of publisher.
6. Disable the foreign key of BOOK_COPIES.
7. Enable the primary key of publisher.
8. Modify the data types of few columns of any table.
9. Add unique constraint to the column phone of borrower table. 10.Drop the EmailId Column from the
borrower table.
11.Drop the BOOK_AUTHOR table. (* Create the table again for later usage)

SET II

Consider the following relational schema, perform the below mentioned operations.

BOOKS (ISBN, Title, Author, Quantity-Instock , Price, Pub-Year) CUSTOMERS (Cust-Id,

Cust-Name, Address, Card-No)

ORDERS (Order-No, Cust-Id, Order-Date)

ORDERLIST (Order-No, ISBN, Quantity, Shipping-Date)

RETURNS (Ref-No, Order-No, Order-Date, ISBN, Cust-Id, Return-Date, Price)

1. Use DDL to create the above mentioned tables and implement the following constraints.

Primary Keys

i. BOOKS (ISBN)
ii. CUSTOMERS (Cust_Id)
iii. ORDERS (Order_No)
iv. ORDERLIST (Order-No, ISBN)
v. RETURNS (Ref-No)

Referential Integrity onstraints


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
26

*Use appropriate on delete cascade,on update cascase,on delete set null clauses.

i. ORDERLIST (Order-No ) -→ ORDERS (Order-No)


ii. ORDERLIST ( ISBN ) -→ BOOKS (ISBN )
iii. ORDERS ( Cust-Id ) -→ CUSTOMERS (Cust-Id)
iv. RETURNS ( Order-No ) -→ ORDERS (Order-No)
v. RETURNS (Order-Date ) -→ ORDERS ( Order-Date )

2. Display the structure of the any three tables.


3. Add EmailId column to the customer table with not null constraint.
4. Add unique constraint to the column card-no of customer table.
5. Disable the unique constraint of the card-no.
6. Change the data type of the column price of returns table.
7. Disable the foreign key Order-Date of returns table.
8. Drop the EmailId column from customer table.
9. Create a new domain called offprice which takes integer values from 0 to 300. 10.Add a new column
offerprice to books table with offprice domain.
11.Drop the returns table. (* Create the table again for later usage)

SET III (For all Students)

Consider the following relational schema, perform the below mentioned operations.

COURSE (Course-ID, Course-Name)

COURSE_FEE (Course-ID, Type, Fees) *Type is mention either fulltime or parttime.

STUDENT (Reg-No, Name, Address, Phone-No, DoB, Total-Amt, Amt-Paid, Installment)

INSTALLMENT (Ref-No, Reg-No, Installment-Amt, Due-Date, Paid) COURSE_TAKEN

(Reg-No, Course-ID, Start-Date, Type, CGPA, Attendance)

1. Use DDL to create the above mentioned tables and implement the following constraints.

Primary Keys

i. COURSE (Course-ID)
ii. COURSE_FEE (Course-ID, Type )
iii. STUDENT (Reg-No)
iv. INSTALLMENT (Ref-No, Reg-No)
v. COURSE_TAKEN (Reg-No)
Referential Integrity Constraints

*Use appropriate on delete cascade,on update cascase,on delete set null clauses.

i. COURSE_FEE (Course-ID) --→ COURSE (Course-ID)


ii. INSTALLMENT (Reg-No) --→ STUDENT (Reg-No)
iii. COURSE_TAKEN (Reg-No) --→ STUDENT (Reg-No)
iv. COURSE_TAKEN (Course-ID) --→ COURSE (Course-ID)
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
27

2. Display the structure of the any three tables.


3. Add EmailId column to the student table with not null constraint.
4. Create a domain for the column ‘Type’ of course_fee table which takes only F or P (fulltime or part
time) and change the existing domain of Type.
5. Change the data type of the column attendance of course_taken table.
6. Disable the foreign key COURSE_TAKEN (Course-ID).
7. Drop the EmailID column from student table.
8. Enable the foreign key COURSE_TAKEN (Course-ID).
9. Add a check constraint the column attendance to verify attendance greater that 65%.
10.Drop the course_taken table. (* Create the table again for later usage)
11.Create a domain install which accepts only three values I, II, and III and change the installment
column using this domain.

Viva Questions:

1. What is a foreign key?


2. differentiate truncate and drop table?
3. What is a primary key?
4. Explain domain constraints.
5. Give the syntax for ADD constraints.
6. How do you add check constraints?
7. How do you disable any constraints?
8. What happens once you drop a constraint?
9. How do you add a new column?
10. What is referential integrity?

Data Manipulation Language


LEARNING MATERIAL
SQL is equipped with data manipulation language (DML). DML modifies the database instance by
inserting, updating and deleting its data. DML is responsible for all froms data modification in a database.
SQL contains the following set of commands in its DML section −

• SELECT/FROM/WHERE
• INSERT INTO/VALUES
• UPDATE/SET/WHERE
• DELETE FROM/WHERE
These basic constructs allow database programmers and users to enter data and information into the
database and retrieve efficiently using a number of filter options.

SQL - SELECT Query

SQL SELECT statement is used to fetch the data from a database table which returns data in the form of
result table. These result tables are called result-sets.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
28

Syntax:
The basic syntax of SELECT statement is as follows:

SELECT column1, column2, columnN FROM table_name;

Here, column1, column2...are the fields of a table whose values you want to fetch. If you want to fetch all
the fields available in the field, then you can use the following syntax:

SELECT * FROM table_name;

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would fetch ID, Name and Salary fields of the customers available in
CUSTOMERS table:

SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;

This would produce the following result:

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
29

| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+

If you want to fetch all the fields of CUSTOMERS table, then use the following query:

SQL> SELECT * FROM CUSTOMERS;

This would produce the following result:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

SQL - INSERT Query


The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.

Syntax:
There are two basic syntaxes of INSERT INTO statement as follows:

INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)]


VALUES (value1, value2, value3,...valueN);

Here, column1, column2,...columnN are the names of the columns in the table into which you want to
insert data.

You may not need to specify the column(s) name in the SQL query if you are adding values for all the
columns of the table. But make sure the order of the values is in the same order as the columns in the table.
The SQL INSERT INTO syntax would be as follows:

INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
30

Example:
Following statements would create six records in CUSTOMERS table:

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

You can create a record in CUSTOMERS table using second syntax as follows:

INSERT INTO CUSTOMERS


VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );

All the above statements would produce the following records in CUSTOMERS table:

+----+----------+-----+-----------+----------+
| 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 |
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
31

| 5 | Hardik | 27 | Bhopal | 8500.00 |


| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Populate one table using another table:


You can populate data into a table through select statement over another table provided another table has a
set of fields, which are required to populate first table. Here is the syntax:

INSERT INTO first_table_name [(column1, column2, ... columnN)]


SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];

Dynamic Insert Query:

Syntax:

Insert into <tablename> values(‘&attribute1’,’&attribute2’,…’&attributen’);

SQL - UPDATE Query


The SQL UPDATE Query is used to modify the existing records in a table.

You can use WHERE clause with UPDATE query to update selected rows otherwise all the rows would be
affected.

Syntax:
The basic syntax of UPDATE query with WHERE clause is as follows:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

You can combine N number of conditions using AND or OR operators.

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
32

| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would update ADDRESS for a customer whose ID is 6:

SQL> UPDATE CUSTOMERS


SET ADDRESS = 'Pune'
WHERE ID = 6;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+-----------+----------+
| 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 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

If you want to modify all ADDRESS and SALARY column values in CUSTOMERS table, you do not
need to use WHERE clause and UPDATE query would be as follows:

SQL> UPDATE CUSTOMERS


SET ADDRESS = 'Pune', SALARY = 1000.00;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+---------+---------+

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
33

| ID | NAME | AGE | ADDRESS | SALARY |


+----+----------+-----+---------+---------+
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune | 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |
+----+----------+-----+---------+---------+

SQL - DELETE Query


The SQL DELETE Query is used to delete the existing records from a table.

You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would
be deleted.

Syntax:
The basic syntax of DELETE query with WHERE clause is as follows:

DELETE FROM table_name


WHERE [condition];

You can combine N number of conditions using AND or OR operators.

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| 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 |
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
34

| 7 | Muffy | 24 | Indore | 10000.00 |


+----+----------+-----+-----------+----------+

Following is an example, which would DELETE a customer, whose ID is 6:

SQL> DELETE FROM CUSTOMERS


WHERE ID = 6;

Now, CUSTOMERS table would have the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

If you want to DELETE all the records from CUSTOMERS table, you do not need to use WHERE clause
and DELETE query would be as follows:

SQL> DELETE FROM CUSTOMERS;

Now, CUSTOMERS table would not have any record.

SQL - TRUNCATE TABLE Command


The SQL TRUNCATE TABLE command is used to delete complete data from an existing table.

You can also use DROP TABLE command to delete complete table but it would remove complete table
structure form the database and you would need to re-create this table once again if you wish you store
some data.

Syntax:
The basic syntax of TRUNCATE TABLE is as follows:

TRUNCATE TABLE table_name;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
35

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is the example to truncate:

SQL > TRUNCATE TABLE CUSTOMERS;

Now, CUSTOMERS table is truncated and following would be the output from SELECT statement:

SQL> SELECT * FROM CUSTOMERS;


Empty set (0.00 sec)

SQL - Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or sequences of
work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort
of a database program.

A transaction is the propagation of one or more changes to the database. For example, if you are creating a
record or updating a record or deleting a record from the table, then you are performing transaction on the
table. It is important to control transactions to ensure data integrity and to handle database errors.

Practically, you will club many SQL queries into a group and you will execute all of them together as a
part of a transaction.

Properties of Transactions:
Transactions have the following four standard properties, usually referred to by the acronym ACID:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
36

• Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the
transaction is aborted at the point of failure, and previous operations are rolled back to their former state.

• Consistency: ensures that the database properly changes states upon a successfully committed transaction.

• Isolation: enables transactions to operate independently of and transparent to each other.

• Durability: ensures that the result or effect of a committed transaction persists in case of a system failure.

Transaction Control:
There are following commands used to control transactions:

• COMMIT: to save the changes.

• ROLLBACK: to rollback the changes.

• SAVEPOINT: creates points within groups of transactions in which to ROLLBACK

• SET TRANSACTION: Places a name on a transaction.

Transactional control commands are only used with the DML commands INSERT, UPDATE and
DELETE only. They can not be used while creating tables or dropping them because these operations are
automatically commited in the database.

The COMMIT Command:


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.

The syntax for COMMIT command is as follows:

COMMIT;

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
37

| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is the example which would delete records from the table having age = 25 and then COMMIT
the changes in the database.

SQL> DELETE FROM CUSTOMERS


WHERE AGE = 25;
SQL> COMMIT;

As a result, two rows from the table would be deleted and SELECT statement would produce the
following result:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

The ROLLBACK Command:


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.

The syntax for ROLLBACK command is as follows:

ROLLBACK;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
38

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is the example, which would delete records from the table having age = 25 and then
ROLLBACK the changes in the database.

SQL> DELETE FROM CUSTOMERS


WHERE AGE = 25;
SQL> ROLLBACK;

As a result, delete operation would not impact the table and SELECT statement would produce the
following result:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
39

The SAVEPOINT Command:


A SAVEPOINT is a point in a transaction when you can roll the transaction back to a certain point without
rolling back the entire transaction.

The syntax for SAVEPOINT command is as follows:

SAVEPOINT SAVEPOINT_NAME;

This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.

The syntax for rolling back to a SAVEPOINT is as follows:

ROLLBACK TO SAVEPOINT_NAME;

Following is an example where you plan to delete the three different records from the CUSTOMERS table.
You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT
at any time to return the appropriate data to its original state:

Example:
Consider the CUSTOMERS table having the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now, here is the series of operations:

SQL> SAVEPOINT SP1;


Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=1;
1 row deleted.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
40

SQL> SAVEPOINT SP2;


Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=2;
1 row deleted.
SQL> SAVEPOINT SP3;
Savepoint created.
SQL> DELETE FROM CUSTOMERS WHERE ID=3;
1 row deleted.

Now that the three deletions have taken place, say you have changed your mind and decided to
ROLLBACK to the SAVEPOINT that you identified as SP2. Because SP2 was created after the first
deletion, the last two deletions are undone:

SQL> ROLLBACK TO SP2;


Rollback complete.

Notice that only the first deletion took place since you rolled back to SP2:

SQL> SELECT * FROM CUSTOMERS;


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
6 rows selected.

The RELEASE SAVEPOINT Command:


The RELEASE SAVEPOINT command is used to remove a SAVEPOINT that you have created.

The syntax for RELEASE SAVEPOINT is as follows:

RELEASE SAVEPOINT SAVEPOINT_NAME;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
41

Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo
transactions performed since the SAVEPOINT.

The SET TRANSACTION Command:


The SET TRANSACTION command can be used to initiate a database transaction. This command is used
to specify characteristics for the transaction that follows.

For example, you can specify a transaction to be read only, or read write.

The syntax for SET TRANSACTION is as follows:

SET TRANSACTION [ READ WRITE | READ ONLY ];

Pre Lab Questions:

1. Give the syntax for SELECT and WHERE clause?


2. Give the syntax for UPDATE clause?
3. What is DML?
4. What are ACID properties?
5. What is TCL?
6. What is a transaction?
7. What is consistency?
8. Give the syntax for DELETE clause?
9. What is a domain constraint?
10. What is a domain value?

DATA MANIPULATION LANGUAGE (DML)

EXERCISES
SET I

1. Insert the necessary rows into the following tables.

i. BOOK
ii. BOOK_AUTHORS
iii. PUBLISHER
iv. BOOK_COPIES
v. BOOK_LOANS
vi. LIBRARY_BRANCH
vii. BORROWER

2. Display the book ids which have more than 5 copies.


3. Display the book titles which have less than 6 copies.
4. Display the book titles of ‘Pearson Publication’.
5. Display the book ids borrowed from July 2016 to august 2016.
6. Display card nos no which have over due.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
42

7. Update the phone no whose card no is “XXXXX”


8. Update the publisher name “Pearson Publication” to “PEARSON PUBLICATION”.
9. Give extra 10 days due time to the bookid “XXXXX”.
10. Delete the book details of “Mc Graw Hill” from book table.
11. Delete the book details issued before 03-03-2017 from book_loans table.
12. Truncate the Book_Authors table.
13.Perform TCL Commands on the above DB.

SET II

1. Insert the necessary rows into the following tables.

BOOKS (ISBN, Title, Author, Quantity-Instock , Price, Pub-Year)

CUSTOMERS (Cust-Id, Cust-Name, Address, Card-No)

ORDERS (Order-No, Cust-Id, Order-Date)

ORDERLIST (Order-No, ISBN, Quantity, Shipping-Date)

RETURNS (Ref-No, Order-No, Order-Date, ISBN, Cust-Id, Return-Date, Price)

2. Display the book titles, author name which cost more than 500.
3. Display the book titles which have less than 10 in quantity.
4. Display the customer names and addresses who have ordered books after 17.07.2016.
5. Display the Order_nos, ISBNs which have been shipped yesterday.
6. Update the order date of the order no “XXXXX” .
7. Update the publication year of the book titled as “DBMS”.
8. Increase the quantity of the book titled “EVS” by 10.
9. Increase the price of the all books by 10% which have been published in the year 2016.
10. Delete the return details which have been returned before “DD-MMM-YY”. (*Give the date according to
your state of the database).
11. Delete the customer details who belong to “Coimbatore”.
12. Truncate the returns table.
13. Perform TCL Commands on the above DB.

SET III (For all)

1. Insert the necessary rows into the following tables.

i. COURSE (Course-ID, Course-Name)

ii. COURSE_FEE (Course-ID, Type, Fees) *Type is mention either fulltime or part-time.)

iii. STUDENT (Reg-No, Name, Address, Phone-No, DoB, Total-Amt, Amt-Paid, Installment)

iv. INSTALLMENT (Ref-No, Reg-No, Installment-Amt, Due-Date, Paid)

v. COURSE_TAKEN (Reg-No, Course-ID, Start-Date, Type, CGPA, Attendance)


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
43

2. Display the Name, Address of all students who have born after 1995.
3. Display the Name, Address, and Phone of all students who belong to “Coimbatore”.
4. Display the Course Names of all part time courses.
5. Display the Name and Phone no of all students who have crossed the installment due date.
6. Display the Name and Phone no of all students who have scored more than 8.00 CGPA.
7. Display the course names which have course fee more than “50000”.
8. Increase the course fee by 15% of all full time courses.
9. Add 500 rupees fine to the students who have missed to pay their installment on time.
10. Increase 0.5 CGPA for the students who maintain attendance more than 90%.
11. Delete the student’s details who have failed to maintain 70% attendance.
12. Delete the student details who have paid all the installments.
13. Perform TCL Commands on the above DB.

Viva Questions

1. How to create save point?


2. What is rollback?
3. What is commit?
4. Why do we use set server output on?
5. Difference between drop and truncate table?
6. What is schema?
7. How do you create a schema?
8. What sql form is used to create schema?
9. What are the roles of DB admin?
10.What is a relation?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
44

Ex.No: 2 Database Querying – Simple queries, Nested queries, Sub queries and Joins

LEARNING MATERIALS

SQL - AND and OR Conjunctive Operators


The SQL AND & OR operators are used to combine multiple conditions to narrow data in an SQL
statement. These two operators are called as the conjunctive operators.

These operators provide a means to make multiple comparisons with different operators in the same SQL
statement.

The AND Operator


The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.

Syntax
The basic syntax of the AND operator with a WHERE clause is as follows −

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] AND [condition2]...AND [conditionN];
You can combine N number of conditions using the AND operator. For an action to be taken by the SQL
statement, whether it be a transaction or a query, all conditions separated by the AND must be TRUE.

Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table,
where the salary is greater than 2000 and the age is less than 25 years −

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
45

WHERE SALARY > 2000 AND age < 25;

This would produce the following result −

+----+-------+----------+
| ID | NAME | SALARY |
+----+-------+----------+
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+-------+----------+
The OR Operator
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.

Syntax
The basic syntax of the OR operator with a WHERE clause is as follows −

SELECT column1, column2, columnN


FROM table_name
WHERE [condition1] OR [condition2]...OR [conditionN]
You can combine N number of conditions using the OR operator. For an action to be taken by the SQL
statement, whether it be a transaction or query, the only any ONE of the conditions separated by the OR
must be TRUE.

Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

The following code block hasa query, which would fetch the ID, Name and Salary fields from the
CUSTOMERS table, where the salary is greater than 2000 and the age is less than 25 years.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
46

SQL> SELECT ID, NAME, SALARY


FROM CUSTOMERS
WHERE SALARY > 2000 OR age < 25;

This would produce the following result −

+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
The SQL LIKE Operator

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

• % - The percent sign represents zero, one, or multiple characters


• _ - The underscore represents a single character

Note: MS Access uses a question mark (?) instead of the underscore (_).

The percent sign and the underscore can also be used in combinations!

LIKE Syntax
SELECT column1,column2, ...
FROM table_name
WHERE columnN LIKE pattern;

Tip: You can also combine any number of conditions using AND or OR operators.

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"

WHERE CustomerName LIKE '%a' Finds any values that ends with "a"

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
47

WHERE CustomerName LIKE


Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE


Finds any values that have "r" in the second position
'_r%'

WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3 characters
'a_%_%' in length

WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:

Customer Customer Contact Postal


Address City Country
ID Name Name Code

Alfreds
1 Maria Anders Obere Str. 57 Berlin 12209 Germany
Futterkiste

Ana Trujillo Avda. de la


México
2 Emparedados y Ana Trujillo Constitución 05021 Mexico
D.F.
helados 2222

Antonio Moreno Antonio Mataderos México


3 05023 Mexico
Taquería Moreno 2312 D.F.

Around the Thomas 120 Hanover


4 London WA1 1DP UK
Horn Hardy Sq.

Berglunds Christina Berguvsvägen


5 Luleå S-958 22 Sweden
snabbköp Berglund 8

SQL LIKE Examples

The following SQL statement selects all customers with a CustomerName starting with "a":

Example

SELECT * FROM Customers


WHERE CustomerName LIKE 'a%';

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
48

The following SQL statement selects all customers with a CustomerName ending with "a":

Example

SELECT * FROM Customers


WHERE CustomerName LIKE '%a';

The following SQL statement selects all customers with a CustomerName that have "or" in any position:

Example

SELECT * FROM Customers


WHERE CustomerName LIKE '%or%';

The following SQL statement selects all customers with a CustomerName that have "r" in the second
position:

Example

SELECT * FROM Customers


WHERE CustomerName LIKE '_r%';

The following SQL statement selects all customers with a CustomerName that starts with "a" and are at
least 3 characters in length:

Example

SELECT * FROM Customers


WHERE CustomerName LIKE 'a_%_%';

The following SQL statement selects all customers with a ContactName that starts with "a" and ends with
"o":

Example

SELECT * FROM Customers


WHERE ContactName LIKE 'a%o';

The following SQL statement selects all customers with a CustomerName that NOT starts with "a":

Example

SELECT * FROM Customers


WHERE CustomerName NOT LIKE 'a%';

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
49

SQL Wildcard Characters

A wildcard character is used to substitute any other character(s) in a string.

Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE clause
to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

• % - The percent sign represents zero, one, or multiple characters


• _ - The underscore represents a single character

Note: MS Access uses a question mark (?) instead of the underscore (_).

In MS Access and SQL Server you can also use:

• [charlist] - Defines sets and ranges of characters to match


• [^charlist] or [!charlist] - Defines sets and ranges of characters NOT to match

The wildcards can also be used in combinations!

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"

WHERE CustomerName LIKE '%a' Finds any values that ends with "a"

WHERE CustomerName LIKE


Finds any values that have "or" in any position
'%or%'

WHERE CustomerName LIKE


Finds any values that have "r" in the second position
'_r%'

WHERE CustomerName LIKE Finds any values that starts with "a" and are at least 3 characters
'a_%_%' in length

WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"
Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
50

Customer Customer Contact Postal


Address City Country
ID Name Name Code

Maria
1 Alfreds Futterkiste Obere Str. 57 Berlin 12209 Germany
Anders

Ana Trujillo Avda. de la


Ana México
2 Emparedados y Constitución 05021 Mexico
Trujillo D.F.
helados 2222

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

Thomas WA1
4 Around the Horn 120 Hanover Sq. London UK
Hardy 1DP

Berglunds Christina S-958


5 Berguvsvägen 8 Luleå Sweden
snabbköp Berglund 22
Using the % Wildcard

The following SQL statement selects all customers with a City starting with "ber":

Example

SELECT * FROM Customers


WHERE City LIKE 'ber%';

The following SQL statement selects all customers with a City containing the pattern "es":

Example

SELECT * FROM Customers


WHERE City LIKE '%es%';
The SQL LIKE clause is used to compare a value to similar values using wildcard operators. There are
two wildcards used in conjunction with the LIKE operator.

• The percent sign (%)


• The underscore (_)
The percent sign represents zero, one or multiple characters. The underscore represents a single number or
character. These symbols can be used in combinations.

Syntax

The basic syntax of % and _ is as follows −

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
51

SELECT FROM table_name


WHERE column LIKE 'XXXX%'

or

SELECT FROM table_name


WHERE column LIKE '%XXXX%'

or

SELECT FROM table_name


WHERE column LIKE 'XXXX_'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX'

or

SELECT FROM table_name


WHERE column LIKE '_XXXX_'
You can combine N number of conditions using AND or OR operators. Here, XXXX could be any
numeric or string value.

Example
The following table has a few examples showing the WHERE part having different LIKE clause with '%'
and '_' operators –

Sr.No. Statement & Description

WHERE SALARY LIKE '200%'


1
Finds any values that start with 200.

WHERE SALARY LIKE '%200%'


2
Finds any values that have 200 in any position.

WHERE SALARY LIKE '_00%'


3
Finds any values that have 00 in the second and third positions.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
52

WHERE SALARY LIKE '2_%_%'


4
Finds any values that start with 2 and are at least 3 characters in length.

WHERE SALARY LIKE '%2'


5
Finds any values that end with 2.

WHERE SALARY LIKE '_2%3'


6
Finds any values that have a 2 in the second position and end with a 3.

WHERE SALARY LIKE '2___3'


7
Finds any values in a five-digit number that start with 2 and end with 3.

Let us take a real example, consider the CUSTOMERS table having the records as shown below.
+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would display all the records from the CUSTOMERS table, where the
SALARY starts with 200.

SQL> SELECT * FROM CUSTOMERS


WHERE SALARY LIKE '200%';

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
+----+----------+-----+-----------+----------+

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
53

The SQL IN Operator

The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

or:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
Demo Database

Below is a selection from the "Customers" table in the Northwind sample database:

Customer Customer Contact Postal


Address City Country
ID Name Name Code

Maria
1 Alfreds Futterkiste Obere Str. 57 Berlin 12209 Germany
Anders

Ana Trujillo Avda. de la


Ana México
2 Emparedados y Constitución 05021 Mexico
Trujillo D.F.
helados 2222

Antonio Moreno Antonio México


3 Mataderos 2312 05023 Mexico
Taquería Moreno D.F.

Thomas WA1
4 Around the Horn 120 Hanover Sq. London UK
Hardy 1DP

Berglunds Christina S-958


5 Berguvsvägen 8 Luleå Sweden
snabbköp Berglund 22

IN Operator Examples

The following SQL statement selects all customers that are located in "Germany", "France" and "UK":

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
54

Example

SELECT * FROM Customers


WHERE Country IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":

Example

SELECT * FROM Customers


WHERE Country NOT IN ('Germany', 'France', 'UK');

The following SQL statement selects all customers that are from the same countries as the suppliers:

Example

SELECT * FROM Customers


WHERE Country IN (SELECT Country FROM Suppliers);
The SQL BETWEEN Operator

The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax

SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

Product Product Supplier Category


Unit Price
ID Name ID ID

1 Chais 1 1 10 boxes x 20 bags 18

2 Chang 1 1 24 - 12 oz bottles 19

3 Aniseed Syrup 1 2 12 - 550 ml bottles 10

4 Chef Anton's Cajun Seasoning 1 2 48 - 6 oz jars 22

5 Chef Anton's Gumbo Mix 1 2 36 boxes 21.35

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
55

BETWEEN Example

The following SQL statement selects all products with a price BETWEEN 10 and 20:

Example

SELECT * FROM Products


WHERE Price BETWEEN 10 AND 20;
NOT BETWEEN Example

To display the products outside the range of the previous example, use NOT BETWEEN:

Example

SELECT * FROM Products


WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN Example

The following SQL statement selects all products with a price BETWEEN 10 and 20. In addition; do not
show products with a CategoryID of 1,2, or 3:

Example

SELECT * FROM Products


WHERE (Price BETWEEN 10 AND 20)
AND NOT CategoryID IN (1,2,3);
BETWEEN Text Values Example

The following SQL statement selects all products with a ProductName BETWEEN 'Carnarvon Tigers' and
'Mozzarella di Giovanni':

Example

SELECT * FROM Products


WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
NOT BETWEEN Text Values Example

The following SQL statement selects all products with a ProductName NOT BETWEEN 'Carnarvon
Tigers' and 'Mozzarella di Giovanni':

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
56

Example

SELECT * FROM Products


WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di Giovanni'
ORDER BY ProductName;
Sample Table

Below is a selection from the "Orders" table in the Northwind sample database:

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 7/4/1996 3

10249 81 6 7/5/1996 1

10250 34 4 7/8/1996 2

10251 84 3 7/9/1996 1

10252 76 4 7/10/1996 2

BETWEEN Dates Example

The following SQL statement selects all orders with an OrderDate BETWEEN '04-July-1996' and '09-July-
1996':

Example

SELECT * FROM Orders


WHERE OrderDate BETWEEN #07/04/1996# AND #07/09/1996#;

SQL TOP, LIMIT or ROWNUM Clause

SQL - ORDER BY Clause


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or
more columns. Some databases sort the query results in an ascending order by default.

Syntax
The basic syntax of the ORDER BY clause is as follows −

SELECT column-list
FROM table_name
[WHERE condition]
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
57

[ORDER BY column1, column2, .. columnN] [ASC | DESC];


You can use more than one column in the ORDER BY clause. Make sure whatever column you are using
to sort that column should be in the column-list.

Example
Consider the CUSTOMERS table having the following records –

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in an ascending order by the NAME
and the SALARY −

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
The following code block has an example, which would sort the result in the descending order by NAME.

SQL> SELECT * FROM CUSTOMERS


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
58

ORDER BY NAME DESC;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

SQL - Distinct Keyword


The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the
duplicate records and fetching only unique records.

There may be a situation when you have multiple duplicate records in a table. While fetching such records,
it makes more sense to fetch only those unique records instead of fetching duplicate records.

Syntax
The basic syntax of DISTINCT keyword to eliminate the duplicate records is as follows −

SELECT DISTINCT column1, column2,.....columnN


FROM table_name
WHERE [condition]
Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
59

+----+----------+-----+-----------+----------+
First, let us see how the following SELECT query returns the duplicate salary records.

SQL> SELECT SALARY FROM CUSTOMERS


ORDER BY SALARY;

This would produce the following result, where the salary (2000) is coming twice which is a duplicate
record from the original table.

+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+
Now, let us use the DISTINCT keyword with the above SELECT query and then see the result.

SQL> SELECT DISTINCT SALARY FROM CUSTOMERS


ORDER BY SALARY;

This would produce the following result where we do not have any duplicate entry.

+----------+
| SALARY |
+----------+
| 1500.00 |
| 2000.00 |
| 4500.00 |
| 6500.00 |
| 8500.00 |
| 10000.00 |
+----------+

SQL - SORTING Results


The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or
more columns. Some databases sort the query results in an ascending order by default.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
60

Syntax
The basic syntax of the ORDER BY clause which would be used to sort the result in an ascending or
descending order is as follows −

SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure that whatever column you are
using to sort, that column should be in the column-list.

Example
Consider the CUSTOMERS table having the following records −

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Following is an example, which would sort the result in an ascending order by NAME and SALARY.

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME, SALARY;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
61

| 3 | kaushik | 23 | Kota | 2000.00 |


| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+

The following code block has an example, which would sort the result in a descending order by NAME.

SQL> SELECT * FROM CUSTOMERS


ORDER BY NAME DESC;

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+

To fetch the rows with their own preferred order, the SELECT query used would be as follows −

SQL> SELECT * FROM CUSTOMERS


ORDER BY (CASE ADDRESS
WHEN 'DELHI' THEN 1
WHEN 'BHOPAL' THEN 2
WHEN 'KOTA' THEN 3
WHEN 'AHMADABAD' THEN 4
WHEN 'MP' THEN 5
ELSE 100 END) ASC, ADDRESS DESC;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
62

This would produce the following result −

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
This will sort the customers by ADDRESS in your ownoOrder of preference first and in a natural order
for the remaining addresses. Also, the remaining Addresses will be sorted in the reverse alphabetical order.

SQL MIN() and MAX() Functions


The SQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN() Syntax

SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax

SELECT MAX(column_name)
FROM table_name
WHERE condition;
Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

10 boxes x 20
1 Chais 1 1 18
bags

2 Chang 1 1 24 - 12 oz bottles 19
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
63

12 - 550 ml
3 Aniseed Syrup 1 2 10
bottles

Chef Anton's Cajun


4 2 2 48 - 6 oz jars 22
Seasoning

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35

MIN() Example

The following SQL statement finds the price of the cheapest product:

Example

SELECT MIN(Price) AS SmallestPrice


FROM Products;
MAX() Example

The following SQL statement finds the price of the most expensive product:

Example

SELECT MAX(Price) AS LargestPrice FROM Products;


SQL COUNT(), AVG() and SUM() Functions
The SQL COUNT(), AVG() and SUM() Functions

The COUNT() function returns the number of rows that matches a specified criteria.

The AVG() function returns the average value of a numeric column.

The SUM() function returns the total sum of a numeric column.

COUNT() Syntax

SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax

SELECT AVG(column_name)
FROM table_name
WHERE condition;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
64

SUM() Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;
Demo Database

Below is a selection from the "Products" table in the Northwind sample database:

ProductID ProductName SupplierID CategoryID Unit Price

10 boxes x 20
1 Chais 1 1 18
bags

2 Chang 1 1 24 - 12 oz bottles 19

12 - 550 ml
3 Aniseed Syrup 1 2 10
bottles

Chef Anton's Cajun


4 2 2 48 - 6 oz jars 22
Seasoning

5 Chef Anton's Gumbo Mix 2 2 36 boxes 21.35


COUNT() Example

The following SQL statement finds the number of products:

Example

SELECT COUNT(ProductID)
FROM Products;
AVG() Example

The following SQL statement finds the average price of all products:

Example

SELECT AVG(Price)
FROM Products;
Demo Database

Below is a selection from the "OrderDetails" table in the Northwind sample database:

OrderDetailID OrderID ProductID Quantity

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
65

1 10248 11 12

2 10248 42 10

3 10248 72 5

4 10249 14 9

5 10249 51 40
SUM() Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:

Example

SELECT SUM(Quantity)
FROM OrderDetails;

Prelab Questions:
1. What is a where clause?
2. What is a having clause?
3. How do you filter duplicates?
4. How do you compute average?
5. What is row number?
6. How do you use IN clause?
7. How do you use BETWEEN clause?
8. How do you find MAX and MIN?
9. What are the sorting clauses available?
10. What is a timestamp?

SET I:
1. List all the author details.
2. List the book details ,copies lies between 2 and 3.
3. List the book details borrowed between date “XXXXX” and “XXXXX”.
4. List the book details borrowed by xxxxx or yyyyy oy zzzzzz.
5. List the book details starts by the title D or O.
6. List all the publishers from book table.
7. List the book details of publisher xxxxx or yyyyy.
8. Increase all the book count by 5.
9. List avg,max and min copies of the books.
10.List the name of the books starts by d and count more than 5.

SET II:
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
66

1. List all the book details.


2. List the book details ,price lies between 200 and 300.
3. List the book details ordered between date “XXXXX” and “XXXXX”.
4. List the book details ordered by the customer xxxxx or yyyyy oy zzzzzz.
5. List the book details starts by the title D or O.
6. List all the return details from returns table.
7. List the book details of author xxxxx or yyyyy.
8. Increase all the book price by 5%.
9. List avg,max and min price of the books.
10.List the name of the books starts by d and price more than 5.

SET III:
1. List all the course fee details.
2. List the student details ,fee paid lies between 200000 and 300000.
3. List the course details fee between “XXXXX” and “XXXXX”.
4. List the student details who studies the course xxxxx or yyyyy oy zzzzzz.
5. List the course details starts by the title C or E.
6. List all the installment details of the students in cse department.
7. List the student details of the department xxxxx or yyyyy.
8. Increase all the course fee by 5%.
9. List avg,max and min fee of the courses.
10.List the name of the students who paid the fee between xxxxx and yyyyy dates.

Viva Questions:
1. What are the aggregate functions?
2. What are the pattern matching clauses?
3. How do you retrieve distinct tuples?
4. How do you use not between clauses?
5. What are the place holders?
6. What is sorting?
7. How do you use distinct keyword?
8. What is an attribute?
9. How do you define domain value of an attribute?
10. What is a metadata?

NESTED QUERIES AND QUERIES USING GROUP BY AND HAVING CLAUSE

LEARNING MATERIALS
The HAVING Clause

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
67

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

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;
Demo Database

In this tutorial we will use the well-known Northwind sample database.

Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10248 90 5 1996-07-04 3

10249 81 6 1996-07-05 1

10250 34 4 1996-07-08 2
And a selection from the "Employees" table:
EmployeeID LastName FirstName BirthDate Photo Notes

1 Davolio Nancy 1968-12- EmpID1.pic Education includes a


08 BA....

2 Fuller Andrew 1952-02- EmpID2.pic Andrew received his


19 BTS....

3 Leverling Janet 1963-08- EmpID3.pic Janet has a BS


30 degree....

SQL HAVING Example

Now we want to find if any of the employees has registered more than 10 orders.

We use the following SQL statement:

Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
68

GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;

Now we want to find if the employees "Davolio" or "Fuller" have registered more than 25 orders.

We add an ordinary WHERE clause to the SQL statement:

Example
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

SQL HAVING Clause

• HAVING filters records that work on summarized GROUP BY results.


• HAVING applies to summarized group records, whereas WHERE applies to individual records.
• Only the groups that meet the HAVING criteria will be returned.
• HAVING requires that a GROUP BY clause is present.
• WHERE and HAVING can be in the same query.

The SQL HAVING syntax


The general syntax is:

1. SELECT column-names
2. FROM table-name
3. WHERE condition
4. GROUP BY column-names
5. HAVING condition

The general syntax with ORDER BY is:

1. SELECT column-names
2. FROM table-name
3. WHERE condition
4. GROUP BY column-names
5. HAVING condition
6. ORDER BY column-names

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
69

CUSTOMER
Id
FirstName
LastName
City
Country
Phone

SQL GROUP BY Examples

Problem: List the number of customers in each country. Only include countries with more than 10
customers.

1. SELECT COUNT(Id), Country


2. FROM Customer
3. GROUP BY Country
4. HAVING COUNT(Id) > 10

Country
Count
11 France
11 Germany
13 USA

CUSTOMER
Id
FirstName
LastName
City
Country
Phone

Problem: List the number of customers in each country, except the USA, sorted high to low.
Only include countries with 9 or more customers.

SELECT COUNT(Id), Country

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
70

1. FROM Customer
2. WHERE Country <> 'USA'
3. GROUP BY Country
4. HAVING COUNT(Id) >= 9
5. ORDER BY COUNT(Id) DESC

Count Country
11 France
11 Germany
9 Brazil

ORDER
Id
OrderDate
OrderNumber
CustomerId
TotalAmount

Problem: List all customer with average orders between $1000 and $1200.

1. SELECT AVG(TotalAmount), FirstName, LastName


2. FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id
3. GROUP BY FirstName, LastName
4. HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200

Average FirstName LastName


1081.215000 Miguel Angel Paolino
1063.420000 Isabel de Castro
1008.440000 Alexander Feuer
1062.038461 Thomas Hardy
1107.806666 Pirkko Koskitalo
1174.945454 Janete Limeira
1073.621428 Antonio Moreno
1065.385000 Rita Müller
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
71

1183.010000 José Pedro Freyre


1057.386666 Carine Schmitt

SQL - Group By
The SQL GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data
into groups.

The GROUP BY clause follows the WHERE clause in a SELECT statement and precedes the ORDER BY
clause.

Syntax:

The basic syntax of GROUP BY clause is given below. The GROUP BY clause must follow the
conditions in the WHERE clause and must precede the ORDER BY clause if one is used.

SELECT column1, column2


FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2
ORDER BY column1, column2

Example:
Consider the CUSTOMERS table is having the following records:

+----+----------+-----+-----------+----------+
| 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 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

If you want to know the total amount of salary on each customer, then GROUP BY query would be as
follows:
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
72

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;

This would produce the following result:

+----------+-------------+
| NAME | SUM(SALARY) |
+----------+-------------+
| Chaitali | 6500.00 |
| Hardik | 8500.00 |
| kaushik | 2000.00 |
| Khilan | 1500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 2000.00 |
+----------+-------------+

Now, let us have following table where CUSTOMERS table has the following records with duplicate
names:

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Ramesh | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | kaushik | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

Now again, if you want to know the total amount of salary on each customer, then GROUP BY query
would be as follows:

SQL> SELECT NAME, SUM(SALARY) FROM CUSTOMERS


GROUP BY NAME;
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
73

This would produce the following result:

+---------+-------------+
| NAME | SUM(SALARY) |
+---------+-------------+
| Hardik | 8500.00 |
| kaushik | 8500.00 |
| Komal | 4500.00 |
| Muffy | 10000.00 |
| Ramesh | 3500.00 |
+---------+-------------+

Pre Lab Questions


1. How the GROUP BY clause project the information?
2. Differentiate HAVING and WHERE clauses?
3. List uses of GROUP BY Clause?
4. Give the syntax for HAVING Clause?
5. Give the syntax for GROUP BY Clause?
6. What is the format for DATE input?
7. Differentiate char and varchar
8. Differentiate int and number
9. Differentiate int and shortint
10. What is an update anamoly?

SET I
1. Display the total no of books published under each publisher.
2. Display the total no books under each published starting with the title ‘data’.
3. Display the total no of books borrowed in each branch.
4. Display the branch name which has maximum borrower.
5. Display the total no books available under each branch located at “XXXXXX”.
6. Display the total no books borrowed under each branch borrowed after “dd-mm-yyyy”.
7. Display the second highest book publisher.
8. Retrieve no of books borrowed, borrower, and branch id under each location.
9. Display the total no of borrowed books in each branch which have crossed the due date.
10. Display maximum no of books borrowed by “XYZplace” borrower in each branch.

SET II
1. Display total no of books available under each author.
2. Display details of the costliest book.
3. Display the no of customers from each city.
4. Display the customer details who ordered maximum books.
5. Display the no of books ordered by each “XYZlocation” customers.
6. Display the no of books written by each author ordered on “DD-MM-YYYY”.
7. Display the no DBMS book returned after “DD-MM-YYYY”.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
74

8. Display the book details of the costliest book ordered after “DD-MM-YYYY”.
9. Display the no of books under each title shipped so far.
10. Display the no of books returned by each customer under each location.

SET III
1. Display the total no of full time and part time courses.
2. Display the maximum course fee in the both full time and part time courses.
3. Display the minimum course fee which is greater than average course fee.
4. Display the maximum course fee of the part time courses which is greater than the average course fee of
full time courses.
5. Display the no of students in each course.
6. Display the toppers in each course.
7. Display the toppers who are having less 80% attendance.
8. Display the total fee paid under each course.
9. Display the total fee paid under part time course.
10. Display the total fee pending under each course.
11. Display the average fee pain by students in each location.

NESTED QUERIES & QUERIES USING GROUP BY AND OTHER CLAUSES


SAMPLES QUERIES
LEARNING MATERIALS
SET OPERATIONS & OTHER CLAUSES:
NESTED QUERY: - A nested query makes use of another sub-query to compute or retrieve
the information.
UNION - OR
INTERSECT - AND
EXCEPT - NOT
Order by : The order by clause is used to display the results in sorted order.
Group by : The attribute or attributes given in the clauses are used to form groups. Tuples with the
same value on all attributes in the group by clause are placed in one group.
Having: SQL applies predicates (conditions) in the having clause after groups have been formed, so
aggregate function be used.

PROBLEM STATEMENTS:
1. Find the name of the institute in which the person studied and developed the costliest package.

INPUT: SQL> SELECT SPLACE, PNAME FROM STUDY WHERE PNAME = (SELECT PNAME
FROM SOFTWARE
WHERE SCOST = (SELECT MAX (SCOST) FROM SOFTWARE);

OUTPUT:
SPLACE PNAME
------------ -------------
SAHBHARI MARY

2. Find the salary and institute of a person who developed the highest selling package.

INPUT: SQL> SELECT STUDY.PNAME, SAL, SPLACE FROM STUDY, PROGRAMMER WHERE
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
75

STUDY.PNAME = PROGRAMMER.PNAME AND STUDY.PNAME = (SELECT PNAME FROM


SOFTWARE WHERE
SCOST = (SELECT MAX (SCOST) FROM SOFTWARE));

OUTPUT:

PNAM SAL SPLACE


----------- ------ -----------
MARY 4500 SABHARI

3. How many packages were developed by the person who developed the cheapest package.

INPUT: SQL> SELECT PNAME, COUNT (TITLE) FROM SOFTWARE WHERE DCOST = (SELECT
MIN(DCOST) FROM SOFTWARE) GROUP BY PNAME;
RESULT
PNAME COUNT(TITLE)
------------- ----------------------
VIJAY 1

4. Calculate the amount to be recovered for those packages whose development cost has not yet recovered.

INPUT: SQL>SELECT TITLE, (DCOST-SCOST) FROM SOFTWARE WHERE DCOST > SCOST;

5. Display the title, scost, dcost, difference of scost and dcost in the descending order of difference.

INPUT: SQL> SELECT TITLE, SCOST, DCOST, (SCOST - DCOST) FROM SOFTWARE
DESCENDING ORDER BY (SCOST-DCOST);

6. Display the details of those who draw the same salary.

INPUT: SQL> SELECT P.PNAME, P.SAL FROM PROGRAMMER P, PROGRAMMER T WHERE


P.PNAME <>
T.PNAME AND P.SAL = T.SAL;(OR)
INPUT: SQL>SELECT PNAME,SAL FROM PROGRAMMER T WHERE PNAME<>T.PNAME AND
SAL= T.SAL;

7. Display total salary spent for each job category.

INPUT: SQL>SELECT JOB,SUM (SAL) FROM EMP GROUP BY JOB;


OUTPUT:
JOB SUM(SAL)
--------- ----------
ANALYST 6000
CLERK 23050
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
assistant 2200
clerk 2003
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
76

7 rows selected.

8. Display lowest paid employee details under each manager.

INPUT: SQL>SELECT ENAME, SAL FROM EMP WHERE SAL IN (SELECT MIN(SAL) FROM EMP
GROUP BY MGR);
OUTPUT:
ENAME SAL
---------- ----------
CHAI 3
JAMES 950
MILLER 1000
ADAMS 1100
russel 2200
5 rows selected.

9. Display number of employees working in each department and their department name.

INPUT: SQL> SELECT DNAME, COUNT (ENAME) FROM EMP, DEPT WHERE
EMP.DEPTNO=DEPT.DEPTNO
GROUP BY DNAME;

OUTPUT:
DNAME COUNT(ENAME)
-------------- ------------
ACCOUNTING 3
RESEARCH 5
SALES 9

10. Display the sales cost of package developed by each programmer.

INPUT: SQL> SELECT PNAME, SUM(SCOST) FROM SOFTWARE GROUP BY PNAME;

OUTPUT:
PNAME SUM(SCOST)
-------------------- ----------
john 12000
kamala 12000
raju 12333
3 rows selected.

11. Display the number of packages sold by each programmer.

INPUT: SQL>SELECT PNAME, COUNT(TITLE) FROM SOFTWARE GROUP BY PNAME;

OUTPUT:
PNAME COUNT(TITLE)
-------------------- ------------
john 1
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
77

kamala 1
raju 1
ramana 1
rani 1
5 rows selected.

12. Display the number of packages in each language for which the development cost is less than thousand.

INPUT: SQL>SELECT DEVIN, COUNT(TITLE) FROM SOFTWARE WHERE DCOST < 1000 GROUP
BY DEVIN;

OUTPUT:
DEVIN COUNT(TITLE)
---------- ------------
cobol 1

13. Display each institute name with number of students.

INPUT: SQL> SELECT SPLACE, COUNT(PNAME) FROM STUDY GROUP BY SPLACE;


OUTPUT:
SPLACE COUNT(PNAME)
-------------------- ------------
BDPS 2
BITS 1
BNRILLIANI 1
COIT 1
HYD 1
5 rows selected.

13. How many copies of package have the least difference between development and selling cost, were
sold?

INPUT: SQL>select SOLD FROM SOFTWARE WHERE SCOST – DCOST=(SELECT MIN(SCOST –


DCOST) FROM SOFTWARE);

OUTPUT:
SOLD
---------
11

14. Which is the costliest package developed in Pascal.

INPUT: SQL>SELECT TITLE FROM SOFTWARE WHERE DEVIN = ‘PASCAL’ AND DCOST =
(SELECT MAX(DCOST) FROM SOFTWARE WHERE DEVIN = ‘PASCAL’);

OUTPUT:
no rows selected
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
78

15. Which language was used to develop most no .of packages?

INPUT: SQL>SELECT DEVIN, COUNT (*) FROM SOFTWARE GROUP BY DEVIN HAVING
COUNT(*)
= (SELECT MAX(COUNT(*) ) FROM SOFTWARE GROUP BY DEVIN);

OUTPUT:
DEVIN COUNT(*)
---------- ----------
jsp 2
16.Who are the male programmers earning below the average salary of female programmers?

INPUT: SQL>SELECT PNAME FROM PROGRAMMER WHERE SAL < (SELECT AVG(SAL) FROM
PROGRAMMER WHERE SEX = ‘F’) AND SEX = ‘M’;

OUTPUT:
PNAME
--------------------
vijay

17. Display the details of software developed by the male programmers earning more than 3000/-.

INPUT: SQL> SELECT PROGRAMMER.PNAME, TITLE, DEVIN FROM PROGRAMMER,


SOFTWARE WHERE SAL > 3000 AND SEX = ‘M’ AND PROGRAMMER.PNAME
= SOFTWARE.PNAME;

OUTPUT:
no rows selected

18. Display the details of software developed in c language by female programmers of Pragathi.

INPUT: SQL>SELECT SOFTWARE.PNAME, TITLE, DEVIN, SCOST, DCOST, SOLD FROM


PROGRAMMER, SOFTWARE, STUDY WHERE DEVIN = ‘C’ AND SEX =’F’ AND SPLACE =
‘PRAGATHI’ AND PROGRAMMER.PNAME = SOFTWARE.PNAME AND SOFTWARE.PNAME =
STUDY.PNAME;

SET I

1. Find the details of the author who has the maximum no of book copies.
2. Find the details of the author who has the maximum no of book copies in “XXXXX” branch.
3. Find the details of the author whose book has been borrowed in maximum nos.
4. Find the details of the author whose book has been borrowed in maximum nos by customers in the
address “XXXXXX”.
5. Find the details of the borrower whose borrowed duration is the maximum in the particular library
branch “XXXXXX”
6. Display the book details in descending based on no of books.
7. Display maximum no of days borrowed for each title.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
79

SET II

1. Display the book details ordered after the date “XXXXX” by the customers from the address
“YYYYYY”.
2. Display the return details of the costliest book ordered by customers from “XXXXXX” address and
ordered after the date “YYYYY”
3. Find the Maximum, minimum and average price of books returned by “XXXXXXX” customers.
4. Find the cheapest book in each year.
5. Find the details of order of the cheapest books in each year.

Viva Questions
1. What is a nested query?
2. What is join query?
3. Can we give an output of an query as an input to another query?
4. What is Cartesian product?
5. What is spurious tuple?
6. How do restrict duplicates when joining two tables?
7. What is a natural join?
8. Give example for left outer join.
9. Explain about right outer join.
10. What is division operation?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
80

Ex.No:3 VIEWS, SEQUENCES, SYNONYMS

Pre Lab Materials


SQL CREATE VIEW Statement

In SQL, a view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.

You can add SQL functions, WHERE, and JOIN statements to a view and present the data as if the data
were coming from one single table.

CREATE VIEW Syntax

CREATE VIEW view_name AS


SELECT column1,column2, ...
FROM table_name
WHERE condition;

Note: A view always shows up-to-date data! The database engine recreates the data, using the view's SQL
statement, every time a user queries a view.

SQL CREATE VIEW Examples

If you have the Northwind database you can see that it has several views installed by default.

The view "Current Product List" lists all active products (products that are not discontinued) from the
"Products" table. The view is created with the following SQL:

CREATE VIEW [Current Product List] AS


SELECT ProductID, ProductName
FROM Products
WHERE Discontinued = No;

Then, we can query the view as follows:

SELECT * FROM [Current Product List];


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
81

Another view in the Northwind sample database selects every product in the "Products" table with a unit
price higher than the average unit price:

CREATE VIEW [Products Above Average Price] AS


SELECT ProductName, UnitPrice
FROM Products
WHERE UnitPrice > (SELECT AVG(UnitPrice) FROM Products);

We can query the view above as follows:

SELECT * FROM [Products Above Average Price];

Another view in the Northwind database calculates the total sale for each category in 1997. Note that this
view selects its data from another view called "Product Sales for 1997":

CREATE VIEW [Category Sales For 1997] AS


SELECT DISTINCT CategoryName, Sum(ProductSales) AS CategorySales
FROM [Product Sales for 1997]
GROUP BY CategoryName;

We can query the view above as follows:

SELECT * FROM [Category Sales For 1997];

We can also add a condition to the query. Let's see the total sale only for the category "Beverages":

SELECT * FROM [Category Sales For 1997]


WHERE CategoryName = 'Beverages';

SQL Updating a View

You can update a view by using the following syntax:

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS


SELECT column1,column2, ...
FROM table_name
WHERE condition;

Now we want to add the "Category" column to the "Current Product List" view. We will update the view
with the following SQL:
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
82

CREATE OR REPLACE VIEW [Current Product List] AS


SELECT ProductID, ProductName, Category
FROM Products
WHERE Discontinued = No;
SQL Dropping a View

You can delete a view with the DROP VIEW command.

SQL DROP VIEW Syntax

DROP VIEW view_name;


SQL CREATE INDEX Statement
SQL CREATE INDEX Statement

The CREATE INDEX statement is used to create indexes in tables.

Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are just
used to speed up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without (because the indexes
also need an update). So, only create indexes on columns that will be frequently searched against.

CREATE INDEX Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax

Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

Note: The syntax for creating indexes varies among different databases. Therefore: Check the syntax for
creating indexes in your database.

CREATE INDEX Example

The SQL statement below creates an index named "idx_lastname" on the "LastName" column in the
"Persons" table:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
83

CREATE INDEX idx_lastname


ON Persons (LastName);

If you want to create an index on a combination of columns, you can list the column names within the
parentheses, separated by commas:

CREATE INDEX idx_pname


ON Persons (LastName, FirstName);
DROP INDEX Statement

The DROP INDEX statement is used to delete an index in a table.

MS Access:

DROP INDEX index_name ON table_name;

SQL Server:

DROP INDEX table_name.index_name;

DB2/Oracle:

DROP INDEX index_name;

MySQL:

ALTER TABLE table_name


DROP INDEX index_name;

CREATE SYNONYM

Purpose

Use the CREATE SYNONYM statement to create a synonym, which is an alternative name for a table,
view, sequence, procedure, stored function, package, materialized view, Java class schema object, user-
defined object type, or another synonym.

Synonyms provide both data independence and location transparency. Synonyms permit applications to
function without modification regardless of which user owns the table or view and regardless of which
database holds the table or view. However, synonyms are not a substitute for privileges on database
objects. Appropriate privileges must be granted to a user before the user can use the synonym.

You can refer to synonyms in the following DML statements:

SELECT, INSERT, UPDATE, DELETE, FLASHBACK TABLE, EXPLAIN PLAN, and LOCK TABLE.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
84

You can refer to synonyms in the following DDL statements: AUDIT, NOAUDIT, GRANT, REVOKE,
and COMMENT.

Prerequisites

To create a private synonym in your own schema, you must have the CREATE SYNONYM system
privilege.

To create a private synonym in another user's schema, you must have


the CREATE ANY SYNONYM system privilege.

To create a PUBLIC synonym, you must have the CREATE PUBLIC SYNONYM system privilege.

Examples

CREATE SYNONYM: Examples To define the synonym offices for the table locations in the schema hr,
issue the following statement:

CREATE SYNONYM offices

FOR hr.locations;

To create a PUBLIC synonym for the employees table in the schema hr on the remote database, you could
issue the following statement:

CREATE PUBLIC SYNONYM emp_table

FOR hr.employees@remote.us.oracle.com;

A synonym may have the same name as the underlying object, provided the underlying object is contained
in another schema.

Oracle Database Resolution of Synonyms: Example Oracle Database attempts to resolve references to
objects at the schema level before resolving them at the PUBLIC synonym level. For example, the
schemas oe and sh both contain tables named customers. In the next example, user SYSTEM creates
a PUBLIC synonym named customers foroe.customers:

CREATE PUBLIC SYNONYM customers FOR oe.customers;

If the user sh then issues the following statement, then the database returns the count of rows
from sh.customers:

SELECT COUNT(*) FROM customers;


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
85

To retrieve the count of rows from oe.customers, the user sh must preface customers with the schema
name. (The user sh must have select permission on oe.customers as well.)

SELECT COUNT(*) FROM oe.customers;

If the user hr's schema does not contain an object named customers, and if hr has select permission
on oe.customers, then hr can access thecustomers table in oe's schema by using the public
synonym customers:

SELECT COUNT(*) FROM customers;

CREATE SEQUENCE

Purpose

Use the CREATE SEQUENCE statement to create a sequence, which is a database object from which
multiple users may generate unique integers. You can use sequences to automatically generate primary key
values.

When a sequence number is generated, the sequence is incremented, independent of the transaction
committing or rolling back. If two users concurrently increment the same sequence, then the sequence
numbers each user acquires may have gaps, because sequence numbers are being generated by the other
user. One user can never acquire the sequence number generated by another user. After a sequence value is
generated by one user, that user can continue to access that value regardless of whether the sequence is
incremented by another user.

Sequence numbers are generated independently of tables, so the same sequence can be used for one or for
multiple tables. It is possible that individual sequence numbers will appear to be skipped, because they
were generated and used in a transaction that ultimately rolled back. Additionally, a single user may not
realize that other users are drawing from the same sequence.

After a sequence is created, you can access its values in SQL statements with
the CURRVAL pseudocolumn, which returns the current value of the sequence, or
the NEXTVAL pseudocolumn, which increments the sequence and returns the new value.

Semantics

schema

Specify the schema to contain the sequence. If you omit schema, then Oracle Database creates the sequence
in your own schema.

sequence

Specify the name of the sequence to be created.


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
86

If you specify none of the following clauses, then you create an ascending sequence that starts with 1 and
increases by 1 with no upper limit. Specifying only INCREMENT BY -1 creates a descending sequence
that starts with -1 and decreases with no lower limit.

• To create a sequence that increments without bound, for ascending sequences, omit
the MAXVALUE parameter or specify NOMAXVALUE. For descending sequences, omit
the MINVALUE parameter or specify the NOMINVALUE.
• To create a sequence that stops at a predefined limit, for an ascending sequence, specify a value for
the MAXVALUE parameter. For a descending sequence, specify a value for the MINVALUE parameter.
Also specify NOCYCLE. Any attempt to generate a sequence number once the sequence has reached its
limit results in an error.
• To create a sequence that restarts after reaching a predefined limit, specify values for both
the MAXVALUE and MINVALUE parameters. Also specify CYCLE. If you do not specify MINVALUE,
then it defaults to NOMINVALUE, which is the value 1.

INCREMENT BY Specify the interval between sequence numbers. This integer value can be any positive
or negative integer, but it cannot be 0. This value can have 28 or fewer digits. The absolute of this value
must be less than the difference of MAXVALUE and MINVALUE. If this value is negative, then the
sequence descends. If the value is positive, then the sequence ascends. If you omit this clause, then the
interval defaults to 1.

START WITH Specify the first sequence number to be generated. Use this clause to start an ascending
sequence at a value greater than its minimum or to start a descending sequence at a value less than its
maximum. For ascending sequences, the default value is the minimum value of the sequence. For
descending sequences, the default value is the maximum value of the sequence. This integer value can have
28 or fewer digits.

Note:
This value is not necessarily the value to which an ascending cycling sequence cycles after reaching its
maximum or minimum value.

MAXVALUE Specify the maximum value the sequence can generate. This integer value can have 28 or
fewer digits. MAXVALUE must be equal to or greater thanSTART WITH and must be greater
than MINVALUE.

NOMAXVALUE Specify NOMAXVALUE to indicate a maximum value of 1027 for an ascending


sequence or -1 for a descending sequence. This is the default.

MINVALUE Specify the minimum value of the sequence. This integer value can have 28 or fewer
digits. MINVALUE must be less than or equal to START WITH and must be less than MAXVALUE.

NOMINVALUE Specify NOMINVALUE to indicate a minimum value of 1 for an ascending sequence or


-1026 for a descending sequence. This is the default.

CYCLE Specify CYCLE to indicate that the sequence continues to generate values after reaching either
its maximum or minimum value. After an ascending sequence reaches its maximum value, it generates its
minimum value. After a descending sequence reaches its minimum, it generates its maximum value.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
87

NOCYCLE Specify NOCYCLE to indicate that the sequence cannot generate more values after reaching
its maximum or minimum value. This is the default.

CACHE Specify how many values of the sequence the database preallocates and keeps in memory for
faster access. This integer value can have 28 or fewer digits. The minimum value for this parameter is 2.
For sequences that cycle, this value must be less than the number of values in the cycle. You cannot cache
more values than will fit in a given cycle of sequence numbers. Therefore, the maximum value allowed
for CACHE must be less than the value determined by the following formula:

(CEIL (MAXVALUE - MINVALUE)) / ABS (INCREMENT)

If a system failure occurs, then all cached sequence values that have not been used in committed DML
statements are lost. The potential number of lost values is equal to the value of the CACHE parameter.

Note:
Oracle recommends using the CACHE setting to enhance performance if you are using sequences in an
Oracle Real Application Clusters environment.

NOCACHE Specify NOCACHE to indicate that values of the sequence are not preallocated. If you omit
both CACHE and NOCACHE, then the database caches 20 sequence numbers by default.

ORDER Specify ORDER to guarantee that sequence numbers are generated in order of request. This
clause is useful if you are using the sequence numbers as timestamps. Guaranteeing order is usually not
important for sequences used to generate primary keys.

ORDER is necessary only to guarantee ordered generation if you are using Oracle Real Application
Clusters. If you are using exclusive mode, then sequence numbers are always generated in order.

NOORDER Specify NOORDER if you do not want to guarantee sequence numbers are generated in order
of request. This is the default.

Example

Creating a Sequence: Example The following statement creates the sequence customers_seq in the
sample schema oe. This sequence could be used to provide customer ID numbers when rows are added to
the customers table.

CREATE SEQUENCE customers_seq

START WITH 1000

INCREMENT BY 1

NOCACHE

NOCYCLE;

The first reference to customers_seq.nextval returns 1000. The second returns 1001. Each subsequent
reference will return a value 1 greater than the previous reference.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
88

DROP SEQUENCE

Purpose

Use the DROP SEQUENCE statement to remove a sequence from the database.

You can also use this statement to restart a sequence by dropping and then re-creating it. For example, if
you have a sequence with a current value of 150 and you would like to restart the sequence with a value of
27, then you can drop the sequence and then re-create it with the same name and aSTART WITH value of
27.

Example

Dropping a Sequence: Example The following statement drops the sequence customers_seq owned by
the user oe, which was created in "Creating a Sequence: Example". To issue this statement, you must either
be connected as user oe or have the DROP ANY SEQUENCE system privilege:

DROP SEQUENCE oe.customers_seq;

ALTER SEQUENCE

Purpose

Use the ALTER SEQUENCE statement to change the increment, minimum and maximum values, cached
numbers, and behavior of an existing sequence. This statement affects only future sequence numbers.

Examples

Modifying a Sequence: Examples This statement sets a new maximum value for
the customers_seq sequence, which was created in "Creating a Sequence: Example":

ALTER SEQUENCE customers_seq

MAXVALUE 1500;

This statement turns on CYCLE and CACHE for the customers_seq sequence:

ALTER SEQUENCE customers_seq

CYCLE

CACHE 5;

Finding the next value of a sequence: Example This example selects the next value of the employee
sequence in the sample schema hr:

SELECT employees_seq.nextval

FROM DUAL;
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
89

Inserting sequence values into a table: Example This example increments the employee sequence and
uses its value for a new employee inserted into the sample table hr.employees:

INSERT INTO employees

VALUES (employees_seq.nextval, 'John', 'Doe', 'jdoe',

'555-1212', TO_DATE(SYSDATE), 'PU_CLERK', 2500, null, null,

30);

Reusing the current value of a sequence:

Example This example adds a new order with the next order number to the master order table. It then adds
suborders with this number to the detail order table:

INSERT INTO orders (order_id, order_date, customer_id)

VALUES (orders_seq.nextval, TO_DATE(SYSDATE), 106);

INSERT INTO order_items (order_id, line_item_id, product_id)

VALUES (orders_seq.currval, 1, 2359);

INSERT INTO order_items (order_id, line_item_id, product_id)

VALUES (orders_seq.currval, 2, 3290);

INSERT INTO order_items (order_id, line_item_id, product_id)

VALUES (orders_seq.currval, 3, 2381);

Pre Lab Questions:

1. List significance of views.

2. Give the syntax for synonym.

3. How do you alter a sequence?

4. List the advantages of sequence.

5. What is meant by CACHE and NOCACHE?

6. How do you alter a sequence?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
90

7. What is the use of CYCLE?

8. How do you drop a sequence?

9. How to delete a view?

10. What is difference between ORDER and NOORDER?

Problem Statements:

1. Create a view from single table containing all columns from the base table.

2. Create a view from single table with selected columns.

3. Create a view from two tables with all columns.

4. Create a view from two tables with selected columns.

5. Use DML operations (insert,delete,update) on the above created views.

6. Create a synonym for a table created by other user.

7. Use DML operations (insert,delete,update) on the above created synonym.

8. Create a sequence to generate unique value for empid field in the employee table while inserting.

9. Create a sequence for SSN of Employee table.

10. Use sequence in DML .

11. Alter the sequence.

12. Drop the sequence.

Viva Questions:

1. Give an example for multiple table views

2. Can we alter a sequence?

3. Give the syntax for dropping a sequence

4. Can we use DML on synonyms?

5. What are the advantages of synonyms?

6. How do you generate unique values?

7. How to perform DML operations in a view?

8. How to create multiple table views?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
91

9. Are views are temporary?

10. Whether the changes made in views affect the table?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
92

Ex.No: 4 Oracle PL/SQL Cursor: Implicit, Explicit, Cursor FOR Loop [Example]

LEARNING MATERILA

What is CURSOR in PL/SQL?

A Cursor is a pointer to this context area. Oracle creates context area for processing an SQL statement
which contains all information about the statement.

PL/SQL allows the programmer to control the context area through the cursor. A cursor holds the rows
returned by the SQL statement. The set of rows the cursor holds is referred as active set. These cursors
can also be named so that they can be referred from another place of the code.

In this tutorial you will learn-

• Implicit Cursor

• Explicit Cursor

• Cursor Attributes

• FOR Loop Cursor statement

The cursor is of two types.

• Implicit Cursor

• Explicit Cursor

Implicit Cursor

Whenever any DML operations occur in the database, an implicit cursor is created that holds the rows
affected, in that particular operation. These cursors cannot be named and, hence they cannot be controlled
or referred from another place of the code. We can refer only to the most recent cursor through the cursor
attributes.

Explicit Cursor

Programmers are allowed to create named context area to execute their DML operations to get more
control over it. The explicit cursor should be defined in the declaration section of the PL/SQL block, and
it is created for the 'SELECT' statement that needs to be used in the code.

Below are steps that involved in working with explicit cursors.

• Declaring the cursor

Declaring the cursor simply means to create one named context area for the 'SELECT' statement that is
defined in the declaration part. The name of this context area is same as the cursor name.

• Opening Cursor

Opening the cursor will instruct the PL/SQL to allocate the memory for this cursor. It will make the
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
93

cursor ready to fetch the records.

• Fetching Data from the Cursor

In this process, the 'SELECT' statement is executed and the rows fetched is stored in the allocated
memory. These are now called as active sets. Fetching data from the cursor is a record-level activity that
means we can access the data in a record-by-record way.

Each fetch statement will fetch one active set and holds the information of that particular record. This
statement is same as 'SELECT' statement that fetches the record and assigns to the variable in the 'INTO'
clause, but it will not throw any exceptions.

• Closing the Cursor

Once all the record is fetched now, we need to close the cursor so that the memory allocated to this
context area will be released.

Syntax:

DECLARE

CURSOR <cursor_name> IS <SELECT statement^>

<cursor_variable declaration>

BEGIN

OPEN <cursor_name>;

FETCH <cursor_name> INTO <cursor_variable>;

CLOSE <cursor_name>;

END;

• In the above syntax, the declaration part contains the declaration of the cursor and the cursor variable in
which the fetched data will be assigned.

• The cursor is created for the 'SELECT' statement that is given in the cursor declaration.

• In execution part, the declared cursor is opened, fetched and closed.

Cursor Attributes

Both Implicit cursor and the explicit cursor has certain attributes that can be accessed. These attributes
give more information about the cursor operations. Below are the different cursor attributes and their
usage.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
94

Cursor Description
Attribute

%FOUND It returns the Boolean result 'TRUE' if the most recent fetch
operation fetched a record successfully, else it will return FALSE.

%NOTFOUND This works oppositely to %FOUND it will return 'TRUE' if the most
recent fetch operation could not able to fetch any record.

%ISOPEN It returns Boolean result 'TRUE' if the given cursor is already


opened, else it returns 'FALSE'

%ROWCOUNT It returns the numerical value. It gives the actual count of records
that got affected by the DML activity.
Example 1: In this example, we are going to see how to declare, open, fetch and close the explicit cursor.

We will project all the employee's name from emp table using a cursor. We will also use cursor attribute
to set the loop to fetch all the record from the cursor.

DECLARE

CURSOR guru99_det IS SELECT emp_name FROM emp;

lv_emp_name emp.emp_name%type;

BEGIN

OPEN guru99_det;
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
95

LOOP

FETCH guru99_det INTO lv_emp_name;

IF guru99_det%NOTFOUND

THEN

EXIT;

END IF;

Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name);

END LOOP;

Dbms_output.put_line(‘Total rows fetched is‘||guru99_det%R0WCOUNT);

CLOSE guru99_det;

END:

Output

Employee Fetched:BBB

Employee Fetched:XXX

Employee Fetched:YYY

Total rows fetched is 3

Code Explanation:

• Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM emp'.

• Code line 3: Declaring variable lv_emp_name.

• Code line 5: Opening the cursor guru99_det.

• Code line 6: Setting the Basic loop statement to fetch all the records in the 'emp' table.

• Code line 7: Fetches the guru99_det data and assign the value to lv_emp_name.

• Code line 9: Using the cursor attribute '%NOTFOUND' to find whether all the record in the cursor
is fetched. If fetched then it will return 'TRUE' and control will exit from the loop, else the control
will keep on fetching the data from the cursor and print the data.

• Code line 11: EXIT condition for the loop statement.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
96

• Code line 12: Print the fetched employee name.

• Code line 14: Using the cursor attribute '%ROWCOUNT' to find the total number of records that got
affected/fetched in the cursor.

• Code line 15: After exiting from the loop the cursor is closed and the memory allocated is set free.

FOR Loop Cursor statement

"FOR LOOP" statement can be used for working with cursors. We can give the cursor name instead of
range limit in the FOR loop statement so that the loop will work from the first record of the cursor to the
last record of the cursor. The cursor variable, opening of cursor, fetching and closing of the cursor will be
done implicitly by the FOR loop.

Syntax:

DECLARE

CURSOR <cursor_name> IS <SELECT statement>;

BEGIN

FOR I IN <cursor_name>

LOOP

END LOOP;

END;

• In the above syntax, the declaration part contains the declaration of the cursor.

• The cursor is created for the 'SELECT' statement that is given in the cursor declaration.

• In execution part, the declared cursor is setup in the FOR loop and the loop variable 'I' will behave as
cursor variable in this case.

Example 1: In this example, we will project all the employee name from emp table using a cursor-FOR
loop.

DECLARE

CURSOR guru99_det IS SELECT emp_name FROM emp;

BEGIN

FOR lv_emp_name IN guru99_det

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
97

LOOP

Dbms_output.put_line(‘Employee Fetched:‘||lv_emp_name);

END LOOP;

END;

Output

Employee Fetched:BBB

Employee Fetched:XXX

Employee Fetched:YYY

Code Explanation:

• Code line 2: Declaring the cursor guru99_det for statement 'SELECT emp_name FROM emp'.

• Code line 4: Constructing the 'FOR' loop for the cursor with the loop variable lv_emp_name.

• Code line 5: Printing the employee name in each iteration of the loop.

• Code line 8: Exit the loop

Note: In Cursor-FOR loop, cursor attributes cannot be used since opening, fetching and closing of the
cursor is done implicitly by FOR loop.

Pre Lab Questions:

1. What is a PL SQL Cursor?

2. Define explicit cursor

3. Give the significance of implicit cursor

4. What is For Loop cursor statement?

5. Give the advantages and applications of cursors in a DB.

6. Give the syntax for PL SQL for loop.

7. Give the syntax for PL SQL function.

8. Give the syntax for PL SQL while loop?

9. How do you declare a variable?

10. How do you start a block?


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
98

Problem Statements:

1. Write a PL SQL cursor block to update the due date of the book_loans table for those who have
borrowed books after the date “XXXXX” and display no rows affected.

2. Copy customers table using PL SQL cursors.

3. Implement PL SQL cursor while,for loops and %ROWCOUNT to count the no of rows affected
by the following operations

i. Update the book quantity

ii. Increase the course fee for a particular department.

Viva questions:

1. What does %FOUND returns?

2. How do you use %ISOPEN?

3. Write a sample code for %ROWCOUNT.

4. Differentiate STOP and END.

5. How do you use CURSOR key word?

6. Differentiate END and END LOOP.

7. Differentiate for and while loop in PL SQL.

8. What is a preprocessor?

9. What is a PL SQL compiler?

10. What doo you mean by PL SQL tokens and keywords?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
99

Ex.No:5. . Procedures and Functions


PROCEDURES
LEARNING MATERIAL:
An Oracle stored procedure is a program stored in an Oracle database. The following are the
advantages of using procedures.
Better performance: Oracle stored procedures load once into the shared pool and remain there
unless they become paged out. Subsequent executions of the Oracle stored procedure are far faster than
executions of external code.
Coupling of data with behaviour: DBAs can use naming conventions to couple relational tables
with the behaviors associated with a table by using Oracle stored procedures as "methods". If all
behaviors associated with the employee table are prefixed with the table name--employee.hire,
employee.give_raise, for example--the data dictionary can be queries to list all behaviors associated with
a table (select * from dba_objects where owner = 'EMPLOYEE'), and it's easy to identify and reuse code
via stored procedures.
Isolation of code: Since all SQL is moved out of the external programs and into the Oracle stored
procedures, the application programs become nothing more than calls to Oracle stored procedures. As
such, it becomes very simple to swap out one database and swap in another one.
SYNTAX:
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
procedure_body
EXCEPTION
Exception handling
END procedure_name
IN - The parameter can be referenced by the procedure or function. The value of the parameter cannot be
overwritten by the procedure or function.
OUT - The parameter cannot be referenced by the procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can
be overwritten by the procedure or function.
Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
100

Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that the
PL/SQL Blocks terminates gracefully.
If the PL/SQL Block contains exceptions that cannot be handled, the Block terminates abruptly with
errors.
PRELAB QUESTIONS
1. What is a stored procedure?
2. What is a stand-alone procedure?
3. What are the modes of parameters that can be passed to a procedure?
4. How to find the list of procedures that were available in the database?
5. What are the purposes of stored procedure?
6. Give the syntax of procedure
7. How a procedure can be executed?
8. Give the syntax for procedure.
9. What is meant by REPLACE procedure?
10. Differentiate IN and OUT

SAMPLE EXERCISE
REFERRED TABLES:
Borrow(acc_no , rollno, date_issue);
1. Write a procedure to insert a record in borrower relation. Before inserting check whether the book is
available or not.
Procedure
CREATE OR REPLACE PROCEDURE PROC_BORROW(ACCNO NUMBER, ROLL VARCHAR,
DOI DATE)
IS
CNT NUMBER(5);
BEGIN
SELECT COUNT(*) INTO CNT FROM BORROW WHERE ACC_NO=ACCNO;
IF(CNT=0)
THEN
INSERT INTO BORROW VALUES (ACCNO,ROLL,DOI);
ELSE
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
101

DBMS_OUTPUT.PUT_LINE(‘BOOK NOT AVAILABLE’);


END IF;
END;
OUTPUT:
SQL> @ e:\proc.sql;
Procedure Created.
SQL> exec pro1(‘123’,’CS01’,’27-OCT-2013’);
Procedure successfully completed.
SQL> SELECT * FROM BORROW;

ACC_NO ROLLNO DOI


---------- ------------ ------------
123 CS01 27-OCT-2013
128 CS10 18-OCT-2013
2. Write a procedure to insert a record in borrower relation with the above constraints and also ensure that
the member has not borrowed more than three books.
Procedure
CREATE OR REPLACE PROCEDURE PROC_BORROW(ACCNO NUMBER, ROLL VARCHAR,
DOI DATE)
IS
CNT NUMBER(5);
BEGIN
SELECT COUNT(*) INTO CNT FROM BORROW WHERE ACC_NO=ACCNO;
IF(CNT=0)
THEN
SELECT COUNT(*) INTO CNT1 FROM BORROW WHERE ROLLNO=ROLL;
IF(CNT1<4)
THEN
INSERT INTO BORROW VALUES (ACCNO,ROLL,DOI);
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE(‘BOOK NOT AVAILABLE’);
END IF;
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
102

END;

OUTPUT:
SQL> @ e:\proc.sql;
Procedure Created.
STUDENT EXERCISE
1. Consider the relations PASSENGER (PID, PNAME, DOB, GENDER)
BOOK_TICKET (PID, ROUTENO, JOURNEY_DATE, SEAT_NO)
Create a PL / SQL stored procedure that accepts journey_date and displays list of passengers booked
ticket on that date.
2. Consider the following employee and department tables.
EMPLOYEE(empno, ename, designation, manager, hiredate, salary, commission,deptno)
Write a procedure to update the salaries by given amount
3. Consider the following relations for a transport management system application:
BUS (ROUTENO, SOURCE, DESTINATION)
DRIVER (DID, DNAME, DOB, GENDER)
ASSIGN_ROUTE (DID, ROUTENO, JOURNEY_DATE)
Create a procedure that displays the details of all drivers
4. Consider the following relations for a transport management system application:
DRIVER (DCODE, DNAME, DOB, GENDER)
CITY (CCODE, CNAME)
TRUCK (TRUCKCODE, TTYPE)
DRIVE_TRUCK (TRUCKCODE, DCODE, DOT, CCODE)
Create a procedure that displays the details of all drivers, the truck_code and DOT.
5. BOOK (BOOKID, TITLE, PUBLISHERCODE, NO_OF_COPIES)
AUTHOR (AUTHORID, AUTHOR_NAME)
BOOK_AUTHOR (BOOKID, AUTHORID)
BOOK_LOAN (BOOK_ID, CARDNO, DATEOUT, DUEDATE, STATUS)
Create a procedure named Author_Details that accepts the BookID and displays the authorID, author
name and also the status of the book.
6. Consider the following Staff relational schema:
STAFF (STAFFNO, NAME, DOB, GENDER, DOJ, DESIGNATION, BASIC_PAY, DEPTNO).

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
103

Develop a procedure Staff_Increment that will accept staff number and increment amount as input and
update the basic pay of the staff in the staff table.
7. Consider the following relational schema for a company database application:
EMPLOYEE (ENO, NAME, GENDER, DOB, DOJ, DESIGNATION, BASIC, DEPT_NO, PAN,
SENO)
Develop a procedure Staff_Increment that will accept staff number and increment amount as input and
update the basic pay of the staff in the staff table.
8. Consider the following relational schema for a Product Sales database application:
Product (Prodid, Prodesc, Price, Stock)
Purchase (Purid, Proid, qty, supplierName)
Sales (Saleid, Proid, qty, custname)
Develop a procedure named Product_Sales that accepts a prodid and displays all the sales and purchase
records of it
9. Consider the following relational schema for a Loan database application:
Customer (Custid, Custname, Age, phno)
HLoan (HLoanid, Amount, Custid)
VLoan (VLoanid, Amount, Custid)
Develop a procedure named Customer_Loan which accepts HLoanid as input and displays Custid,
CustName and loan_amount of HLoan
10. Consider the following relational schema for a Loan database application:
Customer (Custid, Custname, Addr, phno,pan_no)
Loan (Loanid, Amount, Interest,Custid)
Account (Accid, Accbal, Custid)
Develop a procedure named Customer_Loan that displays all the loan details
VIVA QUESTIONS:
1. What are advantages of Stored Procedures?
2. What is the difference between OUT and INOUT parameter?
3. What is the difference between IN and OUT parameter?
4. What is use of exception block?
5. IS exception block optional?
6. What is the use of IS /AS keywords?
7. How do you run a procedure?
8. What are the significances of a procedure?
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
104

9. Give the syntax for IF ELSE


10. What do you mean by THEN keyword?

FUNCTIONS
PRELAB MATERIAL
PL/SQL FUNCTION:
A PL/SQL function is same as a procedure except that it returns a value. A standalone function is created
using the CREATE FUNCTION statement.
SYNTAX
CREATE [OR REPLACE] FUNCTION function_name (parameter_name [IN | OUT | IN OUT] type [,
...])
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
return_variable;
EXCEPTION
exception section
END;

Return Type: The header section defines the return type of the function. The return datatype can be any of
the oracle datatype like varchar, number etc. The execution and exception section both should return a
value which is of the datatype defined in the header section.
IN - The parameter can be referenced by the procedure or function. The value of the parameter cannot be
overwritten by the procedure or function.
OUT - The parameter cannot be referenced by the procedure or function, but the value of the parameter can
be overwritten by the procedure or function.
IN OUT - The parameter can be referenced by the procedure or function and the value of the parameter can
be overwritten by the procedure or function.
Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.
Exception Section: The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be handled in this section, so that
the PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
105

handled, the Block terminates abruptly with errors


The major difference between a procedure and a function is, a function must always return a value, but a
procedure may or may not return a value.
PRELAB QUESTIONS:
1. What is difference between a PROCEDURE & FUNCTION?.
2. How do we call a function normally?
3. Give the basic structure of function definition.
4. What is the difference between OUT and INOUT parameter?
5. What is the difference between IN and INOUT parameter?
6. What is use of exception block?
7. What do you mean by return type?
8. List significances of a function.
9. How do you execute a function?
10. Give the syntax for PL SQL exception.
SAMPLE EXERCISE
REFERRED TABLES:
Transaction (accno number(5), amount number(7,2), trans_type varchar(5),dot date);
1. Create a function to insert the records into the transaction table, after performing each transaction in the
transaction table show the net balance of the particular account.
CREATE OR REPLACE FUNCTION FUNC_TRANS (ACC_ID NUMBER,AMNT NUMBER,TYPE
VARCHAR)
RETURN NUMBER
IS
BALANCE NUMBER;
BEGIN
INSERT INTO TRANSACTION VALUES(ACC_ID,AMNT,TYPE);
SELECT SUM(AMNT) INTO BALANCE FROM TRANSACTION WHERE
ACC_NO=ACC_ID;
RETURN BALANCE;
END;

PL/SQL FUNCTION:
DECLARE
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
106

BALANCE_AMNT NUMBER(6);
ACC_NO VARCHAR(5);
AMNT NUMBER(5);
TYPE VARCHAR(2);
RESULT NUMBER(5);
BEGIN
ACC_NO:=’&ACC_NO’;
AMNT:=’&AMNT’;
TYPE:=’&TYPE’;
BALANCE_AMNT:=FUNC1(ACC_ID,AMNT,TYPE);
DBMS_OUTPUT.PUT_LINE(‘TOTAL AMOUNT ‘|| TOTAL_AMNT);
END;

OUTPUT:
SQL> @E:\SQL\FUNCPLSQL.SQL;
Enter value for accno: 001
Enter value for amt: 25000
Enter value for type=’CRDT’
RESULT 26000
PL/SQL procedure successfully completed.

STUDENT EXERCISE
1. Consider the relation stu_details (reg_no, stu_name, DOB, address, city). Write a pl/sqlprogram to find
the address of a particular student using functions.
2. Consider the relation mark_details (reg_no, mark1, mark2, mark3, total). Write a pl/sql program to find
the sum &avg marks of all the student using procedures.
3. For the relation emp_details (emp_no, emp_name, DOB, address, doj, mobile_no, dept_no, salary). Write
a pl/sql program to display the salary of a particular employee using functions
4. Consider the relation Phone_book(ph_no,name,door_no,street,place). Write a pl/sql program to find the
address of a particular customer using functions.
5. Consider the relations SAILOR (SID, NAME, DOB, GENDER)
BOAT (BID, BTYPE, BNAME, COLOR)
SAILS (SID, BID, DOT, SHIFT)
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
107

Create a PL / SQL stored function that accepts SID and returns the name of sailor
6. Consider the following relations for an order processing application:
CUSTOMER (CID, NAME)
PRODUCT (PCODE, PNAME, UNIT_PRICE)
CUST_ORDER (OCODE, ODATE, CID)
ORDER_PRODUCT (OCODE, PCODE, NOU)
Create a function that accepts PCODE, Unit_Price and NOU. Calculate the total_cost
of the ordered product. Return the total_cost.
7. Consider the following relational schema for a Loan database application:
Customer (Custid, Custname, Age, phno)
Loan (Loanid, Amount, Custid)
Develop a function named Customer_Loan which accepts Loanid as input and displays
Custid, CustName and loan_amount.

VIVA QUESTIONS:
1. How a function can be called from a SELECT statement?
2. Can function return a value?
3. Name the tables where the characteristics of functions are stored?
4. How many values can be returned by functions
5. Is it possible to create recursive function?
6. What is a stored procedure?
7. How do you define a stored procedure data type?
8. How do you print your output?
9. What is a comment?
10. What is an execution block?

Ex.No:6. TRIGGERS

PL/SQL TRIGGERS:
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers
are, in fact, written to be executed in response to any of the following events:
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
108

A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).


Triggers could be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
Synchronous replication of tables
Imposing security authorizations
Preventing invalid transactions.

SYNTAX:
CREATE OR REPLACE TRIGGER < trigger_name >
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name]
ON < table_name >
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN < condition >
DECLARE
< Declaration-statements >
BEGIN
< Executable-statements >
EXCEPTION
< Exception-handling-statements >
END;
A typical trigger has 3 main components
1. Triggering SQL Statement: - This is the DML statement which causes the triggers to be invoked. That
is it tells when to call the trigger – before or after, on which DML statement of the table – INSERT/
UPDATE/ DELETE and whether to call trigger when whole table is processed or only few columns are
processed. BEFORE and AFTER is used on tables and INSTEAD OF is used on views to create triggers.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
109

2. Trigger Restriction: - This is the part of trigger which tells how many times the trigger needs to be
executed. It informs, if the trigger has to be called for each row insert /update/delete, or only once for the
transaction.
3. Trigger Action: - This part will actually perform set of transaction as result of original DML statement.
PRELAB QUESTIONS:
1. What is trigger in oracle?
2. What are the various types of triggers?
3. How the triggers are attached to the table?
4. Describe triggers features and limitations.
5. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database
Trigger? Why?
6. What are cascading triggers?
7. Compare Triggers vs. Declarative Integrity Constraints
8. What are the uses of trigger restriction?
9. What is a trigger action?
10. How do you use a trigger BEFORE statement?
SAMPLE EXERCISE
REFERRED TABLES:
Account ( accnt_no,cst_id,acnt_type,last_trans_date,balance )
Account_bckup(accnt_no,last_trans_date,balance)
Loan (ln_id,cst_id,ln_amount,ln_date);
1. Create a trigger for Account relation such that whenever a record is inserted in the Account table
the same record also gets inserted in the backup table.
CREATE OR REPLACE TRIGGER TRIG_ACNT_BCKUP AFTER INSERT ON ACCOUNT
FOR EACH ROW
DECLARE
BEGIN
INSERT INTO ACCOUNT_BCKUP VALUES (:NEW.ACCNT_NO, :NEW.LAST_TRANS_DATE,
:NEW.BALANCE);
END;
OUTPUT:
SQL> @e:/plsql/accnt_trig.sql
Trigger Created.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
110

SQL> INSERT INTO ACCOUNT VALUES (‘AC010’,’CST011’,’SVNG’,’27-AUG-2013’,12000);


1 Row inserted.
SQL> SELECT * FROM ACCOUNT_BCKUP;
ACCNO LAST_TRANS_DATE BALANCE
---------- ------------------------- --------------
AC010 27-AUG-2013 12,000

2. Create a trigger for account relation such that whenever account record is inserted in account
relation with negative relation then that record should also be inserted in the loan relation with positive
balance.
CREATE OR REPLACE TRIGGER TRIG_LOAN AFTER INSERT ON ACCOUNT
FOR EACH ROW
DECLARE
BEGIN
IF(:NEW.BALANCE<0)
THEN
INSERT INTO LOAN VALUES (:NEW.ACCNT_NO, :NEW.CST_ID, -(:NEW.BALANCE),
SYSDATE);
END IF;
END;

OUTPUT:
SQL> @e:/plsql/loan_trig.sql
Trigger Created.
SQL> INSERT INTO ACCOUNT VALUES (‘AC011’,’CST011’,’SVNG’,’27-DEC-2013’,-8000);
1 Row inserted.
SQL> SELECT * FROM LOAN;
LN_ID CST_ID LN_AMOUNT LN_DATE
---------- ------------- -------------- -----------------
AC010 CST011 8000 30-DEC-2013

STUDENT EXERCISE

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
111

1. Consider the table EMPLOYEE(empno, ename, designation, manager, hiredate, salary, commission,
deptno). Write a trigger to ensure that salary of an employee is always greater than the commission.
2. Consider the following relational schema for a banking database application:
CUSTOMER (CID, CNAME)
BRANCH (BCODE, BNAME)
ACCOUNT (ANO, ATYPE, BALANCE, CID, BCODE)
An account can be a savings account or a current account. Check ATYPE in ‘S’ or
‘C’. A customer can have both types of accounts.
TRANSACTION (TID, ANO, TTYPE, TDATE, TAMOUNT)
TTYPE CAN BE ‘D’ OR ‘W’
D- Deposit; W – Withdrawal
Develop a database trigger that will update the value of BALANCE in ACCOUNT table
when a record is inserted in the transaction table. Consider the following cases:
i. If TTYPE =’D’ the value of BALANCE in the ACCOUNT table must be
incremented by the value of TAMOUNT
ii. If TTYPE =’W’ the value of BALANCE in the ACCOUNT table must be
decremented by the value of TAMOUNT.
If a minimum balance of Rs. 2000/- will be maintained for a savings account and
a minimum balance of Rs. 5000/- will be maintained for a current account else
appropriate messages must be displayed
3. Consider the following relational schema for a Loan database application:
Customer (Custid, Custname, Age, phno)
Loan (Loanid, Amount, Custid)
Create a database trigger that will not permit a customer to get more than 3 loans.
4. Consider the following relational schema for a Sales database application:
Product (Prodid, Prodesc, Price, Stock)
Purchase (Purid, Proid, qty, supplierName)
Sales (Saleid, Proid, qty, custname)
Create a Trigger which reduces the stock of Product that is been inserted in sales and print
if it is out of stock (stock <Reord)
5. Consider the following relational schema for Products Order database application:
Products (p_id, p_name, retail_price, qty_on_hand)

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
112

Orders (order_id, order_date)


Order_details (order_number, product_number, qty_ordered)
Create a database TRIGGER, which deletes the order from Orders table, AFTER the
deletion of corresponding order_number in Order_details
VIVA QUESTIONS:
1. What is RAISE_APPLICATION_ERROR?
2. Give the sql statement to list the triggers associated with a particular table.
3. How to disable and enable triggers?
4. How to drop a trigger?
5. What are two virtual tables available during database trigger execution?
6. What happens if a procedure that updates a column of table X is called in a database trigger of the same
table?
7. Write the order of precedence for validation of a column in a table?
8. What are the instances when triggers are appropriate?
9. How do you use trigger AFTER keyword?
10. Why do we need trigger restrictions?

Ex.No:7. EXCEPTION HANDLING


PRELAB MATERIAL
An exception is an error condition during a program execution. PL/SQL supports programmers to catch
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
113

such conditions using EXCEPTION block in the program and an appropriate action is taken against the
error condition. There are two types of exceptions −
• System-defined exceptions
• User-defined exceptions
Syntax for Exception Handling
The general syntax for exception handling is as follows. Here you can list down as many exceptions as
you can handle. The default exception will be handled using WHEN others THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal database error,
but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is
the simple syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
114

EXCEPTION
WHEN exception_name THEN
statement;
END;
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined
exception must be declared and then raised explicitly, using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;

Pre-defined Exceptions

PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a
program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO
statement returns no rows. The following table lists few of the important pre-defined exceptions

Exception Description
ACCESS_INTO_NULL It is raised when a null object is automatically assigned a value.
It is raised when none of the choices in the WHEN clause of a
CASE_NOT_FOUND
CASE statement is selected, and there is no ELSE clause.
It is raised when a program attempts to apply collection methods
other than EXISTS to an uninitialized nested table, or the program
COLLECTION_IS_NULL
attempts to assign values to the elements of an uninitialized nested
table
It is raised when duplicate values are attempted to be stored in a
DUP_VAL_ON_INDEX
column with unique index.
It is raised when attempts are made to make a cursor operation that
INVALID_CURSOR
is not allowed, such as closing an unopened cursor.
It is raised when the conversion of a character string into a number
INVALID_NUMBER
fails because the string does not represent a valid number.
LOGIN_DENIED It is raised when a program attempts to log on to the database with

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
115

an invalid username or password.


NO_DATA_FOUND It is raised when a SELECT INTO statement returns no rows.
It is raised when a database call is issued without being connected
NOT_LOGGED_ON
to the database.
PROGRAM_ERROR It is raised when PL/SQL has an internal problem.
It is raised when a cursor fetches value in a variable having
ROWTYPE_MISMATCH
incompatible data type.
It is raised when a member method is invoked, but the instance of
SELF_IS_NULL
the object type was not initialized.
It is raised when PL/SQL ran out of memory or memory was
STORAGE_ERROR
corrupted.

PRELAB QUESTIONS

1. What is the use of exception?


2. List the types of exception
3. What is user defined exception?
4. List the pre defined exceptions
5. What is the use of raise statement?
6. Give the syntax of exception
7. Give some examples of sql exceptions
8. How do you raise an exception?
9. What is meant by SELF_IS_NULL?
10. What is meant by ROWTYPE_MISMATCH?

SAMPLE EXERCISE:

1. For the customer relation Customers(ID, Name, Age Address, Salary). Write a PL/SQL block to input
customerid and display address and salary. Use exception to display “ No such customer” when data not
found.

DECLARE
c_id customers.ID%type := &c_id;
c_name customers.Name%type;
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
116

c_addr customers.Address%type;
BEGIN
SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
OUTPUT:
Enter the value of c_id:100
No such customer
2. For the customer relation Customers(ID, Name, Age Address, Salary). Write a PL/SQL block to input
customerid and display address and salary. Use exception to display “ No such customer” when data not
found.
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
117

END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
OUTPUT
Enter the value of c_id:-50
ID must be greater than zero
STUDENT EXERCISE
1. Consider the following relational schema for a Loan database application:
Customer (Custid, Custname, Age, phno)
HLoan (HLoanid, Amount, Custid)
VLoan (VLoanid, Amount, Custid)
Write a PL/SQL which accepts HLoanid as input and displays Custid, CustName and loan_amount of
HLoan. Include exceptions to display “No such HLoanid” when incorrect Hloanid is given.

2. Consider the following relational schema for a Loan database application:


Customer (Custid, Custname, Addr, phno,pan_no)
Loan (Loanid, Amount, Interest,Custid)
Account (Accid, Accbal, Custid)
Develop a procedure named Customer_Loan that displays all the loan details. Include exceptions to display
“No such Loanid” when incorrect loanid is given

3. Consider the following relational schema for a Books Ordering database application:
Books (isbn, title, author, stock_qty, price, pub_year)
Customers (cust_id, cust_name, address)
Orders (order_no, cust_id, order_date) where cust_id refers Customers(cust_id)

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
118

Order_list (order_no, isbn, qty, ship_date) where order_no refers Orders(order_no), isbn refs Books
(isbn)
Create a procedure named Books_Ordered which outputs the customer name, book title and quantity
ordered for the given order number. Also include exception to display “No such Order Number” if
incorrect order number is given.

4. Consider the relations SAILOR (SID, NAME, DOB, GENDER)


BOAT (BID, BTYPE, BNAME, COLOR)
SAILS (SID, BID, DOT, SHIFT)
Create a PL / SQL stored function that accepts SID and returns the name of sailor. Also include
exceptions to display "No such Sailor exist" when the incorrect SID is given

5. Consider the following relational schema for a company database application:


EMPLOYEE (ENO, NAME, GENDER, DOB, DOJ, DESIGNATION, BASIC, DEPT_NO, PAN,
SENO)
Develop a procedure Staff_Increment that will accept staff number and increment amount
as input and update the basic pay of the staff in the staff table. Also include exception in the procedure
that will display a message “Staff has basic pay null” if the basic pay of the staff is null and display a
message “No such staff number” if the staff number does not exist in the staff table.

6. Consider the following relational schema for a Product Sales database application:
Product (Prodid, Prodesc, Price, Stock)
Purchase (Purid, Proid, qty, supplierName)
Sales (Saleid, Proid, qty, custname)
Develop a procedure named Product_Sales that accepts a prodid and displays all the sales and purchase
records of it. Also include exception in the procedure that will display a message
“No such Product ID” if the given product id does not exist in the product table.

VIVA QUESTIONS

1. Give the difference between predefined and user defined exception

2. How exception is raised?

3. What happens if exception is not handled?


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
119

4. Can exception be used with functions and procedures

5. Is it compulsory to use exception with functions and procedures?

6. List the steps to be followed for user defined exception

7. What is meant by LOGIN_DENIED?

8. What is meant by NOT_LOGGED_ON?

9. What is meant by PROGRAM_ERROR?

10. What is meant by NO_DATA_FOUND?

Ex.No: 8. DATABASE DESIGN USING ER MODELING, NORMALIZATION AND


IMPLEMENTATION FOR ANY APPLICATION

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
120

PRE LAB MATERIAL:


NORMALIZATION
Normalization is the analysis of functional dependencies between attributes/data items of user
views. It reduces a complex user view to a set of small and stable subgroups of the fields and relations.
This process helps to design a logical data model known as conceptual data model.
There are different normal forms
1. First Normal Form(1NF)
2. Second Normal Form(2NF)
3. Third Normal Form(3NF)
FIRST NORMAL FORM (1NF)
1NF states that the domain of an attribute must include only atomic values and that value of any
attribute in a tuple must be a single value from the domain of that attribute. Hence 1NF disallows
multivalued attributes, composite attributes. It disallows “relations within relations”.
SECOND NORMAL FORM (2NF)
A relation is said to be in 2NF if it is already in 1NF and it has no partial dependency. 2NF is based
on the concept of full functional dependency.
A functional dependency(FD) x→y is fully functional dependency is (x-(A))→y does not hold
dependency any more if A→x.
A functional dependency x→y is partial dependency if A can be removed which does not affect the
dependency ie (x-(A))→y holds.
A relation is in 2NF if it is in 1NF and every non-primary key attribute is fully and functionally
dependent on primary key.
A relation is in 1NF will be in the 2NF if one of the following conditions is satisfied:
1. The primary key consist of only one attribute.
2. No non-key attribute exist in relation ie all the attributes in the relation are components of the primary
key.
Every non-key attribute is functionally dependent on full set of primary key attributes.

THIRD NORMAL FORM (3NF)


A relation is said to be in 3NF if it is already in 2NF and it has no transitive dependency.
A FD x→y in a relation schema R is a transitive dependency if there is a set of attributes z that is
neither a candidate key nor a subset of any key of the relation and both x→z and z→y hold.
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
121

Entity relationship diagram (ERD):


An entity relationship diagram (ERD) shows the relationships of entity sets stored in a database. An
entity in this context is an object, a component of data. An entity set is a collection of similar entities.
These entities can have attributes that define its properties.
Notation :

PRE LAB QUESTIONS:


1. What is normalization?
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
122

2. What is 1 NF (Normal Form)?


3. What is 2NF?
4. What is 3NF?
5. What is 4NF?
6. What is 5NF?
7. What is ER Diagram?
8. Define functional dependency.
9. What are anomalies?
10. What is a trivial FD?

SAMPLE EXERCISE:
Database design for property database.
E-R DIAGRAMS
1. First Normal Form

Propnorm
1

Propi cnam PAd area price Tax_rat


d e d e

Propi snam city countr


d e y

2. Second Normal Form

propnorm
2

Propi cnam area price Tax_rat


d e e
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
123

3. Third Normal Form

propnorm
3

Propid cnam area


e

First Normal Form


1. Create a property table with the following fields: property id, country name, padd, area, price, tax rate
and having property id as the primary key.
SQL> create table prop(propid number(2) primary key, cname varchar(20), padd varchar(50), area int,
price number(9,2),tax_rate number(2));

SQL> desc prop;


Name Null? Type
----------------------------------------- -------- ----------------------------
PROPID NOT NULL NUMBER(2)
CNAME VARCHAR2(20)
PADD VARCHAR2(50)
AREA NUMBER(38)
PRICE NUMBER(9,2)
TAX_RATE NUMBER(2)

2. Insert values in the property table.


SQL> insert into prop values('34','india','ganthi nagar,Coimbatore, india','500','500000','2');
1 row created.
SQL> insert into prop values('45','united states','first street southeast, Washington, United
states','400','2550000','5');
1 row created.
SQL> insert into prop values('39','scotland','capelrig road, Glasgow, scotland','600','2500000','4');
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
124

1 row created.

Before Normalization
prop
Propid Cname Padd Area Price Tax_rate

Normalization to first normal form

1. Creating the prop11 tabale with propid, cname, area,price, tax_rate from prop.
SQL> create table prop11 as select , cname, area,price, tax_rate from prop;
2. Creating the table prop12 with propid, sname,city,country from prop
SQL> create table prop12 as select propid,padd from emp;
3. Altering the table prop11 with primary key on prop.
SQL> alter table prop12 add constraint c1 foreign key(propid) references prop11(propid);
4. Altering the table prop12 with foreign key on propid with reference from prop11.
SQL> alter table prop12 add constraint c1 foreign key(propid) references prop11(propid);

After Normalization
Prop11
Propid Cname Area Price Tax_rate

Prop12
Propid sname City country

SECOND NORMAL FORM


Normalization to Second Normal Form
1. Create the table prop21 with propid, cname, area, price from the table prop.
SQL> create table prop21 as select propid,cname,area, price from prop;
2. Create the table prop22 with cname, tax_rate from the table prop.
SQL> create table prop22 as select cname,tax_rate from prop;
3. Alter table prop21 with a primary key constraint on propid.
SQL> alter table prop21 add constraint prop21 primary key(propid);

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
125

4. Alter table prop22 with a primary key constraint on cname.


SQL> alter table prop22 add constraint prop22 primary key(cname);
5. Alter table prop21 with foreign key on cname with references on cname from prop22.
SQL> alter table prop21 add constraint prop212 foreign key(cname) references prop22(cname);
After normalization
Prop21 prop22
Propid Cname Area Price Cname Tax_rate

THIRD NORMAL FORM


The 2NF table is given as input here and convert it to 3NF.
Input: prop21, prop22 tables.
For converting to 3NF it is enough making changes in prop21 table.
Before Normalization
Prop21
Propid Cname Area Price

1. Create table prop31 with propid, cname, area from prop21.


SQL> create table prop31 as select propid,cname,area from prop21;
2. Create table prop32 with area, price from prop21.
SQL> create table prop32 as select area, price from prop21;
3. Alter table prop31 with the constraint primary key on propid.
SQL> alter table prop31 add constraint prop31 primary key(propid);
4. Alter table prop32 with the constraint primary key on area.
SQL> alter table prop32 add constraint prop32 primary key(area);
5. Alter table prop31 with the constraint foreign key on area with refernce from area in prop32.
SQL> alter table prop31 add constraint prop311 foreign key(area) references prop32(area);
After Normalization
Prop31 prop32
Propid Cname Area Area Price

STUDENT EXERCISE

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
126

1. Database Design using ER modeling, normalization and Implementation for student management system
which includes the information like student register number, name, address, date of birth, mobile number,
cgpa, city, pincode.
2. Database Design using ER modeling, normalization and Implementation for book management system
which includes the information like bookid, ISBN number, title, author id, author name, publisher
name,price, number of pages.
3. Database Design using ER modeling, normalization and Implementation for bank database which
includes the information like customer account number, customer id, name, address, mobile number,
PAN number, Aadhaar number, Loan id, loan amount, loan interest, account balance.

VIVA QUESTIONS:
1. What is Functional Dependency?
2. What is Lossless join property?
3. What is Fully Functional dependency?
4. What is BCNF (Boyce-Codd Normal Form)?
5. What are the major components of E-R diagram?
6. What are multi valued attributes?
7. What is a composite attribute?
8. What is a non trivial FD?
9. What is weak entity set?
10. What is candidate key?

Ex.No: 9. Generation of Forms Using Oracle Form Builder

Pre Lab Material:

Use Form Builder to simplify for the creation of data-entry screens, also known as Forms. Forms are the
applications that connect to a database, retrieve information requested by the user, present it in a layout

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
127

specified by Form designer, and allow the user to modify or add information. Form Builder allows you
to build forms quickly and easily.

Form Builder Tool

Open the "Form Builder" tool.

Welcome window

You will get the ‘Welcome to the Form Builder’ window. If you don’t want to get this window anymore
uncheck the ‘Display at startup’ box. You can start your work with any of the following options:

• Use the data Block Wizard


• Build a new form manually
• Open an existing form

Build a form based on a template

The default is ‘Use the data Block Wizard.’ If you want to build a new form manually, click on
"Cancel”or check ‘Build a new form manually’ and click ‘OK.’

Connect to database

In the ‘Object Navigator’ window, highlight "Database Objects." Go to the Main menu and choose

"File," then "Connect."

In the ‘Connect’ window, login in as “scott” password “tiger,” then click “CONNECT.”

Notice that the box next to ‘Database Objects’ is not empty anymore and it has a ‘+’ sign in it.

That will indicate that this item is expandable and you are able to see its entire objects.

Click on the ‘+’ sign next to the ‘Database Objects’ to expand all database schemas.

Create a Module

In the ‘Object Navigator’ window, highlight module1. This is a default name. Go to the Main menu and
choose “File,” select “Save as” to store the new object in the “iself” folder and save it as customer data
entry. "c:_de." In this example the ‘DE’ abbreviation stands for Data Entry.

Create a Data Block

In the ‘Object Navigator’ window, highlight "Data Blocks,” and click on the "create” icon. The ‘Create’
icon is in the vertical tool bar in the ‘Object Navigator’ window. It is a green ‘+’ sign. If you drag your
cursor on the icon a tooltip will show ‘Create.’

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
128

New Data Block

In the ‘New Data Block’ window, choose the default option “Data Block Wizard” and click "OK."

Welcome Data Block

In the ‘Welcome Data Block Wizard’ window click on the “NEXT” icon.

Type of Data Block

Select the type of data block you would like to create by clicking on a radio button. Select the default
option ‘Table or View’ and then click “NEXT” again.

Selecting Tables

Click on “browse.” In the ‘Tables’ window, highlight the "cust11” table; then click "OK."

Selecting columns for the Data Block Wizard

To choose all columns, click on the two arrow signs in the ‘Data Block Wizard’ window. To choose
selected columns, click on the one arrow sign. And then select all columns, and click “next.”

Layout Wizard

End of the Data Block Wizard and beginning of the Layout Wizard In the ‘Congratulations’ screen, use
the default checkmark radio button (Create the data block, then call the Layout Wizard), and click
"Finish." You can also use the Data Block Wizard to modify your existing data block. Simply select the
data block in the Object Navigator and click the Data Block Wizard toolbar button, or choose ‘Data
Block wizard’ from the ‘Tools’ menu.

Welcome screen

In the ‘Welcome to the Layout Wizard’ window, click ”Next.”

Selecting canvas

In the ‘Layout Wizard’ window, select the "new canvas" option. Canvas is a place that you will have your
objects such as columns, titles, pictures, etc. If you have already had your canvas, select the canvas and
then click on the next. The following are different types of canvases: Content, Stacked, Vertical Toolbar,
Horizontal Toolbar, and Tab.

Think of the ‘Content’ canvas as one flat place to have all your objects. In the stacked canvas, you can
have multiple layers of objects and it is the same as the tab canvas. You use the vertical or horizontal
toolbar canvases for your push buttons. Check the different types of canvases by clicking on the ‘down
arrow’ box next to the ‘Type’ field. Select "content," then click “Next.”

Selecting Columns for the Layout Wizard

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
129

In the ‘Layout Wizard’ window, select all the columns. These are the columns that you want to be
displayed on the canvas. Then click “Next.”

Change your objects appearances

Change size or prompt if needed. In this window, you can enter a prompt, width, and height for each item
on the canvas. You can change the measurement units. As a default the default units for item width and
height are points. You can change it to inch or centimeter. When you change size, click “Next.”

Selecting a layout style

Select a layout style for your frame by clicking a radio button. Select "Form," if you want one record at a
time to be displayed. Select “Tabular,” if you want more than one record at a time to be displayed. Select
"Forms," and then click “next.”

Record layout

Type the "Frame Title" and click "next." Checkmark the ‘Display Scrollbar’ box when you use multiple
records or the ‘Tabular’ option.

Congratulation Screen

In the ‘Congratulations’ window, click "Finish."

You will see the output layout screen.

Make some window adjustments and then run the form. To run the form, click on the ‘Run’ icon.

The ‘Run’ icon is on the horizontal toolbar in the ‘CUSTOMER_DE’ canvas.

The object module should be compiled successfully before executing the Form.

Execute Query

Click on the "Execute Query" icon below the main menu. If you drag the cursor on the toolbar in the
‘Forms Runtime’ window, a tooltip will be displayed and you see ‘Execute Query.’So to know all your
option, drag your cursor to view all the icon descriptions.

Next Record

Click on the "Next Record" icon to navigate to the next record.

Previous Record

Click on the "Previous Record" icon to navigate to the previous record.

This is an easy way to navigate through the “Customer” table.


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
130

Enter Query

Click on the "Enter Query" icon to query selected records.

Insert Record

Click "Insert Record" to add new customer. All items on the forms will be blanked. You can either type

all the customer information or duplicate it from pervious record.

Duplicate Record

To duplicate the previous record, go to the main menu and select the ‘Record’ sub-menu. A drop down

menu will be displayed. Select the ‘Duplicate’ option in the sub-menu.

Apply the changes. Remember in this stage, your record was inserted but not committed yet.

Next and Previous Record

Click "next record" and "previous record" to navigate through the records and the one was added.

Save transactions

Click "Save" to commit the insert statement.

Delete Record

Click "Remove Record" to delete the record.

Lock a Record

You can also lock the record.

Exit from Form Runtime

Exit the FORM Runtime. If you have not committed any transaction, you will be prompted to save
changes. Click “YES” to save changes.

Click “OK” for acknowledgement.

Don’t forget to save the Form.

Sample Exercise:

Employee Information form

RABAD

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
131

Selecting the type of form to create

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
132

Selecting the canvas on which data block can be displayed

Form showing the Employee details

Pre Lab Questions

1. What is database driver?


2. What is JDBC?
3. What is ODBC?
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
133

4. What is a place holder?


5. What is an IDE?
6. What are the major components of DB connection?
7. How to authenticate application to DB connection?
8. Design a schema for the given application.
9. Draw ER diagram for the given application.
10. What is an API?

Student Exercises:

1. Develop a form for Banking database application.

2. Develop a form for Library management system.

3. Develop a form for Employee payroll management system

4. Develop a form for Student management system

5. Develop Bus ticket management system

Viva Questions:

1. What is oracle form builder?


2. What is a form in Oracle Apps?
3. List the components available for form building.
4. What are database forms?
5. Why do we use forms?
6. What is the location of an oracle driver?
7. How to execute a stored procedure using oracle forms?
8. Where to locate a DB driver?
9. How to monitor the API interactions?
10. What is free version of oracle server?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
134

Ex.No: 10. Database Design and Implementation

Sample Exercise:

Mini project for customer detail management.

CREATE TABLE CUST FOR CUSTOMER DETAILS:


QUERY:

SQL>create table cust(custname varchar2(10),custcity varchar2(10),accno number(10),balance


number(10));

SQL> desc cust;


Name Null? Type
------------------------------- -------- ----
CUSTNAME VARCHAR2 (10)
CUSTCITY VARCHAR2 (10)
ACCNO NUMBER (10)
BALANCE NUMBER (10)

CREATE TABLE TRANS FOR TRANSACTION DETAILS:


QUERY:

SQL>create table trans(accno number(10),amount number(10),trdate date);

SQL> desc trans;


Name Null? Type
------------------------------- -------- ----
ACCNO NUMBER(10)
AMOUNT NUMBER(10)
TRDATE DATE

CODING FOR CREATE BUTTON:

commit;
clear_form;

CODING FOR CREDIT BUTTON:

update cust set balance=balance+:trans.amount where cust.accno=:trans.accno;


execute_query;
commit;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
135

Design Form like this in Form Builder:

CODING FOR DEBIT BUTTON:

debit

declare
wdamount number;
begin
select balance into wdamount from cust where accno=:trans.accno;
if wdamount>=:amount then
update cust set balance = balance-:trans.amount where cust.accno=:trans.accno;
execute_query;
commit;
message('money withdraw succesfully');
else
message('you have low balance');
end if;
end;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
136

After write all codings Run the Form:


The Form will like this,

After Enter the Customer Details:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
137

Then press the Create Button.


MOVE TO SQL PLUS AND ENTER THE QUERY:

SQL> select *from cust;

CUSTNAME CUSTCITY ACCNO BALANCE


---------- ---------- ---------- ----------
A ERODE 101 0

Then Enter Transaction Details:[For Credit]

After that press Credit Button:

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
138

MOVE TO SQL PLUS AND ENTER THE QUERY:

SQL> select *from cust;

CUSTNAME CUSTCITY ACCNO BALANCE


---------- ---------- ---------- ----------
A ERODE 101 1000

SQL> Select *from trans;

ACCNO AMOUNT TRDATE


---------- ---------- ---------
101 1000 01-MAY-09

Then Enter Transaction Details:[For Debit]

Move to Sql plus and enter the query:

SQL> select *from cust;

CUSTNAME CUSTCITY ACCNO BALANCE


---------- ---------- ---------- ----------
A ERODE 101 900

SQL> Select *from trans;

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
139

ACCNO AMOUNT TRDATE


---------- ---------- ---------
101 1000 01-MAY-09
101 100 02-MAY-09

Pre Lab Questions

1. What is the location of an oracle driver?


2. How to execute a stored procedure using oracle forms?
3. Where to locate a DB driver?
4. How to monitor the API interactions?
5. What are the major components of DB connection?
6. How to authenticate application to DB connection?
7. Design a schema for the given application.
8. Draw ER diagram for the given application.
9. What is oracle form builder?
10. What is a form in Oracle Apps?

Student Exercise:

1. Develop a Banking database management application.

2. Develop Library management system Application.

3. Develop Employee payroll management system Application


Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
140

4. Develop Student management system Application.

5. Develop Bus ticket management system Application.

Viva Questions

1. Design a schema for the given application.


2. Draw ER diagram for the given application.
3. What is an API?
4. How do ensure DB security?
5. What are the security issues?
6. What is OO design process?
7. What is a cardinality constraint?
8. What is domain constraint?
9. What is timestamp?
10. List the variants of date domain.

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
141

Ex.No:11 PL/SQL BLOCK


PRELAB MATERIAL:

PL/SQL BLOCK:
PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and written
in logical blocks of code. Each block consists of three sub-parts:
1. Declarations: This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
2: Executable Commands: This section is enclosed between the keywords BEGIN and END and it is a
mandatory section. It consists of the executable PL/SQL statements of the program. It should have at
least one executable line of code, which may be just a NULL command to indicate that nothing should be
executed.
3: Exception Handling: This section starts with the keyword EXCEPTION. This section is again optional
and contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL
blocks using BEGIN and END.
SYNTAX:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

PRELAB QUESTIONS:
1. What is the need for PL/SQL block?
2. Give the syntax of PL/SQL block?
3. What is the use of declare section?
4. What are the parts of PL/SQL block?
5. Which part of PL/SQL block is mandatory?
6. Can exception be used with functions and procedures
7. Is it compulsory to use exception with functions and procedures?
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
142

8. List the steps to be followed for user defined exception


9. What is meant by LOGIN_DENIED?
10. What is meant by NOT_LOGGED_ON?

SAMPLE EXERCISE:
Refered Table:
Customer(id, name, age, address, salary)
1. Create a PL/SQL Block to get id from the user and display the name address and salary of that customer
PL/SQL BLOCK:
DECLARE
c_id customers.id%type :;
c_name customers.name%type;
c_addr customers.address%type;
c_sal customers.salary%type;
BEGIN
c_id:=&c_id;
SELECT name, address, salary INTO c_name, c_addr, c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line
('Customer ' ||c_name || ' from ' || c_addr || ' earns ' || c_sal);
END;
/
OUTPUT:
Customer Kumar from Arasur Coimbatore earns 25000
2. Create a PL/SQL block to find the factorial of a given number
PL/SQL BLOCK:
declare
n number;
fac number:=1;
i number;
begin
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
143

n:=&n;
for i in 1..n
loop
fac:=fac*i;
end loop;
dbms_output.put_line('factorial='||fac);
end;
/

OUTPUT:
Enter the value of n: 5
factorial=120
STUDENT EXERCISE:
REFERED TABLES:
Employe (emp_id,emp_name,dept_id,basic,hra,da,pf,net);
1. Create a PL/SQL block for inserting values in the Employee table. Only emp_id, emp_name,
department & basic should be received as input while executing the block and for the rest of the fields the
values need to be calculated as given below.
Calculations:
HRA=50% OF BASIC
DA=20% OF BASIC
PF=7% OF BASIC
NETPAY=BASIC+DA+HRA-PF
2. Create a PL/SQL block for updating records in Employe table where the user should provide the
emp_id and the new basic salary and thus the HRA,DA, PF and NETPAY should get calculated and
updated accordingly.
3. Create a PL/SQL block for showing the new netpay after getting new basic salary for a particular
employee. Display the new netpay along the old netpay without updating in the table. Also If no
customer found with the given customer id then show appropriate error message.
4. Create a PL/SQL block to find whether the given number is prime or not
5. Create a PL/SQL block to find sum of n numbers
6. Write a PL/SQL block to generate numbers from 0 to 25 in step of 5
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
144

7. Create a PL/SQL block that gets the journey_date and displays the list of passengers booked ticket on
that date. Referred Table: Book_ticket(pid, routeno,journey_date,seat_no)
8. Write a PL/SQLprogram to find the largest of three numbers.
9. Write a PL/SQLprogram to generate the list of even numbers between 20 to 160.
VIVA QUESTIONS:
1. Give the difference between SQL and PL/SQL
2. What is the package used to display the messages through the PL/SQL block?
3. What is an exception?
4. What are the components of PL/SQL block?
5. List the data types available in PL/SQL?
6. What is the use of the statement SET serveroutput on?
7. Describe triggers features and limitations.
8. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger?
Why?
9. What are cascading triggers?
10. Can loop be used in PL/SQL Block?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
145

Ex.No:12 CREATING INDEX


PRELAB MATERIAL
Indexes are special lookup tables that the database search engine can use to speed up data retrieval.
An index is a pointer to data in a table. An index in a database is very similar to an index in the back of a
book. An index helps speed up SELECT queries and WHERE clauses, but it slows down data input, with
UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data. Index in
sql is created on existing tables to retrieve the rows quickly. When there are thousands of records in a table,
retrieving information will take a long time. When an index is created, it first sorts the data and then it
assigns a ROWID for each row.
An index can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries
Syntax to create Index
CREATE INDEX index_name ON table_name (column_name1,column_name2...);
Syntax to create SQL unique index
CREATE UNIQUE INDEX index_name ON table_name (column_name1, column_name2...);
•index_name is the name of the INDEX.
•table_name is the name of the table to which the indexed column belongs.
•column_name1, column_name2.. is the list of columns which make up the INDEX.
The Drop Index Command
An index can be dropped using SQL DROP command. Care should be taken when dropping an
index because performance may be slowed or improved.
DROP INDEX index_name;
PRE LAB QUESTIONS
1. What is an index?
2. What are the types of index?
3. Give the advantages of index.
4. Give the difference between dense and sparse index.
5. What is the use of unique keyword in creating index?
6. What is function based index?
7. Give the syntax for creating a index.
8. How to perform DML operations in a view?
9. How to create multiple table views?
10. Are views are temporary?
Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory
146

SAMPLE EXERCISE

SQL> create table persons (first name varchar (20), last name varchar(10));
Table created;
Create an index for the above relation based on last name
SQL> create index plndex on persons (last name);
Index created.
SQL> select * from persons; No rows selected.
SQL> drop plndex on persons;
Drop index plndex on persons
* ERROR at line1:
ORA_00950: Invalid DROP option

STUDENT EXERCISE
1. Consider the relation Book (Booktitle, authorname, publisher, price, noofcopies). Create an index based on
Booktitle and authorname.
2. Consider the relation Staff(staffId, StaffName, subject, dept, phno,Skill, Salary). Create an index on the
column staffed
3. Consider the relation Product (Prodid, ,Prodesc, Price, Stock). Create an index based on prodid

4. VIVA QUESTIONS
1. Can index be created based on multiple column?
2. Is it possible to alter index
3. How an index is dropped?
4. Is it possible to rename an index?
5. Under what condition index can be used?
6. What is dynamic multilevel indexing?
7. How do you alter a sequence?
8. What is the use of CYCLE?
9. How do you drop a sequence?
10. How to delete a view?

Lab Learning Materials II CSE/IV SEM CS8481 Database Management Systems Laboratory

S-ar putea să vă placă și