DBMS lab
DBMS lab
Name :
Register Number :
Subject Code : CS3481
Subject Name : DATABASE MANAGEMENT SYSTEM LABORATORY
Semester : IV Year: II
CERTIFICATE
Certified that this is the bonafide record of work done by the above
student in the ______________________________laboratory during the year 2023-
2024.
8 Triggers
AIM:
To create a database and write SQL queries to retrieve information from the database.
DESCRIPTION:
DDL (Data Definition Language) statements are used to create, change the objects of a
database. Typically a database administrator is responsible for using DDL statements or
production databases in a large database system. The commands used are:
• Alter - This command is used to add a new column, modify the existing column
definition and to include or drop integrity constraint.
• Drop - It will delete the table structure provided the table should be empty.
• Truncate - If there is no further use of records stored in a table and the structure
has to be retained, and then the records alone can be deleted.
PROCEDURE:
Step 1: Create table by using create table command with column name, data type and size.
Step 3: Add any new column with the existing table by alter table command.
Create Table
Syntax:
1
Example:
Table created.
Alter Table
Syntax:
Example:
2
SQL> Alter table Student drop (Stud_age number(10));
Table altered.
Truncate Table
Syntax:
Example:
Table truncated.
Rename
Syntax
3
Drop Table
Syntax:
Table dropped.
4
DML COMMANDS
AIM:
DESCRIPTION:
DML commands are the most frequently used SQL commands and is used to query and
manipulate the existing database objects. Some of the commands are
• Insert
• Select
• Update
• Delete
PROCEDURE:
Table created.
Insert:
This is used to add one or more rows to a table. The values are separated by commas and the
data types char and date are enclosed in apostrophes. The values must be entered in the same
order as they are defined.
Syntax:
insert into tablename values(
‘&column_name1’,
‘&column_name2’, ‘
‘&column_name3’,…..);
5
Example:
Select Command:
It is used to retrieve information from the table. It is generally referred to as querying the
table. We can either display all columns in a table or only specify column from the table.
Syntax:
Example:
SQL> select * from Student1;
STUD_NAME STUD_ID STUD_DEPT STUD_ROLLNO
Ram 101 MECH 104
Vicky 102 EEE 105
Saddiq 103 CSE 101
David 104 EEE 103
4 rows selected
Update Command:
It is used to alter the column values in a table. A single column may be updated or more than
one column could be updated.
Syntax:
6
Example:
Delete Command:
After inserting row in a table we can also delete them if required. The delete command consists
of a from clause followed by an optional where clause. Syntax:
Example:
RESULT:
Thus the Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on
conditions using SQL commands were executed and verified successfully.
7
Ex. No.: 02
Date : FOREIGN KEY CONSTRAINTS
Aim:
To study and practice to create table, add foreign key constraints and incorporate referential
integrity.
Description:
A referential integrity constraint is also known as foreign key constraint. A foreign key is a key whose
values are derived from the Primary key of another table.
The table from which the values are derived is known as Master or Referenced Table and the Table in
which values are inserted accordingly is known as Child or Referencing Table,
In other words, we can say that the table containing the foreign key is called the child table, and the
table containing the Primary key/candidate key is called the referenced or parent table.
Procedure:
Step 1: Create the master or referenced table with required fields.
Step 2: Create the child table.
Step 3: Create the primary key in master table.
Step 4: Apply the insert and delete constrains.
CONSTRAINTS:
1) Primary key
2) Foreign key/references
3) Check
4) Unique
5) Not null
6) Null
7) Default
NOT NULL:
Syntax:
Create table tablename(
fieldname1 datatype(constraint)not null,
fieldname2 datatype,
8
…………….
fieldnamen datatype);
Example:
SQL> create table notnull (eno varchar(10) not null, ename varchar(10),esalary number(20));
Table created
SQL>insert into notnull values(‘1’,’abdul’,’20000’)
1 row created.
CHECK:
UNIQUE:
Used to set unique constraint to the specified column name which will not allow redundant
values
Syntax:
9
Create table tablename(
fieldname1 datatype(constraint)unique,
fieldname2 datatype,
…………….
Fieldname3 datatype);
Example:
SQL> create table conn(eno varchar(10) unique, ename varchar(20));
Table created.
SQL> insert into conn values(‘1’,’hello’)
1 row created.
PRIMARY KEY:
Primary key is a constraint for both unique and not null.
Syntax:
Create table tablename(
Fieldname1 datatype(constraint)primary key,
fieldname2 datatype,
…………….
Fieldname3 datatype);
Example:
SQL> create table con(empid varchar(10),empname varchar(20) primary key);
Table created.
ADDING CONSTRIANT:
Used to set any constraint to the specified column at the last by specifying the constraint type and
field name.
Syntax:
Create table tablename(
Fieldname1 datatype(constraint),
10
fieldname2 datatype,
constraint constraintname constrainttype(fieldname));
Example:
SQL> create table con(empid varchar(10),empname varchar(10),constraint c1 primary key(empid));
Table created.
SQL> insert into con values (‘1’,’anand’)
Example:
Table altered.
NOT NULL
EMPID VARCHAR(10)
EMPNAME VARCHAR(10)
DROP CONSTRAINT:
Used to drop the constraint.
Syntax:
Alter table table_name drop constraint constraint_name.
11
Example:
SQL> alter table con drop constraint c1;
Table altered.
EMPID VARCHAR(10)
EMPNAME VARCHAR(10)
REFERENTIAL INTEGRITY:
Used to refer the primary key of the parent table from the child table.
Syntax:
a) Create table tablename(
Fieldname1 datatype primary key,
fieldname2 datatype,
…………….
Fieldname3 datatype);
b) Create table tablename(Fieldname1 datatype references,
Parent tablename(fieldname)
…………….
Fieldname n datatype);
Example:
SQL> create table parent(eno varchar(10),ename varchar(10) primary key);
Table created.
SQL>insert into parent values (‘1’,’ajay’)
1 row created.
SQL>insert into parent values (‘2’,’bala’)
1 row created.
Table created.
12
SQL>insert into child values (‘2’,’balaji’)
ERROR at line 1:
ORA-02291: integrity constraint (SCOTT.SYS_C0010290) violated - parent key not
Found
ON DELETE CASCADE:
The changes done in parent table is reflected in the child table when references are made.
Syntax:
Example:
SQL> create table parent(eno varchar(10),ename varchar(10) primary key);
Table created.
13
SQL> select * from parent;
no rows selected
SQL> select * from child;
no rows selected
Result
Thus the various key constraints based on foreign key where written and executed successfully.
14
Ex.No. : 03
Date : WHERE AND AGGREGATE FUNCTIONS
Aim:
To study and execute various database queries using where clause and aggregate functions.
Description:
The WHERE clause is used to filter records. It is used to extract only those records that fulfill a
specified condition.
Where clause’s
Operator Description
= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal.( Note: In some versions of SQL this operator may be written as !=)
BETWEEN Between a certain range
LIKE Search for a pattern
IN To specify multiple possible values for a column
The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE, etc.!
Equal
SQL> select * from table_name where field=condition
Example
SQL> select * from student1 where stud_rollno=101;
Greater Than
SQL> select * from student1 where stud_rollno >101;
Less Than
SQL> select * from student1 where stud_rollno <105;
STUD_NAME STUD_ID STUD_DEPT STUD_ROLLNO
Ram 101 MECH 104
Saddiq 103 CSE 101
David 104 EEE 103
15
Between
SQL> select * from student1 where stud_rollno between 103 AND 105;
STUD_NAME STUD_ID STUD_DEPT STUD_ROLLNO
Ram 101 MECH 104
Vicky 102 EEE 105
David 104 EEE 103
Like
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;
Example
SQL > Select * from student1 where stud_name like ‘d%’;
STUD_NAME STUD_ID STUD_DEPT STUD_ROLLNO
David 104 EEE 103
The UNION operator is used to combine the result-set of two or ore SELECT statements.
• Every SELECT statement within UNION must have the same number of columns
• The columns must also have similar data types
• The columns in every SELECT statement must also be in the same order
Syntax:
select column_name(s) from table1
union
select column_name(s) from table2;
16
SQL> select subject from student union select subject from staff order by subject;
Example
SQL> SELECT dept, subject FROM student
WHERE subject='DBMS'
UNION
SELECT dept, subject FROM staff
WHERE subject='DBMS'
ORDER BY City;
Union All
select column_name(s) from table1
union all
select column_name(s) from table2;
Example
select subject from student
union all
select subject from staff
order by subject;
Intersect:
Syntax:
Select <fieldlist> from <tablename1> where (condition) intersect select<fieldlist> from<tablename2>
where (condition);
Example
SQL> select stud_id from student intersect select staff_id from staff;
In:
The IN operator allows you to specify multiple values in a WHERE clause.
The IN operator is a shorthand for multiple OR conditions.
Syntax:
Select <fieldlist> from <tablename1> where (condition) in select<fieldlist> from<tablename2> where
(condition);
17
Example
SQL>select * from student1 where stud_dept in ('cse', 'mech');
Not like:
Syntax:
Select <fieldlist> from <tablename> where <fieldname> not like <expression>;
All:
ALL means that the condition will be true only if the operation is true for all values in the range.
Syntax:
Select <fieldlist> from <tablename1>where <fieldname> all Select <fieldlist> from <tablename2>
where (condition);
Example
SQL> select stud_name from student where stud_id = all (select subject_id from subject where sem
= 4);
Any:
The ANY operator:
• returns a Boolean value as a result
• returns TRUE if ANY of the sub query values meet the condition
ANY means that the condition will be true if the operation is true for any of the values in the range.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
18
FROM table_name
WHERE condition);
The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Example
SQL> select stud_name from student where stud_id = any (select subject_id from subject where sem
= 4);
The above SQL statement lists the student name if it finds ANY records in the subject table has sem
equal to 4 (this will return TRUE if the sem column having value 4)
Aggregate Functions
MySQL's aggregate function is used to perform calculations on multiple values and return the result in a
single value like the average of all values, the sum of all values, and maximum & minimum value
among certain groups of values. We mostly use the aggregate functions with SELECT statements in the
data query languages.
Sql > create table student(rollno decimal, sname varchar(15), mark1 decimal, mark2 decimal);
Table created
Sql> insert into student values(101, ‘kareem’,95,90);
Sql> insert into student values(102, ‘kaasim’,92,97);
Sql> insert into student values(103, ‘ram’,85,95);
Sql> insert into student values(104, ‘sai’,93,91);
Count
The COUNT () function returns the number of rows that matches a specified criterion.
19
Syntax
SELECT COUNT (column_name) FROM table_name WHERE condition;
Example
SELECT COUNT (rollno) FROM student;
4
Sum
The SUM () function returns the total sum of a numeric column.
Syntax
SELECT SUM(column_name) FROM table_name WHERE condition;
Example
SELECT SUM(mark1) FROM student;
365
Syntax
SELECT AVG(column_name) FROM table_name WHERE condition;
Example
SELECT AVG(mark1) FROM student;
91
Result
Thus the where clause function quires and aggregate function quires are executed successfully.
20
Ex.no. : 04 SUB QUIRES AND JOIN OPERATIONS
Date :
Aim :
To implement and execute simple, nested, sub & join operation queries in mysql database.
Simple Queries
AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ..
Example
SELECT * FROM student1 WHERE stud_id=101 AND stud_dept=’mech’;
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
21
Example
SELECT * FROM student1 WHERE stud_id=101 OR stud_dept=’EEE’;
NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
Example
SELECT * FROM student WHERE NOT stud_id=101;
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
Example
SELECT * FROM student1 ORDER BY STUD_ID ;
22
Subqueries
A MySQL sub query is a query nested within another query such as SELECT, INSERT, UPDATE or
DELETE. In addition, a MySQL sub query can be nested inside another sub query.
A MySQL sub query is called an inner query while the query that contains the sub query is called an
outer query. A sub query can be used anywhere that expression is used and must be closed in
parentheses.
Example SubQueries
In this example:
The sub query returns all office codes of the offices located in the USA.
The outer query selects the last name and first name of employees who work in the offices whose
office codes are in the result set returned by the sub query.
2. Select max(sid) from classa where sid <( select max(sid) from classa)
SQL Joins
Here are the different types of the Joins in SQL:
(INNER) JOIN : Returns records that have matching values in both tables
LEFT (OUTER) JOIN : Return all records from the left table, and the matched records from the
right table
RIGHT (OUTER) JOIN : Return all records from the right table, and the matched records from the
left table
FULL (OUTER) JOIN : Return all records when there is a match in either left or right table
23
Inner Join
The INNER JOIN keyword selects records that have matching values in both tables.
Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT student.name, student.mark1, sports.game FROM student INNER JOIN sports ON
student.rollno=sports.rollno;
Left Join
The LEFT JOIN keyword returns all records from the left table (table1), and the matched records from the
right table (table2). The result is NULL from the right side, if there is no match.
Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT student.name, student.mark1, sports.game FROM student LEFT JOIN sports ON
student.rollno=sports.rollno;
Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
24
ON table1.column_name = table2.column_name;
Example
SELECT student.name, student.mark1, sports.game FROM student RIGHT JOIN sports ON
student.rollno=sports.rollno;
Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name;
If the above syntax is not working then we can go with union operation.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
Union
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
Example
SELECT student.name, student.mark1, sports.game FROM student LEFT JOIN sports ON
student.rollno=sports.rollno
Union
SELECT student.name, student.mark1, sports.game FROM student RIGHT JOIN sports ON
student.rollno=sports.rollno
Result
Thus the SQL sub queries, nested queries and various join operation queries are written and
executed successfully.
25
Ex. No. : 05 NATURAL, EQUI AND OUTER JOINS
Date :
Aim:
To study and execute SQL natural join, equi join and outer joins.
Procedure:
Natural join is an SQL join operation that creates 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.
It works in three steps.
Natural join is an SQL join operation that creates 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. It works in three steps.
Tables
Student
Roll sname dept
101 aaa cse
105 eee it
102 bbb ece
103 ccc eee
104 ddd cse
105 eee it
Game
Gid gname roll
1 cricket 101
2 volley ball 102
3 cricket 104
4 carom 106
5 chess 107
Example
Select * from student NATURAL JOIN game;
26
Equi join:
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 (=).
Syntax
SELECT column_list
FROM table1, table2....
WHERE table1.column_name =
table2.column_name;
Example
SELECT student.roll,student.sname,game.gname FROM student,game WHERE student.roll=game.roll;
Or
SELECT student.roll,student.sname,game.gname FROM student JOIN game ON student.roll=game.roll;
Roll sname game
101 aaa cricket
102 bbb volly ball
104 ddd cricket
NON EQUI JOIN performs a JOIN using comparison operator other than equal(=) sign like >, <, >=, <=
with conditions.
Syntax
SELECT column_list
FROM table1, table2....
WHERE table1.column_name >
table2.column_name;
Example
SELECT student.roll,student.sname,game.gname FROM student,game WHERE student.roll>game.roll;
27
Full outer join
The FULL OUTER JOIN keyword returns all records when there is a match in left (table1) or right
(table2) table records. Full outer join and full join are same
Syntax
SELECT cou
lmn_name(s)
FROM table1
FULL OUTER JOIN tabe l2
ON tabel1
.column_name= tabel.c2ou
lmn_name
WHERE condtion;
Example
select student.roll,student.sname,game.gname from student left join game on student.roll=game.roll
union
select student.roll,student.sname,game.gname from student right join game on student.roll=game.roll;
Result:
Thus the natural join, equi join and outer join queries are written and executed successfully.
28
Ex.No. :06 FUNCTIONS AND STORED PROCEDURES
Date :
Aim:
To Write a program using procedures and functions
Different from a stored procedure, you can use a stored function in SQL statements wherever an
expression is used. This helps improve the readability and maintainability of the procedural code.
syntax
The following illustrates the simplest syntax for creating a new stored function:
CREATE FUNCTION function_name(parameter 1,parameter 2,…)
RETURNS datatype
[NOT] DETERMINISTIC
Statements
Example
Executing function
select funcon('world');
# funcon('world')
'Hello, world!!'
29
Stored procedure
MySQL stored procedure using CREATE PROCEDURE statement. In addition, we will show you
how to call stored procedures from SQL statements.
syntax
DELIMITER //
CREATE PROCEDURE GetAllProducts()
BEGIN
SELECT * FROM products;
END //
DELIMITER ;
Example
30
SQL>select* from cus;
Result :
Thus the SQL functions and procedures are written and executed successfully.
31
Ex.No. :07 DCL AND TCL COMMANDS
Date :
Aim:
To study and execute various Data Control Language and Transaction Control Language
commands in SQL.
Procedure:
1: Start
2: Create the table with its essential attributes.
3: Insert the record into table
4: Execute the DCL commands GRANT and REVOKE
5: Execute the TCL commands COMMIT, SAVEPOINT and ROLLBACK.
6: Stop
DCL Commands.
DCL includes commands such as GRANT and REVOKE which mainly deal with the rights, permissions,
and other controls of the database system.
GRANT:
This command gives users access privileges to the database. For this first we have to create user.
MySQL stores the user account in the user grant table of the mysql database.
The CREATE USER statement in MySQL allows us to create new MySQL accounts or in other words,
the CREATE USER statement is used to create a database account that allows the user to log into the
MySQL database.
Syntax;
CREATE USER user_account IDENTIFIED BY password;
We have already learned about how to create users in MySQL using MySQL | create user statement. But
using the Create User Statement only creates a new user but does not grant any privileges to the user
account. Therefore to grant privileges to a user account, the GRANT statement is used.
Syntax:
32
Parameters Used in Grant Command
privileges_name: These are the access rights or privileges granted to the user.
object:It is the name of the database object to which permissions are being granted. In the case of
granting privileges on a table, this would be the table name.
user:It is the name of the user to whom the privileges would be granted.
Various privileges used are, SELECT, INSERT, DELETE, INDEX, UPDATE, CREATE, ALTER,
DROP, GRANT.
1. Granting SELECT Privilege to a User in a Table:
To grant Select Privilege to a table named “users” where User Name is root, the following GRANT
statement should be executed.
GRANT SELECT ON Users TO 'root'@'localhost;
4. SQL Grant command is specifically used to provide privileges to database objects for a user. This
command also allows users to grant permissions to other users too.
Syntax:
grant privilege_name on object_name
to {user_name | public | role_name}
Example
grant insert,
select on accounts to Ram
33
REVOKE:
This command withdraws the user’s access privileges given by using the GRANT command.
Revoke command withdraw user privileges on database objects if any granted. It does operations
opposite to the Grant command. When a privilege is revoked from a particular user U, then the
privileges granted to all other users by user U will be revoked.
Syntax:
REVOKE privilege_name on object_name
from {user_name | public | role_name}
Example
REVOKE insert,
select on accounts from Ram
34
SQL> insert into class values(1,'john');
SQL> insert into class values(2,'raj');
SQL> insert into class values(3,'rahman');
Let’s use some SQL queries on the above table and see the results.
Id sname
1 john
2 raj
3 rahman
5 abhijit
6 Chris
35
Now rollback to savepoint A
rollback to A;
SELECT * from class;
Id sname
1 john
2 raj
3 rahman
5 abhijit
Result:
Thus the Data Manipulation Language commands (insert, update, delete, retrieve) and TCL
commands are studied and executed successfully and output was verified.
36
Ex. No.:08 TRIGGERS
Date :
Aim:
To execute programs for insert, delete, and update operations in a database table using triggers.
MySQL trigger
A MySQL trigger is a stored program (with queries) which is executed automatically to respond to a specific
event such as insertion, updation or deletion occurring in a table.
In order to create a new trigger, you use the CREATE TRIGGER statement. The following illustrates the
syntax of the CREATE TRIGGER statement:
You put the trigger name after the CREATE TRIGGER statement. The trigger name should follow the
naming convention [trigger time]_[table name]_[trigger event], for example before_employees_update.
Trigger activation time can be BEFORE or AFTER. You must specify the activation time when you
define a trigger. You use the BEFORE keyword if you want to process action prior to the change is
made on the table and AFTER if you need to process action after the change is made.
The trigger event can be INSERT, UPDATE or DELETE. This event causes the trigger to be invoked. A
trigger only can be invoked by one event. To define a trigger that is invoked by multiple events, you
have to define multiple triggers, one for each event.
A trigger must be associated with a specific table. Without a table trigger would not exist therefore you
have to specify the table name after the ON keyword.
You place the SQL statements between BEGIN and END block. This is where you define the logic for
the trigger
Example
SQL> Create table account1(acct_num int,amount int)
SQL> insert into account1 values(1,150)
SQL> select * from account1
Acc_num amount
1 150
37
Trigger for update
DELIMITER $$
USE `sample1`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sample1`.`new_table_BEFORE_UPDATE`
BEFORE UPDATE ON `account1` FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END$$
DELIMITER ;
Acc_num amount
1 100
DELIMITER $$
USE `sample1`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sample1`.`bank_BEFORE_INSERT` BEFORE
INSERT ON `account1` FOR EACH ROW
BEGIN
IF NEW.amount < 0 THEN
SET NEW.amount = 0;
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END
$$
DELIMITER ;
Acc_num amount
1 100
2 0
38
Trigger for Delete
DELIMITER $$
USE `sample1`$$
CREATE DEFINER = CURRENT_USER TRIGGER `sample1`.`bank_BEFORE_DELETE` BEFORE
DELETE ON `account1` FOR EACH ROW
BEGIN
delete from account2 where acct_num=2;
END
$$
DELIMITER ;
Acc_num amount
1 100
2 0
Result
Thus the programs for insert, delete, and update operations in a database table using triggers is
created and executed successfully.
39
Ex.No.:09 VIEW AND INDEX
Date :
Aim:
To create and execute the View and Index for the large database and tables.
VIEWS:
SQL includes the ability to create stored queries that they can then be used as a basis for other queries.
These stored queries are also called views. A view is simply a derived table that is built upon the base
tables of the database. Base tables are the original database tables that actually contain data. Views do
not actually store data they are temporary tables. To define a view, we must give the view a name and
state the query that computes the view.
Syntax:
Create view v-name as <query expression>
Where query expression is any legal query expression and view name is represented
by v-name.( can give any name for view)
CREATING A VIEW:
The first step in creating a view is to define the defining query, which is the query on which the view is
based. While it is not required that the defining query be written before creating a view, it is generally a
good idea. Any errors in the query can be caught and corrected before the view is created.
SQL> create view V as select classa.sid, classa.sname, classa.sdept, classb.grade from classa, classb
where classa.sid=classb.id order by classa.sid;
View created.;
40
SID SNAME SDEPT GRADE
1 aarthi IT B
2 ezhil ECE B
Index
An index is a schema object. It is used by the server to speed up the retrieval of rows by using a pointer.
It can reduce disk I/O(input/output) by using a rapid path access method to locate data quickly. An index
helps to speed up select queries and where clauses, but it slows down data input, with the update and the
insert statements. Indexes can be created or dropped with no effect on the data. In this article, we will
see how to create, delete, and uses the INDEX in the database.
CREATE INDEX
Syntax
CREATE INDEX index_name ON table_name (column1, column2, ...);
Example
SQL> select * from cus;
Cid cname address salary post
1 aa 77,anna salai,arcot 10500 clerk
3 bb 01,anna salai,chennai 15500 staff
2 cc 25,rajaji nagar,banglore 15500 staff
4 dd 02,mettu street,kochin 10500 secretary
5 ee 21,north street,mumbai 15500 manager
41
Unique Indexes:
Unique indexes are used for the maintenance of the integrity of the data present in the table as well as
for fast performance, it does not allow multiple values to enter into the table.
Syntax:
Delete index
Remove an index from the data dictionary by using the DROP INDEX command.
Syntax:
Result :
Thus the view and index for a large database and table is created and executed successfully.
42
Ex. No. 10 XML DATABASE AND VALIDATE IT USING XML SCHEMA
Date :
Aim
Creating XML database and validate it using XML schema.
Procedure
XML
Xml (eXtensible Markup Language) is a mark up language.
XML is designed to store and transport data.
Xml was released in late 90’s. it was created to provide an easy to use and store self
describing data.
XML became a W3C Recommendation on February 10, 1998.
XML is not a replacement for HTML.
XML is designed to be self-descriptive.
XML is designed to carry data, not to display data.
XML tags are not predefined. You must define your own tags.
XML is platform independent and language independent.
XML Schema
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and
validate the structure and the content of XML data. XML schema defines the elements, attributes and
data types. Schema element supports Namespaces. It is similar to a database schema that describes the
data in a database.
Java XML Validation API can be used to validate XML against an XSD. javax.xml.validation.Validator
class is used in this program to validate xml file against xsd file.Here are the sample XSD and XML
files used.
Employee.xsd
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.journaldev.com/Employee"
xmlns:empns="http://www.journaldev.com/Employee" elementFormDefault="qualified">
<element name="empRequest" type="empns:empRequest"></element>
<element name="empResponse" type="empns:empResponse"></element>
<complexType name="empRequest">
<sequence>
<element name="id" type="int"></element>
</sequence>
</complexType>
<complexType name="empResponse">
43
<sequence>
<element name="id" type="int"></element>
<element name="role" type="string"></elemen>
<element name="fullName" type="string"></element>
</sequence>
</complexType>
</schema>
Notice that above XSD contains two root element and namespace also, I have created two sample XML
file from XSD.
Employee Request.xml
EmployeeResponse.xml
employee.xml
<?xml version="1.0"?>
<Employee>
<name>Pankaj</name>
<age>29</age>
<role>Java Developer</role>
<gender>Male</gender>
</Employee>
Here is the program that is used to validate all three XML files against the XSD. The
validateXMLSchema method takes XSD and XML file as argument and return true if validation is
successful or else returns false.
44
XMLValidation.java
package com.journaldev.xml;
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XMLValidation {
public static void main(String[] args) {
System.out.println("EmployeeRequest.xml validates against Employee.xsd?
"+validateXMLSchema("Employee.xsd", "EmployeeRequest.xml"));
System.out.println("EmployeeResponse.xml validates against Employee.xsd?
"+validateXMLSchema("Employee.xsd", "EmployeeResponse.xml"));
System.out.println("employee.xml validates against Employee.xsd?
"+validateXMLSchema("Employee.xsd", "employee.xml"));
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException | SAXException e) {
System.out.println("Exception: "+e.getMessage());
return false;
}
return true;
}
}
RESULT:
Thus the XML database created and validates it using XML schema
45
Ex. No.: 11 NOSQL DATABASE TOOLS
Date :
Aim:
To create the document, columns and graphs based on data by using NoSQL tools.
Procedure :
Document database
A document database (also known as a document-oriented database or a document store) is a database
that stores information in documents.
A document is a record in a document database. A document typically stores information about one
object and any of its related metadata.
Documents store data in field-value pairs. The values can be a variety of types and structures, including
strings, numbers, dates, arrays, or objects. Documents can be stored in formats like JSON, BSON, and
XML.
Below is a JSON document that stores information about a user named Tom.
{
"_id": 1,
"first_name": "Tom",
"email": "[email protected]",
"cell": "765-555-5555",
"likes": [
"fashion",
"spas",
"shopping"
],
"businesses": [
{
"name": "Entertainment 1080",
"partner": "Jean",
"status": "Bankrupt",
"date_founded": {
"$date": "2012-05-19T04:00:00Z"
}
},
{
"name": "Swag for Tweens",
"date_founded": {
"$date": "2012-11-01T04:00:00Z"
}
}
]
}
46
Collections
A collection is a group of documents. Collections typically store documents that have similar contents.
Continuing with the example above, the document with information about Tom could be stored in a
collection named users. More documents could be added to the users collection in order to store
information about other users. For example, the document below that stores information about Donna
could be added to the users collection.
{
"_id": 2,
"first_name": "Donna",
"email": "[email protected]",
"spouse": "Joe",
"likes": [
"spas",
"shopping",
"live tweeting"
],
"businesses": [
{
"name": "Castle Realty",
"status": "Thriving",
"date_founded": {
"$date": "2013-11-21T04:00:00Z"
}
}
]
}
Row-Oriented Table:
47
S.No. Name Course Branch ID
01. Tanmay 2
02. Abhishek 5
03. Samriddha 7
04. Aditi 8
Graph Based Data Model in NoSQL is a type of Data Model which tries to focus on building the
relationship between data elements. As the name suggests Graph-Based Data Model, each element here
is stored as a node, and the association between these elements is often known as Links. Association is
stored directly as these are the first-class elements of the data model. These data models give us a
conceptual view of the data.
These are the data models which are based on topographical network structure. Obviously, in graph
theory, we have terms like Nodes, edges, and properties, let’s see what it means here in the Graph-Based
data model.
Nodes: These are the instances of data that represent objects which is to be tracked.
Edges: As we already know edges represent relationships between nodes.
Properties: It represents information associated with nodes.
The below image represents Nodes with properties from relationships represented by edges.
48
Result :
Thus we studied the various NoSQL database tools to create document, column and graph
successfully.
49
Ex.No.12 SIMPLE GUI APPLICATION
Date : (DISPLAYING STUDENT MARK LIST)
Aim:
Write a program in Java to create Displaying student mark listusing JSP and Databases (three tire
architecture).
Presentation tier encapsulates the presentation logic required to serve clients. A JSP in the presentation
tier intercepts client requests, manages logons, sessions, accesses the business services, and finally
constructs a response, which gets delivered to client.
Business tier provides the business services. This tier contains the business logic and the business data.
All the business logic is centralized into this tier as opposed to 2-tier systems where the business logic is
scattered between the front end and the backend. The benefit of having a centralized business tier is that
same business logic can support different types of clients like browser, WAP (Wireless Application
Protocol) client. In our exercise we will use servlet as business tier.
Data Tier
Data tier is used by the databases
JSP
Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
platform-independent method for building Web-based applications. JSP have access to the entire family
of Java APIs, including the JDBC API to access enterprise databases
Servlet
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to
requests from Web clients, usually across HTTP, the HyperText Transfer Protocol
zs
Client:
Step1: In index.html on the client side declare the contents that you like to transfer to the server using
html form and input type tags.
Step2: create a submit button and close all the included tags.
Servlet:
Step 1: Import all necessary packages
Step 2: Define a class that extends servlet
Step 3: In the doPost() method, do the following:
i) Set the content type of the response to "text/html"
ii) connect with the database which has the student marklist
iii) query the data to the database
Step 4: Display the student marklist
50
First Create database as db8 in that create table as mark with the following field
index.html
<head>
<title>Three Tier Application</title>
<style type="text/css">
body{color:blue;font-family:courier;text-align:center}
</style>
</head>
<body>
<h2>EXAMINATION RESULT</h2><hr/>
<form name="f1" method="GET" action="marklist.jsp">
Enter Your Reg.No:
<input type="text" name="rno"/><br/><br/>
<input type="submit" value="SUBMIT"/>
</form>
</body>
</html>
<html>
Marklist.jsp
<%@page import="java.util.Properties"%>
<%@page contentType="text/html" language="java" import="java.sql.*"%>
<html>
<head>
<title>Three Tier Application</title>
<style type="text/css">
body{color:blue;font-family:courier;text-align:center}
</style>
</head>
<body>
<h2>EXAMINATION RESULT</h2><hr/>
<%
String str=request.getParameter("rno");
Class.forName("org.apache.derby.jdbc.ClientDriver");
Properties p=new Properties();
p.put("user","root");
51
p.put("password","root");
Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/db8",p);
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery( " Select * FROM mark WHERE rno ='"+str+"'");
while(rs.next())
{
%>
Register No:<%=rs.getString(1)%><br/>
Name:<%=rs.getString(2)%><br/>
<table border="1">
<th>SUBJECT</th><th>Mark</th>
<tr><td>DBMS</td><td><%=rs.getString(3)%></td></tr>
<tr><td>TOC</td><td><%=rs.getString(4)%></td></tr>
<tr><td>AI</td><td><%=rs.getString(5)%></td></tr>
<tr><td>OS</td><td><%=rs.getString(6)%></td></tr>
<tr><td>Algorithms</td><td><%=rs.getString(7)%></td></tr>
<tr><td>EVS</td><td><%=rs.getString(8)%></td></tr>
</table>
<%
}
%>
<br/>
<a href="index.jsp">Back</a>
</body>
</html>
52
Output
Result :
Thus the program is created for displaying examination result and successfully verified
53
Ex. No. 13 CASE STUDY OF COP FRIENDLY APP – ESEVA
Date :
Aim
To case Study of Cop Friendly APP –Eseva
Problem Statement
India is known as the world's largest democratic country, little is known about how it polices such a vast,
complex, and unpredictable country. As a result, police officers encounter challenges and barriers in
carrying out their duties on a daily basis. Some of the problems faced are
The police leadership has not placed a high priority on using technology to deliver services to
citizens.
Investigations are being delayed due to a lack of collaboration between internal divisions.
The training standards are quite inadequate and do not account for the use of new technology.
54
There is a significant disparity between the rate at which crimes are committed and the rate
at which FIRs are filed.
The workload is one of the key causes of police inefficiency once again.
Conclusive Summary
The case study shows how as the rate of crime rises; the utilization of existing Artificial Intelligence
algorithms is proving to be extremely beneficial. The tool developed by Sapio Analytics along with
Dinosys Infotech- SMART COP sets a promising example. To a considerable extent, Smart Cop aids in
the prediction of crime as well as the criminal. Artificial intelligence has the potential to become a
permanent element of the criminal justice system. Technological reforms are required to accomplish the
vision of SMART policing, it's important to train the police for new challenges, and strengthen their
investigative and emergency response capabilities. This will eventually increase public confidence in the
police force's effectiveness and its ability to serve efficiently. The police force must be eager to bring a
change and adopt new-age technologies and systems into the realm of law enforcement for it to be more
proactive than reactive.
55
INVENTORY MANAGEMENT SYSTEM
PROBLEM STATEMENT:
INVENTORY MANAGEMENT SYSTEM is a real time application used in the
merchant’s day to day system. This is a database to store the transaction that takes places between the
Manufacturer, Dealer and the Shop Keeper that includes stock inward and stock outward with reference
to the dealer. Here we assume our self as the Dealer and proceed with the transaction as follows:
The Manufacturer is the producer of the items and it contains the necessary information
of the item such as price per item, Date of manufacture, best before use, Number of Item available and
their Company Address.
The Dealer is the secondary source of an Item and he purchases Item from the
manufacturer by requesting the required Item with its corresponding Company Name and the Number of
Items required. The Dealer is only responsible for distribution of the Item to the Retailers in the Town or
City.
The Shop Keeper or Retailer is the one who is prime source for selling items in the market. The
customers get Item from the Shop Keeper and not directly from the Manufacturer or the Dealer.
The Stock is the database used in our System which records all transactions that takes
place between the Manufacturer and the Dealer and the Dealer and the Retailer.
CODING:
FORM1
Dim db As Database
Dim rs As Recordset
End Sub
56
FORM2
Dim db As Database
Dim rs As Recordset
Dim i As Integer
57
rs(0) = Text1.Text
rs(1) = Text2.Text
rs(2) = Text3.Text
rs(3) = Text4.Text
rs(4) = Text5.Text
rs(5) = Text6.Text
rs(6) = Text7.Text
rs(7) = Text8.Text
rs.Update
End Sub
FORM3
Dim db As Database
Dim rs As Recordset
Dim i As Integer
58
rs.Edit
If Text4.Text = "" Then
MsgBox "Enter the no of items needed"
Else
rs(6) = Text4.Text
If rs(6) <= rs(4) Then
rs(7) = rs(5) * rs(6)
rs(4) = rs(4) - Val(Text4.Text)
Text2.Text = rs(4)
Text5.Text = rs(7)
Else
MsgBox " ITEM NOT SUFFICIENT"
End If
rs.Update
GoTo l1
End If
End If
rs.MoveNext
Next i
l1: End Sub
59
Text2.Text = rs(4)
Text3.Text = rs(5)
Text4.Text = ""
Text5.Text = ""
End If
rs.MoveNext
Next i
End Sub
FORM4
Dim db As Database
Dim rs As Recordset
Dim r, i As Integer
MSFlexGrid1.FixedRows = 0
MSFlexGrid1.FixedCols = 0
r=0
MSFlexGrid1.ColWidth(0) = 2000
MSFlexGrid1.ColWidth(1) = 2000
MSFlexGrid1.ColWidth(2) = 2000
MSFlexGrid1.ColWidth(3) = 1700
MSFlexGrid1.ColWidth(4) = 1750
MSFlexGrid1.ColWidth(5) = 1650
'MSFlexGrid1.ForeColor = "GREEN"
MSFlexGrid1.TextMatrix(0, 0) = "COMPANY NAME"
MSFlexGrid1.TextMatrix(0, 1) = "COMPANY ADDRESS"
MSFlexGrid1.TextMatrix(0, 2) = "CONTACT NUMBER"
MSFlexGrid1.TextMatrix(0, 3) = "DATE OF ORDER"
MSFlexGrid1.TextMatrix(0, 4) = "ITEMS AVAILABLE"
MSFlexGrid1.TextMatrix(0, 5) = "PRICE/ITEM"
rs.MoveFirst
r=1
Do Until rs.EOF
60
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 0
MSFlexGrid1.Text = rs(0)
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 1
MSFlexGrid1.Text = rs(1)
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 2
MSFlexGrid1.Text = rs(2)
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 3
MSFlexGrid1.Text = rs(3)
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 4
MSFlexGrid1.Text = rs(4)
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 5
MSFlexGrid1.Text = rs(5)
MSFlexGrid1.FixedRows = r
MSFlexGrid1.FixedCols = 6
'MSFlexGrid1.Text = rs(6)
'MSFlexGrid1.FixedRows = r
'MSFlexGrid1.FixedCols = 7
'MSFlexGrid1.Text = rs(7)
r=r+1
rs.MoveNext
Loop
End Sub
61
FORMS
62
FORM3 : SALES DETAILS
63