Final Dbms Lab Manual
Final Dbms Lab Manual
Final Dbms Lab Manual
History of SQL:
The first version of SQL was developed at IBM by Donald D.Chamberlin and
Raymond F.Boyce in the early 1970s.This version, initially called SEQUEL ,was designed to
manipulate and retrieve data stored in IBM’s original relational database product, system R.IBM
patented their version of SQL in 1985,while the SQL language was not formally standardized
until 1986,by the American National Standards Institute(ANSI) as SQL-86.Subsequent versions
of the SQL standards have been released by ANSI and as International Organization for
standardization (ISO)standards.
1
Varchar / Varchar2 - variable length character string, size ranges from 1 – 4000
bytes. It saves the disk space (only length of the entered value will be assigned as
the size of column)
Long – variable length character string, maximum size is 2 GB
2. Number Data types: Can store +ve, -ve, zero, fixed point, floating point with 38
precision.
Number – {p=38,s=0}
Number(p) – fixed point
Number(p,s) – floating point (p=1 to 38, s =-84 to 127)
3. Date Data type: used to store date and time in the table.
DB uses its own format of storing in fixed length of 7 bytes for century, date,
month, year, hour , minutes, seconds.
Default data type is “dd-mon-yy”
4. Raw Data type: used to store byte oriented data like binary data and byte string.
5. Other:
CLOB – stores character object with single byte character
BLOB – stores large binary objects such as graphics, video, sounds
BFILE – stores file pointers to the LOB’s
EX.NO : 1
DATA DEFINITION LANGUAGES (DDL)
DATE :
AIM
To create and modify a table using Data Definition Language (DDL) commands.
DDL COMMANDS
CREATE - used for creating tables.
ALTER - used for removing an existing table.
RENAME - used to change the name of the table
2
DESC - used to view the table structure.
DESCRIPTION:
1. CREATE COMMAND:
The CREATE command is used for creating tables to store data.
Rules:
1. Oracle reserved words cannot be used.
2. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. Two different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include ‘not null’ conditions when needed. By default it is ’null’.
EXAMPLE :
EXAMPLE:
create table emp1 as select * from emp;
EXAMPLE:
create table emp2 as select empno, ename from emp;
iv) Create a new table from an existing table without any record:
SYNTAX:
create table <traget table name> as select * from <source table name>
where <false condition>;
EXAMPLE:
3
create table emp3 as select * from emp where 1>2;
2. ALTER COMMAND:
The ALTER command is used to modify the definition (structure) of a table by modifying
the definition of its columns.
SYNTAX:
alter table <table name> add (new columnname data type (size));
alter table <table name> modify (columnname data type (new size));
alter table <table name> modify (columnname data type (new size));
alter table<table name> drop (column name);
EXAMPLE:
alter table student add(address varchar2(15),marks number(4));
alter table customer modify (cust_street varchar2(10));
alter table customer drop(acc_no);
3. DROP COMMAND:
This command is used for removing an existing table..
SYNTAX:
drop table <table_name>;
EXAMPLE:
drop table student;
4. TRUNCATE COMMAND:
If there is no further use of records stored in a table and the structure has to be
retained then the records alone can be deleted.
SYNTAX:
truncate table <table_name>;
EXAMPLE:
truncate table student;
5. RENAME COMMAND:
The RENAME command is used to change the name of the table .
SYNTAX:
rename <Old table name> to <New table name>;
EXAMPLE:
rename student to vcet_student;
EXAMPLE QUERIES:
5
SQL> desc loan1;
Name Null? Type
----------------------------------------- -------- ----------------------------
LOAN_NUMBER NOT NULL VARCHAR2(10)
BRANCH_NAME VARCHAR2(10)
AMOUNT NUMBER(10)
RESULT:
EX.NO : 02
DATA MANIPULATION LANGUAGES (DML)
DATE :
AIM:
To manipulate the tables using DML commands.
DML COMMANDS:
1. Insert
2. Select
3. Update
4. Delete
6
DESCRIPTION:
1. INSERT COMMAND
This is used to add one or more rows to a table. The values are separated by commas and
the data types char and date are enclosed in apostrophes. The values must be entered in the same
order as they are defined.
SYNTAX:
insert into <table name> values (value list)
EXAMPLE:
ii) Inserting more than one record using a single insert commands:
SYNTAX:
insert into <table name> values (&col1, &col2, ….)
EXAMPLE:
insert into stud values(®, ‘&name’, &percentage);
2. SELECT COMMAND
It is used to retrieve information from the table. It is generally referred to as querying the
table. We can either display all columns in a table or only specify column from the table.
i) The retrieval of all rows from a table:
SYNTAX:
Select * from tablename; .
EXAMPLE:
Select * from IT;
SYNTAX:
7
Select column_name1, …..,column_namen from table name;
EXAMPLE:
Select empno, empname from emp;
SYNTAX:
Select DISTINCT col1, col2 from table name;
EXAMPLE:
Select DISTINCT job from emp;
SYNTAX:
Select column_name1, …..,column_namen from table name where condition;
In the syntax:
WHERE restricts the query to rows that meet a condition
Condition is composed of column names, expressions,constants, & comparison
operator
The WHERE clause can compare values in columns, literal values, arithmetic
expressions, or functions.
EXAMPLE:
Select empno, empname from emp where sal>4000;
EXAMPLE:
Select empno, empname from emp order by empno;
EXAMPLE:
create table emp1 as select * from emp;
EXAMPLE:
insert into emp1 ( select * from emp);
3. UPDATE COMMAND
It is used to alter the column values in a table. A single column may be updated or
more than one column could be updated.
SYNTAX:
update tablename set field=values where condition;
EXAMPLE:
Update emp set sal = 10000 where empno=135;
4. DELETE COMMAND
After inserting row in a table we can also delete them if required. The delete
command consists of a from clause followed by an optional where clause.
SYNTAX:
Delete from table where conditions;
EXAMPLE:
delete from emp where empno=135;
EXAMPLE QUERIES:
SELECT ALL ATTRIBUTES FROM A RELATION:
SQL> select * from account;
ACCOUNT_NU BRANCH_NAME BALANCE
9
---------- --------------- ----------
A-101 Downtown 500
A-102 Perryridge 400
A-201 Brighton 900
A-215 Mianus 700
A-222 Redwood 700
A-305 Round Hill 350
A-217 Brighton 750
7 rows selected.
SQL> select * from branch;
BRANCH_NAME BRACH_CITY ASSEST
--------------- ------------------------------ ----------
Brighton Brooklyn 7100000
Downtown Brooklyn 9000000
Mianus Horseneck 400000
North Town Rye 3700000
Perryridge Horseneck 1700000
Pownal Bennington 300000
Redwood Palo Alto 2100000
Round Hill Horseneck 8000000
8 rows selected.
SQL> select * from depositor;
CUSTOMER_NAME ACCOUNT_NU
Hayes A-102
Johnson A-101
Johnson A-201
Jones A-217
Lindsay A-222
Smith A-215
Turner A-305
7 rows selected.
10
Adams L-16
Curry L-93
Hayes L-15
Johnson L-14
Jones L-17
Smith L-11
Smith L-23
Williams L-17
8 rows selected.
SELECTING A PARTICULAR ATTRIBUTE FROM THE TABLE:
SQL> SELECT ACC_NO FROM ACCOUNT;
ACC_NO
--------------------
A-101
A-215
A-102
A-305
A-201
A-222
A-217
7 rows selected.
SQL> SELECT BALANCE*0.5 FROM ACCOUNT;
BALANCE*0.5
-----------
250
600
198
173.25
600
600
600
7 rows selected.
11
ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-215 1200 Mianus
12
-------------------- ---------- --------------------
A-101 500 downtown
A-201 1200 brighton
A-217 1200 brighton
9. SQL> SELECT * FROM ACCOUNT WHERE BRANCHNAME LIKE 'b%n';
ACCOUNT BALANCE BRANCHNAME
-------------------- ---------- --------------------
A-201 1200 brighton
A-217 1200 brighton
SQL> update account set balance=1000 where balance>500;
4 rows updated.
SQL> select * from account;
ACCOUNT_NU BRANCH_NAME BALANCE
---------- --------------- ----------
A-101 Downtown 500
A-102 Perryridge 400
A-201 Brighton 1000
A-215 Mianus 1000
A-222 Redwood 1000
A-305 Round Hill 350
A-217 Brighton 1000
7 rows selected.
Delete all the rows:
SQL> delete from account;
7 rows deleted.
SQL> select * from account;
*
ERROR at line 1:
ORA-00942: table or view does not exist
Delete the particular rows using the WHERE clause.
SQL> delete from account where balance=350;
1 row deleted;
SQL> select * from account;
ACCOUNT_NU BRANCH_NAME BALANCE
---------- --------------- ----------
A-101 Downtown 500
A-102 Perryridge 400
A-201 Brighton 1000
A-215 Mianus 1000
A-222 Redwood 1000
A-217 Brighton 1000
6 rows selected.
RESULT:
Thus the DML commands are executed successfully.
13
EX.NO : 03 INTEGRITY CONSTRAINT
DATE :
AIM:
To create and modify a table using Data Definition Language (DDL) commands with
constraints.
DESCRIPTION:
An integrity constraint is a mechanism used by Oracle to prevent invalid data entry into
the table. It has enforcing the rules for the columns in a table. The types of the integrity
constraints are:
1. Domain Integrity
2. Entity Integrity
3. Referential Integrity
1. DOMAIN INTEGRITY
a) NOT NULL – It will not allow null values.
SYNTAX : create table <table name>(columnname data type (size) constraint
constraint_name not null);
b) CHECK - Use the CHECK constraint when you need to enforce integrity rules that
can be evaluated based on a condition (logical expression)
SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name check (check_condition));
2. ENTITY INTEGRITY
a) UNIQUE – Avoid duplicate values
SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name unique);
SYNTAX :
create table <table name>(columnname1 data type (size),
columnname2 data type (size), constraint constraint_name
unique (columnname1, columnname2));
14
c) PRIMARY KEY – It will not allow null values and avoid duplicate values.
SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name primary key);
d) Composite PRIMARY KEY – Multicolumn primary key is called composite
primary key
SYNTAX :
create table <table name>(columnname1 data type (size),
columnname2 data type (size), constraint constraint_name
primary key (columnname1, columnname2));
3.REFERENTIAL INTEGRITY
Reference key (foreign key) – Its represent relationships between tables.
Foreign key is a column whose values are derived from the primary key of the
same or some other table.
SYNTAX :
create table <table name>(columnname data type (size) constraint
constraint_name references parent_table_name);
EXAMPLES QUERIES:
Table created.
15
Enter value for rollno: 501
Enter value for name: ABHILASH
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'ABHILASH','CSE')
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')
1 row created.
UNIQUE CONSTRAINTS
Table created.
16
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(501,'abhilash','cse')
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated
Table created.
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: ABI
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'ABI','CSE')
17
1 row created.
SQL> /
Enter value for rollno: 502
Enter value for name: BHAVYA
Enter value for branch: CSE
old 1: INSERT INTO STUD VALUES(&ROLLNO,'&NAME','&BRANCH')
new 1: INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
INSERT INTO STUD VALUES(502,'BHAVYA','CSE')
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C001290) violated
CHECK CONSTRAINTS
1 row created.
SQL> /
Enter value for rno: 565
Enter value for name: rohit
18
Enter value for sal: 35000
old 1: insert into stud values(&rno,'&name',&sal)
new 1: insert into stud values(565,'rohit',35000)
insert into stud values(565,'rohit',35000)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.NO_CK) violated
1 row created.
SQL> /
Enter value for stuid: 2
Enter value for sname: rohit
Enter value for per: 89
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(2,'rohit',89)
1 row created.
SQL> /
Enter value for stuid: 3
Enter value for sname: sachin
Enter value for per: 99
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(3,'sachin',99)
1 row created.
SQL> /
Enter value for stuid: 4
Enter value for sname: naveen
Enter value for per: 70
old 1: insert into adm values(&stuid,'&sname',&per)
new 1: insert into adm values(4,'naveen',70)
1 row created.
19
STUID SNAME PER
---------- --------------- ----------
1 abi 80
2 rohit 89
3 sachin 99
4 naveen 70
RESULT:
Thus the DDL commands using constraint are executed successfully.
20
EX.NO :04
SQL FUNCTIONS
DATE :
AIM:
To verify the usage of data using built in functions.
DESCRIPTION:
Functions are a very powerful feature of SQL. Function accept zero or more arguments
and both return one or more results. Both are used to manipulate individual data items. Operators
differ from functional in that they follow the format of function_name (arg..). A argument is a
user defined variables or constants. Most operators accept at most 2 arguments while the
structure of functions permit to accept 3 or more arguments.
Function can be classifies into
single row function and
group functions.
SYNTAX:
21
Function _name (column / expression, [arg 1, arg 2, …]
Date Function:
Date functions accept DATE input and may return a value of date type a number.
1. Add_months: This function returns a date after adding a specified date with specified
number of months.
Syntax: Add_months(d,n); where d- date, n- number of months
Eg: select add_months(systemdate,2) from dual;
4. Round(d,[fmt]); This function returns the date, which is rounded to the unit specified by
the format model.
Syntax: round(d,[fmt]);
Where d- date, [fmt] – optional. By default date will be rounded to the nearest
day.
Eg: select round(to_date(‘1-jan-2011’,’dd-mm-yy’),’year’) from dual;
Select round(‘1-jan-2011’’year’) from dual;
5. Next_day(d.day-name); This function returns the first date which is day_name that comes
after the date d
Syntax: Next_day(d.day-name); where day_name – valid day
Eg: select next_day(‘1-jan-2011’,’saturday) from dual;
Character functions:
This function accept character input and can return both character and number values.
22
initcap(char) Converts alpha character values to uppercase for the first
letter of each word, all other letters in lowercase.
23
Number functions:
Conversion Function:
This function converts a value from one data type to another. This function is categorized as :
To_char( )
To_date( )
To_number( )
Syntax : to_char(d/n,[format]);
2. to_date( ): This function converts character to date data format specified in the from
character.
Syntax :to_date (d,[format]);
24
Eg: select to_date(‘jan 1 2011’,’mm-dd-yy’) from dual;
GROUP FUNCTIONS:
Group functions or aggregate functions operate on sets of rows to give one result per
group.
SYNTAX:
25
• The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY
clause. To override this default ordering, DESC can be used in an ORDER BY clause.
Function Description
GROUP BY Clause: This allows us to use simultaneous column name and group functions
If the SQL statement does not contain a WHERE clause then the GROUP BY clause is
specified immediately after the FROM clause.
If the SQL statement contain where a clause then the GROUP BY clause is specified
after the WHERE clause.
SYNTAX:
26
EXAMPLES OF SINGLE ROW FUNCTIONS:
27
curry
glenn
green
5 rows selected.
MONTHS_BETWEEN('02-DEC-14','06-APR-14')
---------------------------------------
7.87096774
ADD_MONTH
---------
08-OCT-14
NEXT_DAY(
---------
08-OCT-14
28
NEXT_DAY(
---------
13-OCT-14
LAST_DAY(
---------
28-FEB-14
LAST_DAY(
---------
31-AUG-14
ROUND(TO_
---------
01-AUG-14
TRUNC(TO_
---------
01-JUL-14
29
SQL> select count (*) from employee where dept = ‘Electronics’;
COUNT(*)
-------------
2
SQL> select location, dept, sum(salary) from employee group by location, dept;
RESULT:
Thus the data are manipulated using SQL functions .
30
EX.NO :05
SET OPERATORS
DATE :
AIM:
To verify the usage of data using set operators.
DESCRIPTION:
The Set operators combine the result of 2 queries into a single result. The following are
the operators:
Union
Union all
Intersect
Minus
The rules to which the set operators are strictly adhere to:
The queries which are related by the set operators should have a same number of
column and column definition.
Such query should not contain a type of long.
Labels under which the result is displayed are those from the first select
statement.
Union:
Returns all distinct rows selected by both queries.
SYNTAX:
Query1 Union Query2;
Union all
Returns all rows selected by either including the dulicates.
SYNTAX:
Query1 Union all Query2;
Intersect:
Returns rows selected that are common to both queries.
SYNTAX:
Query1 Intersect Query2;
Minus:
Returns all distinct rows selected by the first query and are not by the second
SYNTAX:
Query1 Minus Query2;
EXAMPLES QUERIES:
To find all the bank customers having a loan, an account, or both at the bank.
SQL> select customer_name from depositor union select customer_name from
2 borrower;
CUSTOMER_NAME
--------------------
Adams
Curry
Hayes
Johnson
Jones
Lindsay
31
Smith
Turner
Williams
9 rows selected.
To find all customer who have a loan and a account at the bank.
SQL> select distinct customer_name from depositor intersect
2 select distinct customer_name from borrower;
CUSTOMER_NAME
-------------------------
Hayes
Johnson
Jones
Smith
32
Smith
To find all customers who have an account but no loan at the bank
SQL> select customer_name from depositor minus select customer_name from
borrower;
CUSTOMER_NAME
--------------------
Lindsay
Turner
EX.NO :06
SUBQUERIES
DATE :
RESULT:
Thus the data are manipulated using set operators.
AIM:
To perform the queries using subqueries.
DESCRIPTION:
The query within another is known as a subquery. A statement containing subquery is
called parent statement. The rows returned by subquery are used by the parent statement.
TYPES:
1. Subqueries that return several values:
Subqueries can also return more than one value. Such results should be made use
along with the operators in and any.
Eg: Select ename, eno from employee where salary <any (select salary from
employee where deptno=10);
2. Multiple queries:
Here more than one sunquery is used. These multiple subqueries are combined by
means of ‘and’ & ‘or’ keywords.
3. Correlated subquery:
A subquery is evaluated once for the entire parent statement whereas a correlated
subquery is evaluated once per w processed by the parent statement.
33
Eg: selec from emp x where x.salary > (select avg(salary) fro emp where
deptno=x.deptno); selects the employee details that the salary of employee is >
the average salary of his own department.
NESTED SUBQUERIES
EXAMPLE:
SQL> select * from customer;
CUST_NAME CUST_STREET CUST_CITY
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield
SQL> create table consumer as select * from customer;
Table created.
2. INSERT:
SYNTAX:
Insert into <table name> select <column name> from <existing table name>where predicate.
EXAMPLE:
SQL> insert into consumer as select * from customer;
5 rows created.
34
Perryridge Horseneck 17000
Minus Horseneck 29000
Brighon Brooklyn 60000
3. DELETE:
SYNTAX:
Delete from <table name> where condition = (select statement)
EXAMPLE:
SQL> delete from consumer where cust_city=(select branch city from branch
where branch_name=’northtown’);
1 row deleted.
SQL> select * from customer;
CUST_NAME CUST_STREET CUST_CITY
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield
4. UPDATE:
SYNTAX:
Update <table name> set column name = value where condition= (select statement)
EXAMPLE:
SQL> update consumer set customer_street=’main’ where customer_name in
(select customer_name from customer where customer_street=’North’);
2 row updated.
35
----------------------------------------------------------------------------------------
Jonny Main Harrison
Smith North Rye
Hays Main Harrison
Curry North Rye
Lindsay Park Pittsfield
5. SELECT:
Find all the information of customer who has an account number is A-101.
Find all customers who have a loan from the bank, find their names and loan numbers.
CUST_NAME LOAN_NO
--------------------------------------------------------------
Jonny 101
Lindsay 102
Curry 103
Find all customers who are borrowers from the bank and who appear in the list of
depositor.
CUST_NAME
--------------------------------
Jonny
Find all customers who do have a loan at the bank, but do not have an account at the bank.
CUST_NAME
--------------------------------
Curry
36
Lindsay
Find the names of all branches with customers who have an account in the bank and who
live in Harrison city.
BRANCH_NAME
--------------------------------
Downtown
Mianus
select rows from borrower such that the loan numbers are lesser than any Loan number
where the branch name is “Perryridge”.
CUST_NAME LOAN_NO
--------------------------------------------------------------
Jonny 101
Lindsay 102
select rows from borrower such that the loan numbers are greater than all Loan number
where the branch name is “downtown”.
CUST_NAME LOAN_NO
------------------- ---------------------
Lindsay 102
Curry 103
ANOTHER EXAMPLE:
37
30 SALES CHICAGO
40 OPERATIONS BOSTON
Select empno, ename ,job, salary, from table whose location is located in chicago.
Select the empname, each employee’s salary, and find the difference of salary of each
employee from the maximum salary of the employees.
SQL> select ename,(select max(sal) from emp) "maxsal", sal,((select max(sal) from emp ) – sal)
"difference" from emp;
38
ENAME MAXSAL SAL DIFFERENCE
---------- ---------- ---------- ----------
SMITH 5000 800 4200
ALLEN 5000 1600 3400
WARD 5000 1250 3750
JONES 5000 2975 2025
MARTIN 5000 1250 3750
BLAKE 5000 2850 2150
CLARK 5000 2450 2550
SCOTT 5000 3000 2000
TURNER 5000 1500 3500
ADAMS 5000 1100 3900
JAMES 5000 950 4050
FORD 5000 1300 3700
14 rows selected.
select all employees whose salary is less than the average of all the employees' salaries in
the same department.
SQL> select ename ,sal ,deptno from emp a where a.sal < (select avg(sal) from emp b
where a.deptno = b.deptno) order by deptno;
SQL> update emp a set sal = (select avg(sal) from emp b where a.deptno = .deptno)
where sal < (select avg(sal) from emp c where a.deptno = c.deptno);
8 rows updated.
SQL> select ename, sal, deptno from emp order by deptno, ename;
ENAME SAL DEPTNO
---------- ---------- ----------
CLARK 2916.67 10
KING 5000 10
39
MILLER 2916.67 10
ADAMS 2175 20
FORD 3000 20
JONES 2975 20
SCOTT 3000 20
SMITH 2175 20
ALLEN 1600 30
BLAKE 2850 30
JAMES 1566.67 30
MARTIN 1566.67 30
TURNER 1566.67 30
WARD 1566.67 30
14 rows selected.
SQL> delete from emp a where a.sal = (select max(sal) from emp b here a.deptno =
b.deptno);
4 rows deleted.
SQL> select ename, sal, deptno from emp order by deptno, ename;
ENAME SAL DEPTNO
---------- ---------- ----------
CLARK 2916.67 10
MILLER 2916.67 10
ADAMS 2175 20
JONES 2975 20
SMITH 2175 20
ALLEN 1600 30
JAMES 1566.67 30
MARTIN 1566.67 30
TURNER 1566.67 30
WARD 1566.67 30
10 rows selected.
40
RESULT:
Thus the subqueries are executed successfully
EX.NO :08
JOIN OPERATIONS
DATE :
AIM:
To perform the data using join operations.
DESCRIPTION:
The join concept is to combine data spread across tables. A join is actually performed by
the ‘where’ clause which combines specified rows of tables.
When data from more than one table in the database is required, a join condition is used.
Rows in one table can be joined to rows in another table according to common values existing in
corresponding columns, that is, usually primary and foreign key columns. To display data from
two or more related tables, write a simple join condition in the WHERE clause.
Join Syntax:
Select columns from table1, table2 where logical expression;
Prefix the column name with the table name when the same column name appears in more than
one table.
Types of Joins:
1. Simple join
2. Self join
3. Outer join
1. Simple join:
It is the most common types on join. It retrieves the rows from 2 tables having a
common column and is further classified into
a) Equi – join: A join, which is based on equalities, is called equi join.
Eg: select * from item, cust where item.id= cust.id;
In the above eg. , item.id = cust.id performs the join statement. It retrieves
rows from the both tables provided they both have the same id as specified by
the where clause. Since the where clause uses the comparison operator (=) to
41
perform a join, it is said to be equi join. It combines the matched rows of
tables.
b) Non Equi-join: It specifies the relationship between columns belonging to
different tables by making use of relational operators other than ‘=’.
Eg: select * from item, cust where item.id < cust.id
Table Aliases:
Table aliases are used to make multiple table queries shorted and more readable.
We give an aliase name to the table in the ‘from’ clause and use it instead of the name
throughout the query.
2. Self join:
Joining of a table to itself is known as self-join. It joins one row in a table to
another. It can compare each row of the table to itself and also with other rows of
the same table.
Eg; select * from emp x, emp y where x.salary >= (select avg(salary) from x.emp
where x.deptno= y.deptno);
3. Outer join:
It extends the result of a simple join. An outer join returns all the rows returned by
simple join as well as those rows from one table that do not match any row from
the table. The symbol (+) represents outer join.
Eg: select ename, job, dname from emp, dept where emp.deptno (+) =
Dept.deptno;
42
table2.column (+) is the outer join symbol, which can be placed on either side of the
WHERE clause condition, but not on both sides. (Place the outerjoin symbol following
the name of the column in the table withoutthe matching rows.
7 rows selected.
3. RIGHT OUTER JOIN:
SQL> select * from loan right outer join borrower on
loan.loan_number=borrower.loan_number;
LOAN_N BRANCH_NAME AMOUNT CUSTOMER_NAME LOAN_N
------ --------------- ---------- -------------------- ------
L-11 Round Hill 900 Smith L-11
L-15 Perryridge 1500 Hayes L-15
L-16 Perryridge 1300 Adams L-16
L-23 Redwood 2000 Smith L-23
43
L-93 Mianus 500 Curry L-93
RESULT:
EX.NO :09
VIEW, SEQUENCE, SYNONYM AND INDEX
DATE :
AIM:
To verify the usage of objects such as view, sequence and index.
DESCRIPTION:
A view is the tailored presentation of data contained in one or more tables and cam also
be said as restricted view to the data in the tables. A view is a virtual table or a stored query
44
which takes the output of a query and treats is as a table. The table upon which a view is created
is called as base table.
A view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed. The tables
on which a view is based are called base tables. The view is stored as a Select statement in the
data dictionary.
Advantages of a view:
1. Additional level of table security.
2. Hides data complexity.
3. Simplifies the usage by combining multiple tables into a single table.
4. Provides datas in different perspective.
SYNTAX:
CREATE [OR REPLACE ] VIEW <view name> [column alis names] AS <query>
[with <options > conditions];
Eg: Create or replace view emp_view as select * from emp;
QUERIES:
1. SQL> Create view branch_total_loan(branch_name,total_loan) as
Select branch_name, sum(amount) from loan group by branch_name;
View created
2. SQL>Create view all_customer as (select branch_name, customer_name from
Depositor, account where depositor.account_number = account.account_number)
Union (select Branch_name,customer_name from borrower,loan where
borrower.loan_number = loan.loan_number;
View created
SQL> desc all_customer;
Name Null? Type
----------------------------------------- -------- ----------------------------
BRANCH_NAME VARCHAR2(15)
CUSTOMER_NAME VARCHAR2(15)
SYNTAX:
Create sequence <seq_name>increment by n start with n [maxvalue n]
[Minvalue n] [Cycle/no cycle] [Cache/no cache].
45
SQL> create sequence seq1 increment by 1 start with 100 maxvalue 105
minvalue 100 cycle cache 4;
If you want to see the next value from the sequence apply the following
SQL>Select seq1.nextval from dual;
iii) SYNONYM: Which is used as an alias name (alternative name) for a table, view or
sequence.
SYNTAX:
CREATE synonym<synonym_name>for<table_name>
EXAMPLE:
create synonym uni for university;
46
Rathna Sub Slm 10000
Swetha Down Hyd 12000
SQL> create sequence seq 1 increment by 2 start with 100 maxvalue 110
minvalue 100 cache 4;
Sequence created.
SQL>/
Enter value for name:mku
Old 1:insert into university values(seq 1.nextval,’&name’);
new 1:insert into university values(seq 1.nextval,’mku’)
1 row created.
47
5 rows selected.
RESULT:
Thus the data objects such as view ,synonyms index and sequence are executed
successfully.
EX.NO : 10
TRANSACTION CONTROL LANGUAGE(TCL)
DATE :
AIM:
To verify the usage of data using transaction control commands.
DESCRIPTION:
All changes made to the database is defined as a transaction. It is a logical unit of work.
The transaction can be made permanent to a database only if they are committed.
The Transaction Control Language commands are:
COMMIT
ROLLBACK
SAVEPOINT
48
The transaction begins with an executable SQL statement and ends explicitly with either
rollback or commit statements implicitly, i.e., automatically when a DDL statement is used.
Statement Description:
COMMIT : This command is used to make all transaction changes permanent to the
database.
ROLLBACK : This command is used to undo all the changes made in the current
transaction. We can either rollback the entire transaction or rollback a transaction to a savepoint.
SYNTAX:
1. COMMIT;
2. SAVEPOINT id;
3. ROLLBACK ; OR ROLLBACK TO SAVEPOINT id;
If you omit the TO SAVEPOINT clause, the ROLLBACK statement rolls back the entire
transaction. As savepoints are logical, there is no way to list the savepoints you have created.
EXAMPLES:
SAVE POINT:
7 rows selected.
49
SQL> select * from loan;
ROLLBACK:
SQL> rollback;
Rollback complete.
COMMIT:
SQL> select * from loan;
LOANNO BRANCHNAME LOANAMOUNT
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300
L-17 downtown 1000
7 rows selected.
50
LOANNO BRANCHNAME LOAANAMOUNT
L-23 redwood 2000
L-15 perryridge 1500
L-14 downtown 1500
L-93 mianus 500
L-11 roundhill 500
L-16 perryridge 1300
6 rows selected.
RESULT:
EX.NO : 11
DATA CONTROL LANGUAGE (DCL)
DATE :
AIM:
To verify the usage of data using data control commands.
DESCRIPTION;
Data Control Language provide users with privilege commands. The database objects
(table, view etc) of a user can’t be accessed by another user without the permission of the owner
user. The owner can allow other user to access his objects as per his direction. The permission
given by a user (owner) to another is called a privilege.
CREATE USER:
SYNTAX:
CREATE USER < user_name> IDENTIFIED BY password;
51
GRANT:
SYNTAX:
GRANT system privilege TO user;
GRANT object privilege [,object privilege] ON object to user [WITH GRANT
OPTION];
WITH GRANT OPTION this option enables the grantee( to whom the privilege is granted)
to grant the same privilege to another user.
REVOKE:
SYNTAX:
REVOKE ALL/object privilege [,object privilege] ON object_name FROM user;
EXAMPLES:
1. SYSTEM PRIVILIGES:
CREATE USER:
CREATE USER scott IDENTIFIED BY tiger;
User created.
GRANT:
SQL> grant create table to it5;
Grant succeeded.
REVOKE:
SQL> revoke create table from it5;
Revoke succeeded.
OBJECT PRIVILEGES:
GRANT:
52
SQL> grant select on loan to it1;
Grant succeeded.
REVOKE:
SQL> revoke select on loan from it1;
Revoke succeeded.
Revoke succeeded.
RESULT:
Thus the DCL commands are executed.
53
EX.NO : 12
SIMPLE PL/SQL PROGRAMS
DATE :
AIM :
To write and Execute Simple PL/SQL Programs.
DECLARE:
Declarations of memory variables used later.
BEGIN:
SQL executable statements for manipulating table data.
EXCEPTIONS:
SQL and/or PL/SQL code to handle errors that may crop up
During the execution of the above code block.
END;
1. Conditional Control:
A sequence of statements can be executed based on some condition using IF.
Syntax:
If<condition> then <Action>
Else <Action>
End if;
2. Iterative Control:
A sequence of statements can be executed any number of times using loop
constructs.
a) Simple loop
Syntax:
Loop
Statements;
End loop;
b) While loop
Syntax:
While<condition>
Loop
Statements;
End loop;
54
c) For loop
Syntax:
For counter in[reverse] lower bound .. upper bound
Loop
statements
End loop;
PL/SQL PROGRAMS:
1. Write a pl/sql block code to add the two numbers.
OUTPUT:
Enter value for a: 12
old 6: a:=&a;
new 6: a:=12;
Enter value for b: 23
old 7: b:=&b;
new 7: b:=23;
sum of 12 and 23 is :35
55
b:=&b;
dbms_output.put_line('enter c');
c:=&c;
if(a>b)and(a>c)then
dbms_output.put_line('A is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('B is maximum');
else
dbms_output.put_line('C is maximum');
end if;
end;
/
PL/SQL procedure successfully completed.
OUTPUT:
declare
b varchar2(10) := '&b';
c varchar2(10);
l number(2);
i number(2);
g number(2);
d varchar2(10);
begin
l:=length(b);
g:=l;
for i in 1..l
loop
c:=substr(b,g,1);
g := g - 1;
56
d := d || c;
end loop;
dbms_output.put_line('revised string is');
dbms_output.put_line(d);
end;
PL/SQL procedure successfully completed.
SQL> /
Enter value for b:database
old 2: b varchar(10):= ‘&b’;
new 2: b varchar2(10):= ‘database’;
reversed string is
esabatad
OUTPUT:
sum bt 1 to 100 is 5050
5. Write a pl/sql block code to find the sum of odd number using user i/p.
SQl> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1..endvalue
57
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum = '||sum1);
end;
/
PL/SQL procedure successfully completed.
OUTPUT:
.
6. Write a pl/sql block code to find the sum of odd number using while loop.
SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
while(n<endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd numbers bt 1 and '||endvalue||' is '||sum1);
end;
/
PL/SQL procedure successfully completed.
OUTPUT:
58
SQL> declare
2 a number(3);
3 b number(3);
4 c number(3);
5 n number(3):=&n;
6 negative exception;
7 begin
8 if n<2 then
9 raise negative;
10 end if;
11 a:=0;
12 b:=1;
13 dbms_output.put_line(‘Fibonacci series is’);
14 dbms_output.put_line(a);
15 dbms_output.put_line(b);
16 for i in 3..n
17 loop
18 c:=a+b;
19 dbms_output.put_line(c);
20 a:=b;
21 b:=c;
22 end loop;
23 exception
24 when negative then
25 dbms_output.put_line(‘n should be greater than l’);
26 end;
SQL> /
Enter value for n:10
old 5: n number(3):=&n;
new 5:n number(3):=10;
Fibonacci
0
1
1
2
3
5
8
13
21
34
PL/SQL procedure successfully completed
59
3 basic number;
4 da number;
5 hra number;
6 pf number;
7 netsalary number;
8 begin
9 ename:=&ename;
10 basic:=&basic;
11 da:=basic*(41/100);
12 hra:=basic*(15/100);
13 if(basic<3000)
14 then
15 pf:=basic*(5/100);
16 elsif(basic>=3000 and basic<=5000)
17 then
18 pf:=basic*(8/100);
19 else
20 pf:=basic*(10/100);
21 end if;
22 netsalary:=basic+da+hra+pf;
23 dbms_output.put_line('employee name:'||ename);
24 dbms_output.put_line('providend fund:'||pf);
25 dbms_output.put_line('net salary:'||netsalary);
26 end;
27 /
PL/SQL procedure successfully completed.
OUTPUT:
Enter value for ename: 'sudha'
old 9: ename:=&ename;
new 9: ename:='sudha';
Enter value for basic: 100000
old 10: basic:=&basic;
new 10: basic:=100000;
employee name:sudha
providend fund:10000
net salary:166000
60
8 /
PL/SQL procedure successfully completed.
OUTPUT:
1
2
3
4
5
6
7
8
9
10
SQL> declare
2 i number:=0;
3 j number:=0;
4 begin
5 while i<=100 loop
6 j:=j+1;
7 i:=i+2;
8 end loop;
9 dbms_output.put_line(to_char(i));
10 end;
11 /
OUTPUT:
102
SQL> declare
2 a number:=100;
3 begin
4 loop
5 a:=a+25;
61
6 exit when a=250;
7 end loop;
8 dbms_output.put_line(to_char(a));
9 end;
10 /
PL/SQL procedure successfully completed.
OUTPUT:
250
12. Write a pl/sql block code to find the given is prime or not.
SQL> declare
2 no number(3):=&no;
3 a number(4);
4 b number(2);
5 begin
6 for i in 2..no-1
7 loop
8 a:=no MOD i;
9 if a=0
10 then
11 GOTO out;
12 end if;
13 end loop;
14 <<out>>
15 if a=1
16 then
17 dbms_output.put_line(no||' is a prime');
18 else
19 dbms_output.put_line(no||' is not prime');
20 end if;
21 end;
22 /
PL/SQL procedure successfully completed.
OUTPUT:
62
13. Write a pl/sql code block to calculate the area of circle for a value of radius varying
from 3 to 7. Store the radius and the corresponding values of calculated area in an
empty table named area, consisting of two columns radius and area
SQL> declare
2 pi constant number(4,2):=3.14;
3 radius number(5);
4 area number(14,2);
5 begin
6 radius:=3;
7 while radius<=7
8 loop
9 area:=pi*power(radius,2);
10 insert into areas values(radius,area);
11 radius:=radius+1;
12 end loop;
13 end;
14 /
PL/SQL procedure successfully completed.
OUTPUT:
RADIUS AREA
---------- ----------
3 28.26
4 50.24
5 78.5
6 113.04
7 153.86
RESULT:
63
EX.NO : 13
PL/SQL PROGRAM USING CURSORS
DATE :
AIM:
To write a PL/SQL program using cursor.
DESCRPTION:
Oracle allocated an area of memory known as context area for the processing of
SQL statement. The context area contains information necessary to complete the processing,
including the number of rows processed by the statement and a pointer to the parsed
representation of the statement.
A cursor is pointer to the context area. Through the cursor, a PL/SQL program can
control the context area and what happens to it as the statement is processed.
The cursor can be classified into
Implicit cursor
Explicit cursor
Cursors are declared implicitly by PL/SQL for all SQL data manipulation statements,
including the select statements that return one row.
If a query returns more than one row, explicit cursor should be used to access the rows in
the context area.
CURSOR MANAGEMENT:
The steps involved in declaring a cursor and manipulating data in Active Dataset.:
1. Declare a cursor that specifies the SQL Statement that it to be processed.
Syntax:
cursor cursorname is SQL statement;
Example:
Declare Cursor c_emp is
Select emp_code, salary from employee Where depm=3;
2. OPENING A CURSOR: The cursor is initialized with open statement. This defines a
private SQ private SQL area, execute the query associated with the cursor, populates the active
Data Set Data Set row pointer to first record.
Syntax:
open cursor_name;
Example:
Open c_emp;
3. FETCHING A RECORD FROM CURSOR: The fetch statement retrieves the current
row and advances the cursor to the next row. It’s executed repeatedly until all rows
have been retrieved.
Syntax: fetch cursorname into variable1,variable2,------
Example:
fetch c_emp into str_emp_code,num_salary;
64
The % type attribute is used in the declaration of a variable when attributes must be picked
from a table.
The current program will result into a n indefinite loop as there is no exit provided
from the loop. The exit can be provided using explicit cursor variables.
4. CLOSING A CURSOR: The close statement disables the cursor and active set become
undefined. It will release the memory occupied by cursor and it’s data set.
Syntax:
close cursorname;
EXAMPLE:
declare
cursor c_emp is
select emp_code ,salary from employee
where deptno=20;
str_emp_code employee.emp_code %type;
num_salary employee.salary %type;
begin
open c_emp;
loop
fetch c_emp into str_emp_code,num_salary;
end loop;
end;
SOME ATTRIBUTES:
1. %ROWCOUNT:
Return the no of rows fetched from the active set.It is set to zero when the cursor
is opened.
Syntax: cursorname %rowcount;
2.%NOTFOUND:
Evaluates to true if the last fetch has field because no more rows were available
or to false, if the fetch returned a row.
Syntax:cursorname%notfound;
3.%FOUND:
Is the logical opposite of %notfound. It evaluates to true, if the last fetch succeeded
because a row was available or to false, if the last fetch field because no more rows
were available.
Syntax: cursorname%found;
4. %ISOPEN:
Evaluate to true, if an explicit cursor is open % on to false if it is closed.
Syntax: cursorname %isopen;
65
PROGRAM:
1.Write a pl/sql block code for finding the salary of each employee using cursor.
TABLE CREATION
Table created.
INSERTING VALUES
66
7 dbms_output.put_line('empno'||'name'||'net salary');
8 dbms_output.put_line('.............................');
9 open cus_salary;
10 loop
11 fetch cus_salary into eno,ename,netsal;
12 exit when cus_salary%notfound;
13 dbms_output.put_line(eno||' '||ename||' '||netsal);
14 end loop;
15 close cus_salary;
16* end;
SQL> /
Declare
cursor c_emp is
select ename,deptno,salary .from employee
order by salary disc
str_name employee.name%type;
num_deptno employee.deptno%type;
num_salary employee.salary%type;
begin
open c_emp;
dbms_output.put_line(‘NAME DEPARTMENT SALARY’);
dbms_output.put_line(‘----------------------------------------------------‘);
loop
fetch c_emp into str_name,num_deptno,num_salary;
dbms_output.put_lines(str_name||’’||num_deptno||’
’ ||num_salary);
exit when c_emp %rowcount=10;
end loop;
close c_emp;
end
67
SQL>/
ENAME DEPARTMENT SALARY
----------- --------------------------- -------------
surya 20 20000
malathy 18 15000
ivan 20 10000
sonia 20 10000
pradeep 18 7000
PL/SQL procedure successfully completed.
SQL>DECLARE
2 dacno depositer.account_number%type;
3 aacno account.account_number%type;
4 bal account.balance%type;
5 cname depositer.customer_name%type;
6 CURSOR c is SELECT customer_name,account_number FROM depositer;
7 CURSOR c1 is SELECT balance,account_number FROM account;
8 BEGIN
9 OPEN c;
10 OPEN c1;
11 FETCH c INTO cname,dacno;
12 FETCH c1 INTO bal,aacno;
13 LOOP
14 LOOP
15 IF (dacno=aacno) THEN
16 dbms_output.put_line('CUSTOMER NAME');
17 dbms_output.put_line(cname);
18 dbms_output.put_line('BALANCE');
19 dbms_output.put_line(bal);
20 FETCH c INTO cname,dacno;
21 ELSE
22 FETCH c INTO cname,dacno;
23 END IF;
24 EXIT WHEN c%notfound;
25 END LOOP;
26 CLOSE c;
27 OPEN c;
28 EXIT WHEN c1%notfound;
29 FETCH c1 INTO bal, aacno;
30 END LOOP;
31 CLOSE c;
32 CLOSE c1;
33* END;
/
PL/SQL procedure successfully completed.
68
OUTPUT:
CUSTOMER NAME
Johnson
BALANCE
500
CUSTOMER NAME
Hayes
BALANCE
1600
CUSTOMER NAME
Johnson
BALANCE
900
CUSTOMER NAME
Smith
BALANCE
700
CUSTOMER NAME
Jones
BALANCE
752
CUSTOMER NAME
Lindsay
BALANCE
700
CUSTOMER NAME
Lindsay
BALANCE
700
PL/SQL procedure successfully completed.
RESULT:
69
EX.NO : 14
PL/SQL PROGRAM USING FUNCTIONS
DATE :
AIM:
To write and execute program using function.
DESCRIPTION:
Function is a subprogram that computes a value.
SYNTAX:
create [or replace] function <function name> (parameter1,parameter2,……)
return <data type>
is
[constant/variable declaration]
begin
executable statements
return <return values>
exception[exception handling statements]
return <return values>
end;
PROGRAM:
To create a recursive function to find the factorial of a given number using PL/SQL
function.
Function created.
OUTPUT:
70
SQL> select fact (5) from dual;
FACT (5)
-------------
120
(OR)
SQL>create or replace function fact(n number)return number is
2 begin
3 if n=1 then
4 return 1;
5 else
6 return n* fac(n-1);
7 end if;
8 end fac;
SQL>/
Function created.
SQL>declare
2 n number(4):=&n;
3 n1 number (8);
4 begin
5 n1:=fac(n);
6 dbms_output.put_line(‘factorial of’|| n ||’is’|| n1);
7 end;
8
SQL>/
Enter the value for n:6
Old 2: n number(4):=&n;
New 2:n number(4):=6;
Factorial of 6 is 720
PL/SQL Procedure successfully completed.
71
Function created.
OUTPUT:
COUNTING('BRIGHTON')
--------------------
2
COUNTING('PERRYRIDGE')
----------------------
1
RESULT:
72
EX.NO : 15
PL/SQL PROGRAM USING PROCEDURE
DATE :
AIM:
To write and execute program using procedure.
DESCRIPTION:
A procedure is a subprogram that performs a specific action.
SYNTAX:
CREATE [OR REPLACE] procedure procedure name [(parameter1,parameter2,…)]
IS
[CONSTANT/ variable declarations]
BEGIN
Exception statements
[Exception handling statements]
End [procedure name];
PROGRAM:
1. Write a pl/sql block code, if the balance is less than 5000 print the min balance
otherwise update the account table with the given interest.
SQL> /
73
Procedure created.
Call completed.
7 rows selected.
RESULT:
74
EX.NO : 16
TRIGGER
DATE :
AIM:
To write and execute the program to verify the use of triggers.
DESCRIPTION:
Trigger is a stored procedure that is fired when an insert, update or delete
statement is issued against the associated table.
SYNTAX:
EXAMPLES:
1.
SQL> create table stu(name varchar2(15),roll_no number(5) primary key,
sem varchar2(5),dep varchar2(5));
Table created.
75
new 1: insert into stu values('Latha',27,'fifth',' IT')
1 row created.
SQL> /
Enter value for name: Revathi
Enter value for roll_no: 43
Enter value for sem: sixth
Enter value for dep: CSE
old 1: insert into stu values('&name',&roll_no,'&sem','&dep')
new 1: insert into stu values('Revathi',43,'sixth','CSE')
1 row created.
76
SQL> select * from stu;
Table Created
Table Created
77
SQL>edit trig1.sql;
SQL>edit trig2.sql;
SQL>edit trig3.sql;
Output Values:
SQL> get trig1.sql;
Trigger Created.
78
1 row selected
1 row updated.
1 row created.
1 row updated.
79
REGNO NAME DEPT PERCENTAGE
---------- ---------- ---------- ----------
101 GG cse 80
103 dd cse 60
304 ff ece 70
405 EE ece 65
4 rows selected
Table created.
Table created.
1 row created.
SQL> /
Enter value for order_id: 101
Enter value for quantity: 4
Enter value for cost_per_item: 20
old 1: insert into orders30(order_id,quantity,cost_per_item)
values(&order_id,&quantity,&cost_per_
new 1: insert into orders30(order_id,quantity,cost_per_item) values(101,4,20)
1 row created.
SQL> /
Enter value for order_id: 102
Enter value for quantity: 5
Enter value for cost_per_item: 30
old 1: insert into orders30(order_id,quantity,cost_per_item)
values(&order_id,&quantity,&cost_per_
80
new 1: insert into orders30(order_id,quantity,cost_per_item) values(102,5,30)
1 row created.
Trigger created.
1 row updated.
81
3 begin
4 delete from depositer where depositer.accountnumber=:old.accountnumber;
5 end;
6 /
Trigger created.
OUTPUT:
SQL> delete from account where accountnumber='A-101';
1 row deleted.
6 rows selected.
CUSTOMERNAME ACCOUNTNUMBER
-------------------- --------------------
smith A-215
hayes A-102
turner A-305
johnson A-201
jones A-217
lindsay A-222
6 rows selected.
RESULT:
82
EX.NO : 17
Database Design and implementation (Mini Project)
DATE :
AIM
To implement Library Management System by using Visual Basic as front end & Oracle
as back end.
ABSTRACT
In this project we have used visual basic as front end and oracle as back end. Visual Basic
is a flexible and user friendly interface and it can also easily interact with the back end. This
project stores the details of Books stored in an Library.
By using this project, the details of a Book such as Book Name, Book Code, Author can
be stored. We can update the records ,which exists in the database easily and quickly.
Books can be reserved by using this Project.
Also for a particular Author the books written by them can be displayed .We can update
the records into the database. We can also view the records, which already exist in the database
easily and quickly.
83
Dim a As String
rs.Index = "Key"
a = Val(InputBox("Enter Book Code"))
rs.Seek "=", Val(a)
If rs.NoMatch = True Then
MsgBox "Invalid Code"
Else
Text1.Text = rs.Fields("Book Name")
Text2.Text = rs.Fields("Book Code")
Text3.Text = rs.Fields("Author")
End If
End Sub
84
If rs.NoMatch = True Then
MsgBox "Invalid code"
Else
Text1.Text = rs.Fields("Member Name")
Text2.Text = rs.Fields("MemberCode")
Text3.Text = rs.Fields("Age")
End If
End Sub
85
Dim str As String
rs.Index = "Key"
str = Val(InputBox("Enter Member Code"))
rs.Seek "=", Val(str)
If rs.NoMatch = True Then
MsgBox "Invalid Code"
Else
Text1.Text = rs.Fields("Member Name")
Text2.Text = rs.Fields("Member Code")
Text3.Text = rs.Fields("Book Name")
Text4.Text = rs.Fields("Book Code")
Text5.Text = rs.Fields("DOI")
Text6.Text = rs.Fields("DOR")
End If
End Sub
86
OUTPUT
RESULT:
87