0% found this document useful (0 votes)
12 views53 pages

Database Development Lifecycle Overview

The document outlines the phases of the Database Development Life Cycle (DBLC), which includes initial study, design, implementation, testing, operation, and maintenance. It also discusses the process of database design using Entity-Relationship (ER) modeling, specifically for a video rental business, MyFlix, and the implementation of databases using DDL and DML commands in PostgreSQL. Additionally, it covers the application of constraints in databases to ensure data integrity and consistency.

Uploaded by

bharathslijo
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)
12 views53 pages

Database Development Lifecycle Overview

The document outlines the phases of the Database Development Life Cycle (DBLC), which includes initial study, design, implementation, testing, operation, and maintenance. It also discusses the process of database design using Entity-Relationship (ER) modeling, specifically for a video rental business, MyFlix, and the implementation of databases using DDL and DML commands in PostgreSQL. Additionally, it covers the application of constraints in databases to ensure data integrity and consistency.

Uploaded by

bharathslijo
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

[Link].

:1
DATABASE DEVELOPMENT LIFE CYCLE-CASE STUDY
Date:

AIM
To learn about the phases involved in Database Development Lifecycle

THE DATABASE LIFE CYCLE (DBLC)

The Database Life Cycle (DBLC) contains six phases, as shown in the following
Figure: database initial study, database design, implementation and loading, testing
and evaluation, operation, and maintenance and evolution.

1. The Database Initial Study:


In the Database initial study, the designer must examine the current system’s
operation within the company and determine how and why the current system
fails. The overall purpose of the database initial study is to:
 Analyze the company situation.
 Define problems and constraints.
 Define objectives.
 Define scope and boundaries.
2. Database Design:
The second phase focuses on the design of the database model that will support
company operations and objectives. This is arguably the most critical DBLC
phase: making sure that the final product meets user and system requirements.
 The process of database design is loosely related to the analysis and design of
a larger system. The data component is only one element of a larger
information system.

1
 The systems analysts or systems programmers are in charge of designing the
other system components. Their activities create the procedures that will help
transform the data within the database into useful information.
3. Implementation and Loading:
The output of the database design phase is a series of instructions detailing the
creation of tables, attributes, domains, views, indexes, security constraints, and
storage and performance guidelines.
4. Testing and Evaluation:
In the design phase, decisions were made to ensure integrity, security, performance,
and recoverability of the database. In testing and evaluation, the DBA tests and fine-
tunes the database to ensure that it performs as expected. This phase occurs in
conjunction with applications programming.
5. Operation
Once the database has passed the evaluation stage, it is considered to be operational.
At that point, the database, its management, its users, and its application programs
constitute a complete information system. The beginning of the operational phase
invariably starts the process of system evolution.
6. Maintenance and Evolution
The database administrator must be prepared to perform routine maintenance
activities within the database. Some of the required periodic maintenance activities
include:
 Preventive maintenance (backup).
 Corrective maintenance (recovery).
 Adaptive maintenance (enhancing performance, adding entities and
attributes, and so on).
 Assignment of access permissions and their maintenance for new and
old users.

RESULT
Thus various phases of Database Development cycle have been studied.

2
[Link].:2
DATABASE DESIGN USING ER MODELING-CASE STUDY
Date:

AIM

To create database using conceptual modeling (ER-EER) in SQL workbench.

ER-EER MODELING
 Entity Relationship Modeling (ER Modeling) is a graphical approach to database
design. It uses Entity/Relationship to represent real world objects.

 An Entity is a thing or object in real world that is distinguishable from surrounding


environment. For example each employee of an organization is a separate entity.

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

It is deduced that the nature of the relationship between members and payments entities
is one-to-many. Now EER model is created using MySQL Workbench In the MySQL
workbench , Click - "+"Button

In this case study MyFlix Video Library is used to understand the concept of ER
diagrams. MyFlix is a business entity that rents out movies to its members. MyFlix has
been storing its records manually. The management now wants to move to a DBMS.

3
The steps to develop EER diagram for this database are

1. Identify the entities and determine the relationships that exist among them.
2. Each entity, attribute and relationship, should have appropriate names that
can be easilyunderstood by the non-technical people as well.
3. Relationships should not be connected directly to each other. Relationships
should connect entities.
4. Each attribute in a given entity should have a unique name.

 Entities in the "MyFlix" library


The entities to be included in our ER diagram are;

Members - this entity will hold member information.


Movies - this entity will hold information regarding movies
Categories - this entity will hold information that places movies into
different categories suchas "Drama", "Action", and "Epic" etc.
Movie Rentals - this entity will hold information that about movies
rented out to members.
Payments - this entity will hold information about the payments made by
members.

 Defining the relationships among entitiesMembers and movies


The following holds true regarding the interactions between the two entities.

A member can rent a more than movie in a given period.


A movie can be rented by more than one member in a given period.

From the above scenario, it is understood that the nature of the relationship is many-to-
many. Relational databases do not support many-to-many relationships. Hence a
junction entity is introduced. This is the role that the MovieRentals entity plays. It has
a one-to-many relationship with the members table and another one-to-many
relationship with movies table.
In the MySQL workbench, Double click on Add Diagram button to open the
workspace for ER diagrams.

4
Following window appears

The two objects to work with are.

The table object allows us to create entities and define the attributes
associated with the particular entity.
The 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

5
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 [Link] click on it.
The properties window shown below appears

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.

The properties window is given below.

6
Repeat the above steps for all the identified entities.

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

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

7
Repeat above steps for other relationships. The ER diagram should now look like this -

Summary

 ER Diagrams play a very important role in the database designing


process. They serve as anon-technical communication tool for
technical and non-technical people.
 Entities represent real world things; they can be conceptual as a sales
order or physical such as a customer.
 All entities must be given unique names.
 ER models also allow the database designers to identify and define
the relations that exist among entities.

RESULT
Thus the database design using conceptual modeling (ER-EER) and map
it to relational database is performed successfully.

8
[Link].:3 A)
IMPLEMENT THE DATABASE USING DDL AND DML
COMMANDS IN POSTGRE SQL
Date:

AIM
To implement a database using DDL and DML commands.

POSTGRESQL
 PostrgeSQL is an advanced relational database system.
 It supports both relational (SQL) and non-relational (JSON) queries.
 PostgreSQL is free and open-source.

DDL COMMANDS
DDL is an abbreviation for Data Definition Language. It is concerned with
database schemas and descriptions of how data should be stored in the database. DDL
statements are auto-committed, meaning the changes are immediately made to the
database and cannot be rolled back.
The DDL commands in SQL are divided into following major categories:
 CREATE
 ALTER
 TRUNCATE
 DROP

 CREATE
The CREATE query is used to create a database or objects such as tables, views,
stored procedures, etc.
 CREATE DATABASE
The CREATE DATABASE statement is used to create a new SQL database.
Syntax
CREATE DATABASE databasename;
Example
CREATE DATABASE testDB;
 CREATE TABLE
The CREATE TABLE statement is used to create a table in database.
Syntax
CREATE TABLE tablename(attributename1 datatype1,attributename2
datatype2);
Example
create table student(rollno int,name char(10),dept char(10),marks int);
 ALTER
The ALTER command in SQL DDL is used to modify the structure of an already
existing table.
 ADDING A NEW COLUMN
The ALTER command is used to add a new column in an existing database.
Syntax
ALTER TABLE tablename ADD attibutename datatypename;
Example
alter table student add age int;

9
 MODIFYING AN EXISTING COLUMN
The ALTER command is used to modify the datatype and its allocated size of an
existing column.
Syntax
ALTER TABLE tablename ALTER COLUMN columnane datatype;
Example
alter table student alter column name type char(20);
 RENAME
RENAME is a DDL command which is used to change the name of the database
table.
Syntax
ALTER TABLE OldTableName RENAME TO NewTableName;
Example
alter table student rename to stud;

 TRUNCATE
The TRUNCATE command is used to remove all the records from a table.
Syntax
TRUNCATE TABLE tablename;
Example
truncate table student;
 DROP
The DROP command is used to delete an existing database or an object within a
database.
 DROP DATABASE
The DROP DATABASE statement is used to drop an existing SQL database.
Syntax
DROP DATABASE databasename;
Example
DROP DATABASE testDB;

 DROP TABLE
The DROP TABLE statement is used to delete a table from a database.
Syntax
DROP TABLE tablename;
Example
drop table student;

DML COMMANDS
The DML commands in Structured Query Language change the data present in the SQL
database. DML commands are used to access, store, modify, update and delete the
existing records from the database.
The DML commands in SQL are divided into following major categories:
 SELECT
 INSERT
 UPDATE
 DELETE

 SELECT
SELECT is the most important data manipulation command in Structured
Query Language. The SELECT command shows the records of the specified table.

10
It also shows the particular record of a particular column by using the WHERE
clause.
Syntax
SELECT * FROM tablename;
Example
SELECT * FROM Student;
SELECT EmpId, EmpSalary FROM Employee;

 INSERT
The INSERT command is used to insert data in database tables.
Syntax
INSERT into TABLENAME values (attributename1,attributename2….);
Example
INSERT into STUDENT values (102,'lenin','ai',95); (or)
INSERT into STUDENT (rollno,name,dept,marks)values(107,'vinai','ece',99);

 UPDATE
The UPDATE command is used to update or modify the existing data in database
tables.
Syntax
UPDATE tablename SET columnname1= value1 WHERE condition;
Example
UPDATE Product SET ProductPrice = 80 WHERE ProductId = 'P102' ;

 DELETE
DELETE is a DML command which allows SQL users to remove single or
multiple existing records from the database tables.
Syntax
DELETE FROM tableName WHERE condition;
Example
DELETE FROM Product WHERE ProductId = 'P202' ;

QUERIES & OUTPUT

create table student(rollno int,name char(10),dept char(10),marks int);

insert into student values(101,'anu','cse',89);


insert into student values(102,'priya','ece',90);
insert into student values(103,'devi','cse',96);
insert into student (rollno,name,dept,marks)values(107,'vinai','ece',99);

select * from student;

11
alter table student alter column name type char(25);

select * from student;

alter table student add age int;

update student set age=19 where dept='cse';


update student set age=20 where dept='ece';
select * from student;

delete from student where marks=90;

alter table student rename marks to totalmarks;

alter table student rename to stud;

12
select * from student;

ERROR: relation "student" does not exist LINE 1: select * from student; ^ SQL state:
42P01 Character: 15
select * from stud;

truncate table stud;

select * from stud;

drop table stud;


ERROR: relation "stud" does not exist LINE 1: select * from stud; ^ SQL state: 42P01
Character: 15

RESULT
Thus the DDL and DML commands were implemented and the data was
retrieved from the database successfully.

13
[Link].:3 B)
IMPLEMENT THE DATABASE WITH CONSTRAINTS
Date:

AIM
To implement the database with constraints using PosgreSQL.

CONSTRAINTS
Constraints in DBMS (Database Management Systems) are rules or conditions that are
applied to the data within a database to ensure data integrity, consistency, and adherence to
business rules.
There are several types of constraints available in DBMS and they are:
 Domain constraints
 Entity Integrity constraints
 Referential Integrity constraints
 Key constraints

DOMAIN CONSTRAINTS
The domain refers to the allowed values (range of values) for a function. The domain
value of an attribute must be an atomic value .
Types of Domain Constraints
 Not Null
The column value cannot be empty (i.e. cannot contain a null value)
 Check
The CHECK constraint checks the condition that follows it, e.g. CHECK
(Age>21) ensures that each Age column value is greater than 21.

ENTITY INTEGRITY CONSTRAINTS


Entity Integrity Constraint is used to ensure that the primary key cannot be null and it
must contain unique values.
Types of Entity Integrity Constraints
 Primary Key Constraint
When this constraint is associated with the column of a table it will not allow NULL
values into the column and it will maintain unique values as part of the table.
 Unique Constraint
The column cannot contain duplicate values (i.e. all values in the column must be
different).
REFERENTIAL INTEGRITY CONSTRAINTS
Referential Integrity Constraint is defined as it ensures that there always exists a valid
relationship between two tables.

KEY CONSTRAINTS
Keys are the set of entities that are used to identify an entity within its entity set
uniquely. A primary key can only contain unique and not null values in the relational
database table.

14
QUERIES & OUTPUT

// NOT NULL & PRIMARY KEY CONSTRAINT


create table employee(empid int primary key,age int not null,ename char(10),salary int,city
char(10));
insert into employee values(101,25,'anki',21000,'chennai');
insert into employee values(102,24,'malar',15000,'salem');
insert into employee values(103,26,'sara',70000,'ooty');
insert into employee values(104,24,'danush',50000,'salem');
select * from employee;

insert into employee values(102,25,'danya',30000,'thrichy');


ERROR: duplicate key value violates unique constraint "employee_pkey" DETAIL: Key
(empid)=(102) already exists. SQL state: 23505

// UNIQUE CONSTRINT
alter table employee add unique(ename);
insert into employee values(107,24,'sara',85000,'Bangalore');
ERROR: duplicate key value violates unique constraint "employee_ename_key" DETAIL: Key
(ename)=(sara ) already exists. SQL state: 23505

//CHECK CONSTRAINT
alter table employee add check (age>25);

ERROR: check constraint "employee_age_check" of relation "employee" is violated by some


row SQL state: 23514

//REFERNTIAL INTEGRITY
insert into person values(22445566,102);
insert into person values(12332145,103);
insert into person values(42536415,104);
select * from person;

insert into person values(24551242,107);


ERROR: insert or update on table "person" violates foreign key constraint
"person_empid_fkey" DETAIL: Key (empid)=(107) is not present in table "employee". SQL
state: 23503

15
delete from person where aadhar=12332145;

select * from person; select * from employee;

delete from employee where empid=102;


ERROR: update or delete on table "employee" violates foreign key constraint
"person_empid_fkey" on table "person" DETAIL: Key (empid)=(102) is still referenced from
table "person". SQL state: 23503

create table persn(aadhar int primary key,empid int, foreign key(empid) references
employee(empid)on delete cascade on update cascade);
insert into persn values(22445566,102);
insert into persn values(12332145,103);
insert into persn values(42536415,104);

select * from persn;

delete from employee where empid=102;


select * from employee; select * from persn;

update employee set empid=204 where empid=104;


select * from employee; select * from persn;

RESULT
Thus the types of constraints were studied and the commands were implemented in
database successfully.

16
[Link].:3 C)
IMPLEMENT THE DATABASE WITH VIEWS
Date:

AIM
To implement the concept of views in PostgreSQL.

VIEWS

Views allow the user to create a virtual table based on an SQL query referring to other tables
in the database. A view stores an SQL query that is executed whenever user refer to the view.
The view has primarily two purposes:
 Simplify the complex SQL queries.
 Provide restriction to users from accessing sensitive data.

CREATING VIEWS

Views can be created using CREATE VIEW statement. A View can be created from a single
table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE condition;

CREATING VIEWS FROM MULTIPLE TABLES


A View can be created from a single table or multiple tables.
Syntax:
CREATE VIEW view_name AS
SELECT column1, column2.....
FROM table_name1, table_name2
WHERE condition;

INSERTING A ROW IN A VIEW


A row can be inserted into a view like inserting into a table.
Syntax:
INSERT into VIEW_NAME values(attributename1,attribute2…);

DELETING A ROW FROM A VIEW


The rows in a View can be deleted using delete statement.
Syntax:
DELETE FROM view_name WHERE condition;

DROPPING VIEWS
If the view is no longer needed it can be dropped using the DROP statement.
Syntax:
DROP VIEW view_name;

UPDATING VIEWS
The CREATE OR REPLACE VIEW statement is used to add or remove fields from a
view. There could be a situation to create a view or replace it if it already exists.

17
Syntax:
CREATE OR REPLACE VIEW view_name AS
SELECT column1,column2,..
FROM table_name
WHERE condition;

OUTPUT
create table sdetails(regno int,name char(15),marks int,dept char(10));

insert into sdetails values(1001,'adharsh',89,'cse');


insert into sdetails values(1002,'bala',91,'ai');
insert into sdetails values(1003,'chithra',77,'ece');
insert into sdetails values(1004,'shiva',86,'ai');
select * from sdetails;

create view markview as select regno,marks from sdetails where marks>85;


Select * from markview;

insert into markview values(1005,90);


Select * from markview; select * from sdetails;

update sdetails set name='tina',dept='ai' where regno=1005;


select * from sdetails;

create view deptview as select dept,count(*) from sdetails group by dept;


Select * from deptview;

18
create table pers(regno int,age int,address char(20));

insert into pers values(1001,19,'chennai');


insert into pers values(1002,20,'madurai');
insert into pers values(1003,21,'chennai');
insert into pers values(1007,20,'salem');

select * from pers;

CREATE VIEW spview AS SELECT [Link],[Link] FROM sdetails s JOIN pers p ON


[Link] = [Link];
(or)
CREATE VIEW spview AS SELECT [Link],[Link] FROM sdetails,pers where
[Link]=[Link];

select * from spview;

CREATE or replace VIEW ageview AS SELECT


[Link],[Link],[Link],[Link] FROM sdetails,pers where
[Link]=[Link] and [Link]>=20;

RESULT
Thus the usage of views was implemented successfully.

19
[Link].:4 A)
IMPLEMENTATION OF SUB QUERIES
Date:

AIM
To implement various Sub queries in SQL.
SUB QUERY
In PostgreSQL, a subquery (also known as a nested query or inner query) is a query nested
inside another query. Subqueries are enclosed in parentheses and can be used in various parts
of a SQL statement, such as the SELECT, FROM, WHERE, and HAVING clauses.
The common types of subqueries in PostgreSQL are :

AS
 An alias is created with the AS keyword.
 SQL aliases are used to give a table, or a column in a table, a temporary name.
Syntax
SELECT column1, column2 FROM tablename AS aliasname;
Example
SELECT MAX(salary) AS maxsalary FROM employees
IN
The IN operator specify a list of possible values in the WHERE clause.
Syntax
WHERE IN (subquery)
Example
SELECT * FROM customers WHERE country IN ('Germany', 'France', 'UK');

ANY
 The subquery must return exactly one column.
 The ANY operator must be preceded by one of the following comparison
operator =, <=, >, <, > and <>.
 The ANY operator is used to compare a value to any value in a set of values.
Syntax
expression operator ANY (subquery)
Example
SELECT * FROM products WHERE price > ANY (SELECT price FROM
discount_products);

ALL
The ALL operator is used to compare a value to all values in a set of values.
Syntax
expression operator ALL (subquery)
Example
SELECT * FROM products WHERE price > ALL (SELECT price FROM
expensive_products);

20
EXISTS
The EXISTS operator is used to check the existence of rows in a subquery result.
Syntax

WHERE EXISTS (subquery)


Example
SELECT * FROM customers WHERE EXISTS (SELECT 1 FROM orders
WHERE orders.customer_id = customers.customer_id);
OUTPUT
create table product(pid int, price int);
insert into product values(1,200);
insert into product values(2,100);
insert into product values(3,300);
insert into product values(4,50);
select * from product;

pid price
1 200
2 100
3 300
4 50

create table discountprod(pid int,price int);


insert into discountprod values(1,180);
insert into discountprod values(2,80);
insert into discountprod values(4,25);
pid price
1 180
2 80
4 25
SELECT * FROM product WHERE price < All (SELECT price FROM discountprod);
No value
SELECT * FROM product WHERE price > All (SELECT price FROM discountprod);

pid price
1 200
3 300
SELECT * FROM product WHERE price < Any (SELECT price FROM discountprod);

pid price
2 100
4 50

21
SELECT * FROM product WHERE EXISTS (SELECT * FROM discountprod WHERE
[Link] = [Link]);

pid price
1 200
2 100
4 50

SELECT * FROM product WHERE pid IN ( SELECT pid FROM discountprod WHERE
price = 80);

pid price
2 100

SELECT pid, (SELECT MAX(price) FROM product) AS maxprice FROM product;

pid maxprice
1 300
2 300
3 300
4 300

SELECT MAX(price) FROM product AS MAXPRICE;

max
300

RESULT
Thus the SQL sub query commands were implemented and the output was verified
successfully.

22
[Link].:4 B)
SELECT COMMANDS AND AGGREGATE FUNCTIONS IN SQL
Date:

AIM
To study and execute various select commands using SQL
TYPES OF SELECT COMMAND
GROUP BY

The SQL GROUP BY clause is used to arrange identical data into groups with the
help of some aggregate functions (COUNT, MAX, MIN, SUM, AVG) .
ORDERBY
The ORDER BY clause in SQL is used to sort the result set of a query based on one or more
columns. It can be used with both numerical and textual data, and sorted in ascending (asc)
or descending (desc) order.

HAVING

The HAVING clause in SQL is used in conjunction with the GROUP BY clause to filter the
results of a query based on aggregate conditions.
BETWEEN

The BETWEEN operator in SQL is used to filter the result set based on a specified range of
values. It is often used in the WHERE clause of a query.
SET OPERATORS
UNION

 The UNION operator in SQL is used to combine the result sets of two or more
SELECT statements into a single result set.
 It removes duplicate rows from the combined result set.
UNION ALL

 The UNION ALL operator in SQL is similar to the UNION operator but includes
all rows in the result set, including duplicate rows.
INTERSEC

 The INTERSECT operator in SQL is used to combine the result sets of two
SELECT statements and retrieve only the rows that are common to both result sets.

MINUS

 The MINUS operator in SQL is used to combine the result sets of two SELECT
statements.
 It performs set difference operation.

23
AGGREGATE FUNCTIONS

AVG

The AVG aggregate function in SQL is used to calculate the average value of a
numeric column in a result set.

COUNT

The COUNT aggregate function in SQL is used to count the number of rows in a
result set.
MAX

The MAX function is a useful aggregate function for obtaining the maximum value in
a set of data.
MIN
The MIN function is a useful aggregate function for obtaining the minimum value in
a set of data.
SUM

The SUM aggregate function in SQL is used to calculate the total sum of values in a
specified column.
OUTPUT
create table stud(rollno int,name char(20),dbms int,maths int,algorithm int,dept
char(10),address char(15));
insert into stud values(123,'priya',78,80,80,'cse','chennai');
insert into stud values(124,'uma',63,68,70,'cse','madurai');
insert into stud values(125,'ganesh',90,95,75,'ai','ooty');
insert into stud values(126,'varun',94,87,77,'ece','chennai');

select * from stud;

rollno name dbms maths algorithm dept address


123 priya 78 80 80 cse chennai
124 uma 63 68 70 cse madurai
125 ganesh 90 95 75 ai ooty
126 varun 94 87 77 ece chennai

select dept from student group by dept;

dept
cse
ai
ece

24
select dept from stud;

dept
cse
cse
ai
ece

select count(rollno),dept from stud group by dept;

count dept
2 cse
1 ai
1 ece
select name from stud order by (name)desc;

name
varun
uma
priya
ganesh

select name from stud where maths between 80 and 90;;

name
priya
varun

select count(dbms),dept from stud group by dept having count(dbms)>=2;

count dept
2 cse

create table person(rollno int,name char(20),dbms int,maths int,algorithm int,dept


char(10),address char(15));
insert into person values(125,'ganesh',90,95,75,'ai','ooty');
insert into person values(124,'uma',63,68,70,'cse','madurai');
insert into person values(131,'zara',56,61,55,'ece','madurai');
insert into person values(132,'jerin',52,85,61,'eee','salem');
select * from person;

rollno name dbms maths algorithm dept address


125 ganesh 90 95 75 ai ooty
124 uma 63 68 70 cse madurai
131 zara 56 61 55 ece madurai
132 jerin 52 85 61 eee salem

25
select * from stud union select * from person;

rollno name dbms maths algorithm dept address


126 varun 94 87 77 ece chennai
131 zara 56 61 55 ece madurai
125 ganesh 90 95 75 ai ooty
123 priya 78 80 80 cse chennai
132 jerin 52 85 61 eee salem
124 uma 63 68 70 cse madurai
select * from stud union all select * from person;

rollno name dbms maths algorithm dept address


123 priya 78 80 80 cse chennai
124 uma 63 68 70 cse madurai
125 ganesh 90 95 75 ai ooty
126 varun 94 87 77 ece chennai
125 ganesh 90 95 75 ai ooty
124 uma 63 68 70 cse madurai
131 zara 56 61 55 ece madurai
132 jerin 52 85 61 eee salem

select * from stud intersect select * from person;

rollno name dbms maths algorithm dept address


124 uma 63 68 70 cse madurai
125 ganesh 90 95 75 ai ooty
select * from stud except select * from person;

rollno name dbms maths algorithm dept address


126 varun 94 87 77 ece chennai
123 priya 78 80 80 cse chennai

select name from stud where name in (select name from person where dept='ai');

name
ganesh

RESULT
Thus various select command and aggregate functions are executed in SQL
successfully.

26
[Link].:5 A)
PROGRAMS USING PROCEDURES
Date:

AIM
To Querying/Managing the database using SQL Programming -Procedures and
Functions
PL/pgSQL
 PL/pgSQL is a procedural programming language for the PostgreSQL dbms system.
 PL/pgSQL allows you to extend the functionality of the PostgreSQL dbms server by
creating server objects with complex logic.
 PL/pgSQL was designed to :
 Create user-defined functions, stored procedures, and triggers.
 Extend standard SQL by adding control structures such as if, case,
and loop statements.
 Inherit all user-defined functions, operators, and types.

PROCEDURES
PostgreSQL 11 introduced stored procedures that support transactions.
The following illustrates the basic syntax of the create procedure statement:

create [or replace] procedure procedure_name(parameter_list)


language plpgsql
as $$
declare
-- variable declaration
begin
-- stored procedure body
end; $$

SAMPLE PROGRAM TO PRINT ‘ HAI’


DO $$
BEGIN
-- Use RAISE NOTICE to print the statement
RAISE NOTICE 'hai';
END $$;

Output:
NOTICE: hai
DO
Query returned successfully in 37 msec.

27
PL/PGSQL TO SWAP TWO NUMBERS

DO $$
DECLARE
num1 int;
num2 int;
temp int;
BEGIN
num1 := 1000;
num2 := 2000;
RAISE NOTICE 'Before swapping';
RAISE NOTICE 'num1=%, num2=%', num1, num2;
temp := num1;
num1 := num2;
num2 := temp;
RAISE NOTICE 'After swapping';
RAISE NOTICE 'num1=%, num2=%', num1, num2;
END $$;

Output:
NOTICE: Before swapping
NOTICE: num1=1000, num2=2000
NOTICE: After swapping
NOTICE: num1=2000, num2=1000
DO

SAMPLE PROGRAM USING PROCEDURES


CREATE OR REPLACE PROCEDURE proc()
LANGUAGE plpgsql
AS $$
BEGIN
RAISE NOTICE 'Hello from my stored procedure!';
END;
$$;

Call proc();

OUTPUT:
NOTICE: Hello from my stored procedure! CALL Query returned
successfully in 41 msec.

28
PROGRAM USING PROCEDURES TO PERFORM TRANSACTION

create table accounts ( id int, name varchar(100) not null, balance int not null, primary
key(id));
insert into accounts values(1,'Raju', 5000);
insert into accounts values(2,'Nikhil', 10000);

select * from accounts;

id name balance
1 Raju 5000
2 Nikhil 10000

create or replace procedure transfer(sender int, receiver int, amount int)


language plpgsql
as $$
begin
-- subtracting the amount from the sender's account
update accounts
set balance = balance - amount
where id = sender;

-- adding the amount to the receiver's account


update accounts
set balance = balance + amount
where id = receiver;
commit;
end;$$
call transfer(1,2,1000);
select * from accounts;

id name balance
1 Raju 4000
2 Nikhil 11000

RESULT:
Thus the concept of procedures and functions are executed successfully.

29
[Link].:5 B)
PROGRAMS USING FUNCTIONS
Date:

AIM
To execute program using functions in postgreSQL.

FUNCTIONS
PostgreSQL uses the CREATE FUNCTION statement to develop user-defined functions.

Syntax:
CREATE [OR REPLACE] FUNCTION function_name (arguments)
RETURNS return_datatype
LANGUAGE plpgsql
AS $variable_name$
DECLARE
declaration;
[...] -- variable declaration
BEGIN
< function_body >
[...] -- logic
RETURN { variable_name | value }
END;
$$

Example:

CREATE FUNCTION inc(val integer) RETURNS integer AS $$


BEGIN
RETURN val + 1;
END; $$
LANGUAGE PLPGSQL;

select inc(20);

OUTPUT:

inc
21

PROGRAM USING FUNCTIONS


create table car ( id int, price int);

insert into car values(1,50000);


insert into car values(3,82000);

30
insert into car values(2,70000);
select * from car;

Create function get_car_Price(Price_from int, Price_to int)


returns int
language plpgsql
as
$$
Declare
Car_count integer;
Begin
select count(*)
into Car_count
from Car
where price between Price_from and Price_to;
return Car_count;
End;
$$;
Select get_car_Price(25000,75000);

OUTPUT:

PL/PGSQL FUNCTION TO FIND SQUARE OF A NUMBER


CREATE OR REPLACE FUNCTION square(n int)
RETURNS int AS $$
BEGIN
RETURN n * n;
END;
$$ LANGUAGE plpgsql;

//call the function


select square(5);

OUTPUT:

31
PL/PGSQL FUNCTION TO CALCULATE THE FACTORIAL OF A NUMBER:

CREATE OR REPLACE FUNCTION factorial(n int)


RETURNS int AS $$
DECLARE
result int = 1;
i int;
BEGIN
IF n < 0 THEN
RAISE EXCEPTION 'Invalid input. Factorial is not defined for negative numbers.';
END IF;
FOR i IN 1..n LOOP
result := result * i;
END LOOP;
RETURN result;
END;
$$ LANGUAGE plpgsql;

// call the function


SELECT factorial(5);

OUTPUT:

PL/PGSQL FUNCTION TO LARGEST AMONG THREE NUMBERS

CREATE OR REPLACE FUNCTION great(a int, b int, c int)


RETURNS int AS $$
BEGIN
IF a >= b AND a >= c THEN
RETURN a;
ELSIF b >= a AND b >= c THEN
RETURN b;
ELSE
RETURN c;
END IF;
END;
$$ LANGUAGE plpgsql;

SELECT great(5, 20, 15);

OUTPUT:

32
PL/PGSQL FUNCTION TO ACCEPT A NUMBER A PRINT THE SUM OF ITS DIGIT

CREATE OR REPLACE FUNCTION sum_of_digits(n int)


RETURNS int AS $$
DECLARE
sum int = 0;
BEGIN
WHILE n > 0 LOOP
sum := sum + n % 10;
n := n / 10;
END LOOP;

RETURN sum;
END;
$$ LANGUAGE plpgsql;
// call the function

SELECT sum_of_digits(12345);
OUTPUT:

PL/PGSQL FUNCTION TO DISPLAY A NUMBER IN REVERSE ORDER


CREATE OR REPLACE FUNCTION reverse_number(n int)
RETURNS int AS $$
DECLARE
rev int = 0;
BEGIN
WHILE n > 0 LOOP
rev := rev * 10 + n % 10;
n := n / 10;
END LOOP;

RETURN rev;
END;
$$ LANGUAGE plpgsql;

SELECT reverse_number(123);

OUTPUT:

RESULT
Thus the usage of functions was studied and the programs were executed successfully.

33
[Link].:6
CONSTRAINTS AND SECURITY USING TRIGGERS
Date:

AIM
To querying the database using SQL Programming – Constraints and security using
Trigger.

TRIGGERS
A trigger is a stored procedure in a database that 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 specific table columns are updated.

Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

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 affected row.
6. [trigger_body]: This provides the operation to be performed as the trigger is fired

PROGRAM

CREATE TABLE employee(ID int,first_name varchar(40) not null,last_name varchar(40)


not null,primary key(ID));
INSERT into employee VALUES(101,'John','Doe');
INSERT into employee VALUES(102,'Lily','Bush');

select * from employee;

CREATE TABLE employee_audit(ID int,employee_id int not null,last_name


varchar(40)not null,changed_on timestamp(6) not null);

34
SELECT * FROM employee_audit;

CREATE OR REPLACE FUNCTION log_last_name_changes()


returns trigger
language PLPGSQL
as
$$
BEGIN
if NEW.last_name<>OLD.last_name then INSERT into
employee_audit(employee_id,last_name,changed_on)values([Link],OLD.last_name,NOW(
));
END if;
return new;
END;
$$

CREATE trigger last_name_changes


before update
on employee
for each row
execute procedure log_last_name_changes();

SELECT * FROM employee;

UPDATE employee set last_name='Mathew' WHERE ID=102;

RESULT
Thus the trigger was invoked and executed successfully.

35
[Link].:7
DATABASE DESIGN USING NORMALIZATION
Date:

AIM:
To create a database with Normal forms.

NORMALZATION
 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.

Table 1

Here Movies Rented column has multiple [Link] Normal Forms

Now let's move into 1st Normal Forms

1NF (First Normal Form) Rules


 Each table cell should contain a single value.
 Each record needs to be unique.
The above table in 1NF-

36
1NF Example

Table 1: In 1NF Form

What is a KEY?
A KEY is a value used to identify a record in a table uniquely. A KEY could be a
single column orcombination of multiple columns

Note: Columns in a table that are NOT used to identify a record uniquely are called

non-key columns. What is a Primary Key?

A primary is a single column value used to identify a


database recorduniquely.

It has following attributes:

 A primary key cannot be NULL


 A primary key value must be unique
 The primary key values cannot be changed
 The primary key must be given a value when a new
record is inserted.

What is Composite Key?


A composite key is a primary key composed of multiple columns used to identify a
record uniquely
In our database, we have two people with the same name Robert Phil, but they
live in different places.

Hence, both Full Name and Address a r e r e q u ir e d to identify a record uniquely.


That is a compositekey.

37
Let's move into second normal form 2NF

2NF (Second Normal Form) Rules


 Rule 1- Be in 1NF
 Rule 2- Single Column Primary Key

It is clear that we can't move forward to make our simple database in 2nd
Normalization form unlesswe partition the table above.

Table 1

Table 2

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

Foreign Key references the primary key of


another Table! Ithelps connect your Tables
 A foreign key can have a different
name from it s p r i ma r y k e y.
 It ensures rows in one table have
corresponding rows in another table.
 Unlike the Primary key, they do not
have to be unique.
 Foreign keys can be null even though
primary keys cannot

38
Why do we need a foreign key?
Suppose an idiot inserts a record in Table B such as
We will only be able to insert values into your foreign key that exist in the unique
key in the
parenttable. This helps in referential integrity.

The above problem can be overcome by declaring membership id from Table2 as


foreign key ofmembership id from Table1

Now, if somebody tries to insert a value in the membership id field that does not
exist in the parenttable, an error will be shown!

What are transitive functional dependencies?


A transitive functional dependency is when changing a non-key column, might cause
any of the othernon-key columns to change
Consider the table 1. Changing the non-key column Full Name may change Salutation.

39
Let's move into 3NF
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

Table 3

We have again divided our tables and created a new table which stores Salutations.
There are no transitive functional dependencies, and hence our table is in 3NF

In Table 3 Salutation ID is primary key, and in Table 1 Salutation ID is foreign to


primary key inTable 3

Now our little example is at a level that cannot further be decomposed to attain higher
forms of normalization. In fact, it is already in higher normalization forms. Separate
efforts for moving into next levels of normalizing data are normally needed in

40
complex databases. However, we will be discussing next levels of normalizations in
brief in the following.

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.
BCNF is also referred as 3.5 Normal Form.

4NF (Fourth Normal Form) Rules

If no database table instance contains two or more, independent and multivalued data
describing therelevant entity, then it is in 4th Normal Form.

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.

RESULT
Thus the normalization concept was studied and the database was created using
normalization.

41
[Link].:8 DEVELOPING A DATABASE APPLICATIONS USING
Date: VISUALSTUDIO

AIM
To develop a database application for students using VisualStudio
PROCEDURE
1. In the start menu go to all apps and select Microsoft office->Ms Access
2. Select new document .create a table with name mydata . Choose design view and
create three fields name, address and age.
3. Enter the data for the created fields by double clicking the table mydata. Save the
document as mydata and close the document.

4. In the start menu go to Microsoft Visual studio [Link] create a new project->WPF
framework(.Netframework)->next->create a new project.
5. Select and pin toolbox and datasource at the leftside of the [Link] the toolbox
select 3 labels and 3 textboxes, place it in the form and change the label name from
its properties.

6. Add six buttons in the form and change its name.

7. Choose the datasource ->database->dataset->set a connection to Microsoft access


database file.
8. Select the saved database file name and click ok in the dialog box.

42
9. Choose the database objects and click finish.

10. Place the datagridview in the form and from choose data source->mydata
11. Select each textbox and from its properties choose data bindings->tag->select
appropriate field.
12. Write the code for each buttons.
13. Run the project by pressing CTRL+F5.

VISUAL BASIC CODE

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]()
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]()
[Link]([Link])
MsgBox("saved")
End Sub

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]()
End Sub

Private Sub Button6_Click(sender As Object, e As EventArgs) Handles [Link]


[Link]()
End Sub

43
OUTPUT

RESULT
Thus the application to develop student Management System using VisualStudio is
successfully implemented.

44
[Link].:9 DATABASE DESIGN USING EER-TO-ODB MAPPING / UML CLASS
Date: DIAGRAMS

AIM
To design a database using EER-to-ODB mapping and create UML class diagrams for
the object-oriented database model.

ALGORITHM
1. Develop EER or UML diagrams representing system entities, attributes, and
relationships.
2. Extract entities and attributes for tables, considering each entity as a table and
attributes as columns.
3. Translate relationships into foreign keys in corresponding tables, considering
cardinalities and participation constraints.
4. Decide on a mapping strategy for inheritance (table-per-class or table-per-hierarchy)
for generalization/specialization.
5. Map aggregations to foreign keys or separate tables.
6. Assign appropriate data types to attributes based on requirements and the DBMS.
7. Apply normalization to eliminate redundancy and anomalies.
8. Establish primary keys, foreign keys, unique constraints, and other integrity
constraints.
9. Create a SQL script to implement the database schema, relationships, and constraints.
10. Execute the SQL script to create the database, test and optimize the schema for
performance and functionality, and document the structure

DETAILS OF THE CLASSES


1. Library management systemAttributes:
Usertype
Username
PasswordOperations:
Login()
Register()
Logout()
[Link] Attributes:
Name
Id Operations: Verify()
CheckAccount()
get_book_info()
3. staff Attributes:
Dept

45
4. Student Attributes:
Class
5. AccountAttributes:
no_borrowed_books no_reserved_books no_returned_books
no_lost_books fine_amountOperations: Calculate_fine()
6. Book Attributes:
Title
Author
ISBN
publication Operations: Show_duedt()
Reservation_status()
Feedback()
Book_request()
Renew_info()
7. librarianAttributes:
Name
Id
Password
SearchString Operations: Verify_librarian()
Search()
8. Library database
Attributes:
List_of_books Operations:
Add()
Delete()
Update()
Display()
Search()

46
UML DIAGRAM

RESULT

Thus the implementation on database design using eer-to-odb mapping / uml class
diagrams is performed successfully.

47
[Link].:10 A)
PROGRAM USING UDTs AND INHERITANCE
Date:

AIM:
To implement the object features of SQL using UDTs and Inheritance.
ALGORITHM:
1. Create a type called as addresstype to hold street and city.
2. Create a table employ consisting of emp_id,name,salary and address.
3. Create a table manager which inherits employ table and insert values into this table.
4. Create a table developer which inherits employ and insert values into this table.
5. Display the above three tables, now the base table is inherited by the child tables and the
result will be shown.

PROGRAM

// Create the base UDT representing an addresstype


CREATE TYPE addresstype AS (street VARCHAR, city VARCHAR );
// Create a table for employee using the addresstype UDT
CREATE TABLE employ(emp_id SERIAL PRIMARY KEY,name VARCHAR,
salary DECIMAL, address addresstype);
// Create a table for manager using the inheritance from employ table

CREATE TABLE manager (bonus DECIMAL) INHERITS (employ);


drop table developer;
// Create a table for developer using the inheritance from employ table
CREATE TABLE developer ( programming_language VARCHAR) INHERITS (employ);
// Insert some data into the tables
INSERT INTO manager (name, salary, address,bonus) VALUES ('Alice', 80000, ROW('123
Main St','chennai'),5000 );
INSERT INTO developer (name, salary, address,programming_language) VALUES ('Bob',
70000,ROW('11 West St','ooty'), 'Python' );
INSERT INTO developer (name, salary, address,programming_language) VALUES ('Bala',
65000,ROW('car street','madurai'), 'JAVA' );
// Query data from the tables

select * from manager;

emp_id name salary address bonus


1 Alice 80000 ("123 Main St",chennai) 5000

48
select * from developer;

emp_id name salary address programming_language


2 Bob 70000 ("11 West St",ooty) Python
3 Bala 65000 ("car street",madurai) JAVA

select * from employ;

emp_id name salary address


1 Alice 80000 ("123 Main St",chennai)
2 Bob 70000 ("11 West St",ooty)
3 Bala 65000 ("car street",madurai)

RESULT
Thus the object features of SQL like UDT and inheritance was implemented
successfully.

49
[Link].:10 B)
PROGRAM USING UDTs AND SUBTYPES
Date:

AIM
To implement the object features of SQL like UDTs and Subtypes.
SUBTYPE IN POSTGRESQL
In PostgreSQL, subtypes are implemented using the CREATE TYPE statement. Subtypes
allow to create a new data type that is based on an existing data type and inherits its
properties.
ALGORITHM

1. Create a type called as person_name to hold first_name and last_name.


2. Create a type called as employee_name to hold employee_id and full_name.Full_name
inherits the properties of person_name.
3. Create a table employees which holds emp_id and name. The datatype for name attribute is
employee_name, which is inherited.
4. Insert rows into the table employees.
5. Display the table, employees.
PROGRAM
-- Create the base type
CREATE TYPE person_name AS (first_name VARCHAR,last_name VARCHAR);
-- Create the subtype (employee_name) based on the base type (person_name)
CREATE TYPE employee_name AS (salutation varchar,full_name person_name);

-- Create a table using the subtype


CREATE TABLE employees (emp_id SERIAL PRIMARY KEY, name employee_name);
-- Insert some data
INSERT INTO employees VALUES (1, ROW('Mrs', ROW('Uma', 'Rani')));
INSERT INTO employees VALUES (2, ROW('Mr', ROW('Hanu', 'Saran')));
INSERT INTO employees VALUES (3, ROW('Ms', ROW('Riya', 'Gaur')));
-- Query the data
SELECT * FROM employees;

RESULT
Thus the subtype concept under object features of SQL was implemented
successfully.

50
[Link].:10 C)
OBJECT FEATURES OF SQL-METHOD DEFINITION
Date:

AIM
To calculate the length of books title using method definition.

ALGORITHM

1. Create a table named books with columns book_id, title, author, and publication_year.
2. Define a method named calculate_title_length that takes a book title as an argument
and returns the length of the title using the LENGTH function.
3. Insert some sample data into the books table.
4. Use the calculate_title_length method in a query to find the title length for each book.

PROGRAM
-- Create a table
CREATE TABLE books (book_id SERIAL PRIMARY KEY, title VARCHAR, author
VARCHAR, publication_year INT);
-- Create a method to calculate the number of characters in the title of a book
CREATE OR REPLACE FUNCTION calculate_title_length(book_title VARCHAR)
RETURNS INT AS $$
BEGIN
RETURN LENGTH(book_title);
END;
$$ LANGUAGE plpgsql;

-- Insert some data into the table


INSERT INTO books (title, author, publication_year) VALUES
('The Catcher in the Rye', 'J.D. Salinger', 1951),
('To Kill a Mockingbird', 'Harper Lee', 1960),
('1984', 'George Orwell', 1949);

-- Use the method to calculate the title length for a specific book

SELECT title, calculate_title_length(title) AS title_length FROM books;

RESULT
Thus the length of given books title was calculated using method definition and
displayed successfully.

51
[Link].:11 QUERYING THE OBJECT-RELATIONAL DATABASE USING
Date: OBJET QUERY LANGUAGE

AIM
To query the object relational database using object query language.
OBJECT-RELATIONAL DATABASE

 Object-relational databases aim to bridge the gap between relational databases and
object-oriented databases, incorporating concepts from both paradigms.
 They allow the users to define custom data types, store complex data structures, and
use functions to manipulate the data, providing more flexibility than traditional
relational databases.

Popular Object-Relational Database Management Systems include:

 Oracle Database: Oracle supports object-relational features and has a long history of
providing support for complex data types.

 PostgreSQL: PostgreSQL is an open-source database that supports a wide range of


data types, including arrays and user-defined types.

 IBM Db2: Db2 is known for its support for complex data types and object-relational
features.
ALGORITHM & QUERIES

1. Table Creation:
 The Authors table is created with columns AuthorID (primary key),
AuthorName (name of the author), and Books (an array of book titles).
CREATE TABLE Authors ( AuthorID SERIAL PRIMARY KEY, AuthorName
VARCHAR(100), Books VARCHAR(200)[ ]);

2. Data Insertion:
 Sample data is inserted into the Authors table. Authors are associated with an
array of books they have written.
INSERT INTO Authors (AuthorName, Books) VALUES
('Jenith joel', ARRAY['Book1', 'Book2']),
('Reena dev', ARRAY['Book3', 'Book4', 'Book5']),
('Alice mary', ARRAY['Book6']);

3. Query to Retrieve Authors and the Number of Books:


 The first SELECT statement retrieves AuthorID, AuthorName, and the
number of books written by each author using the CARDINALITY function
to get the array length.

52
SELECT [Link], [Link], CARDINALITY(Books) AS NumberofBooks
FROM Authors a;

4. Query to Retrieve All Authors and Their Books:


 The second SELECT statement retrieves all columns from the Authors table,
showing the authors and the arrays of books they have written.

SELECT [Link], [Link], [Link] FROM Authors aut;

5. Query to Retrieve Authors with More Than 1 Book:


 The third SELECT statement filters the authors who have written more than
one book, using the WHERE clause with the CARDINALITY function.
SELECT [Link], [Link], [Link] FROM Authors aut WHERE
CARDINALITY(Books) > 1;

RESULT
Thus the usage of arrays, creation of user-defined types and the inclusion of functions
which are features of object-relational databases are implemented and executed.

53

You might also like