CS8481_DBMSlab
CS8481_DBMSlab
CS8481_DBMSlab
2020-2021
IV Semester
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
MOOKAMBIGAI COLLEGE OF ENGINEERING
(Approved by AICTE & Affiliated to Anna University, Chennai)
(ISO 9001:2008 Certified Institution)
Srinivasa Nagar, Kalamavur-622502.Pudukkottai District, Tamil Nadu.
Name……………………………………………………………………………………….
Year………II……………….Semester………04…………………Branch…..CSE…...
CERTIFICATE
Certified that this is the Bonafide record of work done by the above student in the
______________________________
Signature of Staff-Incharge
EXAMINERS
External: ……………………..
CONTENTS
Page Initials
S.No Date Name of the Experiment No.
1. DDL,DML,TCL COMMANDS
2. DATABASE QUERYING
TRIGGERS
6.
EXCEPTION HANDLING
7.
Aim:
To create table and Execute Data Definition Commands, Create, Alter, Rename, Truncate, Drop,
Data Manipulation Commands for Inserting, Deleting, Updating And Retrieving Tables and
Transaction Control Statements for Rollback, Commit and Savepoint.
Create is a DDL SQL command used to create a table or a database in relational database
management system.
Creating a Database
Create command can also be used to create tables. Now when we create a table, we have to
specify the details of the columns of the tables too. We can specify the names and data types of
various columns in the create command itself.
Alter command is used for altering the table structure, such as,
Rename a Column
TRUNCATE command
TRUNCATE command removes all the records from a table. But this command will not destroy the
table's structure. When we use TRUNCATE command on a table its (auto-increment) primary key is
also initialized.
Syntax,
TRUNCATE TABLE table_name;
DROP command
DROP command completely removes a table from the database. This command will also destroy the
table structure and the data stored in it. Following is its syntax,
RENAME TABLE
RENAME command is used to set a new name for any existing table. Following is the syntax,
DML COMMANDS
INSERT command
Syntax:
DELETE command
TCL COMMANDS
COMMIT command
COMMIT command is used to permanently save any transaction into the database.
COMMIT;
ROLLBACK command
This command restores the database to last commited state. It is also used with SAVEPOINT
command to jump to a savepoint in an ongoing transaction.
ROLLBACK TO savepoint_name;
SAVEPOINT command
SAVEPOINT command is used to temporarily save a transaction so that you can rollback to that
point whenever required.
SAVEPOINT savepoint_name;
COMMANDS
CREATE
Table created.
ALTER
Table altered.
Table altered.
RENAME
TRUNCATE
DROP
Table dropped.
INSERT
1 row created.
SQL> /
1 row created.
SQL> /
1 row created.
SQL> /
Enter value for eno: 4
Enter value for ename: ganesh
Enter value for salary: 35000
Enter value for dob: 9-jan-83
old 1: insert into employee values(&eno,'&ename',&salary,'&dob')
new 1: insert into employee values(4,'ganesh',35000,'9-jan-83')
1 row created.
SQL> /
Enter value for eno: 5
Enter value for ename: dinesh
Enter value for salary: 46000
Enter value for dob: 26-feb-84
old 1: insert into employee values(&eno,'&ename',&salary,'&dob')
new 1: insert into employee values(5,'dinesh',46000,'26-feb-84')
1 row created.
UPDATE
DELETION
ENAME
---------------
kavi
keerthi
geetha
ganesh
dinesh
SAVEPOINT
7 rows selected.
Result : Thus the table created successfully , and applied all the DDL, DML, TCL commands.
EX.NO.2 DATABASE QUERYING
Aim:
To Create a table and apply Simple Queries Nested Queries, Sub Queries and Joins.
SQL - SIMPLE QUERIES
The SQL SELECT statement is used to fetch the data from a database table which returns this data in
the form of a result table. These result tables are called result-sets.
SUB QUERY
If a Query that contains another Query, then the Query inside the main Query is called a Sub
Query and the main Query is known as the parent Query.
Syntax
SELECT <column,...> FROM <table> WHERE expression operator (SELECT column, >FROM <table>
WHERE <condition> );
When we write a Sub Query in a WHERE and HAVING clause of another Sub Query then it is
called a nested Sub Query.
SELECT e.first_name,e.salary FROM employees e WHERE e.manager_id in ( SELECT e.manager_id FROM
employees e WHERE department_id in (select d.department_id FROM departments d WHERE
d.department_name='Purchasing' ));
A Correlated Sub Query contains a reference to a table that appears in the outer query. It is used for
row by row processing, in other words the Sub Query will execute row by row for the parent query.
JOINS
A join is the most powerful operation for merging information from multiple tables based on a
common field. There are various types of joins but an INNER JOIN is the common of them.
Syntax
Equi Join
An Equi join is used to get the data from multiple tables where the names are common and the
columns are specified. It includes the equal ("=") operator.
Inner Join
An Inner Join retrieves the matching records, in other words it retrieves all the rows where there is at
least one match in the tables.
Outer Join
The records that don't match will be retrieved by the Outer join. It is of the following three types:
1. Left Outer Join
2. Right Outer Join
3. Full Outer Join
1. Left Outer Join
A Left outer join retrieves all records from the left hand side of the table with all the matched records.
This query can be written in one of the following two ways.
SELECT Cust_id, Cust_name, Country, item_ordered, Order_date FROM customer C, LEFT OUTER
JOIN Orders O ON (C. Order_id = O.Order_id);
2. Outer Join
A Right Outer Join retrieves the records from the right hand side columns.
To retrieve all the records, both matching and unmatched from all the tables then use the FULL
OUTER JOIN.
2. Non-Equi Join
A Non-Equi join is based on a condition using an operator other than equal to "=".
SELECT Cust_id, Cust_name, Country, Item_ordered, Order_date FROM Customer C, Oredrs O WHERE C.
Order_id > O.Order_id;
3. Self-join
When a table is joined to itself only then that condition is called a self-join.
A natural join is just like an equi-join since it compares the common columns of both tables.
This join is a little bit different from the other joins since it generates the Cartesian product of two
tables as in the following:
Syntax
SELECT * FROM table_name1 CROSS JOIN table_name2;
COMMANDS-SIMPLE QUERIES
no rows selected
SALARY
---------------
28000
35000
40000
46000
AGGREGATE FUNCTION
.
SQL> select sum(salary) from employee;
SUM(SALARY)
-----------------
138000
SQL> select avg(salary) from employee;
AVG(SALARY)
----------------------
27600
MIN(SALARY)
--------------------
15000
MAX(SALARY)
-------------------
40000
COUNT(SALARY)
-------------------------
5
SQL> select count(*) from employee;
COUNT(*)
-----------------
5
.
SQL> select distinct count(eno) from employee;
COUNT(ENO)
--------------------
5
JOINS
EQUI JOIN
LEFTOUTER JOIN
RIGHTOUTER JOIN
SELF JOIN
NESTED QUERIES
SQL> select * from studentdetail;
SQL>select id,firstname from studentdetail where firstname in(select firstname from studentdetail where
subject='science');
ID FIRSTNAME
---------------------------------
100 ragul
102 stephen
SQL> select id,firstname from studentdetail where firstname not in(select firstname from studentdetail where
subject='science');
ID FIRSTNAME
---------------------------------------
101 anjali
103 shekar
104 priya
.
SQL> select * from studentdetail where age>=(selece avg(age) from studentdetail);
Table created.
SQL> insert into mathsgroup(id,name( select id,firstname ||'`|| lastname from studentdetail where
subject='maths';
2 rows created.
SQL> select id,(select name from mathsgroup where id=101 as name,age,subject,games from
Table created.
Result:
The table was create successfully, Simple Queries Nested Queries, Sub Queries and Joins are applied.
EX:NO:3 VIEWS, SEQUENCES, SYNONYMS
Aim:
To create database and apply Views, Sequences, Synonyms.
A view is nothing more than a SQL statement that is stored in the database with an associated name.
A view is actually a composition of a table in the form of a predefined SQL query.
Creating Views
Sql > create view customers_view as select name, age from customers;
Create view customers_view as select name, age from customers Where age is not null with check
option;
Updating a View
Dropping Views
SQL| SEQUENCES
Sequence is a set of integers 1, 2, 3, … that are generated and supported by some database systems to
produce unique values on demand.
Syntax:
CREATE SEQUENCE sequence_2 start with 100 increment by -1 minvalue 1 maxvalue 100 cycle;
SQL: Synonyms
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects.
Syntax
Example
Drop synonym
Syntax
Example
COMMANDS
VIEWS
SQL> create view employeeview as select * from employee;
View created.
7 rows selected.
7 rows selected.
1 row updated.
SQL> select * from employeeview;
7 rows selected.
1 row deleted.
6 rows selected.
SQL> select * from employee;
6 rows selected.
SQL> create view empview as select eno,ename from employee with read only;
View created.
ENO ENAME
----------------------------
1 kavitha
2 prabu
3 geetha
4 bala
5 sundari
6 kayal
6 rows selected.
SYNONYM
7 rows selected.
Sequence created.
NEXTVAL
----------------
1
SQL> /
NEXTVAL
---------------
2
SQL> /
NEXTVAL
----------------
3
SQL> /
NEXTVAL
------------------
4
SQL> /
NEXTVAL
----------------
5
Sequence created.
SQL> select seq1.nextval from dual;
NEXTVAL
----------------
1
SQL> /
NEXTVAL
----------------
2
SQL> /
NEXTVAL
-----------------
3
SQL> /
NEXTVAL
-----------------
1
SQL> /
NEXTVAL
----------------
2
SYNONYMS
Synonym created.
7 rows selected.
INDEX
Index created.
Result:
Aim:
PL/SQL - Cursors
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is
referred to as the active set.
• Implicit cursors
• Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.
DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with
this statement.
For INSERT operations, the cursor holds the data that needs to be inserted.
For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
Attributes used in implicit cursor as the SQL cursor, such as %FOUND, %ISOPEN, %NOTFOUND,
and %ROWCOUNT.
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.
General syntax for creating a cursor:
CURSOR cursor_name IS select_statement;
OPEN c_customers;
CLOSE c_customers;
Example
DECLARE
c_id customers.id%type;
c_name customerS.No.ame%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
PROGRAM
Implicit cursor
SQL> declare
2 id employ.empid%type;
3 begin
4 select empid into id from employ
5 where place='&place';
6 dbms_output.put_line('rollno'||id);
7 exception
8 when no_data_found then
9 dbms_output.put_line('not exists');
10 end;
11 /
Explicit cursor
1 declare
2 ename employ.empname%type;
3 epl employ.place%type;
4 cursor c1 is select empname,place from employ;
5 begin
6 open c1;
7 fetch c1 into ename,epl;
8 dbms_output.put_line(ename||'place is'||epl);
9 fetch c1 into ename,epl;
10 dbms_output.put_line(ename||'place is'||epl);
11 fetch c1 into ename,epl;
12 dbms_output.put_line(ename||'place is'||epl);
13 fetch c1 into ename,epl;
14 dbms_output.put_line(ename||'place is'||epl);
15 close c1;
16* end;
SQL> /
parkavi place is namakkal
meena place is trichy
ramya place is chennai
sugi place is gova
Result:
Thus the Data base was created and applied Implicit and Explicit Cursors in a database.
EX:NO:5 PROCEDURES AND FUNCTIONS
Aim:
To create a database and apply Procedures and Functions.
PL/SQL - Procedures
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram can
be invoked by another subprogram or program which is called the calling program.
• Functions − These subprograms return a single value; mainly used to compute and return a
value.
• Procedures − These subprograms do not return a value directly; mainly used to perform an
action.
Creating a Procedure
PL/SQL - Functions
A function is same as a procedure except that it returns a value. Therefore, all the discussions of
the previous chapter are true for functions too.
Creating a Function
PROGRAMS
1.PROCEDURE
FUNCTIONS
Factorial
output
Enter value for a: 5
old 7: a:=&a;
new 7: a:=5;
Enter value for b: 3
old 8: b:=&b;
new 8: b:=3;
prev value of a and b
5
3
the values of a and b are
3
5
1 declare
2 a number;
3 d number:=0;
4 sum1 number:=0;
5 begin
6 a:=&a;
7 while a>0
8 loop
9 d:=mod(a,10);
10 sum1:=sum1+d;
11 a:=trunc(a/10);
12 end loop;
13 dbms_output.put_line('sum is'||sum1);
14 end;
SQL> /
Result:
Aim:
To create database and apply 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 −
Creating Triggers
Syntax :
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
PROGRAMS
A.CREATE A TRIGGER TO CONVERT LOWERCASE TO UPPERCASE
SQL> create or replace trigger uppercase
2 before insert or update on employee
3 referencing new as n for each row
4 begin
5 :n.ename:=upper(:n.ename);
6 end;
7 /
Trigger created.
SQL> insert into employee values(11,'ravi',20000);
1 row created.
SQL> select * from employee;
ENO ENAME SALARY
-------------------------------------------------
11 RAVI 20000
Result:
Aim:
Exception Handling
An error condition during a program execution is called an exception and the mechanism for
resolving such an exception is known as an exception handler. SQL Server provides TRY,
CATCH, THROW blocks for exception handling.
BEGIN TRY
/* T-SQL Statements */
END TRY
BEGIN CATCH
- Print Error OR
- Rollback Transaction
END CATCH
PL/SQL - Exceptions
• System-defined exceptions
• User-defined exceptions
Syntax
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
User-defined Exceptions
PL/SQL allows to define our own exceptions according to the need of our program.
Syntax
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.
• NO_DATA_FOUND
• ZERO_DIVIDE
PROGRAM
A. NO_DATA_FOUND EXCEPTION
Table created.
1 row created.
SQL> insert into phonebook values(20314, 'vijay', '130/6D' ,'nortè street', 'Thanjavur', 632005);
1 row created.
SQL> declare
2 address varchar(100);
3 begin
4 address:=findaddress(2767375);
5 dbms_output.put_line(address);
6 end;
7 /
SQL> declare
2 address varchar(100);
3 begin
Š 4 address:=findaddress(230612);
5 dbms_output.put_line(address);
6 end;
7 /
address not found
B.DIVIDE_BY_ZERO EXCEPTION
SQL> commit;
Commit complete.
Table created.
SQL> declare
2 pe_ratio number(3,1);
3 begin
4 select price / earnings into pe_ratio from stock1 where name='ram';
5 exception
6 WHEN ZERO_DIVIDE THEN return ‘divide by zero’;
7 commit;
8 end;
SQL> /
1 row created.
NAME RATIO
-----------------------------
ram 1
SQL> declare
2 pe_ratio number(3,1);
3 begin
4 select price / earnings into pe_ratio from stock1 where name='raja';
5 exception
6 WHEN ZERO_DIVIDE THEN return ‘divide by zero’;
7 commit;
8 end;
SQL> /
SQL> insert into stats (name, ratio(select name, DECODE (earnings, 0, NULL, price /earnings from
divide by zero
1 row created.
NAME RATIO
----------------------------
ram 1
raja
Result :
Aim:
To implement a database design using ER modeling, normalization for any real time application.
Entity Relationship Modeling (ER Modeling) is a graphical approach to database design. It uses
Entity/Relationship to represent real world objects.
An Entity is a thing or object in real world that is distinguishable from surrounding environment.
Enhanced Entity Relationship (EER) Model is a high level data model which provides extensions to
original Entity Relationship (ER) model.
1. Identify the entities and determine the relationships that exist among them.
2. Each entity, attribute and relationship, should have appropriate names that can be easily
understood by the non-technical people as well.
3. Relationships should not be connected directly to eachother. Relationships should connect
entities.
4. Each attribute in a given entity should have a unique name.
Attributes
• Membership number
• Full names
• Gender
• Date of birth
• Physical address
• Postal address
Result
Thus the Database design using ER modeling, Normalization was implemented successfully
EX:NO:9 CONNECTING TO ORACLE DATABASE USING VISUAL BASIC
AIM:
To design a Form using Visual Basic and connect with oracle database.
PROCEDURE:
STEP 1: Start
STEP 4: Right click the adodc component and change the properties of general,
STEP 5:Click the TextField, change data source and data field.
Coding
Dim CN As ADODB.Connection
Dim RS As ADODB.Recordset
Dim MENO As Integer
Thus the forms in Visual Basic created and connected with the database successfully.
Ex.No.10 Case Study on Real Life Database Applications (Railway Reservation)
Aim:
The aim of case study is to design and develop a database maintaining the records of different
trains, train status, and passengers.
Description:
The railway reservation system facilitates the passengers to enquire about the trains available on
the basis of source and destination, booking and cancellation of tickets, enquire about the status of the
booked ticket, etc.
The record of train includes its number, name, source, destination, and days on which it is
available, whereas record of train status includes dates for which tickets can be booked, total number of
seats available, and number of seats already booked. The database has been developed and tested on the
Oracle.
Passengers can book their tickets for the train in which seats are available. For this, passenger
has to provide the desired train number and the date for which ticket is to be booked. Before booking a
ticket for a passenger, the validity of train number and booking date is checked.
Once the train number and booking date are validated, it is checked whether the seat is available.
If yes, the ticket is booked with confirm status and corresponding ticket ID is generated which is stored
along with other details of the passenger.
After all the available tickets are booked, certain numbers of tickets are booked with waiting
status.
If waiting lot is also finished, then tickets are not booked and a message of nonavailability of
seats is displayed.
The ticket once booked can be cancelled at any time. For this, the passenger has to provide the
ticket ID (the unique key).
The ticket ID is searched and the corresponding record is deleted. With this, the first ticket with
waiting status also gets confirmed.
List of Assumptions
The reservation system is very large in reality, Therefore, a small sample case study has been
created to demonstrate the working of the reservation system. To implement this case study, some
assumptions have been made, which are as follows:
1. Train List: This table consists of details about all the available trains. The information stored in
this table includes train number, train name, source, destination, fare for AC ticket, fare for
general ticket, and weekdays on which train is available.
2. Train_Status: This table consists of details about the dates on which ticket can be booked for a
train and the status of the availability of tickets. The information stored in this table includes
train number, train date, total number of AC seats, total number of general seats, number of AC
seats booked, and number of general seats booked.
Train number Train date Seats in AC Seats Avail in Seats in Seats Avail
AC General in General
16239 12/02/19 45 21 123 120
16234 14/03/19 22 3 113 75
16223 11/02/19 44 12 110 90
3. Passenger: This table consists of details about the passenger that includes ID,name, age, sex and
address of the passenger, Proof.
Constraint: Passenger ID is unique.
4.Ticket History: This table consists of details about the booked tickets. The information stored in this
table includes ticket ID, train number, date for which ticket is booked, name, age, sex and Proof of the
passenger, status of reservation (either confirmed or waiting), and category for which ticket is booked.
Constraint: Ticket ID is unique and the train number should exist in TrainList table.
4. Booking: In this procedure, the train number, train date, and category is read from the passenger.
On the basis of the values provided by the passenger, corresponding record is retrieved from the
Train_Status table. If the desired category is AC, then total number of AC seats and number of
booked
AC seats are compared in order to find whether ticket can be booked or not. Similarly, it can be
checked for the general category. If ticket can be booked, then passenger details are read and
stored in the Passenger table.
6. Cancel: In this procedure, ticket ID is read from the passenger and corresponding record is searched
in the Passenger table. If the record exists, it is deleted from the table. After deleting the record (if it is
confirmed), first record with waiting status for the same train and same category are searched from the
Passenger table and its status is changed to confirm.
E‐Rdiagram