0% found this document useful (0 votes)
26 views73 pages

Database Design and Management System Manual-1

Uploaded by

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

Database Design and Management System Manual-1

Uploaded by

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

EX.

NO : DATABASE DEVELOPMENT LIFE CYCLE PROBLEM DEFINITION


DATE: AND REQUIREMENTS ANALYSIS , SCOPE AND CONSTRAINTS

AIM
To study about the various concepts such as Problem definition, Requirement analysis, Scope and Constraints
involved in Database Development Life Cycle.

DESCRIPTION
DATABASE ENVIRONMENT

A database environment is a collective system of components that comprise and regulates the group of data, management,
and use of data, which consist of software, hardware, people, techniques of handling database, and the data also. One of the
primary aims of a database is to supply users with an abstract view of data, hiding a certain element of how data is stored and
manipulated.

● Hardware in a database environment means the computers and computer peripherals that are
being used to manage a database,
● Software includes operating system (OS) to the application programs that include database
management software like M.S. Access or SQL Server.
● People in a database environment include administrators and data users in system

COMPONENTS OF DATABASE SYSTEM ENVIRONMENT


Even the database system environment is made up of the following
1. Hardware
2. Software
3. People
4. Procedure
5. Data
System Utilities: Database system utilities are the tools that can be used by the database system
administrator to control and manage the database system.
1. Loading Utility
Loading database utility helps in loading the database file into the database.
2. Backup Utility
The backup utility in the database environment helps in creating a backup copy of the entire database.
3. Database Storage Reorganization Utility
It helps to relocate and organize the database files to a different location and it also produces a new
access path to access the files from its new location.
4. Performance Monitoring Utility
It monitors the usage of the database by its user and provides statistics for the same to the DBA.

DATABASE SYSTEM DEVELOPMENT LIFECYCLE:

● Database life cycle (DBLC) defines the stages involved for implementing a database,
starting with requirements analysis and ending with monitoring and modification.
● DBLC never ends because database monitoring, modification, and maintenance are part of
the life cycle, and these activities continue long after a database has been implemented.
● DBLC encompasses the lifetime of database.

Five stages in database life cycle are:

1. Requirements analysis

2. Logical design

3. Physical design

4. Implementation

5. Monitoring, Modification and Maintenance


Database Development Life Cycle

Steps in Database System Development Process


I. REQUIREMENTS ANALYSIS or REQUIREMENTS COLLECTION:
● Requirements Analysis is the first and most important stage in the Database Life Cycle.
● Process of collecting and analyzing information about organization that is to be supported by
database system, and using this information to identify requirements for new system.

Requirements analysis

Planning – This stages of database design concepts are concerned with planning of entire Database
Development Life Cycle.

System definition – This stage defines the scope and boundaries of the proposed database system.
Requirement Analysis - Example

Customer/End-user expectation: Customer/End-user receive:

Below are the two methodologies used for requirement analysis phase,

1) SDA - Struc ured data analysis

2) SSAD ructured systems analysis and design method

1. Structured Data Analysis (SDA)is a method for analysing the flow of information within
an organization using data flow diagrams.

Specification documents created in requirement analysis phase are used as input to conceptual
schema design phase. Structured data analysis (systems analysis) consists of

▪ Data Flow Diagrams


▪ Systems Analysis
▪ Data Processing

Data Flow Diagrams


▪ A Data-Flow Diagram is a way of representing a flow of data through a process or a
system. DFD also provides information about the outputs and inputs of each entity and
the process itself. A data-flow diagram has no control flow — there are no decision rules
and no loops. Specific operations based on the data can be represented by a flowchart.
▪ Systems analysis is "the process of studying a procedure or business to identify its
goal and purposes and create systems and procedures that will efficiently achieve
them"
▪ Data processing is, "the collection and manipulation of items of data to produce
meaningful information." It is a subset of information processing.

Data processing may involve various processes, including:

● Validation –
● Sorting –
● Summarization(statistical) or (automatic) –
● Aggregation –Analysis –
● Reporting –
● Classification

2. Structured Systems Analysis and Design Method (SSADM), as methodology, is a


systems approach to the analysis and design of information systems.

SSADM techniques Three most important techniques that are used in SSADM are as follows:

▪ Logical design
▪ Physical Design
▪ Implementation

II. Logical design


▪ During the first part of Logical Design, a conceptual model is created based on
the needs assessment performed in stage one.
▪ A conceptual model is typically an entity-relationship (ER) diagram that shows
tables, fields, and primary keys of database, and how tables are related (linked) to
one another.
▪ Tables in the ER diagram are then normalized. Normalization resolves any problems
associated with database design, so that data can be accessed quickly and efficiently.

1. CONCEPTUAL MODEL: describes the structure of a database.


2. ENTITY-RELATIONSHIP (ER) DIAGRAM: A diagram used during design phase
of database development and represents relationships between data during database
design.
3. NORMALIZATION: The process of applying increasingly stringent rules to a
relational database to correct any problems associated with poor design.
III. Physical Design

Physical Design stage has only one purpose: to maximize database efficiency.
This means finding ways to speed up the performance of the RDBMS. Manipulating certain
database design elements can speed up the two slowest operations in an RDBMS: retrieving
data from and writing data to a database.
The final two stages in the DBLC,

1. Implementation
2. Monitoring, Modification, and Maintenance occur after database design is complete.

IV. Implementation

During the implementation stage of the DBLC, the tables developed in the ER diagram (and
subsequently normalized) are converted into SQL statements. These SQL statements are then
executed in the RDBMS to create a database. By this stage in the database life cycle, the System
Administrator has installed and configured an RDBMS.
V. Monitoring, modification, and maintenance
A successfully implemented database must be carefully monitored to ensure that it is
functioning properly and that it is secure from unauthorized access.
RDBMS usually provides utilities to help monitor database functionality and security.

Database modification involves adding and deleting records, importing data from other systems
(as needed), and creating additional tables, user views, and other objects and tools.

DATABASE DESIGN:

▪ Database Design is a collection of processes that facilitate the designing,


development, implementation and maintenance of enterprise data management
systems.
▪ Properly designed database are easy to maintain, improves data consistency and cost
effective in terms of disk storage space.
▪ Database designer decides how data elements correlate and what data must be stored.

Database Design

It helps produce database systems

1. That meet the requirements of the users


2. Have high performance.
3. The database development life cycle has a number of stages that are followed when
developing database systems.
4. The steps in the development life cycle do not necessarily have to be followed
religiously in a sequential manner.
5. On small database systems, the process of database design is usually very simple and
does not involve a lot of steps.
Database designin

● Logical model – This stage is concerned with developing a database model based
on requirements. The entire design is on paper without any physical
implementations or specific DBMS considerations.
● Physical model – This stage implements the logical model of the database taking
into account the DBMS and physical implementation factors.

Implementation

● Data conversion and loading – this stage of relational databases design is


concerned with importing and converting data from the old system into the new
database.
● Testing – this stage is concerned with the identification of errors in the newly
implemented system. It checks the database against requirement specifications.

RESULT:

Thus the various concepts such as Problem definition, Requirement


analysis, Scope and Constraints involved in Database Development Life Cycle
has been studied.
EX.NO : DATABASE DESIGN USING CONCEPTUAL MODELING (ER-EER)
DATE: TOP-DOWN APPROACH MAPPING CONCEPTUAL TO
RELATIONAL DATABASE AND VALIDATE USING
NORMALIZATION.

AIM:

To perform mapping from a ER-EER Model to Relational Database in a Database Design


Using Conceptual Modeling

DESCRIPTION:

ER model
● ER model stands for an Entity-Relationship model. It is a high-level data model. This model
is used to define the data elements and relationship for a specified system.
● It develops a conceptual design for the database. It also develops a very simple and easy
to design view of data.
● In ER modeling, database structure is portrayed as a diagram called entity-relationship
diagram.

Example: Design a school database.

In this database, the student will be an entity with attributes like address, name, id, age, etc. The
address can be another entity with attributes like city, street name, pin code, etc and there will be a
relationship between them.
Component of ER Diagram

ER MODEL to RELATIONAL MAPPING

The database can be represented using the notations, and these notations can be reduced to a collection
of tables.
In the database, every entity set or relationship set can be represented in tabular form.

RULES FOR REDUCTION OF ER DIAGRAM TO TABLE

▪ Entity type becomes a table.

● All single-valued attribute becomes a column for the table.

● A key attribute of the entity type represented by the primary key.

● The multivalued attribute is represented by a separate table.

● Composite attribute represented by components

● Derived attributes are not considered in the table.


The ER diagram is given below:

After Mapping, Final Relational Database Table will be:


SAMPLE ENTITY-RELATIONSHIP DIAGRAM:

TABLE CREATION
CREATE TABLE
SALESMAN (SALESMAN_ID
NUMBER (4),
NAME VARCHAR2 (20),
CITY VARCHAR2 (20),
COMMISSION VARCHAR2 (20),
PRIMARYKEY
(SALESMAN_ID));

CREATE TABLE
CUSTOMER1
(CUSTOMER_ID NUMBER
(4),
CUST_NAME VARCHAR2 (20),
CITY VARCHAR2 (20),
GRADE NUMBER (3),
PRIMARY KEY (CUSTOMER_ID),
SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON DELETE SET NULL);

CREATE TABLE
ORDERS (ORD_NO
NUMBER (5),
PURCHASE_AMT NUMBER (10,
2), ORD_DATE DATE,
PRIMARY KEY (ORD_NO),

CUSTOMER_ID REFERENCES CUSTOMER1 (CUSTOMER_ID) ON DELETE


CASCADE, SALESMAN_ID REFERENCES SALESMAN (SALESMAN_ID) ON
DELETE CASCADE);
TABLE DESCRIPTION:

RESULT:
Thus the mapping from a ER-EER Model to Relational Database in a Database Design Using
Conceptual Modeling was done successfully.
EX.NO : 3 IMPLEMENT THE DATABASE USING SQL DATA DEFINITION
DATE: WITH CONSTRAINTS, VIEWS

AIM
To execute and verify the Data Definition SQL with constraints and views .

COMMANDS:
DDL (DATA DEFINITION LANGUAGE)

The major tasks included are database backup and recovery, access management, hardware maintenance etc

Constraints available in SQL are:

NOT NULL

UNIQUE

PRIMARY KEY

FOREIGN KEY

CHECK

DEFAULT

CREATE INDEX

Now let us try to understand the different constraints available in SQL in more detail with the help of examples. We will use
MySQL database for writing all the queries.

1. NOT NULL

NULL means empty, i.e., the value is not available.

Whenever a table's column is declared as NOT NULL, then the value for that column cannot be empty for any of the table's
records.

There must exist a value in the column to which the NOT NULL constraint is applied.

NOTE: NULL does not mean zero. NULL means empty column, not even zero.

Syntax to apply the NOT NULL constraint during table creation:

CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2 datatype,…., ColumnNameN
datatype);

Example:

Create a student table and apply a NOT NULL constraint on one of the table's column while creating a table.
CREATE TABLE student(StudentID INT NOT NULL, Student_FirstName VARCHAR(20), Student_LastName
VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

mysql> DESC student;

Syntax to apply the NOT NULL constraint on an existing table's column:

1. ALTER TABLE TableName CHANGE Old_ColumnName New_ColumnName Datatype NOT NULL;

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply a NOT NULL
constraint to one of the table's column. Then we will execute the following query:

mysql> ALTER TABLE student CHANGE StudentID StudentID INT NOT NULL;

To verify that the not null constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

2. UNIQUE

o Duplicate values are not allowed in the columns to which the UNIQUE constraint is applied.
o The column with the unique constraint will always contain a unique value.
o This constraint can be applied to one or more than one column of a table, which means more than one unique constraint
can exist on a single table.
o Using the UNIQUE constraint, you can also modify the already created tables.

Syntax to apply the UNIQUE constraint on a single column:

CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2 datatype,…., ColumnNameN datatype);

Example:

Create a student table and apply a UNIQUE constraint on one of the table's column while creating a table.

mysql> CREATE TABLE student(StudentID INT UNIQUE, Student_FirstName VARCHAR(20), Student_LastName VA


RCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

To verify that the unique constraint is applied to the table's column and the student table is created successfully, we will execute
the following query:

mysql> DESC student;

Syntax to apply the UNIQUE constraint on more than one column:

CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype,…., ColumnNameN datatype, UNIQUE (
ColumnName1, ColumnName 2));

Example:

Create a student table and apply a UNIQUE constraint on more than one table's column while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), UNIQUE(StudentID, Student_PhoneNum
ber));
To verify that the unique constraint is applied to more than one table's column and the student table is created successfully, we
will execute the following query:

mysql> DESC student;

Syntax to apply the UNIQUE constraint on an existing table's column:

ALTER TABLE TableName ADD UNIQUE (ColumnName);

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply a UNIQUE
constraint to one of the table's column. Then we will execute the following query:

mysql> ALTER TABLE student ADD UNIQUE (StudentID);

To verify that the unique constraint is applied to the table's column and the student table is created successfully, we will execute
the following query:

mysql> DESC student;

3. PRIMARY KEY

o PRIMARY KEY Constraint is a combination of NOT NULL and Unique constraints.


o NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY constraint.
o The column to which we have applied the primary constraint will always contain a unique value and will not allow
null values.

Syntax of primary key constraint during table creation:


CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY, ColumnName2 datatype,…., ColumnNameN da
tatype);

Example:

Create a student table and apply the PRIMARY KEY constraint while creating a table.

mysql> CREATE TABLE student(StudentID INT PRIMARY KEY, Student_FirstName VARCHAR(20), Student_LastN
ame VARCHAR(20), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40));

To verify that the primary key constraint is applied to the table's column and the student table is created successfully, we will
execute the following query:

mysql> DESC student;

Syntax to apply the primary key constraint on an existing table's column:

ALTER TABLE TableName ADD PRIMARY KEY (ColumnName);

Example:

Consider we have an existing table student, without any constraints applied to it. Later, we decided to apply the PRIMARY
KEY constraint to the table's column. Then we will execute the following query:

mysql> ALTER TABLE student ADD PRIMARY KEY (StudentID);

To verify that the primary key constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;


4. FOREIGN KEY

o A foreign key is used for referential integrity.


o When we have two tables, and one table takes reference from another table, i.e., the same column is present in both the
tables and that column acts as a primary key in one table. That particular column will act as a foreign key in another
table.

Syntax to apply a foreign key constraint during table creation:

CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatype(SIZE), FOREI


GN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_ColumnName));

Example:

Create an employee table and apply the FOREIGN KEY constraint while creating a table.

To create a foreign key on any table, first, we need to create a primary key on a table.

mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR (40), Emp_S
alary VARCHAR (40));

To verify that the primary key constraint is applied to the employee table's column, we will execute the following query:

mysql> DESC employee;

Now, we will write a query to apply a foreign key on the department table referring to the primary key of the employee table,
i.e., Emp_ID.

mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_I
D INT NOT NULL, FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));
To verify that the foreign key constraint is applied to the department table's column, we will execute the following query:

mysql> DESC department;

Syntax to apply the foreign key constraint with constraint name:

1. CREATE TABLE tablename(ColumnName1 Datatype PRIMARY KEY, ColumnNameN Datatype(SIZE),


CONSTRAIN T ConstraintName FOREIGN KEY( ColumnName ) REFERENCES
PARENT_TABLE_NAME(Primary_Key_ColumnN ame));

Example:

Create an employee table and apply the FOREIGN KEY constraint with a constraint name while creating a table.

To create a foreign key on any table, first, we need to create a primary key on a table.

mysql> CREATE TABLE employee (Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR (40), Emp_S
alary VARCHAR (40));

To verify that the primary key constraint is applied to the student table's column, we will execute the following query:

mysql> DESC employee;

Now, we will write a query to apply a foreign key with a constraint name on the department table referring to the primary key
of the employee table, i.e., Emp_ID.

mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_I
D INT NOT NULL, CONSTRAINT emp_id_fk FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));
To verify that the foreign key constraint is applied to the department table's column, we will execute the following query:

mysql> DESC department;

Syntax to apply the foreign key constraint on an existing table's column:

ALTER TABLE Parent_TableName ADD FOREIGN KEY (ColumnName) REFERENCES Child_TableName (Column
Name);

Example:

Consider we have an existing table employee and department. Later, we decided to apply a FOREIGN KEY constraint to the
department table's column. Then we will execute the following query:

mysql> DESC employee;

mysql> ALTER TABLE department ADD FOREIGN KEY (Emp_ID) REFERENCES employee (Emp_ID);

To verify that the foreign key constraint is applied to the department table's column, we will execute the following query:

mysql> DESC department;


5. CHECK

o Whenever a check constraint is applied to the table's column, and the user wants to insert the value in it, then the value
will first be checked for certain conditions before inserting the value into that column.
o For example: if we have an age column in a table, then the user will insert any value of his choice. The user will also
enter even a negative value or any other invalid value. But, if the user has applied check constraint on the age column
with the condition age greater than 18. Then in such cases, even if a user tries to insert an invalid value such as zero or
any other value less than 18, then the age column will not accept that value and will not allow the user to insert it due
to the application of check constraint on the age column.

Syntax to apply check constraint on a single column:

CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1 Condition), ColumnName2 datatype,….,
ColumnNameN datatype);

Example:

Create a student table and apply CHECK constraint to check for the age less than or equal to 15 while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT CHECK( Age <= 15));

To verify that the check constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

Syntax to apply check constraint on multiple columns:

CREATE TABLE TableName (ColumnName1 datatype, ColumnName2 datatype CHECK (ColumnName1 Condition AN
D ColumnName2 Condition),…., ColumnNameN datatype);
Example:

Create a student table and apply CHECK constraint to check for the age less than or equal to 15 and a percentage greater than
85 while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40), Age INT, Percentage INT, CHECK( Age
<= 15 AND Percentage > 85));

To verify that the check constraint is applied to the age and percentage column, we will execute the following query:

1. mysql> DESC student;

Syntax to apply check constraint on an existing table's column:

1. ALTER TABLE TableName ADD CHECK (ColumnName Condition);

Example:

Consider we have an existing table student. Later, we decided to apply the CHECK constraint on the student table's column.
Then we will execute the following query:

mysql> ALTER TABLE student ADD CHECK ( Age <=15 );

To verify that the check constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;


6. DEFAULT

Whenever a default constraint is applied to the table's column, and the user has not specified the value to be inserted in it, then
the default value which was specified while applying the default constraint will be inserted into that particular column.

Syntax to apply default constraint during table creation:

CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value, ColumnName2 datatype,…., ColumnNameN d
atatype);

Example:

Create a student table and apply the default constraint while creating a table.

mysql> CREATE TABLE student(StudentID INT, Student_FirstName VARCHAR(20), Student_LastName VARCHAR(2


0), Student_PhoneNumber VARCHAR(20), Student_Email_ID VARCHAR(40) DEFAULT "[email protected]");

To verify that the default constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

Syntax to apply default constraint on an existing table's column:

ALTER TABLE TableName ALTER ColumnName SET DEFAULT Value;

Example:
Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on the student table's column.
Then we will execute the following query:

mysql> ALTER TABLE student ALTER Student_Email_ID SET DEFAULT "[email protected]";

To verify that the default constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

7. CREATE INDEX

CREATE INDEX constraint is used to create an index on the table. Indexes are not visible to the user, but they help the user
to speed up the searching speed or retrieval of data from the database.

Syntax to create an index on single column:

CREATE INDEX IndexName ON TableName (ColumnName 1);

Example:

Create an index on the student table and apply the default constraint while creating a table.

mysql> CREATE INDEX idx_StudentID ON student (StudentID);

To verify that the create index constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;


Syntax to create an index on multiple columns:

CREATE INDEX IndexName ON TableName (ColumnName 1, ColumnName 2, ColumnName N);

Example:

mysql> CREATE INDEX idx_Student ON student (StudentID, Student_PhoneNumber);

To verify that the create index constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

Syntax to create an index on an existing table:

ALTER TABLE TableName ADD INDEX (ColumnName);

Consider we have an existing table student. Later, we decided to apply the DEFAULT constraint on the student table's column.
Then we will execute the following query:

mysql> ALTER TABLE student ADD INDEX (StudentID);


To verify that the create index constraint is applied to the student table's column, we will execute the following query:

mysql> DESC student;

RESULT:
Thus the Data Definition Language with constraints and view commands are executed and verified.
EX.NO : QUERY THE DATABASE USING SQL MANIPULATION
DATE:

AIM:

To Query the database using SQL Manipulation i.e. Data Manipulation Language (DML) Commands.

DESCRIPTION:

SQL DATA MANIPULATION LANGUAGE (DML)

▪ DML commands are SQL commands, used to manipulation of data i.e., modify
the data present in the database
▪ It is responsible for all form of changes in the database.
▪ The command of DML is not auto-committed that means it can't permanently save
all the changes in the database. They can be rollback.

List of DML commands:

● INSERT : It is used to insert data into a table.


● UPDATE: It is used to update existing data within a table.
● DELETE : It is used to delete records from a database table.
● SELECT: It is used to query or retrieve data from a table in the database

a. SQL INSERT: SQL INSERT statement is used to insert a single or multiple data into row of a
table.

Syntax:

INSERT INTO TABLE_NAME


(col1, col2, col3,. col N)
VALUES (value1, value2, value3, valueN);
Or INSERT INTO TABLE_NAME
VALUES (value1, value2, value3, valueN);

For example:

In SQL, You can insert the data in two ways:

▪ Without specifying column name


▪ By specifying column name
Sample Table - EMPLOYEE

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Russell Los angels 200000 36

1. Without specifying column name


Syntax: INSERT INTO
TABLE_NAME
VALUES (value1, value2, value 3, Value N);

Query: INSERT INTO EMPLOYEE VALUES (6, 'Marry', 'Canada', 600000, 48);

Output:

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Russell Los angels 200000 36
6 Marry Canada 600000 48

2. By specifying column name

To insert partial column values, you must have to specify the column names.
Syntax

INSERT INTO TABLE_NAME

[(col1, col2, col3,. col N)]

VALUES (value1, value2, value 3, Value N);


Query

INSERT INTO EMPLOYEE (EMP_ID, EMP_NAME, AGE) VALUES (7, 'Jack', 40);

Output: After executing this query, the table will look like:

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Russell Los angels 200000 36
6 Marry Canada 600000 48
7 Jack null null 40

b. SQL UPDATE:

● This command is used to update or modify the value of a column in the table.
● SQL UPDATE statement is used to modify the data that is already in the database.
● The condition in the WHERE clause decides that which row is to be updated.

Syntax:

UPDATE table_name

SET column1 = value1, column2 = value2, ... [WHERE


CONDITION]

Sample Table:
EMPLOYEE
EMP_ID EMP_NAME CITY SALARY AGE
1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Russell Los angels 200000 36
6 Marry Canada 600000 48
Updating single record

Update column EMP_NAME and set the value to 'Emma' in the row where SALARY is 500000.

Syntax: UPDATE table_name


S
E
Query T
c
o
l
u
m
n
_
n
a
m
e
=
v
a
l
u
e
W
H
E
R
E
c
o
n
d
i
t
i
o
n
;

UPDATE EMPLOYEE

SET EMP_NAME = 'Emma' WHERE


SALARY = 500000;
Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Emma Washington 500000 29
5 Russell Los angels 200000 36
6 Marry Canada 600000 48
Updating multiple records

If you want to update multiple columns, you should separate each field assigned with a comma.Syntax
UPDATE table_name
SET column_name = value1, column_name2 = value2 WHERE
condition;
Query

UPDATE EMPLOYEE

SET EMP_NAME = 'Kevin', City = 'Boston' WHERE


EMP_ID = 5;
Output
EMP_ID EMP_NAME CITY SALARY AGE
1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
4 Kristen Washington 500000 29
5 Kevin Boston 200000 36
6 Marry Canada 600000 48

Without use of WHERE clause


Syntax: UPDATE
table_name
SET column_name = value1;

Query: UPDATE EMPLOYEE


SET EMP_NAME = 'Harry';
Output

EMP_ID EMP_NAME CITY SALARY AGE


1 Harry Chicago 200000 30
2 Harry Austin 300000 26
3 Harry Denver 100000 42
4 Harry Washington 500000 29
5 Harry Los angels 200000 36
6 Harry Canada 600000 48

c. SQL DELETE: It is used to remove one or more row from a table.

Syntax:

DELETE FROM table_name [WHERE condition];


Example :

Suppose, the EMPLOYEE table having the following records:

EMP_ID EMP_NAME CITY PHONE_NO SALARY


1 Kristen Chicago 9737287378 150000
2 Russell Austin 9262738271 200000
3 Denzel Boston 7353662627 100000
4 Angelina Denver 9232673822 600000
5 Robert Washington 9367238263 350000
6 Christian Los angels 7253847382 260000

The following query will DELETE an employee whose ID is 3.

SQL> DELETE FROM EMPLOYEE WHERE


EMP_ID = 3;
EMP_ID EMP_NAME CITY PHONE_NO SALARY
1 Kristen Chicago 9737287378 150000
2 Russell Austin 9262738271 200000
4 Angelina Denver 9232673822 600000
5 Robert Washington 9367238263 350000
6 Christian Los angels 7253847382 260000

If you don't specify the WHERE condition, it will remove all the rows from the table.

DELETE FROM EMPLOYEE;

Now, the EMPLOYEE table would not have any records.

Deleting Single Record

Delete the row from the table EMPLOYEE where EMP_NAME = 'Kristen'. This will delete only the fourth
row.
Query

DELETE FROM EMPLOYEE WHERE


EMP_NAME = 'Kristen';
Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE


1 Angelina Chicago 200000 30
2 Robert Austin 300000 26
3 Christian Denver 100000 42
5 Russell Los angels 200000 36
6 Marry Canada 600000 48

Deleting Multiple Record

Delete the row from the EMPLOYEE table where AGE is 30.

Query

DELETE FROM EMPLOYEE WHERE AGE= 30;

Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE


2 Robert Austin 300000 26
3 Christian Denver 100000 42
5 Russell Los angels 200000 36
6 Marry Canada 600000 48

Delete all of the records

Delete all the row from the EMPLOYEE table. After this, no records left to display. The EMPLOYEE table
will become empty.
Syntax

DELETE * FROM table_name;

or

DELETE FROM table_name;

Query

DELETE FROM EMPLOYEE;

Output: After executing this query, the EMPLOYEE table will look like:

EMP_ID EMP_NAME CITY SALARY AGE


DATA QUERY LANGUAGE - DQL is used to fetch data from database. It uses only one
command - SELECT

SELECT:

SELECT statement is used to query or retrieve data from a table in the database. The
returns data is stored in a table, and the result table is known as result-set.
Syntax:
SELECT expressions FROM
TABLES
WHERE conditions;
Or
SELECT column1, column2, ... FROM
table_name;
For example:
Use the following syntax to select all the fields available in the table:
SELECT * FROM table_name;

Example: EMPLOYEE

EMP_ID EMP_NAME CITY PHONE_NO SALARY


1 Kristen Chicago 9737287378 150000
2 Russell Austin 9262738271 200000
3 Angelina Denver 9232673822 600000
4 Robert Washington 9367238263 350000
5 Christian Los angels 7253847382 260000
To fetch the EMP_ID of all the employees, use the following query:
SELECT EMP_ID FROM EMPLOYEE;
Output

EMP_ID
1
2
3
4
5

To fetch the EMP_NAME and SALARY, use the following query:


SELECT EMP_NAME, SALARY FROM EMPLOYEE;
EMP_NAME SALARY
Kristen 150000
Russell 200000
Angelina 600000
Robert 350000
Christian 260000

To fetch all the fields from the EMPLOYEE table, use the following query:
SELECT * FROM EMPLOYEE
Output

EMP_ID EMP_NAME CITY PHONE_NO SALARY


1 Kristen Chicago 9737287378 150000
2 Russell Austin 9262738271 200000
3 Angelina Denver 9232673822 600000
4 Robert Washington 9367238263 350000
5 Christian Los angels 7253847382 260000

RESULT:

Thus, SQL Data Manipulation Language (DML) Commands for Querying the database has been
executed.
EX.NO : QUERYING/MANAGING THE DATABASE USING SQL
DATE: MANIPULATION – FUNCTIONS, PROCEDURES AND
TRIGGERS

AIM:
To Query/Manage the Database Using SQL Programming Functions, procedures and triggers.

FUNCTIONS IN SQL

DESCRIPTION: To create a function for deposit and withdrawal of money from an account in a
bank management system this uses bank table.

TABE CREATION:

create table bank_acc(acc_no number, b_name varchar2(10), balance number);

Table created.

insert into bank_acc values (100,‘SBI‘, 25000)

1 row created.

insert into bank_acc values (101,‘SBT‘, 5000)

1 row created.

insert into bank_acc values (102,‘FEDERAL‘, 10000)

1 row created.

insert into bank_acc values (103,‘AXIS‘,15000)

1 row created.

insert into bank_acc values (104,‘CANARA‘, 50000)

1 row created

select * from bank_acc;

ACC_ B_NA BALAN


NO ME CE
100 SBI 25000
101 SBT 5000
102 Federal 10000
103 Axis 15000
104 Canara 50000
WITHDRAW FUNCTION:

Create a function for withdrawing money from an account in bank

PROGRAM:

create or replace function withdraw (n in number, amt in number)


return number is
b number;
begin
select balance into b from bank_acc where acc_no=n;
if b-500>amt then
b:=b-amt;

update bank_acc set balance=b where acc_no=n;


else
dbms_output.put_line('can not withdraw');
end if;
return b;
end;
/
Function
created

WITHDRAW FUNCTION CALL:

Calling function from a PL\SQL block:

declare

n number;
begin
n:=withdraw(100,20000);
end
/

Statement processed.
select * from bank_acc;

ACC_NO B_NAME BALANCE


100 SBI 5000
101 SBT 5000
102 Federal 10000

103 axis 15000

104 canara 50000


Calling function from a PL\SQL block:
declare
n number;

begin
n:=withdraw(101,20000);
end
/

can not withdraw


Statement processed.
select * from bank_acc;
ACC_NO B_NAME BALANCE
100 SBI 5000
101 SBT 5000
102 Federal 10000
103 Axis 15000
104 Canara 50000

DEPOSIT FUNCTION:
Create a function for depositing money to an account in a bank

create or replace function deposit(n in number, amt in number)


return number is
b number;
begin

select balance into b from bank_acc where acc_no=n;


b:=b+amt;
update bank_acc set balance=b where acc_no=n;
return b;
end

/
Function
created

DEPOSIT FUNCTION CALL

Calling function from a PL/SQL block

declare
n number;
begin
n:=deposit(104,5000);
end
/
Statement processed.

select * from bank_acc;

ACC_NO B_NAME BALANCE

100 SBI 5000

101 SBT 5000

102 Federal 10000

103 axis 15000

104 canara 55000

PROCEDURES IN SQL

DESCRIPTION:
To create a procedure for deposit and withdrawal of money in an account in a bank table

Table Creation:

create table bank(acc_no number, name varchar2(10), bal number);

Table created.

Inserting Values in table:

insert into bank values (100,‘Anil‘,50000)

1 row created.

insert into bank values (101,‘Abi‘,10000)

1 row created.

insert into bank values (102,‘Bavi‘,2500)

1 row created.

insert into bank values (103,‘Chandru‘,1000)

1 row created.

insert into bank values (104,‘Divakar‘,20000)

1 row created.
select * from bank;

ACC_NO NAME BAL

100 Anil 50000

101 Abi 10000

102 Bavi 2500

103 Chandru 1000

104 Divakar 20000

CREATING A PROCEDURE

Create a procedure for deposit & withdrawal of money in account in a Bank table.

create or replace procedure bank_pro(opt number, amount number, n number)


as
balance
number; begin
select bal into balance from bank where acc_no=n;
if opt=1 then
balance:= balance+amount;

update bank set bal=balance where acc_no=n;


commit;
dbms_output.put_line('Balance after deposition is '||balance);
elsif opt=2 then
balance:=balance-amount;
if balance<1000 then
dbms_output.put_line('Cannot withdraw… Balance lower than'||balance);
else
update bank set bal=balance where acc_no=n;
commit;
dbms_output.put_line('Balance after withdrawal is'||balance);
end if;
end if;
end;
/

Procedure created.
PROCEDURE CALL - DEPOSIT

begin
bank_pro(1,40000,100);
end;
/
Balance after deposition is 90000
Statement processed.
select * from bank;

ACC_NO NAME BAL


100 Anil 90000

101 Abi 10000

102 Bavi 2500

103 Chandru 1000

104 Divakar 20000

PROCEDURE CALL - WITHDRAW

begin
bank_pro(2,1500,102);
end;
/
OUTPUT:
Balance after withdrawal is1000
Statement processed.
Select * from bank;

ACC_NO NAME BAL


100 Anil 90000

101 Abi 10000

102 Bavi 1000

103 Chandru 1000

104 Divakar 20000

PROCEDURE CALL - WITHDRAW


begin bank_pro(2,1500,103);
end;
/

OUTPUT:
Cannot withdraw… Balance lower than-500
Statement processed.

select * from bank;


ACC_NO NAME BAL

100 Anil 90000

101 Abi 10000

102 Bavi 1000

103 Chandru 1000

104 Divakar 20000

TRIGGERS IN SQL

TRIGGER DESCRIPTION:

A trigger is a stored procedure in database which automatically invokes whenever a special


event in the database occurs. For example, a trigger can be invoked when a row is inserted into a
specified table or when certain table columns are being updated.

SYNTAX:
Create trigger trigger name
BEFORE | AFTER
DELETE, INSERT, UPDATE

ON table name
FOR EACH
ROW BEGIN
Executable-statements
END;
Example:

Given Student Database, in which student marks assessment is recorded.

Create a trigger so that the total and average of specified marks is automatically calculated whenever a
record is inserted.

Database creation:

create table student(sid number(4), name varchar(30), sub1 number(2), sub2 number(2),
sub3 number(2), total number(3), per number(3));

Table Description:
Desc student;
Before Trigger Execution: Inserting Values in table:
insert into student values(1, 'Nivetha', 50, 60, 70, 0, 0);
1 row(s) inserted.

select * from student;

CREATING TRIGGER

create trigger
strigger before insert
on
Student
for each row
Begin
update student set Student.total = Student.sub1 + Student.sub2 + Student.sub3,
Student.per = Student.total/3;
end;

/
OUTPUT: Trigger Created.
After Trigger Execution Inserting Values in table:
Insert into student values(2, 'Rithani', 90, 80, 90, 0, 0);
1 row(s) inserted.

select * from student


insert into student values(3, 'Sankar', 90, 90, 90, 0, 0);
1 row(s) inserted.

select * from student;

insert into student values(4, 'Vijay', 95, 95, 95, 0, 0);


1 row(s) inserted.
select * from
student; OUTPUT:

RESULT:

Thus the function, procedure trigger while insert or update or delete operations are performed on
the table student was successfully executed and output was verified
EX.NO : DATABASE DESIGN USING NORMALIZATION BOTTOM-UP
DATE: APPROACH

AIM:

To Validate a Database Design Using Normalization

DESCRIPTION:

NORAMALIZATION OF TABLE

▪ Database normalization is the process of removing redundant data from tables in order to improve
storage efficiency, data integrity, and scalability

▪ Normalization is process of minimizing redundancy from a relation. Redundancy in relation may


cause insertion, deletion, and update anomalies. So, it helps to minimize redundancy in relations.

▪ Normal forms are used to eliminate or reduce redundancy in database tables

Normalization of Tables in Database

Normal Form Description

1NF A relation is in 1NF if it contains an atomic value.


A relation will be in 2NF if it is in 1NF and all non-key attributes are fully
2NF functional dependent on the primary key.

3NF A relation will be in 3NF if it is in 2NF and no transition dependency exists.

BCNF A stronger definition of 3NF is known as Boyce Codd's normal form.

4NF A relation will be in 4NF if it is in Boyce Codd's normal form and has no
multi-valued dependency.
A relation is in 5NF. If it is in 4NF and does not contain any join dependency,
5NF joining should be lossless.
1. FIRST NORMAL FORM

▪ If a relation contain composite or multi-valued attribute, it violates first normal form


▪ If a relation is in first normal form if it should contain only atomic values.

Example: EMPLOYEE table:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385, UP
9064738238

20 Harry 8574783832 Bihar


12 Sam 7390372389, Punjab
8589830302

The decomposition of the EMPLOYEE table into 1NF has been shown below:

EMP_ID EMP_NAME EMP_PHONE EMP_STATE

14 John 7272826385 UP

14 John 9064738238 UP

20 Harry 8574783832 Bihar


12 Sam 7390372389 Punjab
12 Sam 8589830302 Punjab

Now the table is in First normal Form

2. SECOND NORMAL FORM:

● In the 2NF, relational must be in 1NF.


● In second normal form, all non-key attributes are fully functional dependent on the primary key
● Prime attribute − An attribute, which is a part of the candidate-key, is known as a prime
attribute.
● Non-prime attribute − An attribute, which is not a part of the prime-key, is said to be a non-
prime attribute.

Example 1:
In Second normal form, every non-prime attribute should be fully functionally dependent on prime key
attribute. That is, if X → A holds, then there should not be any proper subset Y of X, for which Y → A also
holds true.

In Student_Project relation that the prime key attributes are Stu_ID and Proj_ID.

According to the rule, non-key attributes, i.e. Stu_Name and Proj_Name must be dependent upon both and
not on any of the prime key attribute individually.

But Stu_Name can be identified by Stu_ID and Proj_Name can be identified by Proj_ID independently.
This is called partial dependency, which is not allowed in Second Normal Form.

In the above tables there is no partial dependency. So it is in second normal form.

Example: 2 TEACHER
table
TEACHER_ID SUBJECT TEACHER_AGE
25 Chemistry 30
25 Biology 30
47 English 35
83 Math 38
83 Computer 38

In the given table, non-prime attribute TEACHER_AGE is dependent on TEACHER_ID which is a proper
subset of a candidate key. That's why it violates the rule for 2NF.
To convert the given table into 2NF, we decompose it into two tables:
TEACHER_DETAIL table:

TEACHER_ID TEACHER_AGE
25 30
47 35
83 38

TEACHER_SUBJECT table:

TEACHER_ID SUBJECT
25 Chemistry
25 Biology
47 English
83 Math
83 Computer

3. THIRD NORMAL FORM (3NF)

● A relation will be in 3NF if it is in 2NF and not contain any transitive partial dependency.
● If there is no transitive dependency for non-prime attributes, then the relation must be in third
normal form.

For a relation to be in Third Normal Form, it must be in Second Normal form and must satisfy −

● No non-prime attribute is transitively dependent on prime key attribute.


● For any non-trivial functional dependency, X → A, then either −
o X is a superkey or,
o A is a prime attribute, i.e., each element of Y is part of some candidate key.

Example:1
In the above Student_detail relation, Stu_ID is the key and only prime key attribute.

City can be identified by Stu_ID as well as Zip itself. Neither Zip is a superkey nor is City a prime
attribute. Additionally, Stu_ID → Zip → City, so there exists transitive dependency.

To bring this relation into third normal form, we break the relation into two relations as follows −

Now both the relations in Third Normal Form

Example 2: EMPLOYEE_DETAIL table:

EMP_ID EMP_NAME EMP_ZIP EMP_STATE EMP_CITY


222 Harry 201010 UP Noida
333 Stephan 02228 US Boston
444 Lan 60007 US Chicago
555 Katharine 06389 UK Norwich
666 John 462007 MP Bhopal

Super key in the table above:

{EMP_ID}, {EMP_ID, EMP_NAME}, {EMP_ID, EMP_NAME, EMP_ZIP} so on

Candidate key: {EMP_ID}

Non-prime attributes: In the given table, all attributes except EMP_ID are non-prime.

Here, EMP_STATE & EMP_CITY dependent on EMP_ZIP and EMP_ZIP dependent on EMP_ID. The non-
prime attributes (EMP_STATE, EMP_CITY) transitively dependent on super key(EMP_ID).

It violates the rule of third normal form. That's why we need to move the EMP_CITY and EMP_STATE
to the new <EMPLOYEE_ZIP> table, with EMP_ZIP as a Primary key.
After 3rd Normalization
EMPLOYEE table:
EMP_ID EMP_NAME EMP_ZIP
222 Harry 201010
333 Stephan 02228
444 Lan 60007
555 Katharine 06389
666 John 462007

EMPLOYEE_ZIP table:

EMP_ZIP EMP_STATE EMP_CITY


201010 UP Noida
02228 US Boston
60007 US Chicago
06389 UK Norwich
462007 MP Bhopal

4. BOYCE CODD NORMAL FORM (BCNF)


Boyce-Codd Normal Form (BCNF) is an extension of Third Normal Form.

BCNF states that For any non-trivial functional dependency, X → A, X must be a super-key.

In the above Example, Stu_ID is the super-key in the relation Student_Detail and Zip is
the super-key in the relation ZipCodes.

Stu_ID → Stu_Name, Zip Zip → City


Which confirms that both the relations are in BCNF.
● BCNF is the advance version of 3NF. It is stricter than 3NF.
● A table is in BCNF if every functional dependency X → Y, X is the super key of the table.
● For BCNF, the table should be in 3NF, and for every FD, LHS is super key.

RESULT:

Thus the Database Design Using Normalization was performed


EX.NO : DEVELOP DATABASE APPLICATIONS USING IDE (NETBEANS)
DATE:

AIM:
To Develop Database Applications Using IDE (Netbeans) To Connect Java Program With
MS-Access Using JDBC Connectivity

JDBC DESCRIPTION

Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).
JDBC API is used to handle database using Java program and can perform the following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:

1) Register the driver class

2) Create the connection object

3) Create the Statement object

4) Execute the query

5) Close the connection object

Connect Java Application with access with DSN

Creating a MS Access Database

Step 1: Open Microsoft Access and select Blank database option and give the database name as File
name option
Step 2: Create a table and insert your data into the table

Step 3: Save the table with the desired name;, we save the following records with the
table name student.
Now Creating DSN of your database

Step 4: Open your Control Panel and then select


Administrative Tools. Step 5 : Click on Data Source(ODBC)--
>System DSN.

Step 6: Now click on add option for making a new DSN.select Microsoft Access Driver
(*.mdb.
*.accdb) and then click on Finish
Step 7: Make your desired Data Source Name and then click on the Select option, for example in this
article we use the name mydsn

Step 8: Now you select your data source file for storing it and then click ok and then click on
Create
and Finish
Step 9: Java
program code
Test.java
import
java.
sql.*
;
class
Test
DB
{
public static void main(String ar[])
{
Try
{
String url="jdbc:odbc:mydsn";
Class.forName("sun.jdbc.odbc.JdbcOdb
cDriver"); Connection
c=DriverManager.getConnection(url);
Statement st=c.createStatement();
ResultSet rs=st.executeQuery("select * from
login"); while(rs.next())
{
System.out.println(rs.getString(1) + " " + rs.getString(2)+ " " rs.getString(2));
}
}

catch(Exception ee){System.out.println(ee);
}}}

RESULT:

Thus the Database Applications Using IDE (Netbeans) To Connect Java Program
With MS- Access Using JDBC Connectivity is executed.
EX.NO : OBJECT DATABASE DESIGN USING EER-ODB MAPPING /UML
DATE: CLASS DIAGRAMS

AIM:
To develop a database design using EER-to-ODB mapping / UML class diagrams
DESCRIPTION
MAPPING EER TO ODB SCHEMA
An EER conceptual schema for a UNIVERSITY database.

A UML class diagram corresponding to the EER diagram


PERSON
tbrne
S•n
Bir1h_d<rte
Sex
Ad,t,. ... ,.

a,ga
...
...
I I
r PI..O¥r[ 1\1..Ut.lNUS DrGREr Sll.lOrNT
Salary
hire_emp new_ar.-.is
,...,_·1 . Year
Dc11rec
Mapr_dept
_Jll&jor
V Mlljor
... ... ...
...

I
t I
i
STAFF FACULTY SJ1U!)ENT ASSISTANT
P'oeiti0e Riu1i Flerc,...,t_time
hi _mff promote hi _studcnl
... ... . ..
I
,,\
I
A I
RESEARCH_ TEACH G_ GRADUATE UNDERGRADUATE_
ASSISTANT ASSISTANT SflUDENT STUDENT
Project Cou""" De9ree- pro!J11ffl c1a..
ch _prnject 1tssign_lo_oo changc_dcgm:_progrill11 cliangic_d1tssif1Calioo
... ... ... ...

FlgureU,9
(a) lntelfa;c.e !fxampl.:: at il d:liab= chtlm!!.
( r::: ,......... , not..J.oon for rBcrn,seolm□ ODL
smem:as. (b) A graph (}bjeci daitabase
crass, STUOe,J
scne.ma fur part of ihe llNIVEFi!SITY
da13ba.ss [GRADE and DEGREE chs.ses
are not s.hown
Relalionsl!ll,s
"'Iii!! al!!

t
CinM inhe!"illln
I herttance u ing eJCtend:i

"F1DE "™ 7
(b)
PEJ SON

STU.ENT
! Mef:-;::lct iicn:i Offarecl_b,;
_IC_O_U_RS--,

1-!a,i;_ flOn

CURR_SECTI N
Reg· ered_swdenw
ODL schema for the UNIVERSITY database
RESULT:

Thus the Database design using EER-to-ODB mapping / UML class diagrams is executed.
EX.NO : OBJECT FEATURES OF SQL-UDTS AND SUB-TYPES, TABLES
DATE: USING UDT’S , INHERITANCE, METHOD DEFINITION

AIM:
To Study about the various Object Features such as SQL-UDTS And Sub-Types, Tables
Using UDTS, Inheritance, Method Definition etc.,

DESCRIPTION

USER DEFINED TYPE (UDT)


● Most important object-oriented feature added to SQL is a user defined type
(UDT). The definition of a UDT is similar to the definition of a class.
● It can include attributes and methods and supports
inheritance. The following expression defines a new UDT called
Person.
create type Person as (pid varchar(10), pname varchar(20)) not final

⮚ UDT Person could also be the root of an inheritance hierarchy


⮚ Key word “not final” indicate that subtypes of Person can be defined.
⮚ Create two new UDTs called customer and employee both of which inherit from Person.
⮚ Key word “under” is similar to the key word “extend” in Java.

create type Customer under Person as (...)


create type Employee under Person as (...)
Modifiers associated with create type statements include

● not instantiable - objects of that type cannot be created

● instantiable - Objects can be created similar to abstract classes in Java

● final - type cannot have subtypes (or subclasses)

SUPERTYPES AND SUBTYPES


A subtype can be derived from a supertype either directly or indirectly through levels of
other subtypes. A supertype can have multiple sibling subtypes, but a subtype can have at most one
direct parent supertype (single inheritance).

Figure: Supertypes and Subtypes in Type Hierarchy


The hierarchy is shown as four boxes labelled A, B, C, and D.

● A is the supertype of all


● B and D are direct subtypes of A
● C is a direct subtype of B

TYPE INHERITANCE

create type Person (name varchar(20), address varchar (20));

create type Student under Person (degree varchar(20), department varchar (20));
create type Teacher under Person (salary integer, department varchar (20));
Both Student and Teacher inherit the attributes of Person—namely, name and address. Student and
Teacher are said to be subtypes of Person, and Person is a supertype of Student, as well as of Teacher

Multiple inheritance:

create type TeachingAssistant under Student , Teacher;

TeachingAssistant inherits all the attributes of Student and Teacher.

Example Creation of a simple UDT hierarchy for a business. The hierarchy implements a Person
UDT and two subtypes:

● Agent and
● Customer.

create type Person as Object (pid varchar(10), pname varchar(30),


address varchar(50)) not final
create type Agent under Person (commission int) not final
create type Customer under Person (discount int) not final

Objects can also be attributes of other objects. The Person type has been created to include an address
UDT. After the types are created a typed table of Agent objects is created and a new row is inserted into
the table.

create type Address as Object (street varchar(30), city varchar(30),


state char(2), zip char(10)) not final
create type Person as Object ( pid varchar(10), pname varchar(30),
pAddr Address) not final
create table Agents of Agent (pid primary key)

insert into Agents values ('001', 'John Smith', Address('123 Main', 'Lal street)
OBJECT FEATURES OF SQL
(b) Using UDTs as types for attributes such as Address and Phon
CREATE TYPE STREET_ADDR_TYPE
AS ( NUMBER
V
, STREET_NAME
A
), APT_NO
R
,
C

C
A 5

R )

SUITE_NO VARCHAR(5)
);
CREATE TYPE USA_ADDR_TYPE AS
( STREET_ADDR
STREET_ADDR_TYP
E, CITY VARCHAR(25),
ZIP VARCHAR(10)
);
CREATE TYPE USA_PHONE_TYPE AS
( PHONE_TYPE
VARCHAR(5
),
AREA_CODE CHAR(3),
PHONE_NUM CHAR(7)
);

(c) Specifying UDT for PERSON_TYPE

CREATE TYPE PERSON_TYPE AS (


NAME VARCHAR(35),
SEX CHAR,
BIRTH_DATE DATE,
PHONES USA_PHONE_TYPE
ARRAY[4], ADDR

USA_ADDR_TYPE
INSTANTIABLE NOT FINAL
INSTANCE METHOD AGE() RETURNS INTEGER;
CREATE INSTANCE METHOD AGE() RETURNS
INTEGER
FOR
PERSON_TYPE
BEGIN
RETURN /* CODE TO CALCULATE A PERSON’S AGE FROM TODAY’S
DATE AND BIRTH_DATE */
END;
);

(d) Specifying UDTs for STUDENT_TYPE and EMPLOYEE_TYPE as two subtypes of


PERSON_TYPE.
CREATE TYPE GRADE_TYPE AS
( COURSENO
CHAR(8)
,
SEMESTER VARCHAR(8),
YEAR CHAR(4),
GRADE CHAR
);
CREATE TYPE STUDENT_TYPE UNDER
PERSON_TYPE AS ( MAJOR CODE CHAR
(4), STUDENT_ID CHAR (12),
DEGREE VARCHAR (5),
TRANSCRIPT GRADE_TYPE ARRAY
[100]
INSTANTIABLE
NOT FINAL
INSTANCE METHOD GPA() RETURNS FLOAT;
CREATE INSTANCE METHOD GPA() RETURNS
FLOAT
FOR
STUDENT_TYPE
BEGIN
RETURN /* CODE TO CALCULATE A STUDENT’S GPA */
END;
);

CREATE TYPE EMPLOYEE_TYPE UNDER


PERSON_TYPE AS ( JOB_CODE CHAR(4),
SALARY FLOAT,
SSN CHAR(11)
INSTANTIABL
E NOT FINAL
);

CREATE TYPE MANAGER_TYPE UNDER


EMPLOYEE_TYPE AS ( DEPT_MANAGED
CHAR (20)
INSTANTIABLE
);
(e) Creating tables based on some of the UDTs, and illustrating table inheritance,

CREATE TABLE PERSON OF PERSON_TYPE


CREATE TABLE EMPLOYEE OF
EMPLOYEE_TYPE
UNDER PERSON;
CREATE TABLE MANAGER OF
MANAGER_TYPE UNDER
EMPLOYEE;
CREATE TABLE STUDENT OF
STUDENT_TYPE UNDER PERSON;

RESULT:

Thus various Object Features such as SQL-UDTS And Sub-Types, Tables Using UDTS,
Inheritance, Method Definition have been studied.
EX.NO : QUERYING THE OBJECT-RELATIONAL DATABASE USING
DATE: OBJECT QUERY LANGUAGE

AIM:

To Query the Object-Relational database using Objet Query language

DESCRIPTION:

OBJECT QUERY LANGUAGE

● Object Query Language (OQL) is a version of the Structured Query Language. Like SQL,
OQL is a declarative (not procedural) language
● Object Query Language is a query language standard for object-oriented databases modeled
after SQL and developed by the Object Data Management Group.
● OQL is the way to access data in an O2 database. OQL is a powerful and easy-to-use SQL-
like query language with special features dealing with complex objects, values and methods.
● OQL is an attempt by the OO community to extend languages like C++ with SQL-
like, relation-at-a-time dictions.
CREATING DATABASE AND TABLE

Create databases and tables with the create command

Create command to create a


database create database
database_name ; Create command to
create a table create table
database_name.table_name (
column_name [constraints ] [default ] ,
[ column_name [ constraints ] [default ] , ]
[ additional_columns ]
[ unique ( column_name ) , ]
[ counter ( column_name ) , ]
[ timestamp ( column_name ) ]
);
Example 1
create database staff; // creates the staff
database The following insert defines the managers
table. create table staff.managers
(

EmployeeID int NOT NULL PRIMARY


KEY, Name text NOT NULL,
Department text default "Sales",
Gender text,
Age int,
unique ( EmployeeID )
);
For the managers table:

● The EmployeeID and Name columns cannot be NULL.


● The EmployeeID column is the primary key and must be unique.
● If no value is inserted into the Department column for a given record it takes the value "Sales".

Example 2

The following insert creates the staff.employees table.


create table staff.employees
(
EmployeeID int NOT NULL PRIMARY
KEY, Name text NOT NULL,
Skills text,
Gender text,
Age int
);

For the staff.employees table:

● The EmployeeID and Name columns cannot be NULL.


INSERTING DATA INTO A TABLE

Use the insert keyword to insert data into a table.

Syntax: insert into database_name.table_name


(
Column [ , column ] [ , column ]
[ ... ]
)
values
(
Data [ , data ] [ , data ]
[ ... ]
);

Specifying all the column names:

insert into staff.managers


(
EmployeeID, Name, Department, Gender, Age
)
values
(
1, "Matt", "Development", "M", 28
);
Does not specifying column names:
insert into staff.managers
values
(
2, "Jane", "Customer Services", "F", 27
);

SELECTING DATA FROM A TABLE


▪ Select keyword is used to Query or retrieve the data in a table
Syntax:
select comma_separated_column_list

from database_name.table_name

[ where conditional_test ]

[ order by field_name [asc|desc] ];

The * symbol can be used in a select statement to return all the columns of the table.

Example 1 : select * from staff.managers;


Output:
EmployeeID=1;
Name='Matt';
Department='Development';
Gender='M';
Age=28;
EmployeeID=2;
Name='Jane';
Department='Customer Services';
Gender='F';
Age=27;
( 2 record(s) : Transaction complete )

Example 2: select EmployeeID, Name from staff.managers


where Department = "Development";
Output:

EmployeeID=1;
Name='Matt';
( 1 record(s) : Transaction complete )

UPDATE RECORDS IN TABLE

▪ Use the update keyword to update an existing record in a table.

Syntax
The following syntax shows how to use the update
keyword. update database_name.table_name
set column = value [ , column = value ... ]
[ where conditional_test ] ;
If the update statement is used without a where condition, all records are updated.

Example: Updates Age column of staff.managers table for any records where Name="John"

Update staff.managers
set Age=30
where Name="John";

DATABASE AND TABLE LISTINGS

▪ Use the show keyword to list the databases, columns, or tables or the current service.

Syntax

show databases ;

show tables from database_name ;


show table database_name.table_name ;
Example 1 shows all the databases of the current service.

show databases;
databases = [ 'staff' ]
( 1 Record(s) : Transaction complete )
Example 2 shows all the tables from the staff database.

show tables from staff;

tables = [ 'managers', 'employees', 'contractors' ]


( 1 Record(s) : Transaction complete )

DELETION OF A RECORD FROM A DATABASE TABLE

▪ Delete a record from a table using the delete command.

Syntax: how to use the delete command.


Delete from database_name.table_name [ where conditional_test ] ;
Example - Deletes all records from the staff.contractors table where Name="James".

delete from
staff.contractors where
Name="Jane";
Deletion of a database or table
▪ Delete a database or table using the drop command.

Syntax to use the drop


command drop table
database_name.table_name ; drop
database databse_name ;
Example deletes the entire staff.managers table.

drop table
staff.managers; drop
database staff;

RESULT:

Thus the Querying of Object-Relational database using Objet Query language was
executed.

You might also like