DBMS Lab Manual
DBMS Lab Manual
Laboratory Manual
G. Mahesh
Associate Professor
Author:
G.MAHESH,
Associate professor,
Dept of C.S.E.
Co-Authors:
K.V Krishnam Raju,
Associate professor,
Dept of C.S.E.
K.Aruna Kumari,
Assistant professor,
Dept of C.S.E.
Index
2. Creation of tables 5
3. Set Operations 12
5. Triggers 26
8. Importing Tables 41
9. Mini Project 45
10. MySQL 46
Database Management System Lab Manual 1
Expno: 01 Date:
Simple SQL commands
Aim:-
To Practice simple SQL commands for retrieving data contained in
‘Emp’ and ‘ Dept’ tables.
Theory:-
Questions including data stored in a Data Base are called Queri es.
The SQL stands for structured quer y language. It is a non procedural
language used to define, access and manipulate data. The meani ng of non -
procedural is that it describes the necessary components (i.e., t ables) and
desired results without dictating exactly how results should be computed.
To bring confor mit y among vendors , the American National Standards
Institute (ANSI) publ ished its first SQL standard in 1986 and a second
widel y adopted standard in1989. ANSI released updates in 1992, known as
SQL92 and SQL2, and again in 1999, ter med as both SQL99 and SQL3.
In SQL92, SQ L statements are grouped into three broad categor ies.
They are the Data Manipulation Language (DML), the Data Definition
Language (DDL), and the Data Control Language ( DCL) . The DML provides
specific data -manipul ation commands such as SELECT, INSERT, UPDAT E,
and DELETE. The DDL contains commands that handle the accessibility and
manipulation of database obj ects, including CREATE and DROP, while the
DCL contains the per mission -related commands GRANT and REVOKE.
The SELECT statement is used to retrieve data f rom a database. The
basic for m of an SQL query is
select [distinct ] sel ect -list f rom from-l ist w here qualification;
Where select, distinct, from and where are key words. Select -list is
list of column names separated by commas and from -list is table or list of
tables from which data is obtained. If from -list is list of tables, then the
result is cross product of both table’s contents. The Qualification in the
optional where clause is a Boolean combination of conditions. The optional
distinct key word is used to select unrepeated values.
We can also use an optional order by clause to display the contents in
sorting order .
Relational operators are <, <=, >, >=, <>, =
They are for less than, less than or equal to, greater than, great er than or
equal to, not equal to, equal to.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 2
Procedure:
1. For getting SQL prompt
a. Click start
b. Click all programs
c. Click Oracle
d. Click Applicattion development
e. Click SQL plus
2. At Logon window enter the following data.
a. User name : syste m
b. Password : manager
c. Host string : oracle9
3. After getting SQL prompt t ype the following command to create a new
user user001 for dial y log in with 100mb of space.
create user user001
identif ied by password001
quota 100m on users;
4. Grant per missions to user using the following command.
grant connect,create session,resource to user001;
5. Now copy emp and dept tables from scott to user001 using the
folowing commands,
create table user001.dept as select * f rom scott.dept ;
create table user001.emp as select * f rom scott.emp;
6. Now use the following sequence to save the wor k and quit from SQL
prompt.
commit;
exit;
7. Again go to SQL prompt.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 3
6. Display the details of employees whose salar ies are greater than 2000.
10. Display the name, designation and salar y of employees whose salaries
are less than 2000.
11. Display the name, designation and salar y of employees whose salaries
are between 2500 and 3000.
12. Display the name, designation and salar y of employees whose salaries
are less than 2500 and that of employees whose salaries are greater
than 3000.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 4
15. Display the names and designation of employees whose desi gnation is
manager and whose salary is greater than 2500.
16. Display the details of employees whose names start with letter s.
17. Display the details of employees whose names end with letter t.
25. Display names o f employees and salaries in order of salaries such that
employee with max sal ary is at the bottom.
27. Display names of employees and j oining dates in the order of j oining
dates.
28. Display the de tails of salesman and manager whose salary is 1500 or
more.
32. Display location of the depart ment in which ‘scott’ is wor king.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 5
Expno: 02 Date:
Creation of tables
Aim: -
To create, modif y and update tables and t o practice some aggregate
functions.
Theory:-
Create table: Tables are defined using the create command. The simplified
for m of create command is
create table r
( A1 D1, A2 D2,…, An Dn,
[ integrit y_constraint1 ],…,[ integrity_constr aintn])
| as select_statement;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 6
insert into r
[(A1, A2, ..,An)] val ues(v1, v2, ..,vn)
| select statement ;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 7
The input to SUM and AVG must be a coll ection of numbers but the
other operators can operate on collection of non -numeric data types li ke
strings.
For example,
select sum(sal) f rom emp; displays total salaries of all the employees.
select count(com) f rom emp; displays no. of employees with
commission.
select count (*) f rom emp; displays no. of records in emp.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 8
All the functions except COUNT (*) i gnore null values in their input
collection.
For SQL null value means unknown or inappl icable.
group by & having Clauses :
The select statement syntax including optional group by and Having
clauses is as under :
select [distinct ] select -list f rom from-list
[w here qualification ]
[group by gr oup -list ]
[having group -qualif ication];
The result of the GROUP BY clause is a grouped table i.e., a set of
groups of rows deri ved from the table by conceptually rearranging it into the
mi ni mum number o f groups such that within any one group all rows have the
same value for the combination of columns identified by GROUP BY clause.
Ex : select sum(sal) from emp group by j ob;
Using this statement we get total salar y for each desi gnation of the
employees.
There is a restriction on the select clause while using group by. Select
item in the select clause must be single valued per group as for the other
aggregate functions. T herefore a statement li ke
select empno, sum(sal ) f rom emp group by j ob;
select * f rom emp group by j ob; are invalid.
But we can gi ve
select j ob f rom emp group by j ob;
and
select j ob, avg(sal) f rom emp group by j ob;
are valid.
HAV ING clause wor ks ver y much like a where clause except that its
logic is related only to the result of group functions i.e., having clause is
used to eliminate groups where as where clause is used to elimi nate rows
from the whole table.
For example,
select deptno, avg(sal) from emp group by deptno having max(sal) > 1500;
Displays average salaries depart wi se for depart ments which have
average salary greater than 1500.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 9
Procedure: -
1. Go to SQL prompt
a. Click start
b. Click all programs
c. Click Oracle
d. Click Application development
e. Click SQL plus
2. At Logon window enter the following data.
f. User name : user001
g. Password : password001
h. Host string : oracle9
3. Go to File menu, click spool and then spool file.
4. Gi ve the spool file name li ke atoz
5. Click save
6. Set the line si ze using the following command.
set linesize 100;
7. Create the tables with create table command.
8. Type the foll owing command after creation or modification of each
table to view the structure of the table.
desc table_name;
9. In insert statement we can use substitution variables like
insert into table1 val ues(&a, &b, &c);
10. Then it asks for the values of a, b, and c. I f we gi ve proper values, the
values are inserted int o the table.
11. For inserting more rows of data we can repeat the command by
typing ‘ /’.
12. In bet ween insertions and after all the data i s inserted, we can t ype the
following command to save the data.
commit;
13. To cancel the changes to the database up to t he last save point use
rollback;
14. After inserting all the data or after modificat ion to data, we can view
the data by t yping
Select * f rom table_name;
15. Use the following commands after all the task is co mpleted.
commit;
exit;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 10
16. Open the spool file at oz with notepad and note down the contents in
the obser vation.
Questions: -
1. Create emp1 table and insert appropriate val ues.
2. Create dept1 table and insert appropriate val ues.
3. Create suppliers table with the following schema
suppliers(sid:integer,sname:string,address:st ring).
4. Create parts table with the following schema
parts( pid:integer, pname:string, color:string).
5. Create catalog table with the following schema
catalog( sid:integer , pid:integer , cost:real ).
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 11
9. Increment the salaries of all employees by 500 except scott for whom
increment the salar y by 1000.
10. Add one row of your own choice and delete t hat row in parts table.
11. Alter the ename field of emp1 table to accommodate more charact ers.
12. Find the maxi mum sal ary.
13. Display maxi mum salary along with name of the employee who gets it.
14. Display total salar y.
15. Display total salar y for each depart ment .
16. Display the maxi mum salary of employees in each depart ment along
with the depart ment number
17. Count number of recor ds in the emp1 table.
18. Count number of empl oyees who get a commission.
19. Count the number of employees wh o get no commission.
20. Create a table dummy with the fields serial number, name and inser t 5
rows.
21. Delete all the rows in dummy table.
22. Delete the field “name” from dummy table.
23. Create table emp2 wit h same data as in emp.
24. Drop table dummy.
Note: the schema f or t ables emp1 and emp2 i s same as the emp.dept tables
of scott. So before creating these tables , we have to note down the schema
of emp and dept tables by the desc command.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 12
Expno: 03 Date:
Set Operations
Aim:-
To Practice set operations, nested queries and j oins in SQL
Theory: -
A nested quer y is query that has another query embedded within it,
the embedded quer y is called sub quer y.
Example:
This query displays depart ment name of the employee whose name is
‘scott’. If a single query is used on emp tabl e then we can obtain deptno but
not dname. So we used the result of the sub query in the nested query.
There are some points to be remembered while using nested quer ies.
They are
Use single -row oper ators with single -row sub queries and use
multiple -row operator s with multiple -row sub queries.
In Single row sub query, operators used are <, >, <= , >=, <>
In multiple row sub query, operators used are all, some and in. whose
meanings are ever y value returned by the sub query, at least one value
returned by the sub query , any value in the list respectivel y.
SQL supports the set operations union, intersection and minus with
the key words union, intersect, and except ( mi nus in oracle). It al so supports
exists and not exists. exists operator returns true if the set is not empt y and
not exists returns true if the set is empt y.
The UNION operator returns records from the result of both que ries
after eliminating the duplicate records whi ch are common in bot h. There is
another option of uni on, the UNION ALL operator, which returns records
from the result of both queries, including duplicate records which are
common in both. The INTERSECT oper ator returns the records which are
common in the result of both queries. The EXCEPT operator returns the
records which are in the result of the first query but not in the result of the
second one.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 13
When data from more than one table in the database is required, a j oin
condition is used. Rows in one table can be j oined to rows in another table
according to common values existing in corresponding columns, that is,
usually pri mar y and f oreign key columns. A j oin with a j oin condition is
known as conditional j oin.
When a j oin condition is invalid or omitted completel y, the result is a
Cartesian product, in which all combinations of row s are displayed. All rows
in the first table are j oined to all rows in the second table.
If there are any values in one table that do not have correspondi ng
values in the other, in an Equi -j oin that row will not be selected. Such rows
can be forcefull y selected by using outer j oin. The left outer j oin takes all
the rows in the left table (fi rst table in the j oin) and pads the rows which
don’t have a matching row with null values for all other attributes in the
right table. The right outer j oin takes all the rows in the right table( first
table in the j oin) and pads the rows which doesn’t have a matching row with
null values for all other attributes in the left table. The full outer j oin
includes all the rows from both tables and pads the rows which doesn’t have
a matching row with null values f or all other attributes in the other table.
In SQL there are four j oin types namel y i nner j oin, left outer join,
right outer j oin and full outer j oin. And there are three j oin conditions
natural, on <condition> , using (field1,field2,..).Here on <conditi on> is for
conditional j oin and using (field1,field2 ,..) is like natural j oin but the j oin
fields are fields specified in the using class.
Examples:
Cartesian product :
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 14
conditional joins:
Equi-join:
inner join:
The following statements display all the dept records which have the
matching emp records along with the matching emp records and i n addition
displays dept records which does not have any employees.
OR
The following statements display all the dept records which have t he
matching emp records along with the matching emp r ecords and i n addition
displays emp records which does not have any depart ment .
OR
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 15
The following statements display all the dept records which have t he
matching emp records along with the matching emp records and i n addition
displays emp records which does not have any depart ment and dept records
which does not have any employees.
OR
The following statement inner j oins the two tables by equating all the
common fields i.e. in this case it is de ptno. So the result is same as the
above inner j oin but in the display the common column deptno is displayed
only once.
The following statement left outer j oins the two tables by equating all
the common fields i.e. in this case it is deptno. So the result is same as the
above left outer j oin but in the display the common column deptno is
displayed onl y once.
The following statement left outer j oins the two tables by equating all
the common fields i.e. in this case it is deptno. So the result is same as the
above right outer j oin but in the display the common column deptno is
displayed onl y once.
The following statement full outer j oins the two tables by equating all
the common fields i.e. in this case it is deptno. So the result is same as the
previous full outer j oin but in the display the comm on column deptno is
displayed onl y once
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 16
Procedure: -
Same as that in expno.2
Questions: -
1. Create three tables wit h the following schema
Sailors(sid:integer, sname:string, rating:integer, age:real)
Boats(bid:integer, bname:string, color:string)
Reser ves(sid:integer, bid:integer, day:date)
Gi ve the appropriate integrit y constraints.
2. Insert the following values into the above tables.
sid sname rating age
22 Dustin 7 45.0
29 Brutus 1 33.0
31 Lubber 8 55.5
32 Andy 8 25.5
58 Rust y 10 35.0
64 Horatio 7 35.0
71 Zorba 10 16.0
74 Horatio 9 40
85 Art 3 25.5
95 Bob 3 63.5
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 17
3. Find the names of sail ors who have reser ved at least one boat.
4. Find the ids of sailors who reser ved a red boat and a green boat.
5. Find the ids of sailors who reser ved a red boat or a green boat.
6. Find the ids of sailors who reser ved a red boat but not a green boat.
7. Find the names of sail ors who reser ved ever y boat.
8. Find the names of sail ors who reser ved ever y red boat.
9. Find the ids of sailors whose rating is more t han the average rating of
all sailors.
10. Find the names of parts for which there is some supplier .
11. Find the ids of suppliers who suppl y a red part and a green part.
12. Find the ids of suppliers who suppl y a red part or a green part.
13. Find the ids of suppliers who suppl y a red part but not a green par t.
14. Find the names of suppliers who suppl y ever y part.
15. Find the names of suppliers who suppl y ever y red part .
16. Find the names of parts supplied by Adams and by no one else .
17. Find the ids of suppliers who char ge more for some part than the
average cost of that part.
18. For each part find the name of the supplier who char ges the most for
that part.
19. Find the ids of suppliers who suppl y onl y red parts .
20. Find the sids of sailors whose rating is better than some sailors called
horatio.
21. Find the sailors whose rating is better than ever y sailor called horatio.
22. Find the names of boats reserved by dustin and by no one else .
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 18
Expno: 04 Date:
Functions and Procedures
Aim: -
To create and execute functions and procedures.
Theory: -
PL/SQL stands for Procedural Language/Structured Query
Language.PL/SQL is the procedural extension to SQL with desi gn features
of programming languages. Data manipulation and quer y statements of SQL
are included within procedural units of code. PL/SQL Block Structure is as
follows.
<header>
IS | AS
Declaration section
BEGIN
Executable section
EXCEPTION (optional)
Exception section
END;
Section Description
Header Required for named blocks. Specifies the way the program is
called by other PL/SQL blocks. Anonymous blocks do not have
a header. They start with the DECLARE keyword if there is a
declaration section, or with the BEGIN keyword i f there are no
declarations.
Declaration It is optional. Declares variables, cursors, T YPEs, and local
programs that are used in the block's execution and exception
sections.
Execution Optional in package and TYPE specifications; contains
statements that are executed when the block is run.
Exception Optional; describes er ror -handling behavior for exceptions
raised in the executabl e section.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 19
The following code declares today as date data type and the default
value is system date which can be obtained f rom the environment variable
SYSDATE. Display the date after concatenat ing it with the string.
DECLARE
today DATE DEFAULT SYSDATE;
BEGIN
DBMS_ OUTPUT.PUT_LINE ( 'Today is ' || today);
END;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 20
Example:
Function that returns t ax to be paid if income is passed as paramet er
CREATE OR REPLACE FUNCTION tax2( p_value IN NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN (p_value * 0.08);
END;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 21
loop Statement:
LOOP
executable_statement(s)
END LOOP;
exit Statement:
EXIT [WHEN condition];
--
FOR loop_index IN [ REVERSE]
lowest_number..hi ghest_number
LOOP
executable_statement(s)
END LOOP;
The REVERSE keywor d causes PL/SQL to st art with the
highest_number and decrement down to the lowest_number
w hile Statement:
WHILE condition
LOOP
executable_statement(s)
END LOOP;
case Statement:
CASE selector
WHEN expression1 THEN result1
WHEN expression2 THEN result2
...
WHEN expressionN THEN resultN
[ELSE result N+1;]
END;
Data types:
• CHAR [(maximum_length)]
• VARCHAR2 ( maximum_length)
• NUMBER [(precision, scale )]
• DATE
• %TYPE Attribute
Declares a variable according to a database column definition or
previousl y declared variable
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 22
Example:
Procedure that displays name of an employee if his empno is gi ven. It uses
the %type.
CREATE OR REPLACE PROCEDURE pemp1(no emp.empno%type)
IS
empname emp.ename%type;
BEGIN
SELECT ename
INTO empname
FROM emp
WHERE empno = no;
DBMS_OUTPUT.PUT_LINE (empname);
END;
/
Cursors:
the syntax of cursor declaration is
DECLARE CURSOR cursor_name
IS select_statement
[FOR UPDATE [OF column_name [,...n]]}]
The DECLARE CURSOR command enables the retrieval and
manipulation of recor ds from a table one r ow at a ti me. This pr ovides row -
by-row processing, rat her than the traditional set processing offered by SQL.
To use this procedure properly, you should:
1. DECLARE the cursor
2. OPEN the cursor
3. FETCH rows from the cursor
4. When finished, CLOSE the cursor
The DECLARE CURSOR command wor ks by specif ying a SELECT
statement . Each row r eturned by the SELECT statement may be individuall y
retrieved and manipulated. In Or acle, var iables are not allowed in the
WHERE clause of the SELECT statement unless they are first declared as
variables. The parameters are not assi gned at the DECLARE. Instead, they
are assigned values at the OPEN command.
Example:
The following code cr ea tes procedure to display empno and ename of
all employees in emp t able using cursors.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 23
Example:
The following code cr eates procedure to update salaries of
employees using cursors
CREATE OR REPLACE PROCEDURE p2
IS
CURSOR c1 IS
SELECT deptno,empno,ename,sal
FROM emp FOR UPDATE OF sal;
BEGIN
FOR emp_record I N c1
LOOP
IF emp_record.sal> 2000 THEN
UPDATE emp
SET sal=emp_recor d.sal* 1.10
WHERE CURRENT OF c1;
END IF;
END LOOP;
END;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 24
Procedure: -
1. Go to SQL prompt
2. Execute the following commands.
set autocommit on;
set serveroutput on;
3. Type edit file1.sql (Then the default editor i.e. notepad is invoked.)
4. Type the procedure or function definition.
5. Save it and exit notepad.
6. Compile the procedure or fu nction by t yping the following command.
@file1
7. If there are any errors type the following command to show the errors.
Show errors;
8. Type the following command to edit the file and introduce the
corrections.
edit file1.sql
9. Save the file and exit the editor.
10. Compile the procedure by t yping the followi ng command again.
@file1
11. If there are any errors type the following command to show the errors.
show errors;
12. Continue the process of reediting and recompilation until the
procedure or function is successfully created.
13. After successful creation of procedure type t he following command to
execute the procedure.
exec procedurename(parameter);
example1 exec pemp1;
example2 exec tax1(1000);
14. If it is a function type the following command to execute the
function.
a. select tax2(1000) f rom dual;
Or
b. Execute Following sequence of statements for getting the value
returned by the functi on into bind variable and print it.
1. variable v1 number;
2. exec : v1:=tax2(1000) ;
3. print v1;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 25
15. We can view the function names and pr ocedure names using the
command.
select obj ect_name, obj ect_type
f rom user_obj ects
w here obj ect_type in ( ‘PROCEDURE’,’FUNCT ION’)
order by obj ect_name;
16. We can view the funct ion or procedure body using the command.
select text
f rom user_source
w here name =’TAX1’ ;
17. Exit SQL after saving the wor k.
commit;
exit;
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 26
Expno: 05 Date:
Triggers
Aim:-
The aim of the experiment is to create views and triggers and to study
the behavior of views and triggers.
Theory:-
A trigger is a special kind of stored procedure that fires automatically
(hence, the term trigger) when a data -modification statement is executed.
Triggers are associ ated with a specific data -modification statement
( INSERT, UPDATE, or DELETE) on a specific table.
Syntax and Descripti on:
Triggers, by default, f ire once at the statement level. That is, a single
INSERT statement mi ght insert 500 rows i nto a table, but an insert trigger
on that table fires only one ti me. Some vendors allow a trigger to fire for
each row of the data -modification operation. So, a statement that i nserts 500
rows into a table that has a row -level insert trigger fires 500
In addition to being associated with a specific data -modification
statement ( INSERT, UPDATE, or DELETE) on a gi ven table, triggers are
associated with a specific time of firing. In general, trig gers can fire
BEFORE the data -modification statement is processed, AFTER it is
processed, or (when supported by the vendor) INSTEAD OF processing the
statement .
Triggers that fire before or instead of the data -modification statement
do not see the changes that the statement renders, while those that fire
afterwards can see and act upon the changes that the data -modification
statement renders. It may be noted that Oracle allows INSTEAD OF tri ggers
to process onl y against views, not /tables.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 27
Examples:
The first trigger is invoked whenever there is an update operation on
the emp table rows and if salar y is changed. It records these changes in
another table to know the changes made to the table. The second trigger is
invoked whenever there is an insert, delete o r update operation on the emp1
table rows and the changes are recorded in the empl and empl1 tables.
CREATE OR REPLACE TRIGGER EMPT 1
BEFORE UPDATE ON EMP
FOR EACH ROW
WHEN ( NEW.SAL <> OLD.SAL)
BEGIN
INSERT INTO EMPLOG VALUES ( 'UPDATED', :OLD.EMP NO,
:OLD.SAL, :NEW.EMPNO ,: NEW.SAL);
END;
View s:
A view is a table whose rows are not explicitly stored in the
database, but are computed as needed from the view definition.
The syntax of creating a view is
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 28
[(column [,...n])]
AS
SELECT_statement
[WITH CHECK OPTION]
Example:
This command creates a view for dbms teacher to view student name
and mar ks in dbms. But the original table contains sno, sname and all
subj ect mar ks.
CREATE VIEW dbms (name, dbmar ks)
AS SELECT sname,s1
FROM Students;
Sequence:
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 29
Questions: -
1) Create a sequence ‘seq1’ which creates the sequence roll numbers of your
class students.
2) Using the above sequence insert values in the dbms table which has the
fields sno, name, smar ks (at least ten records).
4) Create a tri gger which inserts the changes made into a dbms_change table
on dbms table before t here is a deletion or modification of a row.
7) Create a view for a subj ect teacher (name,s1) from student table which
has the fields roll number, name, all subj ect mar ks i.e.s1,s2.. students.
Try to insert a row in to the view.
8) Create a view for head of dept table which contains roll number and all
subj ects’ mar ks of students from student t able. Insert a row in to the
view.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 30
Database
window
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 31
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 32
Data types
Field names
Field properties,
like field size
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 33
You can use the Data Type propert y to speci fy the t ype of data stored
in a table field. Each field can store data consisting of onl y a singl e data
type.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 34
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 35
Questions: -
1. Create a table student with roll number, name, father name as fields
with appropriate data t ypes.
2. Create a table mar ks with roll number and marks in different subj ects
as fields with appropri ate data types.
3. Add address field to st udent table, increase t he size allocated to one
of the fields.
4. Enter the appropriate data in the tables.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 36
Tool Box
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 37
Tool Box: -
The tool box is special kind of tool bar. Control is a graphical user
interface obj ect, such as a text box, check box, scroll bar, or command
button, that lets users control the program. We us e controls to display data
or choices, perform an action, or make the user interface easier to read Open
a for m, report, or data access page in Desi gn view. Toolbox is a set of tools
that are available in Desi gn view to add controls to a form, report, or data
access page. To create a control using the tool box click the tool for the
control we want to create and then drag i t and drop it.
Text boxes
We use text boxes on a form, report, or data access to display data
from a record source . This type of text box is called a bound text box
because it 's bound to data in a field. Text boxes can also be unbound. For
example, we can create an unbound text box to display the results of a
calculation or to accept input from a user. Data in an unbound text box isn't
stored anywhere.
Labels
We use labels on a form, report, to display descriptive text such as
titles, captions, or bri ef in structions.
List boxes
The list in a list box consists of rows of data. In a for m, a list box can
have one or more columns, which can appear with or without headings. If a
multiple -column list box is bound .Bound control is a control used on a
for m, report, or data access page to enter or display the contents of a field in
the underlying table, query, or SQL statement. The control's Cont rol Source
property stores the field name to which the control is bound. Access stores
the values from one of the co lumns. In a dat a access page, a list box has one
column without a heading.
Combo boxes
A combo box is li ke a text box and a list box combined, so it requir es
less room. We can t ype new values in it, as well as select values f rom a list.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 38
Command button s
Command buttons provide us with a way of perfor ming action(s) by
simpl y clicking them. When we choose the button, it not onl y carri es out the
appropriate action, it also looks as if it's being pushed in and released. We
use a command button on a form to start an action or a set of actions. For
example, we can creat e a command button t hat opens another for m. To make
a command button do something on a for m, we write an event procedure and
attach it to the button's On Click propert y.
Check boxes
We can use a check box on a for m, repor t, or as a stand -alone to
display a Yes/ No value from an underl ying t able, quer y, or SQL st atement.
Option buttons
We can use an option button on a form, report, or data access page as
a stand -alone control to display a Yes/ No value from an underl ying record
source. We can also use option buttons in an option group to display values
to choose from.
The option group is t he frame that surrounds the controls inside it.
Onl y one option in an option group can be selected at a time. I f an option
group is bound to a field, only the group frame itself is bound not the check
boxes, toggle buttons, or option buttons inside the frame. Because the
Control Source property of the group frame is set to the field that the option
group is bound t o, we don't set the Control Source propert y for each in the
option group. Instead, we set the Option Val ue (for m or report) or the Value
(data access page) pr operty of each check box, toggle button, or option
button. In a for m or report, set the contr ol pr opert y to a number that 's
meaningful for the field the group frame is bound to. In a data access page,
set the control propert y to either a number or any text that 's meani ngful for
the field the group frame is bound to. When we select an option in an optio n
group, Access sets the value of the field to which the option group is bound
to the value of the sel ected option's Option Value or Value property.
Toggle buttons
We can use a toggle button on a for m as a stand -alone to display a
Yes/No value from an unde rlying record sour ce .
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 39
that can be sorted into two or more categori es. For example, we m ight use a
tab control on an Employees for m to separate employment hi story and
personal infor mation. Infor mation about employment histor y is di splayed on
this page. Personal infor mation, such as home address and phone number, is
displayed on this page.
Procedure:-
PartI Creation of f orms:
1) Click on Forms in the Obj ects column and select either the wi zard or
design view
2) The wizard asks which table the form is to come from, and then which
fields you want. Gi ve the table name and select the fields and move to
the selected field list by clicking ri ght arrow button.
3) Select a layout, st yle, and a title to compl ete your for m. This t hen
opens in for m view for you to begi n entering or viewing infor mation.
4) Change to desi gn view to customi ze.
PartII Creation of reports :
1. Click Report in the Obj ect column and select the wizard or design
view. The wi zard asks which table or quer y you want to print.
2. Gi ve the table name and then select the fiel ds to print.
3. Select grouping levels Grouping brings entries together in the same
categor y, say all people living in Dallas.
4. Select fields to sort and whether to sort ascending or descending
order. Up to four fields can be sorted.
5. Then select the layout i.e. columnar, tabular, or j ustified.
6. Finally, select a st yle and a title.
7. The report open s in pr int preview.
8. Switch to desi gn view to change the for matting.
DESIGN VIEW OF A REPORT
When we print the report, sections are repeated, as appr opriate, until
all the data in the report is printed. The controls in each section tell
Microsoft Access what data to print in the section. The Report Header prints
at the beginning of the report. The Page Header and Footer prints on ever y
page. The Categor y Header and Footer prints for each category. The Details
section prints for each record in the category Controls that we can use to
display, enter, filter, or organize data in Access.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 40
Questions: -
1. Create a for m for entering the data into student table which is already
created in the expno.7.
2. Create a for m for each subj ect teacher to enter mar ks in the
concerned subj ect.
3. Create a report to head of the depart ment to view all subj ect mar ks of
the students.
4. Create a report displaying roll list (roll number and name of the
students) from student table.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 41
Aim: - To create queries, macros and i mport a wor k sheet and a table in
oracle to MS Access.
Theory:-Questions including data stored in a Database are called queries.
By using queries it is possible to:
Extract the records that satisfy the search cr iteria into a record set
Select which fields ar e to be displayed
Procedure:-
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 42
8. Type an SQL quer y, click save and gi ve query name close select
query window.
9. Double click the newl y created quer y to see the r esult.
10. In stead of going to SQL view we can as well add the fields of a table
to SQL desi gn view and can enter the criteria.
11. We attach the query t o any push button in the forms to display the
result whenever the button is pressed or we can as well create a report
for the quer y
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 43
12. Check the option First row contains columns to make the first column
of wor k sheet as column names of the converted table.
13. And then select new table in the next displayed window.
14. Click next and next and choose my ow n primary key and select roll
number.
15. Click next and gi ve the table name and click finish.
16. Double click the newl y created table to check whether the conversion
is completed.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 44
10. After few minutes all the tables of scott are displayed. Then select
one or more tables and click ok to i mport the tables to Access.
Questions::
1. Create a quer y to displ ay total mar ks of each student and execute it
2. Create a quer y to displ ay average mar ks in each subj ect. and execut e
it
3. Create a macro to run an SQL statement.
4. Import an Excel wor k sheet into MS access as a table.
5. Import dept and emp t ables from oracle.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 45
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 46
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 47
required and will default to 16,4, where 4 is the number of decimals. Decimal
precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
DECIMAL(M,D) - An unpacked floating-point number that cannot be unsigned. In
unpacked decimals, each decimal corresponds to one byte. Defining the display
length (M) and the number of decimals (D) is required. NUMERIC is a synonym for
DECIMAL.
Date and Time Types:
DATE - A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For
example, December 30th, 1973 would be stored as 1973-12-30.
DATETIME - A date and time combination in YYYY-MM-DD HH:MM:SS format,
between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the
afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.
TIMESTAMP - A timestamp between midnight, January 1, 1970 and sometime in
2037. This looks like the previous DATETIME format, only without the hyphens
between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as
19731230153000 ( YYYYMMDDHHMMSS ).
TIME - Stores the time in HH:MM:SS format.
YEAR(M) - Stores a year in 2-digit or 4-digit format. If the length is specified as 2
(for example YEAR(2)), YEAR can be 1970 to 2069 (70 to 69). If the length is
specified as 4, YEAR can be 1901 to 2155. The default length is 4.
String Types:
Although numeric and date types are fun, most data you'll store will be in string format.
This list describes the common string datatypes in MySQL.
CHAR(M)- A fixed-length string between 1 and 255 characters in length (for
example CHAR(5)), right-padded with spaces to the specified length when stored.
Defining a length is not required, but the default is 1.
VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for
example VARCHAR(25). You must define a length when creating a VARCHAR
field.
BLOB or TEXT - A field with a maximum length of 65535 characters. BLOBs are
"Binary Large Objects" and are used to store large amounts of binary data, such as
images or other types of files. Fields defined as TEXT also hold large amounts of
data; the difference between the two is that sorts and comparisons on stored data are
case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not
specify a length with BLOB or TEXT.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 48
CREATE
[DEFINER = { user | CURRENT_USER }]
FUNCTION sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
func_parameter:
param_name type
type:
Any valid MySQL data type
Characteristic:
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 49
routine_body:
Valid SQL routine statement
PARAMETERS OF PROCEDURE
The real benefit of a stored procedure is of course when you can pass
values to it, as well as receive values back. The concept of parameters
should be familiar to anyone who has had experience with any procedural
programmi ng experience.
There are three types of parameter:
IN: The default. This parameter is passed to the procedure, and can
change inside the pr ocedure, but remains unchanged outside.
OUT: No value is supplied to the pr ocedure (it is assumed to be
NULL), but it can be modified inside the procedure, and is available
outside the procedure.
INOUT: The characteristics of both IN and OUT parameters. A value
can be passed to the procedure, modified there as well as passed bac k
again.
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 50
Mysql>use mysql;
Database changed
mysql>show tables;
Tables in mysql
columns_pri v
db
event
tables_priv
time_zone
time_zone_leap_second
time_zone_name
time_zone_tranition
time_zone_transition_type
user
23 rows in set(0.05 sec)
mysql>show databases;
Database
infor mation_schema
cdcol
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 51
mysql
phpmyadmin
test
db
6 rows in set (0.00 sec)
mysql>CALL sp_in(‘CSE_BTECH’)
Quer y OK, 0 rows affected (0.00 sec)
mysql>SELECT @X;
@X
CSE_BTECH
1 row in set (0.00 sec)
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 52
mMysql>select @X;
@X
5th sem
1 row in set (0.00 sec)
(or)
mysql>SET @X=’5th sem’;
Quer y OK, 0 rows affected (0.00 sec)
Mysql>select @X;
@X
5th sem
1 row in set (0.00 sec)
mysql>SELECT HELLO(‘CSE”);
HELLO(‘CST’)
CST
1 row in set (0.00 sec)
C.S.E.DEPARTMENT, S.R.K.R.E.C.
Database Management System Lab Manual 53
Practice Questions:
I. Practice the questions in Experi ment No.1 SQL queries in the MYSQL
environment.
II. Practice the questions in Experi ment No. 2 f or creation of tables,
modification of table structure and inserting values into the tables i n
the MYSQL environment also.
III. Practice the questions in Experi ment No 3 for practicing SQL set
operations, j oins and nested queries in the MYSQL environment also.
C.S.E.DEPARTMENT, S.R.K.R.E.C.