0% found this document useful (0 votes)
46 views40 pages

Dbms Lab Spiral

Just for subscribson

Uploaded by

sakthivijay531
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views40 pages

Dbms Lab Spiral

Just for subscribson

Uploaded by

sakthivijay531
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

EX.

NO:1
STUDY OF DDL AND DML COMMANDS
DATE:

AIM:
To execute the Data Definition Language (DDL) commands and Data Manipulation
Language (DML) Commands.
DATA DEFINITION LANGUAGE
1. Creating a Table:
Create command is used to create a table in the database.
Syntax:
create table tablename (column 1 datatype 1, …., column n datatype n);
2. DESC COMMAND
This command is used to view the structure of the table.
Syntax:
desc tablename; (or)describe tablename;
3. ALTERING A TABLE
a. The structure of the table can be changed using this command like add new column,
change the width of a datatype, change the datatype of a column.
a. Modify
Syntax:
alter table tablename modify (column datatype, …);
b. Add / Drop
Syntax:
alter table tablename add (column datatype, …);
alter table tablename drop columnname;
4. TRUNCATING A TABLE
This command is used to delete all records stored in a table, but the
structure of the table is retained.
Syntax:
truncate table tablename;
5. DROPPING A TABLE
This command is used to remove a table from the database.
Syntax: drop table tablename;

DATA MANIPULATION LANGUAGE

1. INSERT COMMANDS
1. Insert a row with values for columns in a table.
This insert command is used to add rows to a table in the database.
Syntax:
insert into tablename values (value1, value2,……, value n);
insert into tablename(column 1,column 2) values(value 1,value 2);
2. Insert a large number of rows.
This insert command is used to add multiple rows to a table in the
Database in user friendly manner..
Syntax:
insert into tablename values (&column1, &column 2,……, &column n);

1
2. SELECT COMMANDS

1. Select all rows from a table.


This select command is used to retrieve all the values stored in the table.
Syntax: select * from tablename;
Select column name(s) from tablename;
Select distinct column name from tablename;
2. Select using where command:
This select command is used to retrieve the particular field values, stored
in the table, which satisfy a required condition.
Syntax: select column name(s) from tablename where search condition;
select * from tablename where search condition;
3. UPDATE COMMAND
This command is used to update (changing values in) one or two columns
of a row in a table. Specific rows can be updated based on some condition.
Syntax:
update tablename set column1=expression, column 2=expression, ……,
column n=expression;
update tablename set column1=expression, column 2=expression, ……,
column n=expression where search condition;
4. DELETE COMMAND
A delete query is expressed in much the same way as Query. We can delete whole tuple
(rows) we can delete values on only particulars attributes.
1. Deletion of all rows:
Syntax delete from tablename ;
2. Deletion of specified number of rows:
Syntax delete from tablename where search condition ;
Additional Operations performed by DDL and DML Commands:
Creating a table from a table
Syntax
CREATE TABLE TABLENAME [(columnname, columnname, ………)]
AS SELECT columnname, columnname ........ FROM tablename;
Elimination of duplicates from the select statement:
Syntax
SELECT DISTINCT columnname, columnname FROM tablename;
Inserting data into a table from another table:
Syntax
INSERT INTO tablename SELECT columnname, columnname, …….
FROM tablename;
Insertion of selected data into a table from another table:
Syntax
INSERT INTO tablename SELECT columnname, columnname……..
FROM tablename WHERE columnname= expression;
Sorting of data in table
Syntax
Select columnname, columnname From table Order by columnname [asc/desc];
RENAME COMMAND
Renaming Table name
Syntax rename oldtablename to newtablename;
Renaming columns used with Expression Lists
Syntax
Select columnname result_columnname, Columnname result_columnname from tablename;

2
OUTPUT
1. Create EMP table.
SQL>create table emp(empno number(4), ename varchar2(10), job varchar2(9), mgr
number(4), hiredate date, sal number(7,2), comm Number(7,2), deptno number(3), age
number(3), esal number(10));
2.Get the description EMP table.
Name Null? Type

EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(3)
AGE NUMBER(3)
ESAL NUMBER(10)
3. Create DEPT table.
SQL>create table dept(deptno number(2) , dname varchar2(14), loc varchar2(13));
4.Get the description DEPT table.
SQL>desc dept;
Name Null? Type

DEPTNO NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
5. Insert records into EMP & DEPT.
SQL> insert into emp values(&empno,’&ename’,’&job’,&mgr,’&date’,&sal,&comm.
deptno,&age, &esal);
SQL>insert into dept values(&deptno,’&dname’,’&loc’);
6. List all employee details.
SQL>select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO AGE ESAL

7369 SMITH CLERK 7902 17-DEC-80 800 0 20 25 0


7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30 25 0
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30 25 0
7566 JONES MANAGER 7839 02-APR-81 2975 500 20 25 0
7698 BLAKE MANAGER 7839 01-MAY-81 2850 1400 30 25 0
7. List all dept details
SQL>select * from dept;
DEPTNO DNAME LOC
------------ ------------ --------
10 accounting New york
20 research Dallas
30 Sales Chicago
40 operations Boston
8. List the employees belonging to the department 20.
SQL> select * from emp where deptno=20;

3
ENAME
SMITH
JONES
9. List the name and salary of the employees whose salary is more than 1000.
SQL >select ename,sal from emp where sal>1000;
ENAME SAL

ALLEN 1600
WARD 1250
JONES 2975
BLAKE 2850
10. List the names of employees who are managers
SQL >select ename from emp where job = ‘MANAGER’
ENAME

JONES
BLAKE
11. List the different jobs available in employee table.
SQL>select distinct job from emp;
JOB

CLERK
MANAGER
SALESMAN
3 rows selected.
12. Alter emp table to add city column which is of string data type.
SQL>Alter table emp add city varchar2(20);
Table altered
13. Alter dept table to change loc column size as 20.
SQL>Alter table dept modify city varchar2(30);
Table altered
14. Update the salary of the employee as 2500 whose job as manager.
SQL>update emp set esal=2500 where job =‘manager’;
15. Delete the employee’s record whose salary is above 2800.
SQL>delete emp where esal>2800;
1 row deleted.
16. Change the name of emp table as EMPLOYEE.
SQL>rename emp to employee;
Table renamed.
17. Delete all records from dept table.
SQL>truncate table dept;
Table truncated.
18. Delete dept table.
SQL>drop table dept;
Table dropped.

4
RESULT:
Thus the DDL and DML commands are executed successfully.

5
EX.NO:2 STUDY OF TRANSACTION AND DATA CONTROL
LANGUAGES
DATE:
AIM:
To study Data Control Language statements and Transactional Control Language
statements.
ILLUSTRATION / PROCEDURE:
TRANSACTION CONTROL LANGUAGE:
All changes made to the database is defined as a transaction. It is logical unit of work.
The transaction can made permanent to a database only they are committed. A transaction
begins with an executable SQL statement.
The two transaction control commands are:
1. COMMIT
2. SAVEPOINT
3. ROLLBACK
1. COMMIT:
This command is used to make all transaction changes permanent to the database.
Syntax:
COMMIT ;
2. SAVEPOINT:
It is only a marker. Save point are used to divide a lengthy transaction into smaller ones.
Syntax:
Savepoint id;
3. ROLLBACK:
Rollback commands undo all the changes made in the current transaction.
Syntax:
a. Rollback;
b. Rollback to Savepoint id1;
The first one will rollback (undo) the entire transaction and the last one will undo all changes
made after the creation of the save point id1.
DATA CONTROL LANGUAGE:
Data control language, the previous user with privileges commands the database
object (table, view, etc) of a user can’t be accessed by another user without the permission of
a user. The owner can allow other user to access his object as per his diversion the permission
given by a user to another is called privilege.

6
The Data Control Commands are:
i. GRANT Privilege
ii. REVOKE Privilege
Types of Privilege:
A permission granted to execute the various data definition command like Create
Table, Create Sequence, create session are called System Privilege.
Granting System Privilege:
Grant Command is used to give System Privilege to an oracle user.
Syntax:
GRANT system privilege TO user;
Object Privilege:
An Object Privilege enables a user to execute some commands on the database object
like table view sequence etc.
• Object privileges vary from object to object.
• An owner has all the privileges on the object.
• An owner can give specific privileges on that owner’s object.
Some of the object privileges are
i. Alter
ii. Insert
iii. Update
iv. Delete
v. Select
Syntax:
GRANT object_priv [(columns)]
ON object
TO {user|role|PUBLIC}
[WITH GRANT OPTION];
object_priv -- is an object privilege to be granted
ALL --specifies all object privileges
columns --specifies the column from a table or view on which privileges are
granted
ON object -- is the object on which the privileges are granted
TO --identifies to whom the privilege is granted
PUBLIC --grants object privileges to all users
WITH GRANT OPTION --allows the grantee to grant the object privileges to other users and
roles.
Example:
• Grant query privileges on the EMPLOYEES table.
GRANT select ON employees TO itc20,itc30;

7
Grant succeeded.
• Grant privileges to update specific columns to users and roles.
GRANT update (department_name, location_id) ON departments
TO itc43, itc50;
Grant succeeded.
Give a user authority to pass along privileges.
GRANT select, insert ON departments TO itc45 WITH GRANT OPTION;
Grant succeeded.
Revoking the permission:
Permission granted to a user can also be taken back by the granter. This can be done
by the REVOKE command.
• Privileges granted to others through the WITH GRANT OPTION clause are also
revoked.
Syntax:
REVOKE {privilege [, privilege...]|ALL}
ON object
FROM {user[, user...]|role|PUBLIC}
[CASCADE CONSTRAINTS];
Example:
REVOKE select, insert ON departments FROM itc20;
Revoke succeeded.

OUTPUT :
TCL
SQL> desc stud;
Name Null? Type

SNO NUMBER(3)
SNAME VARCHAR2(10)
BRANCH VARCHAR2(4)
SQL> insert into stud values(01,'Arun','cse');
1 row created.
SQL> insert into stud values(02,'babu','IT');
1 row created.
SQL> commit;
Commit complete.
SQL> select * from stud;
SNO SNAME BRAN

8
1 Arun cse
2 babu IT
SQL> insert into stud values(03,'chitra','IT');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN

1 Arun cse
2 babu IT
3 chitra IT
SQL> rollback;
Rollback complete.
SQL> select * from stud;
SNO SNAME BRAN

1 Arun cse
2 babu IT
SQL> savepoint s1;
Savepoint created.
SQL> insert into stud values(04,'Devi','CSE');
1 row created.
SQL> select * from stud;
SNO SNAME BRAN

1 Arun cse
2 babu IT
4 Devi CSE
SQL> rollback to s1;
Rollback complete.
SQL> select * from stud;
SNO SNAME BRAN

1 Arun cse
2 babu IT

9
DCL
User it2a40:
SQL> grant all on student to it2a36;
Grant succeeded.
User it2a36:
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3

1 alex ece 92.3 90.5 89.3


2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
insert into it2a40.student values(&roll_no,'&name','&dept',&sem2,&sem2,&sem3);
Enter value for roll_no: 4
Enter value for name: chitra
Enter value for dept: it
Enter value for sem2: 88.5
Enter value for sem2: 90
Enter value for sem3: 92
old 1: insert into it2a40.student values(&roll_no,'&name','&dept',&sem2,&sem2,&sem3)
new 1: insert into it2a40.student values(4,'chitra','it',88.5,90,92)
1 row created.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3

4 chitra it 88.5 90 92
1 alex ece 92.3 90.5 89.3
2 bala ece 88.2 85 89.3
3 booba it 91.1 85 93
SQL> alter table it2a40.student add(avg number(10,3));
Table altered.
SQL> update it2a40.student set avg=91.2 where roll_no=1;
1 row updated.
SQL> update it2a40.student set avg=88.5 where roll_no=2;
1 row updated.

10
SQL> update it2a40.student set avg=89.9 where roll_no=3;
1 row updated.
SQL> update it2a40.student set avg=90.2 where roll_no=4;
1 row updated.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG

4 chitra it 88.5 90 92 90.2

1 alex ece 92. 90. 9 89.3 91.2

2 bala ece 88.2 85 89.3 88.5

3 booba it 91.1 85 93 89.9

SQL> delete from it2a40.student where roll_no=4;


1 row deleted.
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG

1 alex ece 92.3 90.5 89.3 91.2


2 bala ece 88.2 85 89.3 88.5
3 booba it 91.1 85 93 89.9

User it2a40:
SQL> revoke delete on student from it2a36;
Revoke succeeded.
User it2a36:
SQL> delete from it2a40.student where roll_no=2;
delete from it2a40.student where roll_no=2
ERROR at line 1:
ORA-00942: table or view does not exist
User it2a40:
SQL> revoke all on student from it2a36;
Revoke succeeded.
User it2a36:
SQL> select * from it2a40.student;
select * from it2a40.student
User it2a40:

11
SQL> grant select on student to it2a36;
Grant succeeded.
User - it2a36:
SQL> select * from it2a40.student;
ROLL_NO NAME DEPT SEM1 SEM2 SEM3 AVG

1 alex ece 92.3 90.5 89.3 91.2


2 bala ece 88.2 85 89.3 88.5
3 booba it 91.1 85 93 89.9
User it2a40:
SQL> revoke select on student from it2a36;
Revoke succeeded.

RESULT:
Thus the study of DCL commands and TCL commands was performed successfully.

12
EX.NO:3 DATABASE QUERYING-SIMPLE QUERIES, NESTED QUERIES,
DATE:
SUB QUERIES AND JOINS

AIM:
To query simple, nested, sub queries and joins

ILLUSTRATION / PROCEDURE:
SET OPERATIONS:
The SET operators combine the results of two or more component queries into one
result. Queries containing SET operators are called compound queries. Some of set operators
are,
UNION - Rows of first query plus rows of second query
UNION ALL - Rows of first query plus rows of second query, including all duplicates
INTERSECT – common rows from all queries
MINUS - All distinct rows that are selected by the first SELECT statement and not selected
in the second SELECT statement
Syntax:
select query set operator select query
JOINS:

An SQL join clause combines records from two or more tables in a database. It
creates a set that can be saved as a table or used as is. A JOIN is a means for combining fields
from two tables by using values common to each. ANSI standard SQL specifies four types of
Joins: INNER, OUTER, LEFT, and RIGHT. As a special case, a table (base table, view, or joined

table) can JOIN to itself in a self-join.


A programmer writes a JOIN predicate to identify the records for joining. If the
evaluated predicate is true, the combined record is then produced in the expected format, a
record set or a temporary table.
The "explicit join notation" uses the JOIN keyword to specify the table to join, and
the ON keyword to specify the predicates for the join.
The "implicit join notation" simply lists the tables for joining (in the FROM clause of
the SELECT statement), using commas to separate them
Inner Join
Inner join creates a new result table by combining column values of two tables (A and
B) based upon the join-predicate. The query compares each row of A with each row of B to
find all pairs of rows which satisfy the join-predicate. When the join-predicate is satisfied,

13
column values for each matched pair of rows of A and B are combined into a result row. The
result of the join can be defined as the outcome of first taking the Cartesian product (or Cross
join) of all records in the tables (combining every record in table A with every record in table
B)—then return all records which satisfy the join predicate. Inner join is further classified as
equi-joins, as natural joins, or as cross-joins
Syntax:
Explicit Notation:
Select * from table name1 inner join table name2 on table1.fieldname=table2.fieldname;
Select * from table1 inner join table2 using(fieldname);
Implicit Notation
Select * from table1, table2 where table1.fieldname=table2.fieldname;

Equi Join
An equi-join is a specific type of comparator-based join, or theta join that uses only
equality comparisons in the join-predicate. Using other comparison operators (such as <)
disqualifies a join as an equi-join. The query shown above has already provided an example
of an equi-join:
Syntax:
Explicit Notation:
Select * from table1 join table2 on table1.fieldname=table2.fieldname;
Natural join
A natural join offers a further specialization of equi-joins. The join predicate arises
implicitly by comparing all columns in both tables that have the same column-names in the
joined tables. The resulting joined table contains only one column for each pair of equally-
named columns
Explicit Notation:
Select * from table1 natural join table2 on table1.fieldname=table2.fieldname;

Cross join

Cross Join returns the Cartesian product of rows from tables in the join. In other
words, it will produce rows which combine each row from the first table with each row from
the second table.
Explicit Notation:
Select * from table1 cross join table2 ;
Implicit Notation
Select * from table1,table2;

14
Outer joins

An outer join does not require each record in the two joined tables to have a matching
record. The joined table retains each record—even if no other matching record exists. Outer
joins subdivide further into left outer joins, right outer joins, and full outer joins, depending
on which table(s) one retains the rows from (left, right, or both).

Left outer join

The result of a left outer join (or simply left join) for table A and B always contains all
records of the "left" table (A), even if the join-condition does not find any matching record in
the "right" table (B). This means that a left outer join returns all the values from the left table,
plus matched values from the right table (or NULL in case of no matching join predicate).
Explicit Notation:
Select * from table1 left outer join table2 on table1.fieldname=table2.fieldname

Implicit Notation
SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column =
table2.column (+);

Right outer join

A right outer join (or right join) closely resembles a left outer join, except with the
treatment of the tables reversed. Every row from the "right" table (B) will appear in the
joined table at least once. If no matching row from the "left" table (A) exists, NULL will
appear in columns from A for those records that have no match in B.
Explicit Notation:
Select * from table1 right outer join table2 on table1.fieldname=table2.fieldname

Implicit Notation

SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) =


table2.column;

Full outer join

Conceptually, a full outer join combines the effect of applying both left and right outer
joins. Where records in the FULL OUTER JOINed tables do not match, the result set will
have NULL values for every column of the table that lacks a matching row.

15
Explicit Notation:
Select * from table1 full outer join table2 on table1.fieldname=table2.fieldname

Self-join

A self-join is joining a table to itself means each row of the table is combined with
itself and with every other row of the table. The self join is viewed as join of two copies of
the same table.
SET OPERATIONS
1. Display the different designation in department 20 and 30.
SQL> select designation from emp where deptno=20
union
select designation from emp where deptno=30;

SQL> select designation from emp where deptno=20 union all select designation from emp
where deptno=30;
2. List the jobs common to department 20 and 30.
SQL> select designation from emp where deptno=20 intersect select designation from emp
where deptno=30;
3. List the jobs unique to department 20.
SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno=10 minus select designation from emp where deptno=30;
(Or)
SQL> select designation from emp where deptno=20 minus select designation from emp
where deptno in (10,30);
JOINS:
Tables:
SQL> create table two(deptno number(4) primary key,deptname varchar(10));
Table created.
SQL> create table one(name varchar(10),deptno references two(deptno));
Table created.
Insert these values into table one and table two
SQL> select * from one;
NAME DEPTNO

anand 31
babu 32
chitra 32
3 rows selected.
SQL> select * from two;
DEPTNO DEPTNAME

31 sales
32 enggg
Inner join
i.SQL> select * from one, two where one.deptno=two.deptno;
ii.SQL> select * from one inner join two on one.deptno=two.deptno

16
Equi join
i.SQL> select * from one join two on one.deptno=two.deptno;
ii.SQL> select * from one inner join two using(deptno);
Natural join
i.SQL> select * from one natural join two;
Cross Join
i.SQL> select * from one cross join two;
ii.SQL> select * from one,two;
Left outer join
i. SQL> select * from one left outer join two on one.deptno=two.deptno;
ii. SQL> select * from one,two where one.deptno=two.deptno(+);
Right outer join
i. SQL> select * from one right outer join two on one.deptno=two.deptno;
ii. SQL> select * from one,two where one.deptno(+)=two.deptno;
Full outer join
i. SQL> select * from one full outer join two on one.deptno=two.deptno;
Self join
SQL> create table selfj(empno number(5),ename varchar(7),mgr number(5));
Table created.
Insert values for table selfj
SQL> select * from selfj;
EMPNO ENAME MGR

7839 kalyan
7566 jones 7839
7876 anand 7788
7934 babu 7782
7777 raja 7934
List out the names of manager with the employee record.
SQL> select worker.ename,manager.ename from selfj worker,selfj manager where
worker.mgr=manager.empno;
SUBQUERIES
A subquery is a SELECT statement that is embedded in a clause of another SELECT
statement. You can build powerful statements out of simple ones by using subqueries. A
Common use of subquery is to perform tests for
1. set memberships,
2.setcomparisons
3.set cardinality.
➢ The subquery (inner query) executes once before the main query.
➢ The result of the subquery is used by the main query (outer query).
➢ A subquery must be enclosed in parentheses.
➢ Place the subquery on the right side of the comparison condition for readability.
Note: Comparison conditions fall into two classes:
1. single-row operators (>, =, >=, <, <>, <=) and

17
2. multiple-row operators (IN, ANY, ALL).
The subquery is often referred to as a nested SELECT, sub-SELECT, or inner
SELECT statement. The subquery generally executes first, and its output is used to complete
the query condition for the main or outer query.
Subquery Syntax

SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM
table);
Types of Subqueries
• Single-row subqueries: Queries that return only one row from the inner SELECT statement
• Multiple-row subqueries: Queries that return more than one row from the inner SELECT
Statement.
A single-row subquery
Subqueries that returns one row from the inner SELECT statement. This type of
subquery uses a single-row operator.

Multiple-Row Subqueries
Subqueries that return more than one row are called multiple-row subqueries. You use
a multiple-row operator, instead of a single-row operator, with a multiple-row subquery. The
multiple-row operator expects one or more values.

QUERIES:
1. Select loanno, branchname, amount from loan where amount=(select min(amount) from
loan)

18
2. Select sname, rollno, dept, marks from student where marks=(select min(marks) from
student group by dept;
3. Select sname, rollno, dept, marks from student where marks IN (select min(marks) from
student group by dept)
4. Select sname, rollno, dept, marks from student where marks NOT IN (select min(marks)
from student)
5. select * from loan where amount > ANY (select amount from loan where
branchname=’chennai’)
6. select * from loan where amount > ALL (select amount from loan where
branchname=’chennai’)
7. select * from loan where EXISTS (select * from borrower where
loan.loanno=borrower.loanno)
8. select * from loan where NOTEXISTS (select * from borrower where
loan.loanno=borrower.loanno)
9. select * from loan where EXCEPT (select * from borrower where
loan.loanno=borrower.loanno)
10. Find all customers who have both an account and a loan at the bank.
Select distinct cusname from customer where cusname IN (select cusname from depositor)
11. Find all customers who have a loan at the bank but do not have an account at the
bank.
Select distinct cusname from customer where cusname NOT IN (select cusname from
depositor)
12. Find the loanno,amount,branchname who have get second maximum loan amount
at the bank.
Select loanno, branchname, max(amount) from loan where amount<=(select max(amount)
from loan )
13. Write a query that displays the roll numbers and student names of all student who
studied in a department with any student whose name contains a S.
SELECT rollno, sname FROM student WHERE dept IN (SELECT dept FROM student
WHERE sname like ’%s%’);
14. List the employee names whose salary is greater than the lowest salary of an
employee belonging to department number 30.
SQL> select ename from emp
where sal>any
(select sal from emp where deptno=30);
15. List the employee details of those employees whose salary is greater than any of the
salesman.
SQL> select empno, ename, sal from emp where sal>any(
select sal from emp where job='asstprof');
16. List the employee names whose salary is greater than the highest salary of an
employee belonging to department number 20.
SQL> select ename from emp
where sal>all(select sal from emp where deptno=20);

19
RESULT:

Thus the database querying for simple, nested, sub queries and joins were performed
successfully.

20
EX.NO:4
mmmmmm
DATE:
CREATING INDEX AND DROP INDEX

AIM :
To write queries on views and indexes.

PROCEDURE :
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.
A view can contain all rows of a table or select rows from a table. A view can be created from one
or many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −Structure data in a way
that users or classes of users find natural or intuitive.Restrict access to the data in such a way that a user
can see and (sometimes) modify exactly what they need and no more.Summarize data from various tables
which can be used to generate reports.

TABLE CREATION
SQL>create table customer(cname varchar(20),street
varchar(20)); SQL>insert into customer values(‘ajay’,’north
street’); SQL>insert into customer values(‘godson’,’east
street’); SQL>insert into customer values(‘madhan’,’church
street’); SQL>insert into customer values(‘vijay’,’west street’);
SQL>select * from customer;
1. Create a view from single table containing all columns from the base
table. SQL>create view view1 as select * from customer;
SQL>select * from view1;
2. Create a view from single table with selected columns.
SQL>create view view2 as select cname,street from
customer; SQL>select * from view2;
TABLE CREATION
SQL>create table depositor(accno number,brname varchar(20));
SQL>insert into depositor values(101,’nazareth’);
SQL>insert into depositor values(102,’sattankulam’);
SQL>insert into depositor values(103,’mudhalur’);

21
SQL>select * from depositor;
SQL>create table account(accno number,cname varchar(20));
SQL>insert into account values(101,’ajay’);
SQL>insert into account values(102,’godson’);
SQL>insert into account values(105,’darwin’);
SQL>select * from account;
3. Create a view from two tables with selected columns.
SQL>create view xyz as select brname,cname from depositor d, account a where d.accno=a.accno;
SQL>select * from xyz;
TABLE CREATION
SQL>create table borrower(loanno number,brname varchar(20));
SQL>insert into borrower values(1001,’nazareth’);
SQL>insert into borrower values(1002,’sattankulam’);
SQL>insert into borrower values(1003,’mudhalur’);
SQL>select * from borrower;
SQL>create table loan(loanno number,cname varchar(20));
SQL>insert into loan values(1001,’ajay’);
SQL>insert into loan values(1002,’godson’);
SQL>insert into loan values(1005,’darwin’);
SQL>select * from account;
4. Create a view from two or more tables with union operator.
SQL> create view lmn as select brname,cname from depositor,account where depositor.accno=
account.accno union select brname,cname from borrower,loan where borrower.loanno=loan.loanno;
SQL> select * from lmn;
5. Create a view from another view.
SQL>create view view3 as select cname from xyz where brname=’nazareth’;
6. Check all DML commands with above views.
SQL> insert into view1 values (‘darwin’,’church
street’); 1 row created;
SQL>update view1 set street=’main road’ where cname like ‘ajay’;
1 row updated.
Note: Update command does not works for all queries on views.
SQL>delete from view1 where cname like ‘godson’;
1 row deleted.

22
7. Drop view which you
generated. SQL>drop
view view1;
View dropped;

SQL CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve data
from the database more quickly than otherwise. The users cannot see the indexes, they are just used to
speed up searches/queries.
TABLE CREATION
SQL>create table persons(firstname varchar(20),lastname varchar(20));
SQL>insert into persons
values(‘ajay’,’kumar’); SQL>insert into
persons values(‘jenish’,’john’); SQL>insert
into persons values(‘god’,’son’);
Syntax :
SQL>CREATE INDEX index_name ON table_name (column1, column2, ...);
Example :
create index sp1 on persons ( firstname, lastname);
 When should indexes be created:
o A column contains a wide range of values.
o A column does not contain a large number of null values.
o One or more columns are frequently used together in a where clause or a join condition.
 When should indexes be avoided:
o The table is small
o The columns are not often used as a condition in the query
o The column is updated frequently
Confirming Indexes: You can check the different indexes present in a particular table given by the user
or the server itself and their uniqueness.
Syntax :
select * from USER_INDEXES;
It will show you all the indexes present in the server, in which you can locate your
own tables too.

23
Removing an Index: Remove an index from the data dictionary by using the DROP INDEX command.
Syntax :
DROP INDEX
index;
DROP INDEX
sp1;

RESULT :
Thus the program to implement view and indexes was studied and executed successfully.

24
EX.NO:5 IMPLICIT AND EXPLICIT CURSORS

DATE:

AIM:

To create a database and apply Implicit and Explicit Cursors.

PROCEDURE:

Cursor in SQL

A cursor is a temporary work area created in the system memory when a SQL statement is executed. A cursor
contains information on a select statement and the rows of data accessed by it. This temporary work area is
used to store the data retrieved from the database, and manipulate this data. A cursor can hold more than one
row, but can process only one row at a time. The set of rows the cursor holds is called the active set.

Cursor uses

The major function of a cursor is to retrieve data, one row at a time, from a result set. Cursors are used when
the user needs to update records in a singleton fashion or in a row by row manner, in a database table.

Implicit cursors

These are created by default when DML statements like, INSERT, UPDATE, and DELETE statements
are executed. They are also created when a SELECT statement that returns just one row is executed.

Explicit cursors

They must be created when you are executing a SELECT statement that returns more than one row.
Even though the cursor stores multiple records, only one record can be processed at a time, which is
called as current row. When you fetch a row the current row position moves to next row.

IMPLICIT CURSORS:

DML statements like INSERT, UPDATE, DELETE etc.

are executed. Implicit cursor's attributes to check the

status of DML operations.

%FOUND

%NOTFOUND

%ROWCOUNT

%ISOPEN

25
Create and insert the values for customers table:

Create Procedure

DECLARE

total_rows

number(2); BEGIN

UPDATE customers

SET salary = salary + 5000;

IF sql%notfound THEN

dbms_output.put_line('no customers

updated');

ELSIF sql%found THEN

total_rows := sql

%rowcount;

dbms_output.put_line( total_rows || ' customers updated

'); END IF;

END;

Outp

ut:

Execute Query

select * from customers;

26
Explicit Cursors

SELECT statement which returns more than one row.


Syntax of explicit cursor

CURSOR cursor_name IS select_statement;

Steps:

 Declare the cursor to initialize in the memory.


 Open the cursor to allocate memory.
 Fetch the cursor to retrieve data.
 Close the cursor to release
allocated memory. DECLARE

c_id customers.id%type;
c_name customers.name

%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;
/

27
OUTPUT:

RESULT:

Data base created and applied Implicit and Explicit Cursors in a database.

28
EX.NO:6
PROCEDURES AND FUNCTIONS
DATE:

AIM:
To create a database and apply Procedures and Functions.

CREATING A PROCEDURE:

In MySQL, a procedure can also be created. A procedure can return one or more than one value through
parameters or may not return at all. The procedure can be used in SQL queries.

Syntax
CREATE PROCEDURE procedure_name[ (parameter datatype [, parameter
datatype]) ] BEGIN

Declaration_secti on
Executable_secti on

END;
Parameter

procedure_name: name of the procedure.


Parameter: number of parameters. It can be one or more than one.

EXAMPLE:
create database
db1; use db1;
CREATE TABLE Student_Details(Stu_ID int, Name varchar(255), Address
varchar(255)); Insert into Student_Details values(1,'Ramesh','Erode');

Insert into Student_Details values(11,'Arun','Erode');


Insert into Student_Details values(21,'Kumar','Tirupur');
Insert into Student_Details values(31,'Prakash','Erode');
DELIMITER $$
CREATE PROCEDURE
get_student() BEGIN

29
SELECT * FROM Student_Details;
END$$

call get_student();

OUTPUT:
1 Ramesh Erode
11 Arun Erode
21 Kumar Tirupur
31 Prakash Erode

FUNCTIONS:
Creating a function
In MySQL, Function can also be created. A function always returns a value using the return
statement. The function can be used in SQL queries.
Syntax
CREATE FUNCTION function_name [ (parameter datatype [, parameter
datatype]) ] RETURNS return_datatype
BEGIN
Declaration_secti
on
Executable_secti
on END;
Parameter:

Function_name: name of the function


Parameter: number of parameter. It can be one or more than
one. return_datatype: return value datatype of the function
declaration_section: all variables are declared.
executable_section: code for the function is written here.

30
EXAMPLE:
create database
db1; use db1;

CREATE TABLE Student_Marks (Stu_ID int, Name varchar(20), Marks int,


Age int); insert into Student_Marks values(1, "Ramesh",280,24);
insert into Student_Marks values(2,
"Suresh",320,23); insert into Student_Marks
values(3, "Kamesh",300,25); select * from
Student_Marks;

SET GLOBAL
log_bin_trust_function_creators=1;
DELIMITER $$
CREATE FUNCTION mark_check(Stu_ID int, Name varchar(20), Marks int, Age
int) RETURNS text
BEGIN
IF Marks>250 THEN
insert into Student_Marks (Stu_ID, Name, Marks, Age) values (Stu_ID, Name, Marks,
Age); RETURN 'Inserted Successfully';
else
RETURN 'Sorry Marks Less than
250'; END IF;
END;

$$

SELECT
mark_check(4,"Kamalesh",220,25);
SELECT
mark_check(4,"Kamalesh",275,25);
select* from Student_Marks;

31
OUTPUT:
1 Ramesh 280 24
2 Suresh 320 23
3 Kamesh 300 25

Sorry Marks Less than


250 Inserted
Successfully
1 Ramesh 280 24

2 Suresh 320 23
3 Kamesh 300 25
4 Kamalesh 275 25

RESULT:
Database created successfully. Procedures and Functions are executed successfully.

32
EX.NO:7
EXECUTING TRIGGERS
DATE:

AIM:

To build database and apply triggers

PROCEDURE:

TRIGGER

In MySQL, trigger can also be created. There are 6 type of triggers that can be made they
are:-

• After/Before insert
• After/Before update
• After/Before delete

1. AFTER/BEFORE INSERT Trigger

In MySQL, AFTER/BEFORE trigger can also be created. AFTER/BEFORE trigger means


trigger will invoke after the record is inserted.

Syntax:
CREATE TRIGGER
trigger_name
AFTER/BEFORE INSERT
ON table_name
FOR EACH ROW BEGIN
--variable declarations
--trigger
code END;
Parameter:
trigger_name: name of the trigger to be created.

EXAMPLE:

Step 1: Create a table, for example, student and insert the records.
create table student(id int, name varchar(20));
insert into student values(1,
"Ramesh"); insert into student
values(2, "Suresh");

33
insert into student values(3, "Kamesh");

Step 2: Create another table, for example, student1 and don't insert the records.

create table student1(s_id int auto_increment PRIMARY KEY, id int, action varchar(20), rdate

date); Step 3: Now create AFTER INSERT

trigger delimiter // CREATE

TRIGGER student_insert

AFTER INSERT ON student

FOR EACH

ROW BEGIN

INSERT INTO student1 values(null, new.id, 'inserted',

NOW()); END;

//

Step 4: Insert values in student table, it will reflect in student1

table. insert into student values(4, "Kamalesh");

select * from student;

select * from

student1;

OUTPUT:

1 Ramesh

2 Suresh

3 Kamesh

4 Kamalesh

RESULT:

Trigger program executed successfully.

34
EX.NO:8
EXECEPTION HANDLING
DATE:

AIM:

To write PL/SQL program to handle exceptions.

PROCEDURE:

DIVIDE BY ZERO EXCEPTION

PL / SQL Query:

DECLARE
a NUMBER;
b NUMBER;
c NUMBER;

BEGIN
a:=:a;
b:=:b; c:=a/b;
dbms_output.put_line('Result : '||c);

EXCEPTION
WHEN ZERO_DIVIDE
THEN RAISE_APPLICATION_
ERROR(-20003,'Invalid Input');
END;
/

Output1:

Output2:

Output 3:

35
PROGRAM-2: DUPLICATE VALUE EXCEPTION

TABLE CREATION:

QUERY:

(
CREATE TABLE employee (
eid INT PRIMARY KEY, ename VARCHAR(10),
age INT,
sal NUMBER
);

OUTPUT:

Table created .

PL / SQL Query:

DECLARE
eno NUMBER;
name VARCHAR2(10); age NUMBER;
sal NUMBER;

BEGIN
eno:=:eno;
name:=:name;
age:=:age; sal:=:sal;

INSERT INTO employee


VALUES(eno,name,age,sal);
dbms_output.put_line('Inserted');
EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN


dbms_output.put_line('Value already exists');

END;

36
Input 1:
Submit

:ENO 1

:NAME KIRTHEESH
20
:AGE
45000
:SAL

Output 1

Input 2:

Submit
:ENO 1

:NAME RUPESH
25
:AGE
50000
:SAL

Output 2

Inserted

Statement processed.

:ENO 2

:NAME BALA

:AGE 20
:SAL 45000

Output 3

Query:
Select * from employee

Input 4
:ENO 3

SAI
:NAME
20
:AGE
45000
:SAL

RESULT:
Thus the PL/SQL statement that handles exceptions were successfully
executed and verified.

37
EX.NO:10
PL/SQL HOST BLOCK
DATE:

AIM:
To Study about PL/SQL block.

DESCRIPTION:
PL/SQL
PL/SQL stands for Procedural Language extension of SQL.

PL/SQL is a combination of SQL along with the procedural features of


programming languages.
It was developed by Oracle Corporation in the early 90‟s to enhance the capabilities
of SQL.
A Simple PL/SQL Block
Each PL/SQL program consists of SQL and PL/SQL statements which from a PL/SQL
block.
PL/SQL Block consists of three sections
The Declaration section
(optional). The Execution
section (mandatory).
The Exception (or Error) Handling section (optional).
Declaration Section
The Declaration section of a PL/SQL Block starts with the reserved keyword
DECLARE. This section is optional and is used to declare any placeholders like variables,
constants, records and cursors, which are used to manipulate data in the execution section.
Placeholders may be any of Variables, Constants and Records, which stores data temporarily.
Cursors are also declared in this section.
Execution Section
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN
and ends with END. This is a mandatory section and is the section where the program logic is
written to perform any task. The programmatic constructs like loops, conditional statement
and SQL statements from the part of execution section.

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

Every statement in the above three sections must end with a semicolon ; . PL/SQL
blocks can be nested within other PL/SQL blocks. Comments can be used to document code.
A Sample PL/SQL Block Looks like:
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
PL/SQL Block Structure:
DECLARE
v_variable VARCHAR2(5);
BEGIN
SELECT
column_name INTO
v_variable FROM
table_name;
EXCEPTION
WHEN exception_name THEN
...
END;
Block Types
ANONYOUMS
[DECLARE] BEGIN
s- anonyoums
statements

39
[EXCEPTION]
END;
1. Procedur
e PROCEDURE
name IS
BEGIN
--statements
[EXCEPTION]
END;
PROCEDURE name
2. Functio
n FUNCTION
name
RETURN
datatype IS
BEGIN
--statements
RETURN
value;
[EXCEPTIO
N] END;

RESULT:
Thus the PL/SQL host blocks are studied.

40

You might also like