0% found this document useful (0 votes)
91 views

DBMS Practical File

The document describes a lab report submitted by a student for their Database Management System lab. It includes an index listing 12 programs completed by the student for the lab. Program 1 provides an introduction to Oracle and SQL, describing what a DBMS is, the features of Oracle and SQL, and basic SQL commands like DDL, DML, DQL, and DCL. Program 2 explains DDL and DML commands in more detail and provides examples of creating tables for a bank and college database.

Uploaded by

Risen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

DBMS Practical File

The document describes a lab report submitted by a student for their Database Management System lab. It includes an index listing 12 programs completed by the student for the lab. Program 1 provides an introduction to Oracle and SQL, describing what a DBMS is, the features of Oracle and SQL, and basic SQL commands like DDL, DML, DQL, and DCL. Program 2 explains DDL and DML commands in more detail and provides examples of creating tables for a bank and college database.

Uploaded by

Risen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

G.L.

Bajaj Institute of Technology and


Management

Greater Noida

DEPARTMENT OF APPLIED COMPUTATIONAL


SCIENCE AND ENGINEERING

(KCS-551)

Database Management System Lab

Submitted By: Submitted To:

Roll No.:
INDEX
S.No. Name of Program Date Of Date Of Remark
Program Submission
1. Introduction to Oracle, SQL.

2. Write a SQL Statement for implementing


DDL & DML commands and create required
tables for eg: bank college database.

3. Write the queries to implement integrity


constraints & foreign constraints like primary
Key, foreign key, not null etc.

4. Write the queries to implement pattern


matching, range, list operator.

5. Write the queries to implement generalized


projection & aggregate function.

6. Write the queries to implement group by,


having and order by.

7. Write the queries to implement joins.

8. Write the queries to implement the concept


Of views & indexes.

9. Write a PL/SQL block to calculate the area


of a circle.

10. Write a PL/SQL block for inserting rows in


table.

11. Write a PL/SQL block to implement the


concept of cursor.

12. Write a PL/SQL block to implement the


concept of triggers.
PROGRAM 1

AIM: INTRODUCTION TO ORACLE, SQL.


A Database Management System (DBMS) is a set of computer programs that controls the
creation, maintenance, and the use of a database. It allows organizations to place control of
database development in the hands of database administrators (DBAs) and other specialists. A
DBMS is a system software package that helps the use of integrated collection of data records
and files known as databases. It allows different user application programs to easily access the
same database. DBMSs may use any of a variety of database models, such as the network model
or relational model. In large systems, a DBMS allows users and other software to store and
retrieve data in a structured way. Instead of having to write computer programs to extract
information, user can ask simple questions in a query language.

Oracle is an object-relational hybrid database - a relational database with added object-oriented


features - and, since Oracle 10g, a grid-enabled database - the ability to scale across multiple
inexpensive servers to provide more processing resources.

SQL is a database computer language designed for the retrieval and management of data in
relational database. SQL stands for Structured Query Language.
SQL is structure query language.SQL contains different data types those are
1. char(size)
2. varchar2(size)
3. date
4. number(p,s)
5. long
6. raw/long raw

What Can SQL do?

 SQL can execute queries against a database


 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

Different types of commands in SQL:

A). DDL commands: - To create a database objects


B). DML commands: - To manipulate data of a database objects
C). DQL command: - To retrieve the data from a database.
D). DCL/DTL commands: - To control the data of a database…
DDL commands:

1. The Create Table Command: - it defines each column of the table uniquely. Each column
has minimum of three attributes, a name , data type and size.

Syntax:
Create table<table name> (<col1><datatype>(<size>),<col2><datatype><size>));

Ex:
create table emp(empno number(4) primary key, ename char(10));

2. Modifying the structure of tables.


a)add new columns

Syntax:
Alter table<tablename> add(<new col><datatype(size),<new col>datatype(size));

Ex:
alter table emp add(sal number(7,2));

3. Dropping a column from a table.

Syntax:
Alter table <tablename> drop column <col>;

Ex:
alter table emp drop column sal;

4. Modifying existing columns.

Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));

Ex:
alter table emp modify(ename varchar2(15));

5. Renaming the tables

Syntax:
Rename<oldtable> to <new table>;

Ex:
rename emp to emp1;

6. truncating the tables.

Syntax:
Truncate table<tablename>;

Ex:
trunc table emp1;

7. Destroying tables.

Syntax:
Drop table<tablename>;

Ex:
drop table emp;

DML commands:

8. Inserting Data into Tables: - once a table is created the most natural thing to do is load this
table with data to be manipulated later.

Syntax:
insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);

9. Delete operations.

a) remove all rows


Syntax:
delete from <tablename>;

b) removal of a specified row/s


Syntax:
delete from <tablename> where <condition>;

10. Updating the contents of a table.

a) updating all rows


Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>;

b) updating seleted records.


Syntax:
Update <tablename> set <col>=<exp>,<col>=<exp>
where <condition>;

11. Types of data constrains.


a) not null constraint at column level.
Syntax:
<col><datatype>(size)not null

b) unique constraint
Syntax:
Unique constraint at column level.
<col><datatype>(size)unique;
c) unique constraint at table level:
Syntax:
Create table tablename(col=format,col=format,unique(<col1>,<col2>);

d) primary key constraint at column level


Syntax:
<col><datatype>(size)primary key;

e) primary key constraint at table level.


Syntax:
Create table tablename(col=format,col=format
primary key(col1>,<col2>);

f) foreign key constraint at column level.


Syntax:
<col><datatype>(size>) references <tablename>[<col>];

g) foreign key constraint at table level


Syntax:
foreign key(<col>[,<col>])references <tablename>[(<col>,<col>)

h) check constraint
check constraint constraint at column level.
Syntax: <col><datatype>(size) check(<logical expression>)

i) check constraint constraint at table level.


Syntax: check(<logical expression>)

DQL Commands:

12. Viewing data in the tables: - once data has been inserted into a table, the next most logical
operation would be to view what has been inserted.

a) all rows and all columns


Syntax:
Select <col> to <col n> from tablename;

Select * from tablename;

13. Filtering table data: - while viewing data from a table, it is rare that all the data from table
will be required each time. Hence, sql must give us a method of filtering out data that is not
required data.

a) Selected columns and all rows:


Syntax:
select <col1>,<col2> from <tablename>;

b) selected rows and all columns:


Syntax:
select * from <tablename> where <condition>;

c) selected columns and selected rows


Syntax:
select <col1>,<col2> from <tablename> where<condition>;

14. Sorting data in a table.


Syntax:
Select * from <tablename> order by <col1>,<col2><[sortorder]>;

DCL commands:
Oracle provides extensive feature in order to safeguard information stored in its tables from
unauthoraised viewing and damage.The rights that allow the user of some or all oracle resources
on the server are called privileges.

a) Grant privileges using the GRANT statement

The grant statement provides various types of access to database objects such as tables,views
and sequences and so on.

Syntax:
GRANT <object privileges>
ON <objectname>
TO<username>
[WITH GRANT OPTION];

b) Reoke permissions using the REVOKE statement:

The REVOKE statement is used to deny the Grant given on an object.

Syntax:
REVOKE<object privilege>
ON
FROM<user name>;
PROGRAM 2

AIM: WRITE A SQL STATEMENT FOR IMPLEMENTING DDL & DML


COMMANDSAND CREATE REQUIRED TABLES, FOR EG: BANK,
COLLEGE DATABSE.

DEFINITION:

DDL (Data Definition Language)


DDL statements are used to alter/modify a database or table structure and schema. These
statements handle the design and storage of database objects.
CREATE – create a new Table, database, schema
ALTER – alter existing table, column description
DROP – delete existing objects from database
RENAME – used to rename the exiting table

SYNTAX:
CREATE TABLE tablename (column_name data_ type constraints, …)
Alter table<tablename> add(<new col><datatype(size),<new col>datatype(size));
Alter table <tablename> drop column <col>;
Alter table <tablename> modify(<col><newdatatype>(<newsize>));
Drop table<tablename>;
Rename<oldtable> to <new table>;

DML (Data Manipulation Language)


DML statements affect records in a table. These are basic operations we perform on data such as
selecting a few records from a table, inserting new records, deleting unnecessary records, and
updating/modifying existing records.
DML statements include the following:
INSERT – insert new records
UPDATE – update/Modify existing records
DELETE – delete existing records

SYNTAX:
insert into <tablename> (<col1>,<col2>) values(<exp>,<exp>);
Update <tablename> set <col>=<exp>,<col>=<exp>;
a) remove all rows
delete from <tablename>;
b) removal of a specified row/s
delete from <tablename> where <condition>;

DQL (Data Query Language)


Used to query the database
SELECT – select records from a table
SYNTAX:
Select * from tablename;

QUERY:
INPUT:
SQL> CREATE TABLE Emp ( EmpNo short CONSTRAINT PKey PRIMARY KEY,
EName VarChar(15), Job Char(10) CONSTRAINT Unik1 UNIQUE,
Mgr short CONSTRAINT FKey1 REFERENCES EMP (EmpNo),
Hiredate Date, DeptNo short CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
RESULT: Table created.
SQL>Create table prog20 (pname varchar2(20) not null), doj date not null,dob date not
null,
sex varchar(1) not null, prof1 varchar(20),prof2 varchar(20),salary number(7,2) not
null);
RESULT:
Table created.
SQL>desc prog20;
Name Null? Type

PNAME NOT NULL VARCHAR2(20)


DOJ NOT NULL DATE
DOB NOT NULL DATE
SEX NOT NULL VARCHAR2(1)
PROF1 VARCHAR2(20)
PROF2 VARCHAR2(20)
SALARY NOT NULL NUMBER(7,2)

2. SQL - ALTER TABLE

INPUT:
SQL>ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
RESULT: Table Altered.
Similarly, ALTER TABLE EMP DROP CONSTRAINT Pkey1;

3. SQL - DROP TABLE


– Deletes table structure – Cannot be recovered – Use with caution

INPUT:
SQL>DROP TABLE EMP; Here EMP is table name
RESULT: Table Dropped.

4. TRUNCATE TRUNCATE TABLE <TABLE NAME>;

1. SQL - INSERT INTO


Syntax: INSERT INTO tablename VALUES (value list)
Single-row insert
INSERT INTO S VALUES(‘S3’,’SUP3’,’BLORE’,10)
Inserting one row, many columns at a time
INSERT INTO S (SNO, SNAME) VALUES (‘S1’, ‘Smith’);S1’ Smith’
Inserting many rows, all/some columns at a time.
INSERT INTO NEW_SUPPLIER (SNO, SNAME)
SELECT SNO, SNAME FROM S
WHERE CITY IN (‘BLORE’,’MADRAS’)
Other Examples:

INPUT:
SQL>Insert into prog values (‘kkk’,’05-may-56’);
RESULT: 1 row created.

INPUT:
SQL>Insert into prog20 values(‘Hema’,’25-sept-01’28-jan-85’,’f’,’c’,’c++’,’25000’);
RESULT: 1 row created.

INPUT:
SQL>Insert into prog values(‘&pname’,’&doj’);
SQL> Insert into prog values('&pname','&doj');
Enter value for pname: ravi
Enter value for doj: 15-june-81
RESULT:
old 1: Insert into prog values('&pname','&doj')
new 1: Insert into prog values('ravi','15-june-81')
1 row created.

2. SQL - UPDATE
Syntax: UPDATE tablename SET column_name =value [ WHERE condition]
Examples:
UPDATE SET CITY = ‘KANPUR’ WHERE SNO=‘S1’
UPDATE EMP SET SAL = 1.10 * SAL
SQL> update emp set sal=20000 where empno=7369;
1 row updated.

3. SQL - DELETE FROM


Syntax: DELETE FROM tablename WHERE condition
Examples:
DELETE FROM SP WHERE PNO= ‘P1’
DELETE FROM SP
INPUT:
SQL>Delete from emp where empno=7369;
RESULT: 1 row deleted.

Get the description of EMP table.


SQL>desc emp;
RESULT:
Name Null? Type

EMPNO NOT NULL 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 DEPT table.
SQL>desc dept;
RESULT:
Name Null? Type

DEPTNO NOT NULL NUMBER(2)


DNAME VARCHAR2(14)
LOC VARCHAR2(13)

3.List all employee details.


SQL>select * from emp;
RESULT:
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
PROGRAM 3

AIM: WRITE THE QUERIES TO IMPLEMENT INTEGRITY


CONSTRAINTS & FOREIGN CONSTRAINTS LIKE PRIMARY KEY,
FOREIGN KEY, NOT NULL ETC.

DEFINITION:

Integrity constraints are used to ensure accuracy and consistency of data in a relational
database. Data integrity is handled in a relational database through the concept of referential
integrity.There are many types of integrity constraints that play a role in referential integrity
(RI). These constraints include Primary Key, Foreign Key, Unique Constraints

Following are commonly used constraints available in SQL.

 NOT NULL Constraint: Ensures that a column cannot have NULL value.
 DEFAULT Constraint: Provides a default value for a column when none is specified.
 UNIQUE Constraint: Ensures that all values in a column are different.
 PRIMARY Key: Uniquely identified each rows/records in a database table.
 FOREIGN Key: Uniquely identified a rows/records in any another database table.
 CHECK Constraint: The CHECK constraint ensures that all values in a column satisfy
certain conditions.

Dropping Constraints:
Any constraint that you have defined can be dropped using the ALTER TABLE command with
the DROP CONSTRAINT option.
For example, to drop the primary key constraint in the EMPLOYEES table, you can use the
following command:
ALTER TABLE EMPLOYEES DROP CONSTRAINT EMPLOYEES_PK;
Some implementations may provide shortcuts for dropping certain constraints. For example, to
drop the primary key constraint for a table in Oracle, you can use the following command:
ALTER TABLE EMPLOYEES DROP PRIMARY KEY;

SYNTAX:
CREATE TABLE table_name( column_name1 data_type(size) constraint_name,
column_name2 data_type(size) constraint_name, column_name3 data_type(size)
constraint_name, );

QUERY:

Create table employee(emp_id number(5) primary key,emp_name varchar2(25));

SQL>desc employee;

Name Null? Type


………………………………………………………………………………………..
EMP_ID NOT NULL NUMBER(5)
EMP_NAME VARCHAR2(25)
Valid Test Data:

SQL>insert into employee values(&emp_id,’&emp_name’);


SQL>select * from employee;

EMP_ID EMP_NAME
………………………………………………………….
10 Robert
21 Coulthard
30 Fernando Alonso
39 Kartikeyan
87 Kimmi

SQL>create table department(dept_id number(5) primary key,dept_name varchar2(20));

SQL>desc department;
Name Null? Type
………………………………………………………………………………………..
DEPT_ID NOT NULL NUMBER(5)
DEPT_NAME VARCHAR2(20)

SQL>insert into department values(&dept_id,’&dept_name’);


SQL>select * from department;

DEPT_ID DEPT_NAME
100 sales
101 accounts
102 administration
103 production
104 supervisor

SQL>create table paydetails(emp_id number(5) references employee(emp_id),dept_id


number(5) reerences department(dept_id),basic number(7,2),deductions number(5,2),additions
number(5,2),doj date);

SQL>desc paydetails;

Name Null? Type


………………………………………………………………………………………..
EMP_ID NUMBER(5)
DEPT_ID NUMBER(5)
BASIC NUMBER(7,2)
DEDUCTIONS NUMBER(5,2)
ADDITIONS NUMBER(5,2)
DOJ DATE

Different Data Sets:


SQL>insert into paydeatils values(&emp_id,&dept_id,
&basic,&deductions,&additions,&doj);

SQL>select * from paydeatils;


EMP_ID DEPT_ID BASIC DEDUCTIONS ADDITIONS DOJ
……………………………………………………………………………………………………
……………..
10 101 25023.12 43.09 71.23 08-JAN-93
21 100 10500.29 23.98 40.9 01-JAN-06
30 102 6500.5 30.54 15 06-JUL-97
39 103 9700.45 32.78 65.09 08-AUG-03
87 104 15000 97.66 154.8 24-SEP-04

SQL>create table payroll(emp_id number(5)references employee(emp_id),pay_date date);


SQL>desc payroll;

Name Null? Type


………………………………………………………………………………………..
EMP_ID NUMBER(5)
PAY_DATE DATE

SQL>CREATE TABLE PersonsNotNull (P_Id int NOT NULL,LastName varchar(255) NOT


NULL, FirstName varchar(255),Address varchar(255),City varchar(255));

SQL>CREATE TABLE employee ( id number(5) PRIMARY KEY,name char(20),dept


char(10),age number(2),salary number(10),location char(10) UNIQUE );

SQL> CREATE TABLE employee( id number(5) PRIMARY KEY, name char(20), dept
char(10), age number(2), gender char(1) CHECK (gender in ('M','F')),
salary number(10),location char(10));

SQL>CREATE TABLE employee( id number(5) PRIMARY KEY, name char(20),


dept char(10), age number(2), gender char(1), salary number(10),
location char(10), CONSTRAINT gender_ck CHECK (gender in ('M','F')));
PROGRAM 4

AIM: WRITE THE QUERIES TO IMPLEMENT PATTERN MATCHING,


RANGE, LIST OPERATOR.

DEFINITION:

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

SYNTAX:
SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1
AND value2;

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

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

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

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

QUERY:
1. Get the description of EMP table.
SQL>desc emp;
RESULT:
Name Null? Type

EMPNO NOT NULL 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 DEPT table.


SQL>desc dept;
RESULT:
Name Null? Type

DEPTNO NOT NULL NUMBER(2)


DNAME VARCHAR2(14)
LOC VARCHAR2(13)

3. List all employee details.


SQL>select * from emp;
RESULT:
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

4. List all employee names and their salaries, whose salary lies between
1500/- and 3500/- both inclusive.
INPUT
SQL>select ename from emp where sal between 1500 and 3500;
RESULT
ENAME

ALLEN
JONES
BLAKE
CLARK
SCOTT
TURNER
FORD
russel
greg
9 rows selected.

5. List all employee names and their and their manager whose manager is
7902 or 7566 0r 7789.
INPUT SQL>select ename from emp where mgr in(7602,7566,7789);
RESULT
ENAME

SCOTT
FORD

6. List all employees which starts with either J or T.


INPUT SQL>select ename from emp where ename like ‘J%’ or ename like ‘T%’;
RESULT:
ENAME

JONES
TURNER
JAMES

7. List all employee names and jobs, whose job title includes M or P.
INPUT SQL>select ename,job from emp where job like ‘M%’ or job like ‘P%’;
RESULT:
ENAME JOB

JONES MANAGER
BLAKE MANAGER
CLARK MANAGER
KING PRESIDENT

8. List all jobs available in employee table.


INPUT SQL>select distinct job from emp;
RESULT:
JOB

ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
assistant
clerk
7 rows selected.

9. List all employees who belongs to the department 10 or 20.


INPUT SQL>select ename from emp where deptno in (10,20);
RESULT:
ENAME

SMITH
JONES
CLARK
SCOTT
KING
ADAMS
FORD
MILLER
8 rows selected.

10. List all employees who have id in between 1 to 3


INPUTSQL>SELECT * FROM EmployeeDetails WHERE empid BETWEEN 1 and 3;
PROGRAM 5

AIM: WRITE THE QUERIES TO IMPLEMENT GENERALISED


PROJECTION &AGGREGATE FUNCTION.

DEFINITION:
GENERALIZED PROJECTION: - It extends the projection operation by allowing arithmetic
functions to be used in projection list.

SYNTAX:

Π F1,F2 … Fn (E)

Where E: relational algebra expression


Fi: arithmetic expression
AGGREGATE FUNCTION:-It takes a collection of values and returns a single value as a
result.

QUERY& OUTPUT:
1. List all employee names , salary and 15% rise in salary.
INPUT SQL>select ename , sal , sal+0.15* sal from emp;
RESULT:
ENAME SAL SAL+0.15*SAL

SMITH 800 920


ALLEN 1600 1840
WARD 1250 1437.5
JONES 2975 3421.25
MARTIN 1250 1437.5
BLAKE 2850 3277.5
CLARK 2450 2817.5
7 rows selected.
2. List minimum , maximum , average salaries of employee.
INPUT SQL>select min(sal),max(sal),avg(sal) from emp;
RESULT:
MIN(SAL) MAX(SAL) AVG(SAL)

3 5000 1936.94118
3. Find how many job titles are available in employee table.
INPUT SQL>select count (distinct job) from emp;
RESULT:
COUNT(DISTINCTJOB)

4. What is the difference between maximum and minimum salaries of


employees in the organization?
INPUT SQL>select max(sal)-min(sal) from emp;
RESULT:
MAX(SAL)-MIN(SAL)

4997
5. Display all employee names and salary whose salary is greater than
minimum salary of the company and job title starts with ‘M’.
INPUT SQL>select ename,sal from emp where job like ‘M%’ and sal > (select min
(sal)
from emp);
RESULT
ENAME SAL

JONES 2975
BLAKE 2850
CLARK 2450
6. Find how much amount the company is spending towards salaries.
INPUT SQL>select sum (sal) from emp;
RESULT
SUM(SAL)

32928
7. Display name of the dept. with deptno 20.
INPUT SQL>select ename from emp where deptno = 20;
RESULT
ENAME

SMITH
JONES
SCOTT
ADAMS

8. List ename whose commission is NULL.


INPUT SQL>select ename from emp where comm is null;
ENAME
RESULT ----------
CLARK
SCOTT
KING
ADAMS
JAMES
FORD
6 rows selected.

9. Find no.of dept in employee table.


INPUT SQL>select count (distinct ename) from emp;
RESULT
COUNT(DISTINCTENAME

17
10. List ename whose manager is not NULL.
INPUT SQL>select ename from emp where mgr is not null;
RESULT
ENAME

SMITH
ALLEN
WARD
JONES
MARTIN
5 rows selected.
PROGRAM 6

AIM: WRITE THE QUERIES TO IMPLEMENT GROUPBY,HAVING


AND ORDERBY.

DEFINITION:

GROUP BY clause is used in collaboration with the SELECT statement to arrange identical
data into groups. The GROUP BY clause follows the WHERE clause in a SELECT statement
and precedes the ORDER BY clause.

SYNTAX:
SELECT column1, column2 FROM table_name WHERE [ conditions ] GROUP BY column1,
column2 ORDER BY column1, column2;

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

SYNTAX:
SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY
column1, column2 HAVING [ conditions ] ORDER BY column1, column2;

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

SYNTAX:
SELECT column-list FROM table_name [WHERE condition][ORDER BY column1,
column2,.. columnN][ASC | DESC];

QUERY &OUTPUT:

Source tables: emp, dept, programmer, software, study.


1. Display total salary spent for each job category.

INPUT SQL>select job,sum (sal) from emp group by job;


RESULT
JOB SUM(SAL)

ANALYST 6000
CLERK 23050
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
assistant 2200
clerk 2003
7 rows selected.

2. Display lowest paid employee details under each manager.


INPUT
SQL>select ename, sal from emp where sal in (select min(sal) from emp group by
mgr);
RESULT
ENAME SAL

chai 3
JAMES 950
MILLER 1000
ADAMS 1100
russel 2200
5 rows selected.
3. Display number of employees working in each department and their
department name.
INPUT SQL> select dname, count (ename) from emp, dept where
emp.deptno=dept.deptno
group by dname;
RESULT
DNAME COUNT(ENAME)

ACCOUNTING 3
RESEARCH 5
SALES 9
4. Display the sales cost of package developed by each programmer.
INPUT SQL>select pname, sum(scost) from software group by pname;
RESULT
PNAME SUM(SCOST)

john 12000
kamala 12000
raju 12333
3 rows selected.
5. Display the number of packages sold by each programmer.
INPUT SQL>select pname, count(title) from software group by pname;
RESULT
PNAME COUNT(TITLE)

john 1
kamala 1
raju 1
ramana 1
rani 1
5 rows selected.
6. Display the number of packages in each language for which the
development cost is less than thousand.
INPUT SQL>select devin, count(title) from software where dcost < 1000 group by
devin;
RESULT
DEVIN COUNT(TITLE)

cobol 1
7. Display each institute name with number of students.
INPUT
SQL>select splace, count(pname) from study group by splace;

RESULT
SPLACE COUNT(PNAME)

BDPS 2
BITS 1
BNRILLIANI 1
COIT 1
HYD 1
5 rows selected.

8. Display details of customers.


INPUT SQL>select * from customers;
RESULT

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

9. Display details of customers whose age count would be more than or equal to
two.
INPUT SQL>select id, name, age, address, salary from customers group by agehaving
count(age)>=2;
RESULT

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
|2|Khilan|25|Delhi|1500.00|
+ + + + + +

10. Display details of customers &sort the result in ascending order by NAME and
SALARY
INPUT SQL> select * from customersorder by name, salary;
RESULT

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

AIM: WRITE THE QUERIES TO IMPLEMENT JOINS.

DEFINITION:

SQL JOIN clause is used to combine rows from two or more tables, based on a common field
between them.The most common type of join is: SQL INNER JOIN (simple join). An SQL
INNER JOIN returns all rows from multiple tables where the join condition is met.

The types of the different SQL JOINs are:

 INNER JOIN: Returns all rows when there is at least one match in BOTH tables
 LEFT JOIN: Return all rows from the left table, and the matched rows from the right
table
 RIGHT JOIN: Return all rows from the right table, and the matched rows from the left
table
 FULL JOIN: Return all rows when there is a match in ONE of the tables

SYNTAX:

1. SELECT column_name(s) FROM table1INNER JOIN table2 ON


table1.column_name=table2.column_name;
2. SELECT column_name(s)FROM table1LEFT JOIN table2ON
table1.column_name=table2.column_name;
3. SELECT column_name(s)FROM table1RIGHT JOIN table2ON
table1.column_name=table2.column_name;
4. SELECT column_name(s)FROM table1FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

QUERY &OUTPUT:

1. Display details of customers.


INPUT SQL> select * from customers;
RESULT
CustomerName ContactName Address City PostalCode Country
CustomerID
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la
México
2 Ana Trujillo Constitución 05021 Mexico
Emparedados y D.F.
2222
helados
3 Antonio Mataderos México
Antonio Moreno 05023 Mexico
Taquería Moreno 2312 D.F.
2. Display details of orders.
INPUT SQL> select * from orders;
RESULT
OrderID CustomerID EmployeeID OrderDate ShipperID
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
3. Display details of all the customers with orders.
INPUT SQL>Select customers.customername, orders.orderid from customers inner join
orders on customers.customerid=orders.customerid order by customers.customername;
RESULT

Number of Records: 196


CustomerName OrderID
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Around the Horn 10383
Around the Horn 10355
Berglunds snabbköp 10278
Berglunds snabbköp 10280
Berglunds snabbköp 10384
Blondel père et fils 10265

4. Display details of all the customers with any order.

INPUT SQL>select customers.customername, orders.orderid from customers left join


orders on customers.customerid=orders.customerid order by customers.customername;

RESULT

Number of Records: 213


CustomerName OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
Around the Horn 10383
Around the Horn 10355
Berglunds snabbköp 10278
Berglunds snabbköp 10280
Berglunds snabbköp 10384

5. Display details of all the employees.

INPUT
SQL>select * from employees;

RESULT
EmployeeID LastName FirstName BirthDate Photo Notes
Education includes a BA in
1 Davolio Nancy 12/8/1968 EmpID1.pic
psychology.....
Andrew received his BTS
2 Fuller Andrew 2/19/1952 EmpID2.pic
commercial and....
Janet has a BS degree in
3 Leverling Janet 8/30/1963 EmpID3.pic chemistry....

6. Display details of all the employees, and any orders they have placed.
INPUT SQL>select orders.orderid, employees.firstname from orders right join
employees on orders.employeeid=employees.employeeid order by orders.orderid;

RESULT
Number of Records: 197
OrderID FirstName
Adam
10248 Steven
10249 Michael
10250 Margaret
10251 Janet
10252 Margaret
10253 Janet
10254 Steven
10255 Anne
10256 Janet
10257 Margaret
10258 Nancy
10259 Margaret
10260 Margaret
10261 Margaret
10262 Laura
10263 Anne
......... so on

7. Display details of all customers, and all orders.


INPUT SQL>select customers.customername, orders.orderid from customers full outer
join orders on customers.customerid=orders.customerid order by
customers.customername;
RESULT

CustomerName OrderID
Alfreds Futterkiste
Ana Trujillo Emparedados y helados 10308
Antonio Moreno Taquería 10365
10382
10351
ER DIAGRAM OF JOIN

ci
cit Addre Oi d
y s d
cnam
e
Custome M d M
o Order Ei
rs s
ci d
d

Posta Countr Shipper Order


lcode y id date

D.O.
B

Phot
Employe o plac
Ei e
ss
d
note
s
Fnam Lnam
e e
PROGRAM 8

AIM: WRITE THE QUERIES TO IMPLEMENT THE CONCEPT OF


VIEWS & INDEXES.

DEFINITION:
VIEW is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database.

INDEX can be created in a table to find data more quickly and efficiently.
The users cannot see the indexes, they are just used to speed up searches/queries.

SYNTAX:

1. create view view_name as select column_name(s) from table_name where


condition;
2. create index index_name on table_name (column_name);
3. drop view view_name;
4. drop index index_name

QUERY &OUTPUT:

1. Display details of every product in the "Products" table with a unit price higher
than the average unit price.
INPUT SQL>create view [products above average price] as select
productname,unitprice from products where unitprice>(select avg(unitprice) from
products);
RESULT

View created
To see run
SQL>select * from [products above average price]

2. Drop the above view created.


INPUT SQL>drop view [products above average price];
RESULT

View dropped

3. Create an index on a combination of columns.


INPUT SQL>create index pindex on persons (lastname);
RESULT

Index created

4. Drop the above created index.


INPUT SQL>drop index pindex;
RESULT

Index dropped
PROGRAM 9

AIM: WRITE A PL/SQL BLOCK TO CALCULATE THE AREA OF A


CIRCLE.

DEFINITION:
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.
PL/SQL is one of three key programming languages embedded in the Oracle Database, along
with SQL itself and Java.

SYNTAX:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

PROGRAM CODE:

SQL>create table mycircle2 (area number(10),radius number(2));


Table Created.
SQL>set serevroutput on;
Declare
Area number(10);
Radius number(2);
Pi constant number(3,2):=3.14;
Begin
Radius:=&radius;
While radius<8
Loop
Area:=pi*power(radius,2);
Insert into mycircle values(area,radius);
Radius:=radius+1;
end loop;
end;
OUTPUT:
Enter value for radius:5
Old 6:radius:=&radius;
New6:radius:=5;
PL/SQ procedure successfully completed.
SQL>select * from mycircle;
AREA RADIUS
————— ——————–
79 5
113 6
154 7
PROGRAM 10

AIM: WRITE A PL/SQL BLOCK FOR INSERTING ROWS IN TABLE.

SOURCE CODE:

SQL> create table Employee(


2 ID VARCHAR2(4 BYTE),
3 First_Name VARCHAR2(10 BYTE),
4 Last_Name VARCHAR2(10 BYTE),
5 Start_Date DATE,
6 End_Date DATE,
7 Salary Number(8,2),
8 City VARCHAR2(10 BYTE),
9 Description VARCHAR2(15 BYTE)
10 )
11 /

Table created.

SQL> select * from Employee


2 /

ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY


DESCRIPTION

01 Jason Martin 25-JUL-96 25-JUL-06 1234.56 Toronto


Programmer
02 Alison Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester
03 James Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester
04 Celia Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager
05 Robert Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester
06 Linda Green 30-JUL-87 04-JAN-96 4322.78 New York Tester
07 David Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager
08 James Cat 17-SEP-96 15-APR-02 1232.78 Vancouver Tester

8 rows selected.

SQL> DECLARE
2 quant NUMBER := 20;
3 BEGIN
4 INSERT INTO employee (salary)
5 VALUES (quant);
6 IF (SQL%NOTFOUND)
7 THEN
8 dbms_output.put_line('Insert error?!');
9 END IF;
10 END;
11 /
OUTPUT:
PL/SQL procedure successfully completed.

SQL> SELECT * FROM employee;

ID FIRST_NAME LAST_NAME START_DAT END_DATE SALARY CITY


DESCRIPTION

01 Jason Martin 25-JUL-96 25-JUL-06 1234.56 Toronto


Programmer
02 Alison Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester
03 James Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester
04 Celia Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager
05 Robert Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester
06 Linda Green 30-JUL-87 04-JAN-96 4322.78 New York Tester
07 David Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager
08 James Cat 17-SEP-96 15-APR-02 1232.78 Vancouver Tester
20

9 rows selected.
PROGRAM 11

AIM: WRITE A PL/SQL BLOCK TO IMPLEMENT THE CONCEPT OF


CURSOR.

DEFINITION:

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

SYNTAX:

Create a Cursor which update the salaries of an Employee as follows.

1. if sal<1000then update the salary to 1500.

2. if sal>=1000 and <2000 then update the salary to 2500.

3. if sal>=2000 and <=3000 then update the salary to 4000.

And also count the no.of records have been updated.*/

HW/SW requirements:
Processor : Intel i3
RAM : 2 GB
Hard Disk : 500 GB
Software : Oracle, PlSQL

SOURCE CODE:
Declare
Cursor my_cur is select empno,sal from emp;
Xno emp.empno%type;
Xsal emp.sal%type;
C number;
Begin
Open my_cur;
C:=0;
Loop
Fetch my_cur into xno,xsal;
If(xsal<1000) then
Update emp set sal=3000 where empno=xno;
C:=c+1;
Else if(xsal>=2000) and xsa<3000) then
Update emp set sal=4000 where empno=xno;
C:=c+1;
End if;
End if;
Exit when my_cur%NOTFOUND ;
End loop;
Close my_cur;
Dbma_output.put_line(c||’records have been successfully
updated’);
End;
Sql>@a.sql;
records have been successfully updated
pl/sql procedure successfully completed.
Valid Test Data
Before executing the cursor, the records in emp table as follows
Sql>select * from emp;
OUTPUT:

EMPNO ENAME JOB MGR HIREDATE SAL COMMD EPTNO

7369 SMITH CLERK 7902 17-DEC-80 2000 20

7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

7566 JONES MANAGER 7839 02-APR-81 2975 20

7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30

7698 BLAKE MANAGER 7839 01-MAY-81 2850 30

….

14 rows selected.
PROGRAM 12

AIM: WRITE A PL/SQL BLOCK TO IMPLEMENT THE CONCEPT OF


TRIGGERS.

DEFINITION:

TRIGGERS are stored programs, which are automatically executed or fired when some events
occur. Triggers are, in fact, written to be executed in response to any of the following events:

 A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).


 A database definition (DDL) statement (CREATE, ALTER, or DROP).
 A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).

Triggers could be defined on the table, view, schema, or database with which the event is
associated.

SYNTAX:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR]| UPDATE [OR]| DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

SOURCE RELATION:
Select*from customers;

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
|1|Ramesh|32|Ahmedabad|2000.00|
|2|Khilan|25|Delhi|1500.00|
|3| kaushik |23|Kota|2000.00|
|4|Chaitali|25|Mumbai|6500.00|
|5|Hardik|27|Bhopal|8500.00|
|6|Komal|22| MP |4500.00|
+ + + + + +
SOURCE CODE:

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID >0)
DECLARE
sal_diff number;
BEGIN
sal_diff :=:NEW.salary -:OLD.salary;
dbms_output.put_line('Old salary: '||:OLD.salary);
dbms_output.put_line('New salary: '||:NEW.salary);
dbms_output.put_line('Salary difference: '|| sal_diff);
END;
/

OUTPUT:

Trigger created.

TRIGGERING A TRIGGER:
SQL>INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)VALUES
(7,'Kriti',22,'HP',7500.00);

Old salary:
New salary:7500
Salary difference:

SQL>UPDATE customersSET salary = salary +500WHERE id =2;

Old salary:1500
New salary:2000
Salary difference:500

You might also like