AD3381-DDM-Lab Manual
AD3381-DDM-Lab Manual
LABORATORY MANUAL
REGULATION : R2021
1
Ex.no: 1
Database Development Life cycle
Date:
Aim:
To Analyze, Design and implement the problem and come with the entities in it. Identify what
Data has to be persisted in the databases.
Life cycle of database begins with analysis and defining of the problems and
objectives. Let us see the steps involved −
Stage of Database Example of Facts Example of Documentation
system development Produced
Lifecycle
Database Planning Aims and objectives of Mission statements and objectives.
database projects.
System Identification Description of major user Definition of scope and boundary of
views (Job roles, business database system, definition of user
application areas). views to be supported.
Requirements Collection Requirements of user views, User requirement specification,
and Analysis system specifications, system specification.
including performance and
security
requirements.
Database design User‘s responses to checking Logical database design, data
the logical database dictionary, physical database design.
design, functionality
provided by target DBMS.
Application Design Users‘ response to Application design.
checking interface design.
DBMS Selection Functionality provided by target DBMS evaluation
DBMS.
Prototyping User response to prototype. Modified user requirement
specification and system specification.
Implementation Functionality provided by
target DBMS.
Data conversion and loading Format of current data,
data import capability of
target DBMS.
Testing Test Results. Testing strategies used
2
Operational maintenance Performance testing results, User manual, analysis of performance
new or changing user and results, modified users requirements
system and
requirements. system specification.
Database Creation and Constraints:
Note: Use the \dt or \dt+ command in psql to show tables in a specific
database. PostgreSQL – Show Tables
PostgreSQL does not support the SHOW TABLES statement directly like MySQL does but
provides users with an alternative.
datatype,
column3
datatype,
)
;
The column parameters specify the names of the columns of the table.
The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer,
date, etc.).
Example
CREATE TABLE
new_table_name AS
SELECT column1,
column2,...
FROM existing_table_name
WHERE .... ;
The following SQL creates a new table called "TestTables" (which is a copy of the "Customers"
table):
Example
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):
Example
Notice that the new column, "DateOfBirth", is of type date and is going to hold a date.
The data type specifies what type of data the column can hold.
Now we want to change the data type of the column named "DateOfBirth" in the
"Persons" table. We use the following SQL statement:
ALTER TABLE Persons
ALTER COLUMN DateOfBirth year;
Notice that the "DateOfBirth" column is now of type year and is going to hold a year in a
two- or four- digit format.
5
DROP COLUMN Example
SQL Constraints
Syntax
SQL constraints are used to specify rules for the data in a table.
Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the data
action, the action is aborted.
Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table.
The following constraints are commonly used in SQL:
6
SQL NOT NULL on CREATE TABLE
The following SQL ensures that the "ID", "LastName", and "FirstName" columns will NOT accept
NULL values when the "Persons" table is created:
Example
CREATE TABLE
Persons ( ID int
NOT NULL,
LastName varchar(255)
NOT NULL, FirstName
varchar(255) NOT NULL,
Age int);
To create a NOT NULL constraint on the "Age" column when the "Persons" table is already
created, use the following SQL:
The UNIQUE constraint ensures that all values in a column are different.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a
column or set of columns.
A PRIMARY KEY constraint automatically has a UNIQUE constraint.
However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.
The following SQL creates a UNIQUE constraint on the "ID" column when the "Persons" table is
created: CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255)
NOT NULL, FirstName
varchar(255),
Age int,
UNIQUE (ID));
To create a UNIQUE constraint on the "ID" column when the table is already created, use the
following SQL:
ALTER TABLE
Persons ADD
UNIQUE (ID);
The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created: CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255)
NOT NULL, FirstName
varchar(255),
Age
int, PRIMARY
KEY (ID));
To create a PRIMARY KEY constraint on the "ID" column when the table is already created,
use the following SQL:
ALTER TABLE Persons ADD PRIMARY KEY (ID);
To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the following SQL syntax:
The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY
KEY in another table.
The table with the foreign key is called the child table, and the table with the primary key is
called the referenced or parent table.
Look at the following two tables:
Persons Table
8
Orders Table
Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.
The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table. The "PersonID" column in the "Orders" table is a FOREIGN KEY
in the "Orders" table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign
key column, because it has to be one of the values contained in the parent table.
The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:
Result:
Thus, the program for Analyze, Design and implement the problem and come with the entities in it.
Identify what Data has to be persisted in the databases for Database Development Lifecycle is created,
executed and verified successfully.
9
Ex.no: 2
DATABASE DESIGN USING CONCEPTUAL MODELING (ER-EER)
Date:
AIM:
To create database using conceptual modeling using (ER-EER) model using SQLworkbench.
PROCEDURE:
Enhanced Entity Relationship (EER) Model is a high level data model which provides
extensions to original Entity Relationship (ER) model. EER Models supports more details
design. EER Modeling emerged as a solution for modeling highly complex databases.
EER uses UML notation. UML is the acronym for Unified Modeling Language; it is a
general purpose modeling language used when designing object oriented systems. Entities
are represented as class diagrams. Relationships are represented as associations between
entities. The diagram shown below illustrates an ER diagram using the UML notation.
We can deduce from this that the nature of the relationship between members and
payments entities is one-to-many.Now lets create EER model using MySQL Workbench In
the MySQL workbench , Click - "+"Button
10
Double click on Add Diagram button to open the workspace for ER diagrams.
11
Following window appears
12
Let's look at the two objects that we will work with.
The table object allows us to create entities and define the attributes associated with the
particular entity.
• Membership number
• Full names
• Gender
• Date of birth
• Physical address
• Postal address
13
Next ,
Your diagram workspace should now look like the one shown below.
14
Lets create relationship between Members and Movie Rentals
15
Repeat above steps for other relationships. Your ER diagram should now look like this –
Result:
Thus, the program for creating an database using conceptual modeling using (ER-EER) model with
SQL workbench is created, executed and verified successfully.
16
Ex.no: 3
Implement the database using SQL Data definition with constraints
Date:
Aim:
Procedure:
• Launch pgAdmin 4.
17
• Name your column, select the data type, and give a length if needed. Then click Save
• Now that you have created a table, view it under the Tables object. Right click and refresh if it didn‘t
update.
• A tab called query editor will open up on the right. You can write SQL statements and click the
play button to execute. Your results will show below the editor on the Data Output tab.
19
Table Basics
To create a table, you use the aptly named CREATE TABLE command. In this command you specify
at least a name for the new table, the names of the columns and the data type of each column. For
example:
example:
Default Values
In a table definition, default values are listed after the column data type. For example:
example is generating a "serial number" for each row. In PostgreSQL this is typically done by something
like:
Check Constraints
A check constraint is the most generic constraint type. It allows you to specify that the value in a
certain column must satisfy a Boolean (truth-value) expression. For instance, to require positive product
prices, you could use:
21
The syntax is:
CREATE TABLE products (
product_no
integer, name text,
price numeric CONSTRAINT positive_price CHECK (price > 0)
);
CREATE TABLE products (
product_no integer,
name text,
price numeric CHECK (price > 0),
discounted_price numeric CHECK (discounted_price > 0),
CHECK (price > discounted_price)
);
Not-Null Constraints
A not-null constraint simply specifies that a column must not assume the null value. A syntax example:
22
CREATE TABLE products (
product_no integer NOT NULL,
name text NOT NULL,
price numeric NOT NULL CHECK (price > 0)
);
CREATE TABLE products (
product_no integer NULL,
name text NULL,
price numeric NULL
);
and then insert the NOT key word where desired.
In most database designs the majority of columns should be marked not null.
Unique Constraints
Unique constraints ensure that the data contained in a column, or a group of columns, is unique
among all the rows in the table. The syntax is:
A primary key constraint indicates that a column, or group of columns, can be used as a unique
identifier for rows in the table. This requires that the values be both unique and not null. So, the
following two table definitions accept the same data:
Primary keys can span more than one column; the syntax is similar to unique constraints:
24
CREATE TABLE products ( product_no
integer PRIMARY KEY, name text,
price numeric
);
25
CREATE TABLE ... CONSTRAINT ... EXCLUDE for details.
Adding an exclusion constraint will automatically create an index of the type specified in the
constraint declaration.
System Columns
very table has several system columns that are implicitly defined by the system. Therefore, these
names cannot be used as names of user-defined columns. (Note that these restrictions are separate
from whether the name is a key word or not; quoting a name will not allow you to escape these
restrictions.) You do not really need to be concerned about these columns; just know they exist.
oid
x
m
The identity (transaction ID) of the inserting transaction for this row version.
in
x
The command identifier within the deleting transaction, or zero.
m
ax
c
m
ax
cti
d
Modifying Tables
When you create a table and you realize that you made a mistake, or the requirements of the
application change, you can drop the table and create it again. But this is not a convenient option if
the table is already filled with data, or if the table is referenced by other database objects (for
instance a foreign key constraint). Add columns
Remove columns
Add constraints
Remove constraints
Change default values
Change column data types
Rename columns
Rename tables
26
All these actions are performed using the ALTER TABLE command, whose reference page contains
details beyond those given here.
Adding a Column
ALTER TABLE products ADD COLUMN description text CHECK (description <> '');
Removing a Column
Removing a Constraint
To remove a constraint you need to know its name. If you gave it a name then that's easy.
Otherwise the system assigned a generated name, which you need to find out. The psql command
\d tablename can be helpful here; other interfaces might also provide a way to inspect table
details. Then the command is:
27
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;
Renaming a Column
To rename a column:
Renaming a Table
To rename a table:
Result:
Thus, the program for implementing database using SQL Data definition with constraints
was created, executed and verified successfully.
28
Ex.no: 4
QUERY THE DATABASE USING SQL MANIPULATION
Date:
Aim:
Procedure:
SQL Statements
Most of the actions you need to perform on a database are done with
SQL statements. The following SQL statement selects all the records in
the "Customers" table:
SELECT * FROM Customers;
SELECT DISTINCT
Examples
The following SQL statement selects only the DISTINCT values from the "Country" column in the
"Customers" table:
Example
SELECT DISTINCT Country FROM Customers;
The following SQL statement lists the number of different (distinct) customer countries:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
SQL WHERE Clause
The WHERE clause is used to filter records.
It is used to extract only those records that fulfill a specified condition.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
Operator Description
30
= Equal
<> Not equal. Note: In some versions of SQL this operator may be written as
!=
BETWEEN Between a certain range
The AND operator displays a record if all the conditions separated by AND are TRUE.
The OR operator displays a record if any of the conditions separated by OR is TRUE.
31
SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
The following SQL statement selects all fields from "Customers" where country is "Germany" OR "Spain":
Example
Example
SELECT * FROM Customers
WHERE Country='Germany' OR
Country='Spain'; NOT Example
The following SQL statement selects all fields from "Customers" where country is NOT "Germany":
Example
SELECT * FROM
Customers WHERE NOT
Country='Germany';
Combining AND, OR and
NOT
You can also combine the AND, OR and NOT operators.
The following SQL statement selects all fields from "Customers" where country is "Germany" AND city
must be "Berlin" OR "München" (use parenthesis to form complex expressions):
Example
SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München');
The following SQL statement selects all fields from "Customers" where country is NOT
Example
"Germany" and NOT "USA":
SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
SQL ORDER BY Keyword
The ORDER BY keyword is used to sort the result-set in ascending or descending order.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in
descending order, use the DESC keyword.
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ...
ASC|DESC; ORDER BY Example
The following SQL statement selects all customers from the "Customers" table, sorted by the "Country"
column:
Example
SELECT * FROM
Customers ORDER
BY Country; ORDER
BY DESC Example
The following SQL statement selects all customers from the "Customers" table, sorted
DESCENDING by the "Country" column:
Example
SELECT * FROM
Customers ORDER
BY Country DESC;
32
ORDER BY Several Columns Example
The following SQL statement selects all customers from the "Customers" table, sorted by the
"Country" and the "CustomerName" column. This means that it orders by Country, but if some rows
Example
have the same Country, it orders them by CustomerName:
SELECT * FROM Customers
ORDER BY Country,
CustomerName; ORDER BY Several
Columns Example 2
The following SQL statement selects all customers from the "Customers" table, sorted ascending by the
"Country" and descending by the "CustomerName" column:
Example
SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.
INSERT INTO Syntax
It is possible to write the INSERT INTO statement in two ways:
1. Specify both the column names and the values to be inserted:
INSERT INTO table_name (column1, column2,
column3, ...) VALUES (value1, value2, value3, ...);
2. If you are adding values for all the columns of the table, you do not need to specify the
column names in the SQL query. However, make sure the order of the values is in the same order
as the columns in the table. Here, the INSERT INTO syntax would be as follows:
INSERT INTO table_name
VALUES (value1, value2,
value3, ...); INSERT INTO
Example
The following SQL statement inserts a new record in the "Customers" table:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode,
Country) VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006',
'Norway');
Insert Data Only in Specified Columns
It is also possible to only insert data in specific columns.
The following SQL statement will insert a new record, but only insert data in the "CustomerName",
"City", and "Country" columns (CustomerID will be updated automatically):
Example
INSERT INTO Customers (CustomerName, City,
Country) VALUES ('Cardinal', 'Stavanger',
'Norway');
SQL NULL Values
What is a NULL Value?
A field with a NULL value is a field with no value.
If a field in a table is optional, it is possible to insert a new record or update a record without adding a
value to this field. Then, the field will be saved with a NULL value.
Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is
one that has been left blank during record creation!
UPDATE Customers
SET
ContactName='Juan'
; SQL DELETE
Statement The SQL
DELETE Statement
The DELETE statement is used to delete existing records in a table.
DELETE Syntax
DELETE FROM table_name WHERE condition;
Note: Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement.
The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the
table will be deleted!
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers" table:
Example
DELETE FROM Customers WHERE CustomerName='Alfreds
Futterkiste'; Delete All Records
It is possible to delete all rows in a table without deleting the table. This means that the table
structure, attributes, and indexes will be intact:
DELETE FROM table_name;
The following SQL statement deletes all rows in the "Customers" table, without deleting the table:
Example
DELETE FROM Customers;
SQL MIN() and MAX() Functions
The SQL MIN() and MAX() Functions
The MIN() function returns the smallest value of the
selected column. The MAX() function returns the largest
value of the selected column. MIN() Syntax
SELECT
MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT
MAX(column_name)
FROM table_name
WHERE
condition;
MIN()
Example
The following SQL statement finds the price of the cheapest product:
35
Example
SELECT MIN(Price) AS
SmallestPrice FROM Products;
MAX() Example
The following SQL statement finds the price of the most expensive product:
Example
SELECT MAX(Price) AS
LargestPrice FROM Products;
SQL COUNT(), AVG() and SUM() Functions
The SQL COUNT(), AVG() and SUM() Functions
The COUNT() function returns the number of rows that matches a specified criterion.
COUNT() Syntax
SELECT
COUNT(column_name)
FROM table_name
WHERE condition;
The AVG() function returns the average value of a numeric column.
AVG() Syntax
SELECT
AVG(column_name)
FROM table_name
WHERE condition;
The SUM() function returns the total sum of a numeric column.
SUM() Syntax
SELECT
SUM(column_name)
FROM table_name
WHERE
condition;
COUNT()
Example
The following SQL statement finds the number of products:
Example
SELECT COUNT(ProductID)
FROM Products;
Note: NULL values are not
counted. AVG() Example
The following SQL statement finds the average price of all products:
Example
SELECT AVG(Price)
FROM Products;
Note: NULL values are
ignored. SUM()
Example
The following SQL statement finds the sum of the "Quantity" fields in the "OrderDetails" table:
Example
SELECT
SUM(Quantity)
FROM
OrderDetails;
Note: NULL values are ignored.
SQL IN Operator 36
The SQL IN Operator
The IN operator allows you to specify multiple values in a
WHERE clause. The IN operator is a shorthand for multiple OR
conditions.
IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,
value2, ...); or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
IN Operator Examples
The following SQL statement selects all customers that are located in "Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are NOT located in "Germany", "France" or "UK":
Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');
The following SQL statement selects all customers that are from the same countries as the suppliers:
Example
SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
SQL BETWEEN Operator
The SQL BETWEEN Operator
The BETWEEN operator selects values within a given range. The values can be numbers,
text, or dates. The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Syntax SELECT column_name(s) FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN Example
The following SQL statement selects all products with a price between 10 and 20:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
NOT BETWEEN Example
To display the products outside the range of the previous example, use NOT BETWEEN:
Example
SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
BETWEEN with IN Example
The following SQL statement selects all products with a price between 10 and 20. In addition;
do not show products with a CategoryID of 1,2, or 3:
Example
SELECT * FROM Products
WHERE Price BETWEEN 10
AND 20 AND CategoryID NOT
IN (1,2,3);
BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName between Carnarvon Tigers and
Mozzarella di Giovanni: 37
Example
SELECT * FROM Products
WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni' ORDER BY ProductName;
The following SQL statement selects all products with a ProductName between Carnarvon
Tigers and Chef Anton's Cajun Seasoning:
Example
SELECT * FROM Products
WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's Cajun
Seasoning" ORDER BY ProductName;
NOT BETWEEN Text Values Example
The following SQL statement selects all products with a ProductName not between Carnarvon Tigers
and Mozzarella di Giovanni:
Example
SELECT * FROM Products
WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni' ORDER BY ProductName;
Result:
Thus, the program for implementing database using SQL Data manipulation commands was
created, executed and verified successfully.
38
Ex.no: 5 QUERYING / MANAGING THE DATABASE USING SQL PROGRAMMING
STORED PROCEDURES/FUNCTIONS, CONSTRAINTS AND SECURITY USING
Date: TRIGGERS
Aim:
Procedure:
Execute a Stored
Procedure EXEC
procedure_name;
(Create a Demo
database) Stored
Procedure
Example
The following SQL statement creates a stored procedure named "SelectAllCustomers" that selects all
records from the "Customers" table:
CREATE PROCEDURE
SelectAllCustomers AS
SELECT * FROM
Customers GO;
The following SQL statement creates a stored procedure that selects Customers from a particular
City from the "Customers" table:
Setting up multiple parameters is very easy. Just list each parameter and the data type separated
by a comma as shown below.
The following SQL statement creates a stored procedure that selects Customers from a particular
City with a particular PostalCode from the "Customers" table:
CREATE PROCEDURE SelectAllCustomers @City nvarchar(30), @PostalCode
nvarchar(10) AS
SELECT * FROM Customers WHERE City = @City AND PostalCode =
@PostalCode GO;
Syntax:
create trigger
[trigger_name]
[before | after]
{insert |
update |
delete} on
[table_name]
[for
each
row]
[trigg
er_bo
dy]
Explanation of syntax:
1. create trigger [trigger_name]: Creates or replaces an existing trigger with the trigger_name.
2. [before | after]: This specifies when the trigger will be executed.
3. {insert | update | delete}: This specifies the DML operation.
4. on [table_name]: This specifies the name of the table associated with the trigger.
5. [for each row]: This specifies a row-level trigger, i.e., the trigger will be executed for each row being
affected.
6. [trigger_body]: This provides the operation to be performed as trigger is fired
+ + + + + + +
+ + + + + + +
Above SQL statement will create a trigger in the student database in which whenever subjects
marks are entered, before inserting this data into the database, trigger will compute those two
values and insert with the entered values. i.e.,
+ + + + + + + +
+ + + + + + + +
| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |
Result:
Thus, the program for Querying/Managing the database using SQL Programming - Stored
Procedures/Functions – Constraints and security using Triggers was created, executed and verified
successfully. 41
Ex.no: 6
DATABASE DESIGN USING NORMALIZATION
Date:
AIM:
Apply the database Normalization techniques for designing relational database tables
to minimize duplication of information like 1NF, 2NF, 3NF, BCNF and for creating relationship
between the databases as tables using SQL commands.
PROCEDURE
It divides larger tables to smaller tables and links them using relationships.
The inventor of the relational model Edgar Codd proposed the theory of normalization with
the introduction of First Normal Form, and he continued to extend theory with Second and
Third Normal Form. Later he joined with Raymond F. Boyce to develop the theory of Boyce-
Codd Normal Form.
Theory of Data Normalization in SQL is still being developed further. For example, there are
discussions even on 6thNormal Form. However, in most practical applications,
normalization achieves its best in 3rd Normal Form. The evolution of Normalization
theories is illustrated below-
Assume a video library maintains a database of movies rented out. Without any normalization, all
information is stored in one table as shown below.
42
1NF (First Normal Form) Rules
1NF Example
• Rule 1- Be in 1NF
• Rule 2- Single Column Primary Key
Table 1
Table 2
43
We have divided our 1NF table into two tables viz. Table 1 and Table2. Table 1 contains
member information. Table 2 contains information on movies rented.
We have introduced a new column called Membership_id which is the primary key for table 1.
Records can be uniquely identified in Table 1 using membership id.
• Rule 1- Be in 2NF
• Rule 2- Has no transitive functional dependencies
To move our 2NF table into 3NF, we again need to again divide our table.
3NF Example
TABLE 1
Table 2
44
Table 3
Even when a database is in 3rd Normal Form, still there would be anomalies resulted if it has
more than one Candidate Key.
Sometimes is BCNF is also referred as 3.5 Normal Form. 4NF (Fourth Normal Form) Rules
A table is in 5th Normal Form only if it is in 4NF and it cannot be decomposed into any
number of smaller tables without loss of data.
6th Normal Form is not standardized, yet however, it is being discussed by database experts for
some time. Hopefully, we would have a clear & standardized definition for 6 th Normal Form in
thenear future...
Result:
Thus, the program for database design using Normalization was created, executed and verified
successfully.
45
Ex.no: 7 DEVELOPMENT OF DATABASE APPLICATIONS
USING NETBEANS
Date:
AIM:
To develop a database application using NetBeans.
IMPLEMENTION:
The java DB database will start to process. Once the process is stopped, the java
DB will be created.
46
Step 3: select the created one > right click > connect
Once you are connected, you can see the database list.
Step 4: select test > tables > create table > give table name
47
Step 5: click add column button > give name > select type > give size > then click OK button
48
Step 7: select new project > java > java application > click NEXT
Step 8: give project name > remove tick in create main class > click FINISH
49
Step 9: click the project you created. Under that, click source packages > default
package > new >java package> give package name > click finish.
The package will be created in the source package under your project.
Step 10: click the package created under source package > new > JFrame Form >
A new JFrame form window will be popped. Give class name and click finish.
50
Step 11: This window will be shown. Click panel (if you want you can resize it). Then
clickproperties and start doing designing your application.
Result:
Thus, the program for developing aa database application using NetBeans was created, executed and
verified successfully.
51
Ex. DATABASE DESIGN USING EER-TO-ODB MAPPING / UML CLASS DIAGRAMS
No.:8
AIM:
PROCEDURE:
Step 1: First make sure you have a Database and Tables created on the MySQLserver.
For Example :-
Database - bank.
Tables - account, bQUERYING/MANAGING THE DATABASE USING SQL PROGRAMMING
➢ STORED PROCEDURES/FUNCTIONS
➢ CONSTRAINTS AND SECURITY USING TRIGGERS
ranch, customer, loan, trandetails.
52
Step 3: Select your stored connection (for connecting to your MySQL Server in whichdatabase
is present) from the dropdown. Then click Next.
Step 4: After the execution gets completed successfully (connection to DBMS), click Next.
Step 5: Select your Database from the MySQL Server for which you want to create the ER
Diagram (in our case the database name is “bank”), then click Next.
53
Step 6: After the retrieval gets completed successfully for the selected Database, click Next.
Step 7: Select the Tables of the Database which you want to be visible on the ER Diagram
(In this case I am importing all the tables of the DB), then click Execute>.
54
Step 8: After the Reverse Engineering Process gets completed successfully, click Next.
9: Click Finish.
55
✓ Now you can see the ER Diagram/UML diagram of the
Database.
Result:
Thus, the program for creating ER/ UML diagram of a database using MySQL workbench was created,
executed and verified successfully.
56
Ex.no: 9
USER-DEFINED TYPES IN SQLSERVER
Date:
AIM:
To create datas using User-Defined Types (UDTs) in SQL server.
PROCEDURE:
You can access user-defined type (UDT) functionality in Microsoft SQL Server from the
Transact- SQL language by using regular query syntax. UDTs can be used in the definition of
database objects, as variables in Transact-SQL batches, in functions and stored procedures,
and as arguments in functions and stored procedures.
There is no special syntax for creating a UDT column in a table. You can use the name of
the UDT in a column definition as though it were one of the intrinsic SQL Server data types.
The following CREATE TABLE Transact-SQL statement creates a table named Points,
with a column named ID, which is defined as an int identity column and the primary key for
the table. The second column is named PointValue, with a data type of Point. The schema
name used in this example is dbo. Note that you must have the necessary permissions to
specify a schema name. If you omit the schema name, the default schema for the database
user is used.
The following Transact-SQL statements insert three rows of sample data into the Points
table. The Point data type consists of X and Y integer values that are exposed as properties
of the UDT. You must use either the CAST or CONVERT function to cast the comma-delimited
X and Y values to the Point type. The first two statements use the CONVERT function to
convert a string value to the Point type, and the third statement uses the CAST function:
INSERT INTO dbo.Points (PointValue) VALUES (CONVERT(Point, '3,4'));
INSERT INTO dbo.Points (PointValue) VALUES (CONVERT(Point, '1,5'));
57
INSERT INTO dbo.Points (PointValue) VALUES (CAST ('1,99' AS Point));
➢ Selecting Data
The following SELECT statement selects the binary value of the UDT.
To see the output displayed in a readable format, call the ToString method of the Point
UDT, which converts the value to its string representation.
ID PointValue
-- ------
---- 1
3,4
2 1,5
3 1,99
You can also use the Transact-SQL CAST and CONVERT functions to achieve the same results.
The Point UDT exposes its X and Y coordinates as properties, which you can then select
individually. The following Transact-SQL statement selects the X and Y coordinates separately:
The X and Y properties return an integer value, which is displayed in the result set.
ID xVal yVal
- - -
- - -
- -
- -
1 3 4
2 1 5
3 1 9
9
➢ WORKING WITH VARIABLES
58
You can work with variables using the DECLARE statement to assign a variable to a UDT
type. The following statements assign a value using the Transact-SQL SET statement and
display the results by calling the UDT's ToString method on the variable:
PointValue
----------
-1,5
The following Transact-SQL statements achieve the same result using SELECT rather than
SET for the variable assignment:
The difference between using SELECT and SET for variable assignment is that SELECT allows
you to assign multiple variables in one SELECT statement, whereas the SET syntax requires
each variable assignment to have its own SET statement.
➢ COMPARING DATA
You can use comparison operators to compare values in your UDT if you have
set the IsByteOrdered property to true when defining the class.
You can compare internal values of the UDT regardless of the IsByteOrdered setting if the
values themselves are comparable. The following Transact-SQL statement selects rows where
X is greater than Y:
You can also use comparison operators with variables, as shown in this query that searches
for a matching PointValue.
59
SELECT ID, PointValue.ToString() AS MatchingPoint
FROM dbo.Points
WHERE PointValue = @ComparePoint;
You can also invoke methods that are defined in your UDT in Transact-SQL. The Point class
contains three methods, Distance, DistanceFrom, and DistanceFromXY. For the code
listings defining these three methods, see Coding User-Defined Types.
I X Y Distance
D - - ----------------
- - -
-
1 3 4 5
2 1 5 5.099019513
59278
3 1 9 99.00505037
9 62308
The DistanceFrom method takes an argument of Point data type, and displays the distance
from the specified point to the PointValue:
The results display the results of the DistanceFrom method for each row in the table:
ID Pnt DistanceFromPoint
-- --- -----------------
1 3,4 95.0210502993942
2 1,5 94
3 1,9 90
To update data in a UDT column, use the Transact-SQL UPDATE statement. You can also use
a method of the UDT to update the state of the object. The following Transact-SQL statement
updates a single row in the table:
UPDATE dbo.Points
SET PointValue = CAST('1,88' AS
Point) WHERE ID = 3
You can also update UDT elements separately. The following Transact-SQL statement updates
only the Y coordinate:
UPDATE dbo.Points
SET PointValue.Y =
99 WHERE ID = 3
If the UDT has been defined with byte ordering set to true, Transact-SQL can evaluate the
UDT column in a WHERE clause.
UPDATE
dbo.Points SET
PointValue = '4,5'
WHERE PointValue = '3,4';
➢ UPDATING LIMITATIONS
You cannot update multiple properties at once using Transact-SQL. For example, the
following UPDATE statement fails with an error because you cannot use the same column
name twice in one UPDATE statement.
UPDATE dbo.Points
SET PointValue.X = 5, PointValue.Y
= 99 WHERE ID = 3
To update each point individually, you would need to create a mutator method in the Point
UDT assembly. You can then invoke the mutator method to update the object in a Transact-
SQL UPDATE statement, as in the following:
UPDATE dbo.Points
SET PointValue.SetXY(5,
99) WHERE ID = 3
61
➢ DELETING DATA IN A UDT COLUMN
To delete data in a UDT, use the Transact-SQL DELETE statement. The following statement
deletes all rows in the table that match the criteria specified in the WHERE clause. If you omit
the WHERE clause in a DELETE statement, all rows in the table will be deleted.
Use the UPDATE statement if you want to remove the values in a UDT column while leaving
other row values intact. This example sets the PointValue to null.
UPDATE
dbo.Points SET
PointValue = null
WHERE ID = 2
Result:
Thus, the program for creating datas using User-Defined Types (UDTs) in SQL server was created,
executed and verified successfully.
62
Ex.no: 10 USER-DEFINED TYPES IN SQLSERVER
Date:
AIM:
To Query object-relational database using object query language.
PROCEDURE:
OQL is ap powerful and easy-to-use SQL-like query language with special features dealing with
complex objects, values and methods.
Example:
The above is valid for both SQL and OQL, but the results are different.
63
We will discuss the syntax of simple OQL queries and the concept of using named objects or
extents as database entry points. Then, we will discuss the structure of query results and the
use of path expressions to traverse relationships among objects.
from D in
DEPARTMENTS
where D.College =
„Engineering‟;
In general, an entry point to the database is needed for each query, which can be any
named persistent object. For many queries, the entry point is the name of the extent of a
class. Recall that the extent name is considered to be the name of a persistent object whose
type is a collection (in most cases, a set) of objects from the class. Looking at the extent
names in Figure 11.10, the named object DEPARTMENTS is of type set <DEPARTMENT>;
PERSONS is of type set<PERSON>; FACULTY is of type set<FACULTY>; and so on.
64
in Q0, the query will select certain objects from the collection, based on the conditions
specified in the where clause. In Q0, only persistent objects D in the collection of
DEPARTMENTS that satisfy the condition D.College = ‗Engineering‗ are selected for the query
result. For each selected object D, the value of D.Dname is retrieved in the query result.
Hence, the type ofthe result for Q0 is bag<string> because the type of each Dname value is
string (even though theactual result is a set because Dname is a key attribute). In general, the
result of a query would be of type bag for select ... from ... and of type set for select distinct ...
from ... , as in SQL (adding the keyword distinct eliminates duplicates).
Using the example in Q0, there are three syntactic options for specifying iterator variables:
D in DEPARTMENTS
DEPARTMENTS D DEPARTMENTS AS D
We will use the first construct in our examples.
The named objects used as database entry points for OQL queries are not limited to the names
of extents. Any named persistent object, whether it refers to an atomic (single) object or to a
collection object, can be used as a database entry point.
structure; in the simplest case, any persistent name on its own is a query, whose result is a
reference to that persistent object. For example, the query
Q1:DEPARTMENTS;
returns a reference to the collection of all persistent DEPARTMENT objects, whose type is
set<DEPARTMENT>. Similarly, suppose we had given (via the database bind operation, see
Figure 11.8) a persistent name CS_DEPARTMENT to a single DEPARTMENT object (the
Computer Science department); then, the query
Q1A: CS_DEPARTMENT;
returns a reference to that individual object of type DEPARTMENT. Once an entry point is
specified, the concept of a path expression can be used to specify a path to related attributes
and objects. A path expression typically starts at a persistent object name, or at the iterator
variable that ranges over individual objects in a collection. This name will be followed by zero
or more relationship names or attribute names connected using the dot notation. For example,
referring tothe UNIVERSITY data-base in Figure 11.10, the following are examples of path
expressions, whichare also valid queries in OQL:
Q2:CS_DEPARTMENT.Chair;
Q2A:
CS_DEPARTMENT.Chair.Rank;
Q2B:
CS_DEPARTMENT.Has_faculty;
The first expression Q2 returns an object of type FACULTY, because that is the type of
the attribute Chair of the DEPARTMENT class. This will be a reference to the FACULTY object
that isrelated to the DEPARTMENT object whose 65 persistent name is CS_DEPARTMENT via the
attribute Chair; that is, a reference to the FACULTY object who is chairperson of the Computer
Science department. The second expression Q2A is similar, except that it returns the Rank of
this FACULTY object (the Computer Science chair) rather than the object reference; hence, the
typereturned by Q2A is string, which is the data type for the Rank attribute of the FACULTY
class.
Path expressions Q2 and Q2A return single values, because the ttributes Chair (of
DEPARTMENT) and Rank (of FACULTY) are both single-valued and they are applied to a single
object. The third expression, Q2B, is different; it returns an object of type set<FACULTY> even
when applied to a single object, because that is the type of the relationship Has_faculty of the
DEPARTMENT class. The collection returned will include references to all FACULTY objects
that are related tothe DEPARTMENT object whose persistent name is CS_DEPARTMENT via
the relationship Has_faculty; that is, references to all FACULTY objects who are working in the
Computer Science department. Now, to return the ranks of Computer Science faculty, we
cannot write
Q3 : CS_DEPARTMENT.Has_faculty.Rank;
because it is not clear whether the object returned would be of type set<string> or
bag<string> (the latter being more likely, since multiple faculty may share the same rank).
Because of this type of ambiguity problem, OQL does not allow expressions such as Q3 .
Rather, one must use an iterator variable over any collections, as in Q3A or Q3B below:
In general, an OQL query can return a result with a complex structure specified in the query
itself by utilizing the struct keyword. Consider the following examples:
Q4:CS_DEPARTMENT.Chair.Advises;
66
Q4A: select struct ( name: struct (last_name: S.name.Lname, first_name:
S.name.Fname),degrees:( select struct (deg: D.Degree, yr: D.Year,
college: D.College) from D in S.Degrees )) from
S in CS_DEPARTMENT.Chair.Advises;
The name component is a further struct made up of last_name and first_name, each being a single
string.
The degrees component is defined by an embedded query and is itself a collection of further
(second level) structs, each with three string compo-nents: deg, yr, and college.
Note that OQL is orthogonal with respect to specifying path expressions. That is, attributes,
relationships, and operation names (methods) can be used interchange-ably within the path
expressions, as long as the type system of OQL is not compro-mised. For example, one can
write thefollowing queries to retrieve the grade point average of all senior students majoring in
Computer Science, with the result ordered by GPA, and within that by last and first name:
Q5A used the named entry point CS_DEPARTMENT to directly locate the reference to the Computer
67
Science department and then locate the students via the relation-ship Has_majors, whereas
Q5B searches the STUDENTS extent to locate all students majoring in that department. Notice
how attribute names, relationship names, and operation (method) names are all used
interchangeably (in an orthogonal manner) in the path expressions: gpa is an
operation; Majors_in and Has_majors are relation- ships; and Class, Name, Dname, Lname,
and Fname are attributes. The implementa-tion of the gpa operation computes the grade point
average and returns its value as a float type for each selected STUDENT.
The order by clause is similar to the corresponding SQL construct, and specifies in which order
the query result is to be displayed. Hence, the collection returned by a query with an order
by clause isof type list
Result:
Thus, the program for Querying object-relational database using object query language was created,
executed and verified successfully.
68