Cs3481 - Dbms Lab Manual
Cs3481 - Dbms Lab Manual
Cs3481 - Dbms Lab Manual
No : 01 DDL COMMANDS
Date :
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.
Example:
Table created.
Alter Table
Syntax:
Example:
2
Name Null? Type
Truncate Table
Syntax:
Example:
SQL> Truncate table Student;
3
Table truncated.
Rename
Syntax
Drop Table
Syntax:
Table dropped.
AIM:
To Study and Practice Insertion, Deletion, Modifying, Altering, Updating and Viewing records based on
conditions in RDBMS.
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:
SQL> Create table Student(Stud_name char(20), Stud_id varchar2(10), Stud_ dept varchar2(20),
Stud_age number(5));
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’,…..);
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:
6
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:
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:
8
RESULT:
Thus the DDL and DML command Insertion, Deletion, Modifying, Altering, Updating and
Viewing records based on conditions using SQL commands were executed and verified successfully.
9
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,
…………….
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:
Check constraint specify conditions that each tuple must satisfy.
Syntax:
Create table tablename(
Fieldname1 datatype(constraint),
Fieldname2 datatype,
………………….
Fieldname3 datatype);
Example:
SQL> create table con ( empid decimal(10) not null, empname varchar(20),empsalary decimal(10),
check(empsalary>10000));
11
SQL>insert into con values (‘1’,’kumar’,’20000’)
1 row created
UNIQUE:
Used to set unique constraint to the specified column name which will not allow redundant
values
Syntax:
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.
12
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),
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’)
13
ADD CONSTRAINT (ALTER)
Used to set the constraint for the table already created by using alter command.
Syntax:
Alter table tablename add constraint constraintname (fieldname)datatype,primary key.
Example:
SQL> create table con(empid varchar(10),empname varchar(10));
Table created.
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.
Example:
SQL> alter table con drop constraint c1;
Table altered.
14
Name Null? Type
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.
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.
16
ENO ENAME
2 a
SQL> delete from parent where eno=1;
1 row deleted.
SQL> select * from parent;
no rows selected
SQL> select * from child;
no rows selected
17
Result
Thus the various key constraints based on foreign key where written and executed successfully.
18
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
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;
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
21
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);
Example
SQL>select * from student1 where stud_dept in ('cse', 'mech');
Not like:
Syntax:
22
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
FROM table_name
WHERE condition);
The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or <=).
Example
23
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.
24
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.
26
Ex.no. : 04
Date :
Sub Quires and Join Operations
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’;
27
STUD_NAME STUD_ID STUD_DEPT STUD_ROLLNO
Ram 101 MECH 104
OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
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 ;
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
29
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
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
30
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
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
32
Result
Thus the SQL sub queries, nested queries and various join operation queries are written and
executed successfully.
33
Ex. No. : 05
Date :
Natural, equi and outer joins
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
34
Select * from student NATURAL JOIN game;
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
35
SELECT student.roll,student.sname,game.gname FROM student,game WHERE student.roll>game.roll;
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 column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
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;
36
Result:
Thus the natural join, equi join and outer join queries are written and executed successfully.
37
Ex.No. :06
Date :
Functions and Stored Procedures
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
38
select funcon('world');
# funcon('world')
'Hello, world!!'
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
39
Creating stored procedure
USE `sample1`;
DROP procedure IF EXISTS `new_pro`;
DELIMITER $$
USE `sample1`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `new_pro`()
BEGIN
UPDATE cus
SET salary = salary + 500;
END$$
DELIMITER ;
40
Result :
Thus the SQL functions and procedures are written and executed successfully.
41
Ex.No. :07
Date :
DCL and TCL Commands
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;
42
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:
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;
43
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
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
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
Id sname
1 john
2 raj
3 rahman
5 abhijit
46
Result:
Thus the Data Manipulation Language commands (insert, update, delete, retrieve) and TCL
commands are studied and executed successfully and output was verified.
47
Ex. No.:08
Date :
Triggers
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
48
Acc_num amount
1 150
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;
49
ELSEIF NEW.amount > 100 THEN
SET NEW.amount = 100;
END IF;
END
$$
DELIMITER ;
Acc_num amount
1 100
2 0
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
50
Result:
Thus the programs using trigger was executed and verified successfully
51
View and Index
EX NO: 9
Date:
AIM
To execute and verify the SQL commands for Views and Index.
PROCEDURE
STEP 1: Start
STEP 2: Create the table with its essential attributes.
STEP 3: Insert attribute values into the table.
STEP 4: Create the view from the above created table.
STEP 5: Execute different Commands and extract information from the View.
STEP 6: Stop
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:
1 aarthi IT 450
52
3 sakthi IT 900
7 viji IT 900
6 rows selected.
ID NAME GRADE
---------- ---------- ----------
1 aarthi b
2 ezhil b
6 sumathi a
7 viji a
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> select classa.sid, classa.sname, classa.sdept, classb.name1 from classa, classb where
classa.sid=classb.id order by classa.sid;
SID SNAME SDEPT Name1
Another useful feature available when creating a view is that columns can be renamed
in the CREATE VIEW statement. The new column names only apply to the views, the column
names in the base tables do not change.
Query:
ID DEPT
---------- ----------
1 IT
2 ECE
3 IT
4 ECE
5 IT
54
6 ECE
6 rows selected.
Query:
SQL> select * from classa
# sid, sname, sdept, total
'1', 'john', 'it', '100'
'2', 'raj', 'it', '200'
'3', 'rahman', 'it', '300'
'4', 'joseph', 'it', '400'
'5', 'ram', 'it', '600'
SQL> create view student_count_min(sno,count) as select min(total),count(total)from
classa;
View created.
SQL> select *from student_count_min;
# sno, count
'100', '5'
SQL> create view student_sum_avg(tot,avgtotal)as select sum(total),avg(total) from classa;
View created.
SQL> select * from student_sum_avg;
# tot, avgtotal
'1600', '320.0000'
View created.
55
SQL> select * from stud_max;
# tot
'600'
CREATE INDEX
The CREATE INDEX command is used to create indexes in tables (allows duplicate
values).
Indexes are used to retrieve data from the database very fast. The users cannot see
the indexes, they are just used to speed up searches/queries.
DROP INDEX
DROP INDEX index_name;
DROP INDEX dup_name;
56
RESULT:
Thus the SQL commands for View and Index has been executed successfully and output was
verified.
57
EX. NO: 10 XML database and validate it using XML schema
Date:
Aim
Creating XML database and validate it using XML schema
Procedure
XML
o Xml (eXtensible Markup Language) is a mark up language.
o XML is designed to store and transport data.
o Xml was released in late 90’s. it was created to provide an easy to use and store self
describing data.
o XML became a W3C Recommendation on February 10, 1998.
o XML is not a replacement for HTML.
o XML is designed to be self-descriptive.
o XML is designed to carry data, not to display data.
o XML tags are not predefined. You must define your own tags.
o 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
58
class is used in this program to validate xml file against xsd file.Here are the sample XSD and XML files
used.
Employee.xsd
EmployeeRequest.xml
<empns:empRequest xmlns:empns="http://www.journaldev.com/Employee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.journaldev.com/Employee Employee.xsd ">
59
EmployeeResponse.xml
<empns:empResponse xmlns:empns="http://www.journaldev.com/Employee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.journaldev.com/Employee Employee.xsd ">
<empns:id>1</empns:id>
<empns:role>Developer</empns:role>
<empns:fullName>Pankaj Kumar</empns:fullName>
</empns:empResponse>
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.
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;
60
import org.xml.sax.SAXException;
public class XMLValidation {
public static void main(String[] args) {
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
System.out.println("Exception: "+e.getMessage());
return false;
return true;
61
}
62
RESULT:
Thus the XML database created and validates it using XML schema
63
Ex.No 11 Displaying student mark list
Date:
Aim:
Write a program in Java to create Displaying student mark listusing JSP and Databases (three tire
architecture).
Three tier architecture is a very common architecture. A three tier architecture is typically split into a
presentation or GUI tier, an application logic tier, and a data tier.
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
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
64
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
First Create database as db8 in that create table as mark with the following field
create table mark(rno varchar(20),name1 varchar(20),m1 varchar(20),m2 varchar(20),m3
varchar(20),m4 varchar(20),m5 varchar(20),m6 varchar(20))
insert into mark values('100','mohammed','90','90','90','90','90','90')
select * from mark
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>
65
<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");
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>NPM</td><td><%=rs.getString(3)%></td></tr>
<tr><td>OOAD</td><td><%=rs.getString(4)%></td></tr>
<tr><td>CNS</td><td><%=rs.getString(5)%></td></tr>
<tr><td>Es</td><td><%=rs.getString(6)%></td></tr>
<tr><td>Web Technology</td><td><%=rs.getString(7)%></td></tr>
<tr><td>UID</td><td><%=rs.getString(8)%></td></tr>
</table>
<%
}
%>
<br/>
<a href="index.jsp">Back</a>
</body>
</html>
66
Output:
67
68
Result
Thus the program is created for displaying examination result and successfully verified
69
Ex.No 12 Case Study of Cop Friendly App – Eseva
Date:
Aim
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.
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
The fundamental function of police forces is to uphold and investigate crimes, safeguard the safety of
citizens, and enforce laws. In a large and populous country like India, police forces must be well-
equipped to fulfill their duties effectively. As a result, the police force must adjust to changing
conditions. Police modernization has been needed for data protection, counterterrorism/insurgency, and
reliance on technology for policing. This necessitates more investment in technological advancement
and modernization. So, to solve the problem in a modern way Sapio Analytics Came up with Smart Cop
which aims to train the law enforcement agencies on emerging technology, mitigating cybercrimes,
enhancing their skill set as well as capacity building so that they are combatready in a real-time basis.
The Smart Cop is an essential guarantee to modernize the police to manage local security. It will also
emphasize the new exigencies of the police management system.
The main aim of Smart Cop is to digitize the whole functioning of beats. In the due process, we
facilitated the beat police with one application and have integrated the IT applications and databases
which are in line with the beat system, and converged them on to Smart Cop
Effectively utilizing Information and Communication Technology (ICT) traversing from E-Governance to
M-Governance
Empowering and delegating the frontline Beat Police Officers for demonstrating quick & smart decision
making
Delivering Services 'Anytime & Anywhere' for faster response to the Citizens
Seamless integration of different application functionalities through Single-Sign-On services
71
Efficient identification and tracking of suspects, quicker resolution of cases, and increased rate of
convictions for the offenders
Proactively preventing crimes through real-time intelligence inputs and analysis relating to crimes and
criminals
Encouraging transparency and accountability in every police personnel
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.
72