0% found this document useful (0 votes)
139 views68 pages

AD3381-DDM-Lab Manual

The document is a laboratory manual for a course on Database Design and Management, detailing the database development lifecycle, SQL commands for database creation, and constraints. It includes practical exercises on creating databases using PostgreSQL and conceptual modeling with Enhanced Entity Relationship (EER) models. The manual emphasizes the importance of analyzing, designing, and implementing databases effectively while adhering to specified constraints.
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)
139 views68 pages

AD3381-DDM-Lab Manual

The document is a laboratory manual for a course on Database Design and Management, detailing the database development lifecycle, SQL commands for database creation, and constraints. It includes practical exercises on creating databases using PostgreSQL and conceptual modeling with Enhanced Entity Relationship (EER) models. The manual emphasizes the importance of analyzing, designing, and implementing databases effectively while adhering to specified constraints.
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/ 68

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND BUSINESS SYSTEMS

LABORATORY MANUAL

COURSE CODE : AD3381

COURSE NAME : DATABASE DESIGN AND MANAGEMENT LABORATORY

REGULATION : R2021

CLASS & SEMESTER : II / III

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.

Getting started with PostgreSQL:

Download the PostgreSQL software from the given link


and install it. https://www.postgresql.org/download/
Database Development Life cycle:

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:

SQL CREATE DATABASE Statement

The CREATE DATABASE statement is used to create a new SQL


database. Syntax
CREATE DATABASE
databasename; Example
CREATE DATABASE testDB;

SQL DROP DATABASE


Statement

The DROP DATABASE statement is used to drop an existing SQL


database. Syntax
DROP DATABASE
databasename; Example
DROP DATABASE testDB;

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.

SELECT * FROM tablename;

SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a


database. Syntax
CREATE TABLE table_name (
column1 datatype,
column2

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 Persons ( PersonID int,


LastName
3
varchar(255),
FirstName
varchar(255),
Address
varchar(255),
City varchar(255));

Create Table Using Another Table

A copy of an existing table can also be created using CREATE TABLE.


The new table gets the same column definitions. All columns or specific columns can be selected.
If you create a new table using an existing table, the new table will be filled with the
existing values from the old table.
Syntax

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

CREATE TABLE TestTable AS


SELECT customername,
contactname FROM
customers;

SQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a


database. Syntax
DROP TABLE
table_name; SQL
TRUNCATE TABLE
The TRUNCATE TABLE statement is used to delete the data inside a table, but not the
table itself. Syntax
TRUNCATE TABLE table_name;

SQL ALTER TABLE Statement

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.

ALTER TABLE - ADD Column


To add a column in a table, use the
following syntax: ALTER TABLE table_name
ADD column_name datatype;
The following SQL adds an "Email" column to the
"Customers" table: ALTER TABLE Customers
4
ADD Email varchar(255);
ALTER TABLE - DROP COLUMN

To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;
The following SQL deletes the "Email" column from the
"Customers" table: ALTER TABLE Customers
DROP COLUMN Email;

ALTER TABLE - ALTER/MODIFY COLUMN


To change the data type of a column in a table, use the
following syntax: ALTER TABLE table_name
ALTER COLUMN column_name datatype;

Example

Look at the "Persons" table:

ID LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to add a column named "DateOfBirth" in the


"Persons" table. We use the following SQL statement:
ALTER TABLE
Persons ADD
DateOfBirth
date;

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.

The "Persons" table will now look like this:

ID LastName FirstName Address City DateOfBirth


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Change Data Type Example

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

Next, we want to delete the column named "DateOfBirth" in the


"Persons" table. We use the following SQL statement:
ALTER TABLE Persons DROP COLUMN DateOfBirth;

The "Persons" table will now look like this:

ID LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

SQL Constraints

SQL constraints are used to specify rules for


data in a table. SQL Create Constraints
Constraints can be specified when the table is created with the CREATE TABLE statement,
or after the table is created with the ALTER TABLE statement.

Syntax

CREATE TABLE table_name


( column1 datatype
constraint, column2
datatype constraint,
column3 datatype
constraint, );

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:

• NOT NULL - Ensures that a column cannot have a NULL value


• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very quickly

SQL NOT NULL Constraint

By default, a column can hold NULL values.


The NOT NULL constraint enforces a column to NOT accept NULL values.
This enforces a field to always contain a value, which means that you cannot insert a new
record, or update a record without adding a value to this field.

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);

SQL NOT NULL on ALTER TABLE

To create a NOT NULL constraint on the "Age" column when the "Persons" table is already
created, use the following SQL:

ALTER TABLE Persons MODIFY Age int NOT NULL;

SQL UNIQUE Constraint

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.

SQL UNIQUE Constraint on CREATE 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));

SQL UNIQUE Constraint on ALTER TABLE

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);

DROP a UNIQUE Constraint

To drop a UNIQUE constraint, use the


following SQL: ALTER TABLE Persons
DROP INDEX UC_Person;
7
SQL PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in


a table. Primary keys must contain UNIQUE values, and cannot
contain NULL values.
A table can have only ONE primary key; and in the table, this primary key can consist of single
or multiple columns (fields).

SQL PRIMARY KEY on CREATE TABLE

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));

SQL PRIMARY KEY on ALTER TABLE

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:

ALTER TABLE Persons


ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName);

DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the


following SQL: ALTER TABLE Persons
DROP PRIMARY KEY;

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

PersonID LastName FirstName Age


1 Hansen Ola 30
2 Svendson Tove 23

8
Orders Table

OrderID OrderNumber PersonID


1 77895 3
2 44678 3
3 22456 2
4 24562 1

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.

SQL FOREIGN KEY on CREATE TABLE

The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders"
table is created:

CREATE TABLE Orders (


OrderID int NOT
NULL, OrderNumber
int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID));

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:

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.

The place relationship button allows us to define relationships between entities.

The members' entity will have the following attributes

• Membership number
• Full names
• Gender
• Date of birth
• Physical address
• Postal address

Let's now create the members table

1. Drag the table object from the tools panel


2. Drop it in the workspace area. An entity named table 1 appears 3.Double click
on it. The properties window shown below appears

13
Next ,

1. Change table 1 to Members


2. Edit the default idtable1 to membership_number
3. Click on the next line to add the next field
4. Do the same for all the attributes identified in members' entity.

Your properties window should now look like this.

Repeat the above steps for all the identified entities.

Your diagram workspace should now look like the one shown below.

14
Lets create relationship between Members and Movie Rentals

1. Select the place relationship using existing columns too


2. Click on membership_number in the Members table
3. Click on reference_number in the MovieRentals table

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:

To implement database using SQL Data definition with constraints

Procedure:

Do with pgAdmin application in your PostgreSQL

• Launch pgAdmin 4.

Let‘s create a table by right clicking on Tables and click Table…

• Give your table a name and then click Columns

• Click the + symbol to add columns

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.

Query Tool Example: 18


Note: I‘m showing you my database with data for demonstration purposes
When an object is selected under the database tree view menu, you can click the
Tools tab and click Query Tool. Query tool brings up an editor to execute SQL
statements.
You can also right click the database and click Query Tool …

• 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:

CREATE TABLE my_first_table (


first_column
text
, second_column integer
);
Of course, the previous example was heavily contrived. Normally, you would give names to
your tables and columns that convey what kind of data they store. So let's look at a more realistic

example:

CREATE TABLE products (


20
product_no
integer, name text,
price numeric
);
If you no longer need a table, you can remove it using the DROP TABLE
command. For example:
DROP TABLE my_first_table;
DROP TABLE products;

Default Values
In a table definition, default values are listed after the column data type. For example:

CREATE TABLE products (


product_no integer,
name text,
price numeric DEFAULT 9.99
);

example is generating a "serial number" for each row. In PostgreSQL this is typically done by something
like:

CREATE TABLE products (


product_no integer DEFAULT nextval('products_product_no_seq'),
...
);

CREATE TABLE products (


product_no SERIAL,
...
);

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:

CREATE TABLE products (


product_no integer,
name text,
price numeric CHECK (price > 0)
);

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)
);

CREATE TABLE products (


product_no integer,
name text,
price numeric CHECK (price >
0), discounted_price numeric,
CHECK (discounted_price > 0 AND price > discounted_price)
);
It's a matter of taste.
Names can be assigned to table constraints in the same way as column constraints:

CREATE TABLE products (


product_no integer,
name
text
, price
numeric,
CHECK (price > 0),
discounted_price numeric,
CHECK (discounted_price >
0),
CONSTRAINT valid_discount 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:

CREATE TABLE products (


product_no integer NOT NULL,
name text NOT NULL,
price numeric
);

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:

CREATE TABLE products (


product_no integer
UNIQUE, name text,
price numeric
);
when written as a column constraint, and:

CREATE TABLE products (


product_no integer,
name
text
, price
numeric,
UNIQUE (product_no)
);
when written as a table constraint.
To define a unique constraint for a group of columns, write it as a table constraint with the
column names separated by commas:

CREATE TABLE example ( a


integer,
b
integer, c
integer,
UNIQUE (a, c)
);
CREATE TABLE products (
product_no integer CONSTRAINT must_be_different
UNIQUE, name text,
price numeric
);
23
Primary Keys

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:

CREATE TABLE products (


product_no integer UNIQUE NOT NULL,
name text,
price numeric
);
CREATE TABLE products ( product_no
integer PRIMARY KEY, name text,
price numeric
);

Primary keys can span more than one column; the syntax is similar to unique constraints:

CREATE TABLE example ( a


integer,
b
integer, c
integer,
PRIMARY KEY (a, c)
);
CREATE TABLE products ( product_no
integer PRIMARY KEY, name text,
price numeric
);

CREATE TABLE orders (


order_id integer PRIMARY KEY,
product_no integer REFERENCES products
(product_no), quantity integer
);
CREATE TABLE orders (
order_id integer PRIMARY KEY,
product_no integer REFERENCES
products, quantity integer
);
CREATE TABLE t1 (
a integer PRIMARY KEY, b
integer,
c integer,
FOREIGN KEY (b, c) REFERENCES other_table (c1, c2)
);

24
CREATE TABLE products ( product_no
integer PRIMARY KEY, name text,
price numeric
);

CREATE TABLE orders (


order_id integer PRIMARY KEY,
shipping_address text,
...
);

CREATE TABLE order_items (


product_no integer REFERENCES products,
order_id integer REFERENCES orders,
quantity integer,
PRIMARY KEY (product_no, order_id)
);

CREATE TABLE products ( product_no


integer PRIMARY KEY, name text,
price numeric
);

CREATE TABLE orders (


order_id integer PRIMARY KEY,
shipping_address text,
...
);

CREATE TABLE order_items (


product_no integer REFERENCES products ON DELETE RESTRICT,
order_id integer REFERENCES orders ON DELETE CASCADE,
quantity integer,
PRIMARY KEY (product_no, order_id)
);

CREATE TABLE circles ( c


circle,
EXCLUDE USING gist (c WITH &&)
);

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

The object identifier (object ID)


of a row. tableoid
The OID of the table containing this row.

x
m
The identity (transaction ID) of the inserting transaction for this row version.
in

The command identifier (starting at zero) within the inserting transaction.


c
m
in
The identity (transaction ID) of the deleting transaction, or zero for an undeleted row version.

x
The command identifier within the deleting transaction, or zero.
m
ax

The physical location of the row version within its table.

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

To add a column, use a command like:

ALTER TABLE products ADD COLUMN description text;


The new column is initially filled with whatever default value is given (null if you
don't specify a DEFAULT clause).
You can also define constraints on the column at the same time, using the usual syntax:

ALTER TABLE products ADD COLUMN description text CHECK (description <> '');

Removing a Column

To remove a column, use a command like:

ALTER TABLE products DROP COLUMN description;


Whatever data was in the column disappears. Table constraints involving the column are dropped,
too. However, if the column is referenced by a foreign key constraint of another table, PostgreSQL
will not silently drop that constraint. You can authorize dropping everything that depends on the
column by adding CASCADE:

ALTER TABLE products DROP COLUMN description CASCADE;


Adding a Constraint

To add a constraint, the table constraint syntax is used. For example:

ALTER TABLE products ADD CHECK (name <> '');


ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no);
ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;
To add a not-null constraint, which cannot be written as a table constraint, use this syntax:

ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;


The constraint will be checked immediately, so the table data must satisfy the constraint before it can be
added.

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:

ALTER TABLE products DROP CONSTRAINT some_name;


ALTER TABLE products ALTER COLUMN product_no DROP NOT NULL;

Changing a Column's Default Value

To set a new default for a column, use a command like:

ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77;

27
ALTER TABLE products ALTER COLUMN price DROP DEFAULT;

Changing a Column's Data Type

To convert a column to a different data type, use a command like:

ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);

Renaming a Column

To rename a column:

ALTER TABLE products RENAME COLUMN product_no TO product_number;

Renaming a Table

To rename a table:

ALTER TABLE products RENAME TO items;

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:

To query the database using SQL Data Manipulation commands

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;

Semicolon after SQL Statements?


Some database systems require a semicolon at the end of each SQL statement.
Semicolon is the standard way to separate each SQL statement in database systems that allow more
than one SQL statement to be executed in the same call to the server.
In this tutorial, we will use semicolon at the end of each SQL
statement. Some of The Most Important SQL Commands

SELECT - extracts data from a database


UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

SQL SELECT Statement


The SQL SELECT Statement
The SELECT statement is used to select data from a
database. The data returned is stored in a result
table, called the result-set. SELECT Syntax
SELECT column1, column2, ... FROM
table_name; the following syntax:
SELECT * FROM table_name;

SELECT Column Example


The following SQL statement selects the "CustomerName" and "City" columns from the "Customers"
table: SELECT CustomerName, City FROM Customers;
SELECT * Example
The following SQL statement selects all the columns from the
"Customers" table: SELECT * FROM Customers;
SQL SELECT DISTINCT Statement
The SQL SELECT DISTINCT Statement
29
The SELECT DISTINCT statement is used to return only distinct (different) values.
Inside a table, a column often contains many duplicate values; and sometimes you only want to list
the different (distinct) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...FROM table_name;

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.!

WHERE Clause Example


The following SQL statement selects all the customers from the country "Mexico", in the "Customers"
table:
Example
SELECT * FROM
Customers WHERE
Country='Mexico';
Text Fields vs.
Numeric Fields
SQL requires single quotes around text values (most database systems will also allow
double quotes). However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM
Customers WHERE
Custo
merID=1; Operators in
The WHERE Clause
The following operators can be used in the WHERE clause:

Operator Description

30
= Equal

> Greater than

< Less than

>= Greater than or equal

<= Less than or equal

<> Not equal. Note: In some versions of SQL this operator may be written as
!=
BETWEEN Between a certain range

LIKE Search for a pattern

IN To specify multiple possible values for a column

SQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.
The AND and OR operators are used to filter records based on more than one condition:

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.

The NOT operator displays a record if the condition(s) is NOT TRUE.


AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
NOT Syntax
SELECT column1,
column2, ... FROM
table_na
me WHERE NOT
condition; AND
Example
The following SQL statement selects all fields from "Customers" where country is "Germany" AND
city is "Berlin":
Example
SELECT * FROM Customers
WHERE Country='Germany' AND
City='Berlin'; OR Example
The following SQL statement selects all fields from "Customers" where city is "Berlin" OR "München":

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!

How to Test for NULL Values? 33


It is not possible to test for NULL values with comparison operators, such as
=, <, or <>. We will have to use the IS NULL and IS NOT NULL operators
instead.
IS NULL
Syntax SELECT
column_names
FROM
table_name
WHERE column_name IS
NULL; IS NOT NULL
Syntax SELECT
column_names
FROM table_name
WHERE column_name IS NOT
NULL; The IS NULL Operator
The IS NULL operator is used to test for empty values (NULL values).
The following SQL lists all customers with a NULL value in the "Address" field:
Example
SELECT CustomerName, ContactName,
Address FROM Customers
WHERE Address IS NULL;
Tip: Always use IS NULL to look for NULL
values. The IS NOT NULL Operator
The IS NOT NULL operator is used to test for non-empty values (NOT NULL
values). The following SQL lists all customers with a value in the "Address"
field:
Example
SELECT CustomerName, ContactName,
Address FROM Customers
WHERE Address IS NOT NULL;
SQL UPDATE Statement
The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.
UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 =
value2, ... WHERE condition;
Note: Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement.
The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records
in the table will be updated!
UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact person
and a new city.
Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City=
'Frankfurt' WHERE CustomerID = 1;
UPDATE Multiple Records
It is the WHERE clause that determines how many records will be updated.
The following SQL statement will update the ContactName to "Juan" for all records where country is
"Mexico":
Example 34
UPDATE
Cust
omers SET
ContactName='Jua
n' WHERE
Country='Mexico';
Update Warning!
Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!
Example

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:

To Querying/Managing the database using SQL Programming - Stored Procedures/Functions –


Constraints and security using Triggers

Procedure:

SQL Stored Procedures for


SQL Server What is a Stored
Procedure?
A stored procedure is a prepared SQL code that you can save, so the code can be reused over and over
again.
So if you have an SQL query that you write over and over again, save it as a stored procedure, and
then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored procedure can act based
on the parameter value(s) that is passed.
Stored Procedure Syntax

CREATE PROCEDURE procedure_name


AS
sql_statement
GO;

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;

Execute the stored procedure above


as follows: EXEC SelectAllCustomers;

Stored Procedure With One Parameter

The following SQL statement creates a stored procedure that selects Customers from a particular
City from the "Customers" table:

CREATE PROCEDURE SelectAllCustomers @City


nvarchar(30) AS
SELECT * FROM Customers WHERE City = 39
@City GO;
Execute the stored procedure above as follows:
EXEC SelectAllCustomers @City = 'London';
Stored Procedure With Multiple Parameters

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;

Execute the stored procedure above as follows:

EXEC SelectAllCustomers @City = 'London', @PostalCode = 'WA1 1DP';

Trigger: 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]
{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

BEFORE and AFTER of Trigger:


BEFORE triggers run the trigger action before the triggering
statement is run. AFTER triggers run the trigger action after the
triggering statement is run.
Example:
Given Student Report Database, in which student marks assessment is recorded. In such schema,
create a trigger so that the total and average of specified
40 marks is automatically inserted whenever
a record is insert.
Here, as trigger will invoke before record is inserted so, BEFORE Tag can be used.
Suppose the database Schema –
mysql> desc Student;

+ + + + + + +

| Field | Type | Null | Key | Default | Extra |

+ + + + + + +

| tid | int(4) | NO | PRI | NULL | auto_increment |

| name | varchar(30) | YES | | NULL | |

| subj1 | int(2) | YES | | NULL | |

| subj2 | int(2) | YES | | NULL | |

| subj3 | int(2) | YES | | NULL | |

| total | int(3) | YES | | NULL | |

| per | int(3) | YES | | NULL | |

+ + + + + + + 7 rows in set (0.00 sec)


SQL Trigger to problem
statement. create trigger
stud_marks
before
INSER
T on
Student

for each row

set Student.total = Student.subj1 + Student.subj2 + Student.subj3, Student.per = Student.total * 60 /


100;

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.,

mysql> insert into Student values(0, "ABCDE", 20,


20, 20, 0, 0); Query OK, 1 row affected (0.09 sec)
mysql> select * from Student;

+ + + + + + + +

| tid | name | subj1 | subj2 | subj3 | total | per |

+ + + + + + + +

| 100 | ABCDE | 20 | 20 | 20 | 60 | 36 |

+ + + + + + + + 1 row in set (0.00 sec)

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

Normalization is a database design technique which organizes tables in a manner that


reduces redundancy and dependency of data.

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-

Database Normalization Examples -

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

• Each table cell should contain a single value.


• Each record needs to be unique.

The above table in 1NF-

1NF Example

Table 1: In 1NF Form

2NF (Second Normal Form) Rules

• 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.

Database - Foreign Key

In Table 2, Membership_ID is the Foreign Key

3NF (Third Normal Form) Rules

• 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

Boyce-Codd Normal Form (BCNF)

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

5NF (Fifth 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.

6NF (Sixth Normal Form) Proposed

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:

Creating Application using Netbeans


Step 1: click services > database > java DB > right click > create database. Then
create java DBdatabase box is popped.
Step 2: give database name > give user name as PECAI&DS > set password as
PECAI&DS > clickOK button.

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

If you want more columns, you can repeat this step 5


and add columns.Then the table will be created.
Step 6: at the top corner, select project. In the empty space under project, right click.

48
Step 7: select new project > java > java application > click NEXT

Step 8: give project name > remove tick in create main class > click FINISH

So, the project will be created under the project menu.

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:

To create ER/ UML diagram of a database using MySQL workbench.

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.

Step 2: Click on Database -> Reverse Engineer.

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.

• Defining UDT Tables and Columns


Describes how to use Transact-SQL to create a UDT column in a table.

• Manipulating UDT Data


Describes how to use Transact-SQL to work with UDT data in SQL Server.

• Defining UDT Tables and Columns

➢ CREATING TABLES WITH UDTS

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.

CREATE TABLE dbo.Points


(ID int IDENTITY(1,1) PRIMARY KEY, PointValue Point)

• Manipulating UDT Data

➢ Inserting Data in a UDT Column

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.

SELECT ID, PointValue FROM dbo.Points

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.

SELECT ID, PointValue.ToString() AS PointValue


FROM dbo.Points;

This produces the following results.

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.

SELECT ID, CAST(PointValue AS


varchar) FROM dbo.Points;

SELECT ID, CONVERT(varchar,


PointValue) FROM dbo.Points;

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:

SELECT ID, PointValue.X AS xVal, PointValue.Y AS


yVal FROM dbo.Points;

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:

DECLARE @PointValue Point;


SET @PointValue = (SELECT PointValue FROM
dbo.Points WHERE ID = 2);
SELECT @PointValue.ToString() AS PointValue;

The result set displays the variable value:

PointValue
----------
-1,5

The following Transact-SQL statements achieve the same result using SELECT rather than
SET for the variable assignment:

DECLARE @PointValue Point;


SELECT @PointValue = PointValue FROM
dbo.Points WHERE ID = 2;
SELECT @PointValue.ToString() AS PointValue;

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.

SELECT ID, PointValue.ToString() AS


Points FROM dbo.Points
WHERE PointValue > CONVERT(Point, '2,2');

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:

SELECT ID, PointValue.ToString() AS


PointValue FROM dbo.Points
WHERE PointValue.X < PointValue.Y;

You can also use comparison operators with variables, as shown in this query that searches
for a matching PointValue.

DECLARE @ComparePoint Point;


SET @ComparePoint = CONVERT(Point, '3,4');

59
SELECT ID, PointValue.ToString() AS MatchingPoint

FROM dbo.Points
WHERE PointValue = @ComparePoint;

➢ INVOKING UDT METHODS

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.

The following Transact-SQL statement calls the PointValue.Distance method:

SELECT ID, PointValue.X AS [Point.X],


PointValue.Y AS
[Point.Y],
PointValue.Distance() AS
DistanceFromZero
FROM dbo.Points;

The results are displayed in the Distance column:

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:

SELECT ID, PointValue.ToString() AS Pnt, PointValue.DistanceFro


FROM dbo.Points;

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

The DistanceFromXY method takes the points individually as arguments:

SELECT ID, PointValue.X as X, PointValue.Y as Y,


PointValue.DistanceFromXY(1, 99) AS
60
DistanceFromXY FROM dbo.Points
The result set is the same as the DistanceFrom method.

➢ UPDATING DATA IN A UDT COLUMN

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.

DELETE FROM dbo.Points


WHERE PointValue = CAST('1,99' AS Point)

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 following is the sample query:


―what are the names of the black
product?‖ Firstly, create table and insert columns.
Then,
Select distinct p.name
From products p
Where
p.color=‖black‖

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.

1. Simple OQL Queries, Database Entry Points, and Iterator Variables


The basic OQL syntax is a select ... from ... where ... structure, as it is for SQL. For example,
the query to retrieve the names of all departments in the college of ‗Engineering‗ can be
written as follows:

Q0: select D.Dname

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.

The use of an extent name—DEPARTMENTS in Q0—as an entry point refers to a persistent


collection of objects. Whenever a collection is referenced in an OQL query, we should
define an iterator variable—D in Q0—that ranges over each object in the collection. In
many cases, as

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.

2. Query Results and Path Expressions


In general, the result of a query can be of any type that can be expressed in the ODMG object
model. A query does not have to follow the select ... from ... where ...

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:

Q3A: select F.Rank


from F in CS_DEPARTMENT.Has_faculty;
Q3B: select distinct F.Rank
from F in CS_DEPARTMENT.Has_faculty;
Here, Q3A returns bag<string> (duplicate rank values appear in the
result), whereas Q3B returns set<string> (duplicates are eliminated via the
distinct keyword). Both Q3A and Q3B illustrate how an iterator variable can be defined in the
from clause to range over a restricted collection specified in the query. The variable F in Q3A
and Q3B ranges over the elements of the collection CS_DEPARTMENT.Has_faculty, which is of
type set<FACULTY>, and includes only those faculty who are members of the Computer
Science department.

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;

Here, Q4 is straightforward, returning an object of type set<GRAD_STUDENT> as its result;


this is the collection of graduate students who are advised by the chair of the Computer
Science department. Now, suppose that a query is needed to retrieve the last and first names
of these graduate students, plus the list of previous degrees of each. This can be written as in
Q4A, where thevariable S ranges over the collec-tion of graduate students advised by the
chairperson, and the variable D ranges over the degrees of each such student S. The type
of the result of Q4A is acollection of (first-level) structs where each struct has two
components: name and degrees.

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: select struct ( last_name: S.name.Lname, first_name: S.name.Fname,gpa: S.gpa


)
from S in
CS_DEPARTMENT.Has_majorswhere S.Class
= “senior”
order by gpa desc, last_name asc, first_name asc;

Q5B: select struct ( last_name: S.name.Lname, first_name:


S.name.Fname, gpa: S.gpa )
from S in STUDENTS
where S.Majors_in.Dname = “Computer Science” and S.Class
= “senior”
order by gpa desc, last_name asc, first_name asc;

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

You might also like