DBMS Practical File
DBMS Practical File
Greater Noida
(KCS-551)
Roll No.:
INDEX
S.No. Name of Program Date Of Date Of Remark
Program Submission
1. Introduction to Oracle, SQL.
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
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));
Syntax:
Alter table<tablename> add(<new col><datatype(size),<new col>datatype(size));
Ex:
alter table emp add(sal number(7,2));
Syntax:
Alter table <tablename> drop column <col>;
Ex:
alter table emp drop column sal;
Syntax:
Alter table <tablename> modify(<col><newdatatype>(<newsize>));
Ex:
alter table emp modify(ename varchar2(15));
Syntax:
Rename<oldtable> to <new table>;
Ex:
rename emp to emp1;
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.
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>);
h) check constraint
check constraint constraint at column level.
Syntax: <col><datatype>(size) 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.
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.
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.
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];
Syntax:
REVOKE<object privilege>
ON
FROM<user name>;
PROGRAM 2
DEFINITION:
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>;
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>;
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
INPUT:
SQL>ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
RESULT: Table Altered.
Similarly, ALTER TABLE EMP DROP CONSTRAINT Pkey1;
INPUT:
SQL>DROP TABLE EMP; Here EMP is table name
RESULT: Table Dropped.
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.
---
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
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
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:
SQL>desc employee;
EMP_ID EMP_NAME
………………………………………………………….
10 Robert
21 Coulthard
30 Fernando Alonso
39 Kartikeyan
87 Kimmi
SQL>desc department;
Name Null? Type
………………………………………………………………………………………..
DEPT_ID NOT NULL NUMBER(5)
DEPT_NAME VARCHAR2(20)
DEPT_ID DEPT_NAME
100 sales
101 accounts
102 administration
103 production
104 supervisor
SQL>desc paydetails;
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));
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;
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
---
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
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
ANALYST
CLERK
MANAGER
PRESIDENT
SALESMAN
assistant
clerk
7 rows selected.
SMITH
JONES
CLARK
SCOTT
KING
ADAMS
FORD
MILLER
8 rows selected.
DEFINITION:
GENERALIZED PROJECTION: - It extends the projection operation by allowing arithmetic
functions to be used in projection list.
SYNTAX:
Π F1,F2 … Fn (E)
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
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)
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
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
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:
ANALYST 6000
CLERK 23050
MANAGER 8275
PRESIDENT 5000
SALESMAN 5600
assistant 2200
clerk 2003
7 rows selected.
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.
+ + + + + +
| 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
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.
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:
QUERY &OUTPUT:
RESULT
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
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
D.O.
B
Phot
Employe o plac
Ei e
ss
d
note
s
Fnam Lnam
e e
PROGRAM 8
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:
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]
View dropped
Index created
Index dropped
PROGRAM 9
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:
SOURCE CODE:
Table created.
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.
9 rows selected.
PROGRAM 11
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:
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:
….
14 rows selected.
PROGRAM 12
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:
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
SYNTAX:
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:
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:
Old salary:1500
New salary:2000
Salary difference:500