0% found this document useful (0 votes)
2 views

‎Untitled 2nd year practical

The document outlines a series of exercises focused on SQL commands for creating and managing database tables, including the use of constraints, DDL and DML commands, foreign keys, referential integrity, and various types of joins. Each exercise details the aim, procedure, syntax, and example queries with outputs to demonstrate the successful execution of SQL operations. The exercises culminate in the exploration of advanced SQL features such as subqueries and aggregate functions.

Uploaded by

Neona josh
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)
2 views

‎Untitled 2nd year practical

The document outlines a series of exercises focused on SQL commands for creating and managing database tables, including the use of constraints, DDL and DML commands, foreign keys, referential integrity, and various types of joins. Each exercise details the aim, procedure, syntax, and example queries with outputs to demonstrate the successful execution of SQL operations. The exercises culminate in the exploration of advanced SQL features such as subqueries and aggregate functions.

Uploaded by

Neona josh
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/ 35

Ex. No.

:01 TABLE CREATION, CONSTRAINTS, DDL AND DML COMMANDS


Date: 23.1.25

AIM:
To create a database table, add constraints (primary key, unique, check, Not null), insert rows, update and
delete rows using SQL DDL and DML commands.

PROCEDURE:
Step 1: Open SQLPlus with necessary login credentials
Step 2: Create necessary tables and populate records
Step 3: Execute necessary DDl and DML SQL commands and verify its output.
Step 4: close the session.
SYNTAX AND DESCRIPTION:
CREATE TABLE COMMAND:

Syntax:
CREATE TABLE table_name ( column1
datatype,
column2 datatype,
column3 datatype,
);

Description:
The CREATE TABLE statement is used to create a new table in a database. INSERT
INTO COMMAND:

Syntax:
INSERT INTO table_name (column1, column2, column3, ...) VALUES
(value1, value2, value3, ...);

Description:
The INSERT INTO statement is used to insert new records in a table.

UPDATE COMMAND:

Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ... WHERE
condition;
Description:
The UPDATE statement is used to modify the existing records in a table.

DELETE COMMAND:

Syntax:
DELETE FROM table_name WHERE condition;

Description:
The DELETE statement is used to delete existing records in a table.

QUERIES AND OUTPUT:

SQL> CREATE TABLE WF_LANGUAGES ("LANGUAGE_ID" NUMBER(4,0), "LANGUAGE_NAME"


VARCHAR2(50) );
Table created.
SQL> DESC WF_LANGUAGES;
Name Null? Type

LANGUAGE_ID NUMBER(4)
LANGUAGE_NAME VARCHAR2(50)
SQL> ALTER TABLE WF_LANGUAGES ADD CONSTRAINT PK_WF_LANGUAGES PRIMARY
KEY (LANGUAGE_ID);
Table altered.
SQL> DESC WF_LANGUAGES;
Name Null? Type

LANGUAGE_ID NOT NULL NUMBER(4)


LANGUAGE_NAME VARCHAR2(50)
SQL> ALTER TABLE WF_LANGUAGES DROP CONSTRAINT PK_WF_LANGUAGES;
Table altered.
SQL> DESC WF_LANGUAGES;
Name Null? Type

LANGUAGE_ID NUMBER(4)
LANGUAGE_NAME VARCHAR2(50)
SQL> ALTER TABLE WF_LANGUAGES ADD CONSTRAINT UK_WF_LANGUAGES UNIQUE
(LANGUAGE_ID);
Table altered.
SQL> INSERT INTO wf_languages(language_id,language_name) VALUES(20,'Afar'); 1 row
created
SQL> INSERT INTO wf_languages(language_id,language_name) VALUES(20,'Afar');
ERROR at line 1:
ORA-00001: unique constraint (CSA4076.UK_WF_LANGUAGES) violated
SQL> ALTER TABLE WF_LANGUAGES ADD CONSTRAINT CK_WF_LANGUAGES
CHECK(LANGUAGE_ID > 0);
Table altered.
SQL> INSERT INTO wf_languages(language_id,language_name) VALUES(0,'Amerindian'); ERROR at
line 1:
ORA-02290: check constraint (CSA4076.CK_WF_LANGUAGES) violated
SQL> ALTER TABLE WF_LANGUAGES MODIFY LANGUAGE_ID NUMBER(4) NOT NULL;
Table altered.
SQL> DESC WF_LANGUAGES;
Name Null? Type

LANGUAGE_ID NOT NULL NUMBER(4)


LANGUAGE_NAME VARCHAR2(50)
SQL> SELECT * FROM WF_LANGUAGES;
LANGUAGE_ID LANGUAGE_NAME

20 Afar
SQL> UPDATE WF_LANGUAGES SET LANGUAGE_NAME='ASHOK' WHERE LANGUAGE_ID=20 ;
1 row updated.
SQL> SELECT * FROM WF_LANGUAGES;
LANGUAGE_ID LANGUAGE_NAME

20 ASHOK
SQL> DELETE FROM WF_LANGUAGES WHERE LANGUAGE_ID=20;
1 row deleted.
SQL> SELECT * FROM WF_LANGUAGES;
no rows selected
SQL> ALTER TABLE WF_LANGUAGES ADD (demo VARCHAR(10));
Table altered.
SQL> DESC WF_LANGUAGES;
Name Null? Type

LANGUAGE_ID NOT NULL NUMBER(4)


LANGUAGE_NAME VARCHAR2(50)

DEMO VARCHAR2(10)
Page of
RESULT:
Thus the creation of a database table, adding constraints (primary key, unique, check, Not null), inserting
rows, update and delete rows using SQL DDL and DML commands were executed successfully and its
outputs verified.
Page of

Ex.No.:02 FOREIGN KEY, REFERENTIAL INTEGRITY CONSTRAINT


Date: 30.1.25

AIM:

To create a set of tables, add foreign key constraints and incorporate referential Integrity.
PROCEDURE:
Step 1: Open SQLPlus with Necessary Login Credentials
Step 2: Create Necessary Tables
Step 3: Insert, Test Constraints, Modify NOT NULL, Update, Delete, Add Demo, Verify
Step 4: close the section

SYNTAX AND DESCRIPTION:


Foreign key constraint:

Syntax:
CREATE TABLE table_name ( column1
data_type,
column2 data_type,
...,
FOREIGN KEY (column_name)
REFERENCES referenced_table_name (referenced_column_name)
);
ALTER TABLE table_name
ADD CONSTRAINT constraint_name
FOREIGN KEY (column1, column2, ... column_n) REFERENCES
parent_table (column1, column2, ... column_n);

Description:
A foreign key means that values in one table must also appear in another table. The referenced
table is called the parent table while the table with the foreign key is called the child table. The
foreign key in the child table will generally reference a primary key in the parent table. A foreign key
can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.
A foreign key with cascade delete means that if a record in the parent table is
deleted, then the corresponding records in the child table will automatically be deleted. This is called
a cascade delete.
A foreign key with "set null on delete" means that if a record in the parent table is
deleted, then the corresponding records in the child table will have the foreign key fields set to null.
The records in the child table will not be deleted.

QUERIES AND OUTPUT:

1 SQL> CREATE TABLE WF_COUNTRIES


2 ("COUNTRY_ID" NUMBER(4,0),
3 "REGION_ID" NUMBER(3,0) NOT NULL ENABLE,
4 "COUNTRY_NAME" VARCHAR2(70) CONSTRAINT "WF_CNAME_NN" NOT NULL ,
5 "COUNTRY_TRANSLATED_NAME" VARCHAR2(40),
6 "LOCATION" VARCHAR2(90),
7 "CAPITOL" VARCHAR2(50),
8 "AREA" NUMBER(15,0),
9 "COASTLINE" NUMBER(8,0),
10 "LOWEST_ELEVATION" NUMBER(6,0),
11 "LOWEST_ELEV_NAME" VARCHAR2(70),
12 "HIGHEST_ELEVATION" NUMBER(6,0),
13 "HIGHEST_ELEV_NAME" VARCHAR2(50),
14 "DATE_OF_INDEPENDENCE" VARCHAR2(30),
15 "NATIONAL_HOLIDAY_NAME" VARCHAR2(200),
16 "NATIONAL_HOLIDAY_DATE" VARCHAR2(30),
17 "POPULATION" NUMBER(12,0),
18 "POPULATION_GROWTH_RATE" VARCHAR2(10),
19 "LIFE_EXPECT_AT_BIRTH" NUMBER(6,2),
20 "MEDIAN_AGE" NUMBER(6,2),
21 "AIRPORTS" NUMBER(6,0),
22 "CLIMATE" VARCHAR2(1000),
23 "FIPS_ID" CHAR(2),
24 "INTERNET_EXTENSION" VARCHAR2(3),
25 "FLAG" BLOB,
26 "CURRENCY_CODE" VARCHAR2(7) NOT NULL ENABLE,
27 CONSTRAINT "WF_CRTY_PK" PRIMARY KEY ("COUNTRY_ID")
28 USING INDEX ENABLE );
Table created.
SQL> desc wf_countries Name
Null? Type

COUNTRY_ID NOT NULL NUMBER(4) REGION_ID NOT


NULL NUMBER(3) COUNTRY_NAME NOT NULL
VARCHAR2(70) COUNTRY_TRANSLATED_NAME
VARCHAR2(40) LOCATION VARCHAR2(90)
CAPITOL VARCHAR2(50)
AREA NUMBER(15)
COASTLINE NUMBER(8)
LOWEST_ELEVATION NUMBER(6)
LOWEST_ELEV_NAME VARCHAR2(70) HIGHEST_ELEVATION NUMBER(6) HIGHEST_ELEV_NAME
VARCHAR2(50) DATE_OF_INDEPENDENCE VARCHAR2(30) NATIONAL_HOLIDAY_NAME
VARCHAR2(200) NATIONAL_HOLIDAY_DATE VARCHAR2(30) POPULATION NUMBER(12)
POPULATION_GROWTH_RATE VARCHAR2(10) LIFE_EXPECT_AT_BIRTH NUMBER(6,2)
MEDIAN_AGE NUMBER(6,2)
AIRPORTS NUMBER(6)
CLIMATE VARCHAR2(1000)
FIPS_ID CHAR(2)
INTERNET_EXTENSION VARCHAR2(3)
FLAG BLOB
CURRENCY_CODE NOT NULL VARCHAR2(7)
SQL> CREATE TABLE WF_WORLD_REGIONS
2 ("REGION_ID" NUMBER(3,0),
3 "REGION_NAME" VARCHAR2(35) CONSTRAINT "WF_REG_REGNAME_NN" NOT NULL
ENABLE,
3 CONSTRAINT "WF_REG_PK" PRIMARY KEY ("REGION_ID")
4 USING INDEX ENABLE );
Table created.
SQL> desc wf_world_regions;
Name Null? Type

REGION_ID NOT NULL NUMBER(3) REGION_NAME


NOT NULL VARCHAR2(35)
SQL> ALTER TABLE WF_COUNTRIES ADD CONSTRAINT "WF_REGION_ID_FK1" FOREIGN
KEY ("REGION_ID") REFERENCES WF_WORLD_REGIONS ("REGION_ID") ON DELETE
CASCADE ;
Table altered.
SQL> SELECT region_id from wf_world_regions;
REGION_ID
14
SQL> SELECT region_id from wf_countries;
REGION_ID
14
SQL> delete from wf_world_regions where region_id = 14;
1 row deleted.
SQL> SELECT region_id from wf_countries; no
rows selected

RESULT:
Thus the creation of a set of tables, adding foreign key constraints and incorporating referential

integrity were successfully executed and its outputs verified


Page of

Ex.No.:03 WHERE CLAUSE AND AGGREGATE FUNCTIONS


Date: 6.2.25

AIM:

To query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.
PROCEDURE:
Step 1: Open SQLPlus with Necessary Login Credentials
Step 2: Create Necessary Tables
Step 3: Insert, Test WHERE, Aggregate Functions, Modify, Update, Delete, Add Demo and Verify
Step 4: close the section

SYNTAX AND DESCRIPTION:


WHERE CLAUSE:

Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Description:
The WHERE clause is used to filter records. It is used to extract only those records that fulfill
a specified condition.
AGGREGATE FUNCTIONS:
COUNT()

Syntax:
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

Description:
The COUNT() function returns the number of rows that matches a specified criterion. MIN()
Syntax:
SELECT MIN(column_name)
FROM table_name
WHERE condition;

Description:
The MIN() function returns the smallest value of the selected column. AVG()

Syntax:
SELECT AVG(column_name)
FROM table_name WHERE condition;

Description:
The AVG() function returns the average value of a numeric column.
GROUP BY()

Syntax:
SELECT column_name(s)
FROM table_name WHERE
condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Description:
The GROUP BY statement groups rows that have the same values into summary rows.
HAVING()

Syntax:
SELECT column_name(s)
FROM table_name WHERE
condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Description:
The HAVING clause allows for filtering based on multiple aggregate values.

QUERIES AND OUTPUT:

SQL> desc wf_world_regions;


Name Null? Type

REGION_ID NOT NULL NUMBER(3) REGION_NAME


NOT NULL VARCHAR2(35)
SQL> SELECT COUNT(*) FROM wf_world_regions; 19
SQL> SELECT region_name,MIN(region_id) as "MINIMUM",MAX(region_id) as "MAXIMUM" FROM
wf_world_regions GROUP BY region_name HAVING AVG(region_id)>50; REGION_NAME
MINIMUM MAXIMUM

Western Europe 155 155


Central Asia 143 143
Western Asia 145 145
Eastern Europe 151 151
SQL> SELECT region_name,AVG(region_id),SUM(region_id) FROM wf_world_regions
GROUP BY region_name HAVING AVG(region_id)>50; REGION_NAME AVG(REGION_ID)
SUM(REGION_ID)

Western Europe 155 155


Central Asia 143 143
Western Asia 145 145
Eastern Europe 151 151

RESULT:

Thus the SQL commands to query the database tables using different ‘where’ clause conditions and
to perform the aggregate operations were executed successfully and their outputs were verified
Page of

Ex.No.:04 SUBQUERIES AND JOIN OPERATION


Date: 13.2.25

AIM:

To query the database tables and explore sub queries and simple join operations.

PROCEDURE:
Step 1: Open SQLPlus with Necessary Login Credentials
Step 2: Create Necessary Tables
Step 3: Insert, Test Subqueries, Joins, Modify, Update, Delete, Add Demo and Verify
Step 4: close the section

SYNTAX AND DESCRIPTION:


Subqueries:

Syntax:
SELECT column_name [, column_name ] FROM
table1 [, table2 ]
WHERE column_name OPERATOR (SELECT
column_name [, column_name ] FROM table1
[, table2 ]
[WHERE]);

Description:
A Subquery or Inner query or Nested query is a query within another SQL query and embedded
within the WHERE clause.
A subquery is used to return data that will be used in the main query as a condition to further restrict
the data to be retrieved.
Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN etc. Join queries:

Syntax:
SELECT columns_from_both_tables FROM table1
JOIN table2
ON table1.column1 = table2.column2
SELECT columns
FROM table1 INNER
JOIN table2
ON table1.column = table2.column;

Description:
SQL JOIN clause is used to query and access data from multiple tables by establishing logical
relationships between them. It can access data from multiple tables simultaneously using common key
values shared across different tables.
SQL INNER JOIN (or sometimes called simple join). It is the most common type of
SQL join. SQL INNER JOINS return all rows from multiple tables where the join condition is met.

QUERIES AND OUTPUT:

SQL> DESC wf_languages;


Name Null? Type

LANGUAGE_ID NOT NULL NUMBER(4)


LANGUAGE_NAME NOT NULL VARCHAR2(50)
SQL> DESC WF_SPOKEN_LANGUAGES;
Name Null? Type

COUNTRY_ID NOT NULL NUMBER(4)


LANGUAGE_ID NOT NULL NUMBER(4)
OFFICIAL VARCHAR2(2)
COMMENTS VARCHAR2(512)
SQL> SELECT language_id,language_name FROM wf_languages WHERE language_id IN (SELECT
language_id FROM wf_spoken_languages );
LANGUAGE_ID LANGUAGE_NAME
0 N/A
20 Afar
30 Afrikaans
40 Albanian
50 Amerindian
60 Amharic
80 Arabic
90 Armenian
100 Assyrian
101 Aymara
SQL> SELECT l.language_id,l.language_name FROM wf_languages l JOIN
wf_spoken_languages s ON s.language_id=l.language_id;
LANGUAGE_ID LANGUAGE_NAME
0 N/A
20 Afar
30 Afrikaans
40 Albanian
50 Amerindian
60 Amharic
80 Arabic
90 Armenian
100 Assyrian
101 Aymara
RESULT:
Thus the SQL commands to query the database tables, exploring the sub queries and simple join
operations were successfully executed and its outputs verified.

Ex.No.:05 NATURAL, EQUI AND OUTER JOINS


Date: 27.2.25

AIM:

To query the database tables and explore natural, equi and outer joins.

PROCEDURE:

Step 1: Open SQLPlus with Necessary Login Credentials


Step 2: Create Necessary Tables
Step 3:Insert,Test Joins (Natural Join, Equi Join, Outer Joins), Modify, Update, Delete, Add demo
Step 4: close the section
SYNTAX AND DESCRIPTION:
NATURAL JOIN:

Syntax:
SELECT*FROM
TABLE1
NATURAL JOIN TABLE2;

Description:
Natural join is an SQL join operation that creates a join on the base of the common columns in the
tables. To perform natural join there must be one common attribute(Column) between two tables.
Natural join will retrieve from multiple relations.
EQUI JOIN:

Syntax:
SELECT column_list FROM
table1, table2....
WHERE table1.column_name =
table2.column_name;

Description:
EQUI JOIN creates a JOIN for equality or matching column(s) values of the relative tables. EQUI JOIN
also create JOIN by using JOIN with ON and then providing the names of the columns with their relative
tables to check equality using equal sign (=).

OUTER JOIN Queries:


Syntax:

SELECT columns FROM


table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;
SELECT columns
FROM table1
FULL [OUTER] JOIN table2
ON table1.column = table2.column;

Description:
SQL OUTER JOINS are used to retrieve data from multiple tables. A SQL JOIN is
performed whenever two or more tables are joined in a SQL statement.
There different types of SQL outer joins:
1. SQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
This type of join returns all rows from the LEFT-hand table specified in the ON condition and
only those rows from the other table where the joined fields are equal (join condition is met)
2. SQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)
This type of join returns all rows from the RIGHT-hand table specified in the ON condition and
only those rows from the other table where the joined fields are equal (join condition is met)
3. SQL FULL OUTER JOIN (or sometimes called FULL JOIN)
This type of join returns all rows from the LEFT-hand table and RIGHT-hand table with
nulls in place where the join condition is not met.

QUERIES AND OUTPUT:

SQL> DESC wf_languages;


Name Null? Type

LANGUAGE_ID NOT NULL NUMBER(4)


LANGUAGE_NAME NOT NULL VARCHAR2(50)
SQL> DESC WF_SPOKEN_LANGUAGES;
Name Null? Type

COUNTRY_ID NOT NULL NUMBER(4)


LANGUAGE_ID NOT NULL NUMBER(4)
OFFICIAL VARCHAR2(2)
COMMENTS VARCHAR2(512)
SQL> SELECT language_id,language_name FROM wf_languages NATURAL JOIN
wf_spoken_languages ; LANGUAGE_ID LANGUAGE_NAME

0 N/A
20 Afar
30 Afrikaans
40 Albanian
50 Amerindian
60 Amharic
80 Arabic
90 Armenian
100 Assyrian
101 Aymara

SQL> SELECT l.language_id,l.language_name FROM wf_languages l INNER JOIN


wf_spoken_languages s ON s.language_id=l.language_id;
LANGUAGE_ID LANGUAGE_NAME
0 N/A
20 Afar
30 Afrikaans
40 Albanian
50 Amerindian
60 Amharic
80 Arabic
90 Armenian
100 Assyrian
101 Aymara

SQL> SELECT * FROM wf_languages l LEFT JOIN wf_spoken_languages s ON


s.language_id=l.language_id;

LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID LANGUAGE_ID OF COMMENTS

0 N/A 207 0 N
20 Afar 253 20 N

LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

20 Afar 291
20 N
30 Afrikaans 27

LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID LANGUAGE_ID OF COMMENTS

30 N
30 Afrikaans 264
30 N
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF
COMMENTS

40 Albanian 389
40 N

40 Albanian 41
40 N
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

40 Albanian 355
40 Y
50 Amerindian 593
50 N
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

50 Amerindian 504
50 N

50 Amerindian 592
SQL> SELECT * FROM wf_languages l RIGHT JOIN wf_spoken_languages s ON
s.language_id=l.language_id;
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

1810 Slovene 39
1810 N
Slovene-speaking minority in the Trieste-Gorizia area 560
French 225
560 Y
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

80 Arabic 964
80 N
1000 Kurdish 964
1000 QY
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS
official in Kurdish regions
100 Assyrian 964
100 N
90 Armenian 964

LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

90 N
860 Japanese 81
860 Y

SQL> SELECT * FROM wf_languages l FULL JOIN wf_spoken_languages s ON


s.language_id=l.language_id;

LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

1810 Slovene 39
1810 N

Slovene-speaking minority in the Trieste-Gorizia area 560


French 225
560 Y
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

80 Arabic 964
80 N
1000 Kurdish 964
1000 QY
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

official in Kurdish regions


100 Assyrian 964
100 N
90 Armenian 964
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS 90 N
860 Japanese 81
860 Y
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID
LANGUAGE_ID OF

COMMENTS

460 English 203

460 Y
1580 Portuguese 203
1580 N
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

0 N/A 204
0N
80 Arabic 962
80 Y
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

0 N/A 205
0N
460 English 254
LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

460 Y
970 Kiswahili 254
970 Y

LANGUAGE_ID LANGUAGE_NAME COUNTRY_ID

LANGUAGE_ID OF

COMMENTS

1100 Kyrgyz 996


1100
RESULT:

Thus the SQL commands to query the database tables and explore natural, equl and outer
joins were executed successfully and their outputs were verified.

Ex.No.:06 USER DEFINED FUNCTIONS, PROCEDURES


Date: 27.2.25

AIM:

To write user defined functions and stored procedures in SQL.

PROCEDURE:
Step 1: Open SQLPlus with Necessary Login Credentials
Step 2: Create Necessary Tables
Step 3: Insert, Test Functions and Procedures, Modify, Update, and Verify
Step 4: close the section

SYNTAX AND DESCRIPTION:


FUNCTION:
Syntax : CREATE [OR REPLACE] FUNCTION function_name(parameter1 datatype [,..]) RETURN
return_datatype
IS
-- Declarations (optional)
variable1 datatype;
variable2 datatype; BEGIN
-- SQL statements
-- Return statement (required)
RETURN value;
END function_name;
/
Description :Functions in SQL are named blocks of code that can accept parameters, perform
actions using SQL statements and programming constructs, and return a single value to the caller.
They are often used for calculations, data transformations, and reusable logic.
PROCEDURE:
Syntax :CREATE [OR REPLACE] PROCEDURE procedure_name (parameter1 datatype [,.]) IS
-- Declarations (optional)
variable1 datatype;

variable2 datatype;
BEGIN
-- SQL statements
-- Exception handling (optional)
END procedure_name;
/

Description:

Procedures in SQL are named blocks of code that can accept parameters, perform actions using
SQL statements and programming constructs, and optionally handle exceptions. Unlike functions,
procedures do not return a value directly; they are typically used for executing tasks, performing
operations, or managing transactions.

QUERIES AND OUTPUT:

SQL> DESC wf_currencies;


Name Null? Type

CURRENCY_CODE NOT NULL VARCHAR2(7)


CURRENCY_NAME NOT NULL VARCHAR2(40)
COMMENTS VARCHAR2(150)
SQL> CREATE OR REPLACE FUNCTION get_currency_name(p_currency_code
VARCHAR2)
2 RETURN VARCHAR2 IS
3 v_currency_name VARCHAR2(40);
4 BEGIN
5 SELECT CURRENCY_NAME
6 INTO v_currency_name
7 FROM WF_CURRENCIES
8 WHERE CURRENCY_CODE = p_currency_code; 9
10 RETURN v_currency_name;
11 EXCEPTION
12 WHEN NO_DATA_FOUND THEN
13 RETURN 'Currency code not found';
14 WHEN OTHERS THEN
15 RETURN 'Error occurred';
16 END;
17 /
Function created.
SQL> BEGIN
2 DBMS_OUTPUT.PUT_LINE('Currency Name : '||get_currency_name('USD'));
3 END;
4/
Currency Name : US Dollar
PL/SQL procedure successfully completed.

SQL> SELECT * FROM wf_currencies;


CURRENC CURRENCY_NAME

AED Emirati dirham


AFA Afghani
ALL Lek
SQL> CREATE OR REPLACE PROCEDURE update_currency_name
2 (p_currency_code VARCHAR2, p_new_currency_name VARCHAR2 ) IS
3 BEGIN
4 UPDATE WF_CURRENCIES
5 SET CURRENCY_NAME = p_new_currency_name
6 WHERE CURRENCY_CODE = p_currency_code;
7 WHERE CURRENCY_CODE = p_currency_code
8 IF SQL%ROWCOUNT = 0 THEN
9 DBMS_OUTPUT.PUT_LINE('Error: Currency code not found.');
10 END IF;
11 EXCEPTION
12 WHEN OTHERS THEN
13 DBMS_OUTPUT.PUT_LINE('Error occurred while updating currency name.');
14 END;
15 /
Procedure created.
SQL> BEGIN
2 update_currency_name('AED', 'NOTHING');
3 END;
4/
PL/SQL procedure successfully completed. SQL>
SELECT * FROM WF_CURRENCIES;
CURRENC CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek

RESULT:

Thus the user defined functions and stored procedures in SQL are written, executed successfully
and their outputs were verified.
Page of

Ex.No.:07 DCL AND TCL COMMANDS


Date: 6.3.25

AIM:

To execute complex transactions and realize DCL and TCL commands.

PROCEDURE:

Step 1: Open SQLPlus with Necessary Login Credentials


Step 2: Create Necessary Tables
Step 3: Grant, Revoke privileges, Update, Rollback, Commit, Savepoint, Rollback to Savepoint.
Step 4: close the section

SYNTAX AND DESCRIPTION:


DCL Commands:
GRANT:

Syntax:
GRANT privilege_type [(column_list)] ON [object_type] object_name TO user [WITH GRANT
OPTION];

Description:
Assigns new privileges to a user account, allowing access to specific database objects,
actions, or functions.
REVOKE:

Syntax:
REVOKE [GRANT OPTION FOR] privilege_type [(column_list)] ON [object_type]
object_name FROM user [CASCADE];

Description:
Removes previously granted privileges from a user account, taking away their access to
certain database objects or actions.
TCL Commands:
COMMIT:

Syntax:

commit;
Description :

This command is used to save the data permanently.Whenever we perform any of the DML command
like -INSERT, DELETE or UPDATE, these can be rollback if the data is not stored permanently. So in
order to be at the safer side COMMIT command is used.
SAVEPOINT:

Syntax:
Savepoint savepoint_name;

Description:
This command is used to save the data at a particular point temporarily, so that whenever
needed can be rollback to that particular point.
ROLLBACK:

Syntax:
Rollback;

Description:
This command is used to get the data or restore the data to the last savepoint or last committed state. If
due to some reasons the data inserted, deleted or updated is not correct, you can rollback the data to a
particular savepoint or if savepoint is not done, then to the last committed state.

QUERIES AND OUTPUT:

DCL Commands:
SQL> GRANT SELECT, INSERT ON wf_currencies TO mexam4; Grant
succeeded.
SQL> SELECT * FROM csa4077.wf_currencies;
CURRENCY CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek
SQL> REVOKE SELECT, INSERT ON wf_currencies FROM mexam4; Revoke
succeeded.
SQL> SELECT * FROM cs4077.wf_currencies;
SELECT * FROM cs4077.wf_currencies ERROR
at line 1:
ORA-00942: table or view does not exist TCL
Commands:
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME
AED Emirati dirham
AFA Afghani
ALL Lek

SQL> UPDATE wf_currencies SET CURRENCY_NAME='NOTHING' WHERE CURRENCY_CODE =


'AED';
1 row updated.
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek
SQL> ROLLBACK;
Rollback complete.
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME

AED Emirati dirham


AFA Afghani
ALL Lek
SQL> UPDATE wf_currencies SET CURRENCY_NAME='NOTHING' WHERE
CURRENCY_CODE = 'AED';
1 row updated.
SQL> COMMIT;
Commit complete.
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek
SQL> ROLLBACK;
Rollback complete.
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek
SQL> SAVEPOINT update_point;
Savepoint created.
SQL> UPDATE wf_currencies SET CURRENCY_NAME='NULL' WHERE
CURRENCY_CODE = 'AED';
row updated.
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME

AED NULL
AFA Afghani ALL
Lek
SQL> ROLLBACK TO update_point;
Rollback complete.
SQL> SELECT * FROM wf_currencies;
CURRENCY CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek
RESULT:

Thus the SQL commands to execute complex transactions and to realize DCL and TCL commands were

successfully executed and their outputs were verified.


Page of

Ex.No.:08 TRIGGERS
Date: 13.3.25

AIM:

To write SQL Triggers for insert, delete, and update operations in a database table.

PROCEDURE:
Step 1: Open SQLPlus with Necessary Login Credentials
Step 2: Create Necessary Tables
Step 3: Create a trigger to log actions on WF_LANGUAGES.
Step 4: close the section

SYNTAX AND DESCRIPTION:


Syntax :CREATE OR REPLACE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}
ON table_name
[REFERENCING OLD AS old NEW AS new] [FOR
EACH ROW | FOR EACH STATEMENT] DECLARE
-- Declarations (optional)
BEGIN
-- Trigger body (SQL statements) END
trigger_name;
/

Description:

Triggers in SQL are named blocks of code that automatically execute in response to specified
events (like INSERT, UPDATE, or DELETE) occurring on a particular table. They can be defined to
fire either before (BEFORE) or after (AFTER) the triggering event. Triggers are useful for enforcing
business rules, auditing changes, and maintaining data integrity within a database.

QUERIES AND OUTPUT:

SQL> DESC WF_LANGUAGES;


Name Null? Type

LANGUAGE_ID NOT NULL NUMBER(4)

LANGUAGE_NAME VARCHAR2(50) SQL> CREATE


TABLE WF_LANGUAGES_AUDIT (
LANGUAGE_ID NUMBER,
ACTION VARCHAR2(10),
ACTION_DATE DATE,
OLD_LANGUAGE_NAME VARCHAR2(50),
NEW_LANGUAGE_NAME VARCHAR2(50) );
Table created.
SQL> DESC WF_LANGUAGES_AUDIT;
Name Null? Type

LANGUAGE_ID NUMBER
ACTION VARCHAR2(10)
ACTION_DATE DATE
OLD_LANGUAGE_NAME VARCHAR2(50) NEW_LANGUAGE_NAME
VARCHAR2(50)
SQL> CREATE OR REPLACE TRIGGER trg_wf_languages_audit
2 AFTER INSERT OR UPDATE OR DELETE ON WF_LANGUAGES
3 FOR EACH ROW
4 BEGIN
5 IF INSERTING THEN
6 INSERT INTO WF_LANGUAGES_AUDIT (LANGUAGE_ID, ACTION,
ACTION_DATE, NEW_LANGUAGE_NAME)
7 VALUES (:NEW.LANGUAGE_ID, 'INSERT', SYSDATE,
:NEW.LANGUAGE_NAME);
8 ELSIF UPDATING THEN
9 INSERT INTO WF_LANGUAGES_AUDIT (LANGUAGE_ID, ACTION,
ACTION_DATE, OLD_LANGUAGE_NAME, NEW_LANGUAGE_NAME)
10 VALUES (:OLD.LANGUAGE_ID, 'UPDATE', SYSDATE, :OLD.LANGUAGE_NAME,
:NEW.LANGUAGE_NAME);
11 ELSIF DELETING THEN
12 INSERT INTO WF_LANGUAGES_AUDIT (LANGUAGE_ID, ACTION,
ACTION_DATE, OLD_LANGUAGE_NAME)
13 VALUES (:OLD.LANGUAGE_ID, 'DELETE', SYSDATE,
:OLD.LANGUAGE_NAME);
14 END IF;
15 END;
16 /
Trigger created.
SQL> UPDATE WF_LANGUAGES SET LANGUAGE_NAME = 'ARMENIAN' WHERE
LANGUAGE_ID=20;
1 row updated.
SQL> INSERT INTO WF_LANGUAGES VALUES(21,'AZERBAIJANI');
1 row created.
SQL> DELETE FROM WF_LANGUAGES WHERE LANGUAGE_NAME = 'Angaur';
row deleted.
SQL> SELECT * FROM WF_LANGUAGES_AUDIT;
RESULT:

Thus the SQL Triggers for insert, delete, and update operations in a database table are written,

executed successfully and their outputs were verified.


Page of

Ex.No.:09 VIEW AND INDEX


Date: 20.3.25

AIM:

To create View and index for database tables with a large number of records.

PROCEDURE:
Step 1: Create a view to simplify data retrieval from WF_CURRENCIES.
Step 2: Perform an update on WF_CURRENCIES and verify the view's data.
Step 3: Create an index on CURRENCY_NAME to optimize query performance.
Step 4: Drop the view and index when no longer needed.

SYNTAX AND DESCRIPTION:


VIEW:

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

Description:

Views in SQL are virtual tables based on the result set of a SELECT query. They provide a way to
present data from one or more tables in a structured format, which can simplify complex queries,
provide a layer of abstraction over the underlying tables, and restrict access to certain columns or
rows based on specified conditions.
INDEX:
Syntax : CREATE [UNIQUE] INDEX index_name ON table_name (column1 [, column2, ...]);
Description:

Indexes in SQL are data structures associated with tables that improve the speed of data retrieval
operations on those tables. They are created on one or more columns of a table and allow the
database system to quickly find rows based on the indexed column(s). Indexes are crucial for
optimizing query performance, especially for tables with a large number of records.

QUERIES AND OUTPUT:

SQL> CREATE VIEW vw_wf_currencies


1 AS SELECT CURRENCY_CODE, CURRENCY_NAME
2 FROM WF_CURRENCIES;
View created.
SQL> SELECT * FROM vw_wf_currencies;
CURRENCY CURRENCY_NAME

AED NOTHING
AFA Afghani ALL
Lek
SQL> UPDATE wf_currencies SET CURRENCY_NAME='NULL' WHERE
CURRENCY_CODE = 'AED';
1 row updated.
SQL> SELECT * FROM vw_wf_currencies;
CURRENCY CURRENCY_NAME

AED NULL
AFA Afghani ALL
Lek
SQL> CREATE INDEX idx_currency_name ON WF_CURRENCIES (CURRENCY_NAME); Index
created.
SQL> SELECT index_name, table_name FROM user_indexes WHERE table_name =
'WF_CURRENCIES';
INDEX_NAME TABLE_NAME

WF_CURR_PK WF_CURRENCIES
IDX_CURRENCY_NAME WF_CURRENCIES
SQL> drop view vw_wf_currencies; View
dropped.
SQL> DROP INDEX idx_currency_name; Index
dropped.

RESULT:

Thus the creation of a view and index for database tables with a large number of records were
executed successfully and their outputs were verified
Page of

Ex.No.:10 XML DATABASE.


Date: 27.3.25

AIM:

To create an XML database and validate it using XML schema.


PROCEDURE:
Step 1: Register XML Schema with DBMS_XMLSCHEMA.registerSchema procedure.
Step 2: Create XML data and perform XML validation against the schema.
Step 3: Retrieve registered XML schemas
Step 4: Use SQL queries to extract, update, and manipulate XML data stored in XMLType columns.

SYNTAX AND DESCRIPTION:


Register XML Schema:

Syntax:
BEGIN
DBMS_XMLSCHEMA.registerSchema( schemaURL
=>'http://example.com/schema.xsd', schemaDoc =>
'schema_content',
local => TRUE, genTypes
=> TRUE, genTables =>
TRUE, force => FALSE,
enableHierarchy => DBMS_XMLSCHEMA.ENABLE_ALL_HIERARCHY); END;

Description:
-DBMS_XMLSCHEMA.registerSchema: Oracle Database procedure to register an XML schema.
-schemaURL: Specifies the URL identifier for the schema (e.g.,
'http://example.com/schema.xsd').
- schemaDoc: Contains the actual XML schema content as a string.
- local: When TRUE, the schema is registered as a local schema.
- genTypes: When TRUE, generates object types based on the schema.
- genTables: When TRUE, generates default tables for all global elements.
-force: When FALSE, doesn't overwrite existing schemas.
-enableHierarchy: Specifies how to manage hierarchical data in generated tables. Validate
XML against Schema:

Syntax:
l_xmltype.schemavalidate;

Description:
- l_xmltype: An XMLType variable or column containing the XML data to be validated.
- schemavalidate: Method to validate the XML data against its associated schema. Display
registered XML Schemas:

Syntax:
SELECT schema_url FROM user_xml_schemas;

Description:
-SELECT schema_url FROM user_xml_schemas: Retrieves and displays the URLs of all XML
schemas registered for the current user.
-This query helps verify that the schema was successfully registered and is available for use.

QUERIES AND OUTPUT:

query:
SELECT XMLELEMENT("Language", XMLATTRIBUTES(LANGUAGE_ID
AS "LanguageID"), XMLELEMENT("Name", LANGUAGE_NAME)
) AS LanguageXML FROM
WF_LANGUAGES
WHERE LANGUAGE_ID = 1;
output:
<Language LanguageID="1">
<Name>English</Name>
</Language>
query:
WITH XMLData AS (
SELECT XMLTYPE(
'<Languages>
<Language LanguageID="1">
<Name>English</Name>
</Language>
<Language LanguageID="2">
<Name>Spanish</Name>
</Language>
</Languages>'
) AS xml FROM DUAL
)
SELECT ExtractValue(Value(e), '/Language/Name') AS LanguageName
FROM XMLData x, TABLE(XMLSEQUENCE(EXTRACT(x.xml, '/Languages/Language'))) e; output:
LanguageName
English Spanish query:
UPDATE (
SELECT XMLTYPE(
'<Language>
<Name>English</Name>
</Language>'
) AS xml FROM DUAL
)
SET xml = UPDATEXML(xml, '/Language/Name/text()', 'French') WHERE
ExtractValue(xml, '/Language/Name') = 'English';

-- Verifying the Update SELECT


XMLTYPE(
'<Language>
<Name>French</Name>
</Language>'
) AS UpdatedXML FROM DUAL;
output:
<Language>
<Name>French</Name>
</Language>
query:
SELECT XMLELEMENT("Country", XMLATTRIBUTES(COUNTRY_ID AS
"CountryID"), XMLELEMENT("Name", COUNTRY_NAME),
XMLELEMENT("RegionID", REGION_ID)
) AS CountryXML
FROM WF_COUNTRIES
WHERE COUNTRY_ID = 1;
output:
<Country CountryID="1">
<Name>United States</Name>
<RegionID>1</RegionID>
</Country>
query:
WITH XMLData
AS ( SELECT
XMLTYPE(
'<Countries>
<Country CountryID="1">
<Name>United States</Name>
<RegionID>1</RegionID>
</Country>
<Country CountryID="2">
<Name>Canada</Name>
<RegionID>1</RegionID>
</Country>
</Countries>'
) AS xml FROM DUAL
)
SELECT ExtractValue(Value(e), '/Country/Name') AS CountryName,
ExtractValue(Value(e), '/Country/RegionID') AS RegionID
FROM XMLData x, TABLE(XMLSEQUENCE(EXTRACT(x.xml, '/Countries/Country'))) e;

OUTPUT:
CountryName RegionID

United States 1
Canada 1
query:
UPDATE (
SELECT XMLTYPE(
'<Country>
<Name>United States</Name>
<RegionID>1</RegionID>
</Country>'
) AS xml FROM DUAL
)
SET xml = UPDATEXML(xml, '/Country/Name/text()', 'United States of America') WHERE
ExtractValue(xml, '/Country/Name') = 'United States';
SELECT XMLTYPE(
'<Country>
<Name>United States of America</Name>
<RegionID>1</RegionID>
</Country>'
) AS UpdatedXML FROM DUAL;

OUTPUT:
<Country>
<Name>United States of America</Name>
<RegionID>1</RegionID>
</Country>

RESULT:

Thus the creation of an XML database and validating it using XML schema were

successfully executed and its results were verified.


Page of

Ex.No.:11 NOSQL
Date: 3.4.25

AIM:

To create Document, column and graph based data using NOSQL database tools.

PROCEDURE:
Step 1: Insert data into MongoDB, create keyspace and table in Cassandra, and create nodes in Neo4j.
Step 2: Retrieve and display data from MongoDB, Cassandra, and Neo4j.
Step 3: Update language data in MongoDB, Cassandra, and Neo4j.
Step 4: Verify data update in MongoDB, Cassandra, and Neo4j.

SYNTAX AND DESCRIPTION:


MongoDB
MongoDB utilizes a document-based model with collections and documents. Insert
Document:
db.collection_name.insertOne({
key1: value1,
key2: value2,
});
Find Document:
db.collection_name.find({ key: value }); Cassandra
Apache Cassandra uses a column-family model with keyspaces, tables, rows, and
columns.
Create Keyspace:
CREATE KEYSPACE keyspace_name WITH replication = {'class': 'SimpleStrategy', 'replication_factor':
1};
Use the keyspace:
USE keyspace_name; // To
Create the table:
CREATE TABLE table_name (
key1 data_type PRIMARY KEY,
key2 data_type,
// More columns
);
Inserts one row:
INSERT INTO table_name (key1, key2, ...) VALUES (value1, value2, ...); Selects
data:
SELECT * FROM table_name WHERE key1 = value;
Neo4j
Neo4j employs a graph-based model with nodes, relationships, and properties. Create
Node:
CREATE (:Label {key: value}); // Create Node
Creating Relationship:
MATCH (node1:Label1), (node2:Label2)
WHERE node1.key = value1 AND node2.key = value2 CREATE
(node1)-[:RELATIONSHIP]->(node2);
Querying Nodes and Relationships:
MATCH (node1)-[:RELATIONSHIP]->(node2)
WHERE node1.key = value
RETURN node1, node2;

QUERIES AND OUTPUT:

1.Document-based Data using MongoDB


CODE:
from pymongo import MongoClient client =
MongoClient('localhost', 27017) db =
client['languageDB']
collection = db['WF_LANGUAGES']
languages = [
{"LANGUAGE_ID": 1, "LANGUAGE_NAME": "English"},
{"LANGUAGE_ID": 2, "LANGUAGE_NAME": "Spanish"},
{"LANGUAGE_ID": 3, "LANGUAGE_NAME": "French"},
{"LANGUAGE_ID": 4, "LANGUAGE_NAME": "German"}
]
collection.insert_many(languages) for
language in collection.find():
print(language)
OUTPUT:
{'_id': ObjectId('...'), 'LANGUAGE_ID': 1, 'LANGUAGE_NAME': 'English'}
{'_id': ObjectId('...'), 'LANGUAGE_ID': 2, 'LANGUAGE_NAME': 'Spanish'}
{'_id': ObjectId('...'), 'LANGUAGE_ID': 3, 'LANGUAGE_NAME': 'French'}
{'_id': ObjectId('...'), 'LANGUAGE_ID': 4, 'LANGUAGE_NAME': 'German'}

1.Column-based Data using Apache Cassandra


CODE:
CREATE KEYSPACE languageKeyspace WITH REPLICATION = {'class': 'SimpleStrategy',
'replication_factor': 1};
USE languageKeyspace;
CREATE TABLE WF_LANGUAGES (LANGUAGE_ID int PRIMARY KEY,
LANGUAGE_NAME text );
INSERT INTO WF_LANGUAGES (LANGUAGE_ID, LANGUAGE_NAME) VALUES (1,
'English');
INSERT INTO WF_LANGUAGES (LANGUAGE_ID, LANGUAGE_NAME) VALUES (2,
'Spanish');
INSERT INTO WF_LANGUAGES (LANGUAGE_ID, LANGUAGE_NAME) VALUES (3,
'French');
INSERT INTO WF_LANGUAGES (LANGUAGE_ID, LANGUAGE_NAME) VALUES (4,
'German');
SELECT * FROM WF_LANGUAGES;
OUTPUT:
LANGUAGE_ID | LANGUAGE_NAME
+
1| English
2| Spanish
3 | French
4 | German
5 |Graph-based Data using Neo4j
CODE:
CREATE (:Language {LANGUAGE_ID: 1, LANGUAGE_NAME: 'English'});
CREATE (:Language {LANGUAGE_ID: 2, LANGUAGE_NAME: 'Spanish'});
CREATE (:Language {LANGUAGE_ID: 3, LANGUAGE_NAME: 'French'});
CREATE (:Language {LANGUAGE_ID: 4, LANGUAGE_NAME: 'German'});
MATCH (l:Language) RETURN l;

OUTPUT:
RESULT:

Thus the creation of document, column and graph based data using NOSQL database were executed

successfully and its outputs were verified.


Page of

Ex.No.:12 MINI PROJECT - WF_COUNTRIES


Date: 3.4.25

AIM:

To build a real time database application by designing an ER diagram , applying normalization


principle on the entities and incorporating the necessary SQL and PL/SQL features.

Procedure:
1. Design the main GUI frame (JFrame) named f to serve as the application window.
2. Create three panels (JPanels) – one for adding records (p1), one for editing records (p2), and
one for deleting records (p3).

3. Add a JTabbedPane (tp) to the JFrame to organize the three panels.


4. Place various JLabels and JTextFields on the panels for user inputs such as title_id, title,
description, rating, category, and release_date.

5. Add JButtons to the panels for actions: save button for adding, reset btn for clearing inputs, edit btn
for fetching records to edit, update btn for saving edits, and delete button for record deletion. Step 6:
Integrate JDBC within the button action listeners to interact with the Oracle database for CRUD
operations.

6. Test the GUI to ensure proper functionality for adding, editing, and deleting movie records.
7. Launch and manage the application using the wf_countries class.
DESCRIPTION:
wf_countries Class Overview:
The wf_countries class creates a GUI for managing movie records in a database.
It uses Java Swing components to create the interface and JDBC to interact with an Oracle
database.
Main Components:
1. JFrame:
○ f: The main frame of the application.
2. JPanels:
○ p1: Panel for adding new records.
○ p2: Panel for editing existing records.
○ p3: Panel for deleting records.
3. JTabbedPane:
○ tp: A tabbed pane that holds the three panels (p1, p2, and p3).
4. JLabels and JTextFields:
Various labels and text fields for user inputs like title_id, title, description, rating,
category, and release_date.
5. JButtons:
save btn: Button to add a new record to the database.
reset btn: Button to reset the input fields in the add record panel.
edit btn: Button to fetch a record for editing.
update btn: Button to save the edited record.

delete btn: Button to delete a record from the database.

FUNCTIONALITIES:

1. Add Record:
○ Users can input details like title_id, title, description, rating, category, and
release_date.
○ Clicking the "Add" button inserts the new record into the database. ○ The "Reset" button
clears all input fields.
2. Edit Record:
○ Users can enter a title_id to fetch the existing record details. ○ Clicking
the "Edit" button retrieves the record from the database. ○ Users can then modify the title
and description.
○ The "Save" button updates the record in the database.
3. Delete Record:
○ Users can enter a title_id to delete the corresponding record. ○ Clicking the
"Delete" button removes the record from the database.
Database Connection:
The application connects to an Oracle database using JDBC.
It executes SQL queries to insert, update, and delete
records.
Error Handling:
Displays error messages using JOptionPane if any database operation fails. User
Interface:
The application is designed with a simple and intuitive interface using
GridLayout.
The main frame is not resizable and has a fixed size.
Execution:
● The main method creates an instance of wf_countries and displays the GUI.
This application is suitable for basic CRUD (Create, Read, Update, Delete) operations on a movie
database, providing a straightforward interface for database management.
ER DIAGRAM:

SCHEMA:
SQL> CREATE TABLE WF_LANGUAGES
2 ("LANGUAGE_ID" NUMBER(4,0),
3 "LANGUAGE_NAME" VARCHAR2(50) CONSTRAINT "WF_LANG_LANGNAME_NN" NOT
NULL ENABLE,
4 CONSTRAINT "WF_LANG_PK" PRIMARY KEY ("LANGUAGE_ID")
5 USING INDEX ENABLE
6 );
Table created.
SQL> CREATE TABLE WF_CURRENCIES
2 ("CURRENCY_CODE" VARCHAR2(7),
3 "CURRENCY_NAME" VARCHAR2(40) CONSTRAINT "WF_CURR_NN" NOT NULL
ENABLE,
4 "COMMENTS" VARCHAR2(150),
5 CONSTRAINT "WF_CURR_PK" PRIMARY KEY ("CURRENCY_CODE")
6 USING INDEX ENABLE
7 );
Table created.
Page of

SQL> CREATE TABLE WF_SPOKEN_LANGUAGES


2 ("COUNTRY_ID" NUMBER(4,0),
3 "LANGUAGE_ID" NUMBER(4,0),
4 "OFFICIAL" VARCHAR2(2),
5 "COMMENTS" VARCHAR2(512),
6CONSTRAINT "WF_SPOKEN_LANG_PK" PRIMARY KEY ("COUNTRY_ID",
"LANGUAGE_ID")
6 USING INDEX ENABLE
7 );
Table created.
SQL> CREATE TABLE WF_COUNTRIES
2 ("COUNTRY_ID" NUMBER(4,0),
3 "REGION_ID" NUMBER(3,0) NOT NULL ENABLE,
4 "COUNTRY_NAME" VARCHAR2(70) CONSTRAINT "WF_CNAME_NN" NOT NULL ,
5 "COUNTRY_TRANSLATED_NAME" VARCHAR2(40),
6 "LOCATION" VARCHAR2(90),
7 "CAPITOL" VARCHAR2(50),
8 "AREA" NUMBER(15,0),
9 "COASTLINE" NUMBER(8,0),
10 "LOWEST_ELEVATION" NUMBER(6,0),
11 "LOWEST_ELEV_NAME" VARCHAR2(70),
12 "HIGHEST_ELEVATION" NUMBER(6,0),
13 "HIGHEST_ELEV_NAME" VARCHAR2(50),
14 "DATE_OF_INDEPENDENCE" VARCHAR2(30),
15 "NATIONAL_HOLIDAY_NAME" VARCHAR2(200),
16 "NATIONAL_HOLIDAY_DATE" VARCHAR2(30),
17 "POPULATION" NUMBER(12,0),
18 "POPULATION_GROWTH_RATE" VARCHAR2(10),
19 "LIFE_EXPECT_AT_BIRTH" NUMBER(6,2),
20 "MEDIAN_AGE" NUMBER(6,2),
21 "AIRPORTS" NUMBER(6,0),
22 "CLIMATE" VARCHAR2(1000),
23 "FIPS_ID" CHAR(2),
24 "INTERNET_EXTENSION" VARCHAR2(3),
25 "FLAG" BLOB,
26 "CURRENCY_CODE" VARCHAR2(7) NOT NULL ENABLE,
27 CONSTRAINT "WF_CRTY_PK" PRIMARY KEY ("COUNTRY_ID")
28 USING INDEX ENABLE );
Table created.
SQL> CREATE TABLE WF_WORLD_REGIONS 2

("REGION_ID" NUMBER(3,0),
Page of

3 "REGION_NAME" VARCHAR2(35) CONSTRAINT "WF_REG_REGNAME_NN" NOT NULL


ENABLE,
4 CONSTRAINT "WF_REG_PK" PRIMARY KEY ("REGION_ID")
5 USING INDEX ENABLE
6 );
Table created.
SQL> select table_name from user_tables;
TABLE_NAME

WF_COUNTRIES
WF_WORLD_REGIONS
WF_LANGUAGES
WF_CURRENCIES
WF_SPOKEN_LANGUAGES

PROGRAM:
import java.awt.*; import
javax.swing.*; import
java.awt.event.*; import
java.sql.*;
class VendorForms {
JFrame f;
JPanel p1, p2, p3;
JTabbedPane tp;
JLabel l1, l2, l3, l4, l5, l7, l8, l9, l10; JTextField tf1,
tf2, tf3, tf4, tf5, tf7, tf8, tf9, tf10;
JButton save btn, reset btn, edit btn, update btn, delete btn;
VendorForms() {
f=newJFrame("Form");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p1 = new JPanel(new GridLayout(5, 2));
p2 = new JPanel(new GridLayout(5, 2)); p3
= new JPanel(new GridLayout(2, 2)); tp =
new JTabbedPane();
l1 = new JLabel("Country ID:");
l2 = new JLabel("Country Name:"); l3
= new JLabel("Region ID:");
l5 = new JLabel("Enter the Country ID:"); l7
= new JLabel("Enter the Country ID:"); l8 =
new JLabel("Country Name:");
l9 = new JLabel("Region ID:"); tf1
= new JTextField(2);
tf2 = new JTextField(40); tf3 =
new JTextField(10); tf5 = new
JTextField(2); tf7 = new
JTextField(2); tf8 = new
JTextField(40); tf9 = new
JTextField(10);
savebtn = new JButton("Add"); resetbtn =
new JButton("Reset"); editbtn = new
JButton("Edit"); updatebtn = new
JButton("Save"); deletebtn = new
JButton("Delete"); p1.add(l1);
p1.add(tf1);
p1.add(l2);
p1.add(tf2);
p1.add(l3);
p1.add(tf3);
p1.add(savebtn);
p1.add(resetbtn);
p2.add(l7);
p2.add(tf7);
p2.add(l8);
p2.add(tf8);
p2.add(l9);
p2.add(tf9); p2.add(editbtn);
p2.add(updatebtn);
p3.add(l5);
p3.add(tf5);
p3.add(deletebtn);
resetbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
tf1.setText("");
tf2.setText("");
tf3.setText("");
}
});
savebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { String
value1 = tf1.getText();
String value2 = tf2.getText();
String value3 = tf3.getText(); Connection con = null;
try { Class.forName("oracle.jdbc.driver.OracleDriver");
con =DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.18:1521:ORCL", "csa4077", "licet");
PreparedStatement st = con.prepareStatement(
"INSERT INTO wf_countries(country_id, country_name, region_id)
VALUES(?, ?, ?)");
st.setString(1, value1);
st.setString(2, value2);
st.setInt(3, Integer.parseInt(value3));
st.executeUpdate();
JOptionPane.showMessageDialog(p1, "Data is Successfully Inserted into Database"); con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(p1, "Error in Record Insertion!");
}
}
});
deletebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { String
value1 = tf5.getText();
Connection con = null; try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con =DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.18:1521:ORCL", "csa4077", "licet");
PreparedStatement st = con.prepareStatement("DELETE FROM wf_countries WHERE
country_id = ?");
st.setString(1, value1);
int status = st.executeUpdate(); if
(status == 1) {
JOptionPane.showMessageDialog(p3, "Record is Deleted Successfully!");
} else {
JOptionPane.showMessageDialog(p3, "Country ID Does Not Exist!");
}
con.close();
} catch (Exception exp3) {
JOptionPane.showMessageDialog(p3, "Error in Record Deletion!");
}
}
});
editbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) { String
value1 = tf7.getText();
Connection con = null; try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con =DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.18:1521:ORCL", "csa4077","licet");
PreparedStatement st = con.prepareStatement("SELECT * FROM wf_countries WHERE
country_id = ?");
st.setString(1, value1);
ResultSet res = st.executeQuery();
res.next(); tf7.setText(res.getString(1));
tf8.setText(res.getString(2));
tf9.setText(res.getString(3));
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(p2, "Country ID Does Not Exist!");
}
}
});
updatebtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Connection con = null;
try {
int x = JOptionPane.showConfirmDialog(p2, "Confirm Edit? Record Data will be Replaced"); if (x ==
0) {
try {
String value1 = tf7.getText();
String value2 = tf8.getText();
String value3 = tf9.getText();
Class.forName("oracle.jdbc.driver.OracleDriver");
con =DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.18:1521:ORCL", "csa4077","licet");
PreparedStatement pstmt = con.prepareStatement( "UPDATE
wf_countries SET country_name = ?, region_id = ? WHERE
country_id = ?");
ustmt.setString(1, value2);
ustmt.setInt(2, Integer.parseInt(value3)); ustmt.setString(3, value1); ustmt.executeUpdate();
JOptionPane.showMessageDialog(p2, "Updated Successfully");
con.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(p2, "Error in Updating a Record");
}
}
} catch (Exception ex) { JOptionPane.showMessageDialog(p2,
"Optional Error");
}
}
});
}
void dis() {
f.getContentPane().add(tp);
tp.addTab("Add Record", p1);
tp.addTab("Edit Record", p2);
tp.addTab("Delete Record", p3);
f.setSize(350, 180);
f.setVisible(true);
f.setResizable(false);
}
public static void main(String args[]) { VendorForms vfo = new VendorForms(); vfo.dis(); }
}

OUTPUT:

BEFORE INSERTION :
SQL> SELECT * FROM WF_COUNTRIES;
no rows selected
AFTER INSERTION :
SQL> SELECT * FROM WF_COUNTRIES;

COUNTRY_ID REGION_ID
COUNTRY_NAME

123 789 xyz BEFORE


EDITING :
SQL> SELECT * FROM WF_COUNTRIES;

COUNTRY_ID REGION_ID COUNTRY_NAME


123 789 xyz

AFTER EDITING :
SQL> SELECT * FROM WF_COUNTRIES;

COUNTRY_ID REGION_ID COUNTRY_NAM

123 567
BEFORE DELETION :
SQL> SELECT * FROM WF_COUNTRIES;
COUNTRY_ID REGION_ID
COUNTRY_NAME

123 567 abc


Page of
AFTER DELETION:
SQL> SELECT * FROM WF_COUNTRIES;
no rows selected

RESULT:

Thus To build a real time database application by designing an ER diagram ,applying normalization
principle on the entities and incorporating the necessary SQL and PL/SQL features.have been done and
output is verified successfully.
Page of

You might also like