Professional Documents
Culture Documents
AIM:
To create a DDL to perform creation of table, alter, modify and drop column.
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:
Syntax:
Syntax:
Syntax:
Syntax:
Syntax:
7. Destroying tables.
Syntax:
CREATION OF TABLE:
SYNTAX:
EXAMPLE:
SQL>create table std(sno number(5),sname varchar(20),age number(5),sdob date,sm1
number(4,2),sm2 number(4,2),sm3 number(4,4));
Table created.
OUTPUT:
SYNTAX:
EXAMPLE:
OUTPUT:
ID NAME GAME
1 Mercy Cricket
1 Mercy cricket
2 Sharmi Tennis 19
SYNTAX:
EXAMPLE:
OUTPUT:
MODIFY
desc student;
Name Varchar(20)
Game Varchar(25)
Age Number(4)
DROP:
EXAMPLE:
SQL>Table dropped.
TRUNCATE TABLE
DESC
--------------------------------- --------
EmpNo NOT NULL number(5)
EName VarChar(15)
CONSTRAINTS:
Example:
Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) constraint
un unique, DeptNo number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null,dob date not null);
DOMAIN INTEGRITY
CHECK CONSTRAINT
Example: Create table student (regno number (6), mark number (3) constraint b check
(mark >=0 and mark <=100)); Alter table student add constraint b2 check
(length(regno<=4));
ENTITY INTEGRITY
Example: Create table cust(custid number(6) constraint unique, name char(10)); Alter table
cust add(constraint c unique(custid));
Example: Create table stud(regno number(6) constraint primary key, name char(20));
Queries:
Name Type
---------- ----------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
JOB VARCHAR2(10)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Ans:
Q3: Modify the column width of the job field of emp table.
Name Type
------------ ---------------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
Ans:
SQL> create table dept(deptno number(2) primary key,dname
varchar2(10),loc varchar2(10));
Table created.
Q5: create the emp1 table with ename and empno, add constraints to check the empno value
while entering (i.e) empno > 100.
Ans:
SQL> create table emp1(ename varchar2(10),empno number(6) constraint
check(empno>100));
Table created.
Ans:
Q7: Truncate the emp table and drop the dept table
RESULT:
Thus the DDL commands have been executed successfully.
EX.NO:1(b) IMPLEMENTATION OF DML AND DCL COMMANDS
AIM:
To study the various DML commands and implement them on the database.
DML COMMANDS
DML commands are the most frequently used SQL commands and is used to
query and manipulate the existing database objects. Some of the commands are Insert,
Select, Update, Delete.
Insert Command : This is used to add one or more rows to a table. The values are separated
by commas and the data types char and date are enclosed in apostrophes. The values must be
entered in the same order as they are defined.
Select Commands : It is used to retrieve information from the table. It is generally referred
to as querying the table. We can either display all columns in a table or only specify
column from the table.
Update Command :It is used to alter the column values in a table. A single column may
be updated or more than one column could be updated.
Delete command :After inserting row in a table we can also delete them if required. The
delete command consists of a from clause followed by an optional where clause.
Q2: Insert more than a record into emp table using a single insert command.
Ans: SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename: Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal: 10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)
1 row created.
1 row created.
Q3: Update the emp table to set the salary of all employees to Rs15000/- who are working as
ASP
1 Mathi AP 1 10000
1 Mathi AP 1 10000
Q4: Create a pseudo table employee with the same structure as the table emp and insert
rows into the table using select clauses.
Table created.
EMPNO NUMBER(6)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Q5: select employee name, job from the emp table
ENAME JOB
-------------------- -------------
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
suresh lect
6 rows selected.
Q6: Delete only those who are working as lecturer
1 Mathi AP 1 10000
5 Akalya AP 1 10000
6 rows selected.
1 row deleted.
1 Mathi AP 1 10000
5 Akalya AP 1 10000
Q7: List the records in the emp table orderby salary in ascending order.
1 Mathi AP 1 10000
5 Akalya AP 1 10000
Q8: List the records in the emp table orderby salary in descending order.
1 Mathi AP 1 10000
5 Akalya AP 1 10000
1 Mathi AP 1 10000
5 Akalya AP 1 10000
Q10: Display deptno from the table employee avoiding the duplicated values.
Solution:
DEPTNO
----------
2
IMPLEMENTATION OF DATA AND BUILT IN FUNCTIONS IN SQL
CHARACTER/STRING FUNCTION:
-----------
WELCOME
LOW
---
hai
INITCAP('Hello
--------------
Hello World
---
hai
RTRIM('
------
-
hai
------------------------
SRM university
LENGTH('SRM')
----------------------
12
RPAD('
------
hai***
REPLACE
-------
Danie
SYSDATE
---------
07-APR-10
ROUND(SYS
---------
07-APR-10
ADD_MONTH
---------
07-JUL-10
LAST_DAY(
---------
30-APR-10
SYSDATE+2
---------
27-APR-10
NEXT_DAY(
---------
13-APR-10
NUMERIC FUNCTION
ROUND(15.6789)
--------------
16
CEIL(23.20)
-----------
24
FLOOR(34.56)
------------
34
TRUNC(15.56743)
---------------
15
SIGN(-345)
----------
-1
ABS(-70)
---------
70
MATH FUNCTION:
ABS(45)
---------
45
POWER(10,12)
------------
1.000E+12
MOD(11,5)
---------
EXP(10)
---------
22026.466
SQRT(225)
---------
15
DCL COMMANDS
The DCL language is used for controlling the access to the table and hence securing the
database. DCL is used to provide certain privileges to a particular user. Privileges are rights
to be allocated.The privilege commands are namely, Grant and Revoke.The various
privileges that can be granted or revoked are, Select Insert Delete Update References
Execute All.
GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user
can grant access to their database objects to other users.
REVOKE COMMAND: Using this command , the DBA can revoke the granted database
privileges from the user.
TCL COMMAND
Queries:
Their schemas are as follows , Departments ( dept _no , dept_ name , dept_location );
Employees ( emp_id , emp_name , emp_salary );
Q1: Develop a query to grant all privileges of employees table into departments table
Q2: Develop a query to grant some privileges of employees table into departments table
Ans: SQL> Grant select, update , insert on departments to departments with grant
option; Grant succeeded.
Q3: Develop a query to revoke all privileges of employees table from departments table
Q4: Develop a query to revoke some privileges of employees table from departments table
Savepoint created.
1 Mathi AP 1 10000
1 Mathi AP 1 10000
5 Akalya AP 1 10000
Q6: Write a query to implement the rollback
1 Mathi AP 1 10000
Commit complete.
RESULT
Thus the DML, DCL,TCL commands was performed successfully and executed.
Exp. 2.
Database Querying – Simple queries, Nested queries, Sub queries and Joins
Aim:
To execute and verify the Simple queries, Nested queries, Sub queries and Joins in SQL.
Table 1:
Table created.
Table 2:
create table course ( courseid varchar(8) primary key, title varchar(50), deptname
varchar(20), credits number(2), foreign key (deptname) references department) ;
Table created.
Table 3:
Table 4:
Create table section ( courseid varchar(8), secid varchar(8), semester varchar(6), year
number(4), building varchar(15) , roomnumner varchar(7), timeslot varchar(4),
primary key (courseid, secid, semester, year), foreign key (courseid) references
course);
Table 5:
Questions:
Find the names of all departments with instructor, and remove duplicates
select distinct dept_name from instructor;
To find all instructors in CSE with salary > 80000
select name from instructor where dept_name = ‘Comp. Sci.' and salary >
80000;
Find the Cartesian product instructor X teaches
select *from instructor, teaches;
Find the course ID, semester, year and title of each course offered by the Comp.
Sci. department
Find the names of all instructors who have a higher salary than some
instructor in ‘Comp. Sci’.
select distinct T. name from instructor as T, instructor as S where
T.salary > S.salary and S.deptname = ‘CSE’
o Find the names of all instructors whose name includes the substring
“dar”.
select name from instructor where name like '%dar%';
nested quries:
Q1: Display all employee names and salary whose salary is greater than minimum salary
of the company and job title starts with ‗M‘.
Solution:
2. Use like operator to match job and in select clause to get the result.
Ans: SQL> select ename,sal from emp where sal>(select min(sal) from emp where job
like 'A%');
ENAME SAL
-------------------- ----------
Arjun 12000
Gugan 20000
Karthik 15000
Q2: Issue a query to find all the employees who work in the same job as Arjun.
Ans: SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
---------- -------------------- ---------- ---------- ----------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
SQL> select ename from emp where job=(select job from emp where
ename='Arjun');
ENAME
--------------
Arjun
Gugan
Set Operations:
Find courses that ran in Fall 2009 or in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009) union (select
course_id from section where sem = ‘Spring’ and year = 2010)
Find courses that ran in Fall 2009 but not in Spring 2010
(select course_id from section where sem = ‘Fall’ and year = 2009) except (select
course_id from section where sem = ‘Spring’ and year = 2010)
AGGREGATE FUNCTIONS:
Find the average salary of instructors in the Computer Science department
select avg (salary) from instructor where dept_name= ’Comp.Sci.’;
Find the total number of instructors who teach a course in the Spring 2010
semester
select count (distinct ID) from teaches where
semester = ’Spring’ and year = 2010
Find the number of tuples in the course relation
o select count (*) from course;
o Find the names and average salaries of all departments whose average
salary is greater than 42000
select dept_name, avg (salary) from instructor group by dept_name having
avg (salary) > 42000;
NESTED SUBQUERIES:
Find courses offered in Fall 2009 and in Spring 2010
select distinct course_id from section where semester =
’Fall’ and year= 2009 and course_id in (select course_id
from section where semester = ’Spring’ and year= 2010);
Find courses offered in Fall 2009 but not in Spring 2010
select distinct course_id from section where semester = ’Fall’ and year=
2009 and course_id not in (select course_id from section where semester =
’Spring’ and year= 2010);
JOINED RELATIONS
Join operations – Example
Relation course
Relation prereq
Outer Join
An extension of the join operation that avoids loss of information.
Computes the join and then adds tuples form one relation that does not match
tuples in the other relation to the result of the join.
Uses null values.
Left Join:
SELECT * FROM course left join prereq on course.course_id=prereq.course_id;
Right Join:
Select *from course right join prereq on course.course_id=prereq.course_id;
Full join:
Select *from course full join prereq on course.course_id=prereq.course_id:
RESULT:
Thus the Simple queries, Nested queries, Sub queries and Joins in SQL are executed
successfully.
Exp.3
Views, Synonyms, Sequence
AIM:
View:
Database views are created using the CREATE VIEW statement. Views can be
created from a single table, multiple tables, or another view. To create a view, a user must
have the appropriate system privilege according to the specific implementation.
EMPLOYEE_NAMEVARCHAR2(10),
EMPLOYEE_NO NUMBER(8),
DEPT_NAME VARCHAR2(10),
Table created.
CREATE VIEW
CREATION OF VIEW
EMPLOYEE_NO,
DEPT_NAME,
DEPT_NO,
DATE_OF_JOIN FROM EMPLOYEE;
View Created.
DISPLAY VIEW:
1 ROW CREATED.
EXAMPLE-5:
A.ENAME,
A.DEPTNO,
B.DNAME,
B.LOC
WHERE
A.DEPTNO=B.DEPTNO;
Synonyms
A synonym is an alias for any table, view, materialized view, sequence,
procedure, function, package, type, Java class schema object, user-defined object type,
or another synonym. Because a synonym is simply an alias, it requires no storage other
than its definition in the data dictionary.
Synonyms are often used for security and convenience. For example, they can do the following:
Mask the name and owner of an object
Synonym created.
DISPLAY THE VALUES OF TABLE BY USING THE SYSNONYM
1 row created.
Sequence
The sequence generator provides a sequential series of numbers. The sequence
generator is especially useful in multiuser environments for generating unique
sequential numbers without the overhead of disk I/O or transaction locking
Sequence numbers are integers of up to 38 digits defined in the database. A
sequence definition indicates general information, such as the following:
SYNTAX:
SQL>CREATE SEQUENCE sequence_name
[INCREMENT BY increment_num]
[ { MAXVALUE maximum_num | NOMAXVALUE } ] [
[ { CYCLE | NOCYCLE } ]
{ ORDER | NOORDER } ];
NOCYCLE means the sequence cannot generate any more integers after reaching its
maximum or minimum value. NOCYCLE is the default.
NOMAXVALUE specifies the maximum is 1027 for an ascending sequence or –1 for a
descending sequence. NOMAXVALUE is the default.
NOMINVALUE specifies the minimum is 1 for an ascending sequence or –1026 for a
descending sequence. NOMINVALUE is the default.
If you omit CACHE and NOCACHE, the database caches 20 sequence numbers by
default.
ORDER guarantees the integers are generated in the order of the request. You typically
use ORDER when using Real Application Clusters, which are set up and managed by
database administrators.
NOORDER doesn’t guarantee the integers are generated in the order of the
request.
Example: 1
Command:
Sequence created.
NEXTVAL
----------
1
SQL> select seq1.nextval from dual;
NEXTVAL
----------
NEXTVAL
----------
3
CURRVAL
----------
3
TO ALTER THE SEQUENCES
TO DROP SEQUENCES
Thus the view, Synonyms, Sequenceeen created and various operations are performed
and output is verified..
EXP.4
Procedures:
At the schema level, subprogram is a standalone subprogram. It is created with the CREATE
PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be
deleted with the DROP PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is stored in the database
and can be deleted only when the package is deleted with the DROP PACKAGE statement. We
will discuss packages in the chapter 'PL/SQL - Packages'.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
PL/SQL provides two kinds of subprograms −
Functions − These subprograms return a single value; mainly used to compute and return
a value.
Procedures − These subprograms do not return a value directly; mainly used to perform
an action.
Program 1:
Procedure created.
Program 2:
Procedure created.
SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=23;
7 b:=4;
8 findMin(a,b,c);
9 dbms_output.put_line('Minimum value is:'||c);
10 end;
11 /
Minimum value is:4
SQL>
Program 3:
Table created.
SQL> insert into emp22 values(3,'john','manager',100000);
1 row created.
SQL> insert into emp22 values(3,'jagan','hr',400000);
1 row created.
Function created.
SQL> declare
2 a number:=0;
3 begin
4 a:=totalemployee();
5 dbms_output.put_line('Total employees are '||a);
6 end;
7 /
Total employees are 2
Result:
Thus the procedure for finding minimum value and function to count number of employees is
executed successfully.
Exp.5
Implicit and explicit Cursors
Aim:
To create PL/SQL procedure using an implicit and explicit cursor in SQL.
Implicit Cursors:
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement. Programmers cannot control the implicit
cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
S.No Attribute & Description
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows
or a SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE
statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or
returned by a SELECT INTO statement.
Table creation:
Create table employee22(empid number,empname varchar(20),empdept varchar(20),salary
number);
Example:
DECLARE
total number(2);
BEGIN
UPDATE employee22 SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no employees selected');
ELSIF sql%found THEN
total := sql%rowcount;
dbms_output.put_line( total || ' employees selected ');
END IF;
END;
/
Output:
Explicit cursor:
Explicit cursors are programmer-defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created
on a SELECT Statement which returns more than one row.
The syntax for creating an explicit cursor is −
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
Declaring the cursor for initializing the memory
Opening the cursor for allocating the memory
Fetching the cursor for retrieving the data
Closing the cursor to release the allocated memory
Example:
DECLARE
id employee22.empid%type;
name employee22.empname%type;
dept employee22.empdept%type;
sal employee22.salary%type;
CURSOR c is
SELECT empid, empname, empdept,salary FROM employee22;
BEGIN
OPEN c;
LOOP
FETCH c into id, name, dept,sal;
EXIT WHEN c%notfound;
dbms_output.put_line(id|| ' ' ||name || ' ' || dept||’ ‘|| sal);
END LOOP;
CLOSE c;
END;
/
Output:
Result:
Thus the PL/SQL procedures using implicit and explicit cursor is executed successfully.
Exp.6.
Triggers
Aim:
To create PL/SQL procedure for trigger.
Trigger :
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 can be defined on the table, view, schema, or database with which the event is
associated.
Table creation:
Create table employee22(empid number,empname varchar(20),empdept varchar(20),salary
number);
Example:
Result:
Thus , the PL/SQL procedure using trigger is executed successfully.
Exp.no.7
EXCEPTION HANDLING
Aim:
To create PL/SQL procedure with exception handling.
Exception:
An exception is an error condition during a program execution. PL/SQL supports programmers
to catch such conditions using EXCEPTION block in the program and an appropriate action is
taken against the error condition. There are two types of exceptions −
System-defined exceptions
User-defined exceptions
The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others THEN
−
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised
when a SELECT INTO statement returns no rows. The following table lists few of the
important pre-defined exceptions −
Exception Description
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using a RAISE statement.
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
System-defined exceptions:
DECLARE
id employee.empid%type := 8;
name employee.empname%type;
sal employee.salary%type;
BEGIN
SELECT empname, salary INTO name, sal FROM employee WHERE empid = id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| name);
DBMS_OUTPUT.PUT_LINE ('salary: ' || sal);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such employee');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
User-defined exceptions:
DECLARE
id employee.empid%type := &id;
name employee.empname%type;
sal employee.salary%type;
ex_invalid_id EXCEPTION;
BEGIN
IF id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT empname, salary INTO name, sal FROM employee WHERE empid = id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || sal);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such employee!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
Result:
Thus , the PL/SQL procedure with exception handling is executed successfully.
Exp. No.8:
Procedure:
Entity relationship diagram (ERD) is one of the most widely used technique for data modeling.
Data modeling is an essential component of database design and development. It provides a
means to analyze business requirements so as to standardize organizational vocabulary, enforce
business rules, and ensure adequate data quality. Data modeling is performed during the initial
phases of the database development process (also referred as database life cycle) as shown in
Figure 1. During this process, the top two phases are concerned with the information content of
the database, while the last two phases are concerned with the implementation of the database on
some commercial DBMS.
Figure 1
During the conceptual data modeling phase, data requirements are expressed through an ERD.
The conceptual data modeling phase in general is independent of a DBMS. The logical design
phase transforms the conceptual data model into a format understandable to DBMS. This phase
may also enhance or refine the data model (ERD) of the previous phase to ensure efficient
utilization of the database. Since most of the commercial DBMS are based on the relational
model, the end product of this phase is relational model design.
One of the ways an ERD is enhanced during the logical design phase is through the process of
normalization. Normalization is one of the key tenets in relational model design. It is the process
of removing redundancy in a table so that the table is easier to modify . It usually involves
dividing an entity table into two or more tables and defining relationships between the tables.
The objective is to isolate data so that additions, deletions, and modifications of an attribute can
be made in just one table and then propagated through the rest of the database via the defined
relationships.
Normalization utilizes association among attributes within an entity table to accomplish its
objective. Since an ERD also utilizes association among attributes as a basis to identify entity
type structure, it is possible to apply normalization principles during the conceptual data
modeling phase. Performing normalization during ERD development can improve the conceptual
model, and speed its implementation. This paper outlines the application of normalization
principles to ERD development during the conceptual modeling phase. There are various
standards for ERD. In this paper, the Crow’s Foot notation is utilized.
Data modeling is an iterative process. Generally a preliminary data model is constructed which is
then refined many times. There are many guidelines (rules) for refining an ERD. Some of these
rules are as follows (Mannino, 2006):
1. Transform attributes into entity types. This transformation involves the addition of an
entity type and a 1-M (one-to-many) relationship.
2. Split compound attributes into smaller attributes. A compound attribute contains multiple
kinds of data.
3. Expand entity types into two entity types and a relationship. This transformation can be
useful to record a finer level of detail about an entity.
4. Transform a weak entity type into a strong entity type. This transformation is most useful
for associative entity types.
5. Add historical details to a data model. Historical details may be necessary for legal as
well as strategic reporting requirements. This transformation can be applied to attributes
and relationships.
6. Add generalization hierarchies by transforming entity types into generalization hierarchy.
Representation of Dependencies
Functional dependency in an entity type occurs if one observes the association among the entity
identifier and other attributes as reflected in an entity instance. Each entity instance represents a
set of values taken by the non entity identifier attributes for each primary key (entity identifier)
value. So, in a way an entity instance structure also reflects an application of the functional
dependency concept. For example, the Student entity type of Figure 2 can represent the
functional dependency SID ?Name, Street, City, Zip.
Figure 2
Each entity instance will now represent the functional dependency among the entity attributes as
shown in Figure 3.
Figure 3
During requirement analysis, some entity types may be identified through functional
dependencies, while others may be determined through database relationships. For example, the
statement, “A faculty teaches many offerings but an offering is taught by one faculty” defines
entity type Faculty and Offerings. Another important consideration is to distinguish when one
attribute alone is the entity identifier versus a composite entity identifier. A composite entity
identifier is an entity identifier with more than one attribute. A functional dependency in which
the determinant contains more than one attribute usually represents a many-to-many relationship,
which is more addressed through higher normal forms. The notion of having a composite entity
identifier is not very common, and often times is a matter of expediency, rather than good entity
structure or design.
Transitive dependency in an entity type occurs if non entity identifier attributes have dependency
among themselves. For example, consider the modified Student entity type as shown in Figure 4.
Figure 4
In this entity type, suppose there is a functional dependency BuildingName ? Fee. Existence of
BuildingName ? Fee dependency implies that the value assigned to the Fee attribute is fixed for
distinct BuildingName attribute values. In other words, the Fee attribute values are not specific to
the SID value of a student, but rather the BuildingName value. The entity instance of transitive
dependency is shown in Figure 5.
Figure 5
Multi-valued dependency equivalency in ERD occurs when attributes within an entity instance
have more than one value. This is a situation when some attributes within an entity instance have
maximum cardinality of N (more than 1). When an attribute has multiple values in an entity
instance, it can be setup either as a composite key identifier of the entity type, or split into a
weak entity type. For example, consider the following entity type Student Details as shown in
Figure 6.
Figure 6
The Student Details entity type has a composite entity identifier consisting of three attributes –
SID, MajorMinor, and Activity. The composition of entity identifier is due to the fact that a
student has multiple MajorMinor values along with being involved in multiple activities.
However, a student has only one value for Name, Street, City, Zip attributes based on the
functional dependency SID, MajorMinor, Activity ? Name, Street, City, Zip. The multi-valued
dependency affects the key structure. So, in the Student Details entity type, there can be an MVD
SID ?? MajorMinor, Activity. This means that a SID value is associated with multiple values of
MajorMinor and Activity attributes, and together they determine other attributes. The entity
instance of Student Details entity type is shown Figure 7.
Figure 7
Now we utilize the representation of dependency concepts in ERD toward their use in the
application of normal forms. Each normal form rule and its application is outlined.
An entity instance of this entity type is shown in Figure 9. Now, if there is a functional
dependency City ? Status, then the entity type structure will violate the second normal form.
Figure 9
To resolve the violation of the second normal form a separate entity type City with one-to-many
relationship is created as shown in Figure 10. The relationship cardinalities can be further
modified to reflect organizational working. In general, the second normal form violation can be
avoided by ensuring that there is only one attribute as an entity identifier.
Figure 10
Figure 11
These situations are only possible if there is a composite entity identifier, and dependencies exist
from a non-entity identifier attribute to part of the entity identifier. For example, consider the
entity type StudentConcentration as shown in Figure 12. The entity type is in third normal form,
but since there is a dependency FacultyName ? MajorMinor, it is not in Boyce-Codd normal
form.
Figure 12
To ensure that StudentConcentration entity type stays in Boyce-Codd normal form, another
entity type Faculty with one-to-many relationship is constructed as shown in Figure 13. The
relationship cardinalities can be further modified to reflect organizational working.
Figure 13
Figure 14
Result:
Thus database is designed with normalization.
Exp.no. 9.
Database Connectivity with Front End Tools
Aim :
Procedure:
3. In the New Connection wizard, select Oracle Thin in the Driver dropdown list.
4. Click Add and locate the ojdbc6.jar file that you previously downloaded. Click Next.
5. In the Customize Connection panel of the wizard, enter the following values and click Next.
Name Value
Driver Name Oracle Thin (with Service ID (SID))
localhost or 127.0.0.1.
Note: In the case of a remote connection, provide the IP
Host
address or resolvable hostname of the machine where the
database is installed.
Port 1521 (default)
XE (default SID for Oracle Database XE).
Service ID (SID) Note: If you are connecting to a remote database, ask the
database administrator to provide you with the database SID.
Note: You need to unlock the HR schema before you can access it in NetBeans.
Unlocking the HR database is described in the Oracle Database XE Getting Started
tutorial.
The new connection will appear under the Databases node in the Services window. You can
expand it and start browsing the database object's structure.
Change the display name for the connection node: choose Properties from the node's popup
menu and click the ellipsis button for the Display Name property. Enter OracleDB as the Display
Name and click OK.
Note. Although the steps above demonstrate the case of connecting to a local database instance,
the steps for connecting to a remote database are the same. The only difference is that instead of
specifying localhost as the hostname, enter the IP address or hostname of the remote machine
where Oracle Database is installed.
Result:
Ex.No : 10
AIM :
To implement the project for Employee management system.
Description :
Employee Management System is used to maintain the detail of employees of an
organization. HR can view the details department wise. HR can delete the employees.HR can
update the employees details. HR can add new employees.
Tables :
o Employee(empno number primary key , empname varchar(20) , department
varchar(20) , salary number)
Net beans:
Procedure:
1. Code for components in GUI will come automatically.
2. Do oracle connectivity. (click on services----right click on database—select new
connection—
Select oracle thin driver----give service id as orcl.---give username and password.---click
test connection.
Coding:
Statement stmt=con.createStatement();
}
}
if (temp==1)
{
String query="delete from employee where empid= " + a ;
stmt.execute(query);
JOptionPane.showMessageDialog (null,"employee record deleted");
}
else
con.close();
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");
Statement stmt=con.createStatement();
String query="insert into employee values( "
+ id.getText()+", '"+name.getText()+"' , '"+department.getText()+"' ,"
+salary.getText()+")";
id.setText(null);
name.setText(null);
department.setText(null);
salary.setText(null);
//con.close();
catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");
Statement stmt=con.createStatement();
String a=JOptionPane.showInputDialog(null,"Enter Employee id");
}
}
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:orcl","system","manager
");
Statement stmt=con.createStatement();
String query="update employee set empid= " + id.getText()+",empname='"
+name.getText()+"' , empdept='"+department.getText()+"' ,salary="
+salary.getText()+"where empid= " + id.getText();
id.setText(null);
name.setText(null);
department.setText(null);
salary.setText(null);
con.close();
catch(SQLException ex)
{
JOptionPane.showMessageDialog (null,ex);
Result: