0% found this document useful (0 votes)
3 views97 pages

Dbms Faculty Manuval

The document is a faculty lab manual for a Database Management Systems course at NPR College of Engineering & Technology, outlining the vision and mission of the department, program educational objectives, and a comprehensive list of experiments to be conducted. It includes details on SQL commands, course objectives, outcomes, and mappings of course outcomes to program outcomes. The manual aims to equip students with the necessary skills and knowledge to excel in the field of Information Technology.

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views97 pages

Dbms Faculty Manuval

The document is a faculty lab manual for a Database Management Systems course at NPR College of Engineering & Technology, outlining the vision and mission of the department, program educational objectives, and a comprehensive list of experiments to be conducted. It includes details on SQL commands, course objectives, outcomes, and mappings of course outcomes to program outcomes. The manual aims to equip students with the necessary skills and knowledge to excel in the field of Information Technology.

Uploaded by

Senthil Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 97

DEPARTMENT OF INFORMATION TECHNOLOGY

Semester IV

CS3481-DATA BASE MANAGEMENT SYSTEMS LABORATORY

Faculty Lab Manual


Regulation 2021
NPR COLLEGE OF ENGINEERING& TECHNOLOGY, NATHAM

VISION

 To develop students with intellectual curiosity and technical expertise to meet the global needs.

MISSION

 To achieve academic excellence by offering quality technical education using


best teaching techniques.
 To improve Industry– Institute interactions and expose industrial atmosphere.
 To develop interpersonal skills along with value based education in a dynamic
learning environment.
 To explore solutions for real time problems in the society.
NPR COLLEGE OF ENGINEERING & TECHNOLOGY, NATHAM

DEPARTMENT OF INFORMATION TECHNOLOGY

VISION
 To cultivate a generation of globally competitive IT professionals who are equipped with
the knowledge, skills, and adaptability to flourish amidst technological advancements.
MISSION
 To achieve academic excellence in Information Technology by fostering a dynamic learning
environment that seamlessly integrates innovative computing methodologies into the teaching
and learning process
 To create a nurturing environment for students to develop professionalism, ethical awareness,
and social responsibility while adapting to evolving programming paradigms.
 To foster industry-institute collaboration that leverages emerging technologies and
programming expertise, aligning them with global standards and industry expectations

PROGRAM EDUCATIONAL OBJECTIVES

Graduates of information technology Program will be able to:

 Demonstrate technical competence with analytical and critical thinking to understand and meet
the diversified requirements of industry, academia, and research.
 Exhibit technical leadership, team skills, and entrepreneurship skills to provide business solutions to
real- world problems.
 Work in multi-disciplinary industries with social and environmental responsibility, work ethics,
and adaptability to address complex engineering and social problems.
 Pursue lifelong learning, use cutting-edge technologies, and be involved in applied research to
design optimal solutions
List of Experiments with COs, POs and PSOs

Exp. Name of the Experiment COs POs PSOs


No.
Create a database table, add
1 constraints (primary key, 1 1,2,4,5,8,9,10,12 1 &2
unique, check, Not null),
insert rows, update and
delete
rows using SQL DDL and
DML commands.
Create a set of tables, add foreign 1 1,2,3,8,9,10,12
2 key constraints and incorporate 1 &2
referential integrity.
Query the database tables using 2
3 different ‘where’ clause 1,2,3,8,9,10,12 1 &2
conditions and also
implement aggregate functions.
Query the database tables and
4 explore sub queries and 2 1,2,3,8,9,10,12 1 &2
simple join operations.

Query the database tables


5 and explore natural, 2,3 1,2,3,8,9,10,12 1 &2
equi and outer joins.
Write user defined functions and
6 stored procedures in SQL. 2,3,4,5 1,2,3,8,9,10,12 1 &2

7 Execute complex transactions and 4&5 1,2,3,8,9,10,12 1 &2


realize DCL and TCL commands.

8 Write SQL Triggers for insert, 3&5 1,2,3,8,9,10,12 1 &2


delete, and update operations in a
database table.

9 Create View and index for database 3 1,2,3,8,9,10,12 1 &2


tables with a large number of
records.

10 Create an XML database and validate 3 1,2,3,8,9,10,12 1 &2


it using XML schema.

11 Create Document, column and graph 4,5 1,2,3,8,9,10,12 1 &2


based data using NOSQL database
tools.
12 Develop a simple GUI based 5 1,2,3,8,9,10,12 1 &2
database application and incorporate
all the above mentioned features
Customer.
• Ability to showcase ACID
Properties with sample queries with
appropriate settings
13 Case Study using any of the real
life database applications from
the following list 1&5 1,2,3,4,5,6,9,11,12 1 &2

a) Inventory Management for


a EMart Grocery Shop
b) Society Financial Management

c) Cop Friendly App – E-seva


d) Property Management – e-Mall

e) Star Small and


Medium Banking and
Finance
• Build Entity Model diagram.
The diagram should align with
the business and functional
goals stated in the application.
• Apply Normalization rules in
designing the tables in
scope.
• Prepared applicable views,
triggers (for auditing purposes),
and functions for enabling
enterprise grade features.
• Build PL SQL / Stored
Procedures for
Complex
Functionalities, ex EOD
Batch Processing for calculating
the EMI for Gold Loan for
each eligible

`
Program Outcomes

1. Engineering Knowledge 7.Environment and Sustainability


2. Problem Analysis 8.Ethics
3. Design/Development of Solutions 9. Individual and Team Work
4. Conduct Investigations of Complex Problems 10.Communication
5. Modern Tool Usage 11.Project Management and Finance
6. The Engineer and Society 12. Life-long Learning

Program Specific Outcomes

At the end of the program students will be able to

 Have proficiency in programming skills to design, develop and apply appropriate techniques, to solve
complex engineering problems.

 Have the knowledge to build, automate, and manage business solutions using cutting-edge technologies.

 Have excitement about research in applied computer technologies.


lOMoARcPSD|39705338

LIST OF EXPERIMENTS

1. Create a database table, add constraints (primary key, unique, check, Not null),
insert rows, update and delete rows using SQL DDL and DML commands.
2. Create a set of tables, add foreign key constraints and incorporate referential integrity.
3. Query the database tables using different ‘where’ clause conditions and
also implement aggregate functions.
4. Query the database tables and explore sub queries and simple join operations.
5. Query the database tables and explore natural, equi and outer joins.
6. Write user defined functions and stored procedures in SQL.
7. Execute complex transactions and realize DCL and TCL commands.
8. Write SQL Triggers for insert, delete, and update operations in a database table.
9. Create View and index for database tables with a large number of records.
10. Create an XML database and validate it using XML schema.
11. Create Document, column and graph based data using NOSQL database tools.
12. Develop a simple GUI based database application and incorporate all the
above- mentioned features
13. Case Study using any of the real life database applications from the following list
a) Inventory Management for a EMart Grocery Shop
b) Society Financial Management
c) Cop Friendly App – Eseva
d) Property Management – eMall
e) Star Small and Medium Banking and Finance
 Build Entity Model diagram. The diagram should align with the
business and functional goals stated in the application.
 Apply Normalization rules in designing the tables in scope.
 Prepared applicable views, triggers (for auditing
purposes), functions for enabling enterprise grade features.
 Build PL SQL / Stored Procedures for Complex Functionalities, ex EOD
Batch Processing for calculating the EMI for Gold Loan for each eligible
Customer.
 Ability to showcase ACID Properties with sample queries with appropriate
settings
lOMoARcPSD|39705338

Course Objectives & Course Outcomes

COURSE OBJECTIVES:

 To learn and implement important commands in SQL.


 To learn the usage of nested and joint queries.
 To understand functions, procedures and procedural extensions of databases.
 To understand design and implementation of typical database applications.
 To be familiar with the use of a front end tool for GUI based
application development.

COURSE OUTCOMES:
At the end of this course, the students will be able to:

CO1: Create databases with different types of key constraints.


CO2: Construct simple and complex SQL queries using DML and DCL commands.
CO3: Use advanced features such as stored procedures and triggers and
incorporate in GUI based application development.
CO4: Create an XML database and validate with meta-data (XML schema).
CO5: Create and manipulate data using NOSQL database.

CO’s- PO’s & PSO’s MAPPING


CO’s PO’s PSO’s
1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
1 3 3 3 3 - - - - 3 1 3 2 2 3 2
2 2 2 3 2 2 - - - 1 2 3 3 2 1 2
3 3 3 2 1 1 - - - 1 1 1 3 2 3 3
4 1 3 3 3 1 - - - 1 1 3 2 3 1 3
5 3 2 1 1 1 - - - 2 2 3 1 3 1 2
Avg. 2 3 2 2 1 - - - 2 1 3 2 2 2 2
1 - low, 2 - medium, 3 - high, ‘-“- no correlation
lOMoARcPSD|39705338
lOMoARcPSD|39705338

EX: NO: 1
CREATION OF TABLES (DDL COMMANDS)

AIM:

To execute and verify the Data Definition Language commands.

Description:
SQL Command Categories

SQL commands are grouped into four major categories depending on their
functionality. They are as follows:

Data Definition Language (DDL)

These SQL commands are used for creating, modifying, and dropping the
structure of database objects. The commands are CREATE, ALTER, DROP, RENAME,
and TRUNCATE.

Data Manipulation Language (DML)

These SQL commands are used for storing, retrieving, modifying, and
deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.

Transaction Control Language (TCL)

These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK, and SAVEPOINT.

Data Control Language (DCL)

These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.

DDL (DATA DEFINITION LANGUAGE)

 CREATE
 ALTER
 DROP
 TRUNCATE
 RENAME

PROCEDURE

STEP 1: Start
STEP 2: Create the table with its essential attributes.
STEP 3: Execute different Commands and extract information from the table.
lOMoARcPSD|39705338

STEP 4: Stop

SQL COMMANDS

1. COMMAND NAME: CREATE


COMMAND DESCRIPTION: CREATE command is used to create objects in the
database.

CREATE <OBJ.TYPE> <OBJ.NAME> (COLUMN NAME.1<DATATYPE>


(SIZE), COLUMN NAME.1 <DATATYPE> (SIZE)......................);

Syntax For Create A from an Existing Table With All Fields

CREATE TABLE <TARGET TABLE NAME> AS SELECT * FROM <SOURCE TABLE


NAME>;

2. COMMAND NAME: DROP


COMMAND DESCRIPTION: DROP command is used to delete the object from the
database.

Syntax for drop a new column:

ALTER TABLE <TABLE NAME> DROP COLUMN <COLUMN NAME>;

Syntax for drop a table:

Drop table <tablename>;

3. COMMAND NAME: TRUNCATE


COMMAND DESCRIPTION: TRUNCATE command is used to remove all the records
from the table

Syntax truncating the tables.


Truncate table <tablename>;

4. COMMAND NAME: ALTER


COMMAND DESCRIPTION: ALTER command is used to alter the structure of
database.

ALTER <TABLE NAME> MODIFY <COLUMN NAME> <DATATYPE>(SIZE);

Syntax for alter table with multiple column:

SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME1> <DATATYPE>


lOMoARcPSD|39705338

(SIZE), MODIFY <COLUMN NAME2> <DATATYPE> (SIZE)…….;

Syntax for add a new column:

SQL> ALTER TABLE <TABLE NAME> ADD (<COLUMN NAME1> <DATA


TYPE> <SIZE>,<COLUMN NAME2> <DATA TYPE> <SIZE>,
............................................................................................................................................... )
;

5. COMMAND NAME: RENAME


COMMAND DESCRIPTION: RENAME command is used to rename the objects.

Syntax For Renaming A table

Rename table <oldname> To <newname>;

Syntax For Renaming A Column

ALTER TABLE tablename RENAME COLUMN old column name TO new column
name;

Data base commands:


Create database: create database <databasename>;
Show database: show databases;
Use: use <databasename>;
Show table: show tables;
Description of a table: desc <tablename>;

QUERY: 01
Q1. Write a query to create a table employee with empno, ename, designation, and
salary.

QUERY: 01

SQL>CREATE TABLE EMP (EMPNO INT(4),ENAME VARCHAR(10),DESIGNATION


VARCHAR(10),SALARY FLOAT(8,2));

Table created.

QUERY: 02
Q2. Write a query to display the column name and datatype of the table employee.

SQL> DESC EMP;


lOMoARcPSD|39705338

Name Null? Type


----------------------------------------- --------
------------- EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUERY: 03

Q3. Write a query for create a new table from an existing table with all the fields.

QUERY: 03
SQL> CREATE TABLE EMP1 AS SELECT * FROM EMP;
Table created.
SQL> DESC
EMP1
Name Null? Type
----------------------------------------- --------
------------------ EMPNO NUMBER(4)
ENAME VARCHAR(10)
DESIGNATIN VARCHAR(10)
SALARY NUMBER(8,2)

QUERY: 04
Q4. Write a query to create a table from an existing table with selected fields.

Syntax
SQL> CREATE TABLE <TARGET TABLE NAME> SELECT EMPNO, ENAME
FROM <SOURCE TABLE NAME>;

QUERY: 04
SQL> CREATE TABLE EMP2 AS SELECT EMPNO, ENAME FROM EMP;
Table created.

SQL> DESC EMP2;

Name Null? Type


----------------------------------------- --------
---------------------- EMPNO NUMBER (4)
ENAME VARCHAR(10)

ALTER & MODIFICATION ON TABLE

QUERY: 06
Q6. Write a Query to Alter the column EMPNO NUMBER (4) TO EMPNO NUMBER(6).
lOMoARcPSD|39705338

QUERY: 06
SQL>ALTER TABLE EMP MODIFY EMPNO NUMBER (6);
Table altered.

SQL> DESC EMP;


Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(6)
ENAME VARCHAR(10)
DESIGNATIN VARCHAR(10)
SALARY NUMBER(8,2)

QUERY: 07

Q7. Write a Query to Alter the table employee with multiple columns
(EMPNO, ENAME.)

Syntax for alter table with multiple column:

SQL > ALTER <TABLE NAME> MODIFY <COLUMN NAME1> <DATATYPE>


(SIZE), MODIFY <COLUMN NAME2> <DATATYPE> (SIZE)…….;

QUERY: 07
SQL>ALTER TABLE EMP MODIFY EMPNO INT (7),MODIFY ENAME
VARCHAR(12));

Table altered.

SQL> DESC EMP;


Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR(12)
DESIGNATIN VARCHAR(10)
SALARY NUMBER(8,2);

QUERY: 08

Q8. Write a query to add a new column in to employee

QUERY: 08

SQL> ALTER TABLE EMP ADD QUALIFICATION VARCHAR2(6);


Table altered.
SQL> DESC EMP;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Name Null? Type


----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR(12)
DESIGNATIN VARCHAR(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)

QUERY: 09

Q9. Write a query to add multiple columns in to employee

SQL>ALTER TABLE EMP ADD (DOB DATE, DOJ DATE);

Table altered.
SQL> DESC EMP;
Name Null? Type
----------------------------------------- -------- ----------------------------
EMPNO NUMBER(7)
ENAME VARCHAR(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR(6)
DOB DATE
DOJ DATE

QUERY: 10
Q10. Write the query to change the table name emp as employee

SQL> Rename table emp to employee;

QUERY: 11

Q11. Write the query to change the column name empno to eno of the table
employee
SQL> ALTER TABLE employee RENAME COLUMN EMPNO TO ENO;

SQL> DESC EMPLOYEE;


Name Null? Type
----------------------------------------- -------- ----------------------------
ENO NUMBER(7)
ENAME VARCHAR(12)
DESIGNATION VARCHAR(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

DOB DATE
DOJ DATE

REMOVE / DROP

QUERY: 12

Q12. Write a query to drop a column from an existing table employee

SQL> ALTER TABLE EMPLOYEE DROP COLUMN DOJ;

SQL> DESC EMP;


Name Null? Type
----------------------------------------- -------- -------------
ENO NUMBER(7)
ENAME VARCHAR2(12)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
QUALIFICATION VARCHAR2(6)
DOB DATE

QUERY: 13

Q13. Write a query to truncate table employee

SQL> truncate table employee;

QUERY: 14

Q14. Write a query to drop table employee

SQL> drop table employee;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

DML COMMANDS

Data Manipulation Language (DML)

These SQL commands are used for storing, retrieving, modifying, and
deleting data. These commands are SELECT, INSERT, UPDATE, and DELETE.

DML (DATA MANIPULATION LANGUAGE)

 SELECT- It is used to retrieve information from the table. It is generally


referred to as querying the table.

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

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

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

PROCEDURE:

STEP 1: Start.
STEP 2: Create the table with its essential
attributes. STEP 3: Insert the record into table.
STEP 4: Update the existing records into the table.
STEP 5: Delete the records in to the table.

SQL COMMANDS

1. COMMAND NAME: INSERT


COMMAND DESCRIPTION: INSERT command is used to Insert objects in the
database.

2. COMMAND NAME: SELECT


COMMAND DESCRIPTION: SELECT command is used to SELECT the object from the
database.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

3. COMMAND NAME: UPDATE


COMMAND DESCRIPTION: UPDATE command is used to UPDATE the records from
the table

4. COMMAND NAME: DELETE


COMMAND DESCRIPTION: DELETE command is used to DELETE the Records form
the table

INSERT

QUERY:

01
Q1. Write a query to insert the records in to employee.

Syntax for Insert Records in to a table:


SQL > INSERT INTO <TABLE NAME> VALUES< VAL1, ‘VAL2’,

…..); QUERY: 01

INSERT A RECORD INTO AN EXISTING TABLE:

SQL>INSERT INTO EMP VALUES(101,'NAGARAJAN','LECTURER',15000); SQL


>INSERT INTO EMP VALUES(102 ,‘SARAVANAN’,’ LECTURER’,15000); SQL
>INSERT INTO EMP VALUES(103,’PANNERSELVAM’,’ ASST. PROF,20000);SQL
>INSERT INTO EMP VALUES(104,’CHINNI HOD’, ‘PROF’,45000);

1 row created.

SELECT

QUERY: 02

Q3. Write a query to display the records from employee.

Syntax for select Records from the table:

SQL> SELECT * FROM <TABLE NAME>;

QUERY: 02

DISPLAY THE EMP TABLE:

SQL> SELECT * FROM EMP;


lOMoARcPSD|39705338

EMPNO ENAME DESIGNATIN SALARY


---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 15000
102 SARAVANAN LECTURER 15000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

UPDATE

QUERY: 04
Q1. Write a query to update the records from employee.
Syntax for update Records from the table:

SQL> UPDATE <<TABLE NAME> SET <COLUMNANE>=<VALUE> WHERE


<COLUMN NAME=<VALUE>;

QUERY: 04
SQL> UPDATE EMP SET SALARY=16000 WHERE EMPNO=101;
1 row updated.

SQL> SELECT * FROM EMP;

EMPNO ENAME DESIGNATIN SALARY


---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN LECTURER 15000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

UPDATE MULTIPLE COLUMNS

QUERY: 05
Q5. Write a query to update multiple records from employee.

Syntax for update multiple Records from the table:

SQL> UPDATE <<TABLE NAME> SET <COLUMNAME>=<VALUE> WHERE


<COLUMN NAME=<VALUE>;

QUERY: 05

SQL>UPDATE EMP SET SALARY = 16000, DESIGNATIN='ASST. PROF' WHERE


EMPNO=102;
1 row updated.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL> SELECT * FROM EMP;


EMPNO ENAME DESIGNATIN SALARY
---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 15000
103 PANNERSELVAM ASST. PROF 20000
104 CHINNI HOD, PROF 45000

DELETE

QUERY: 06
Q5. Write a query to delete records from employee.

Syntax for delete Records from the table:


SQL> DELETE <TABLE NAME> WHERE <COLUMN NAME>=<VALUE>;
QUERY: 06

SQL> DELETE EMP WHERE

EMPNO=103; SQL> SELECT * FROM

EMP;

EMPNO ENAME DESIGNATIN SALARY


---------- ------------ ---------- ----------
101 NAGARAJAN LECTURER 16000
102 SARAVANAN ASST. PROF 15000
104 CHINNI HOD, PROF 45000

Result:
Thus the DDL, DML commands are executed in SQL and verified
successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 2 CREATION OF TABLES WITH CONSTRAINTS

AIM:
To execute and verify the SQL commands for adding constraints.

SQL Constraints

 SQL constraints are used to specify rules for the data in a table.

 Constraints are used to limit the type of data that can go into a
table. This ensures the accuracy and reliability of the data in the
table. If there is any violation between the constraint and the data
action, the action is aborted.

 Constraints can be column level or table level. Column level


constraints apply to a column, and table level constraints apply to
the whole table.

The following constraints are commonlyused in SQL:

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


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE.
Uniquely identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified

PROCEDURE:

STEP 1: Start.
STEP 2: Create the table with its essential attributes.
STEP 3: Add the constraint as a column level and table level
STEP 4: check all the constraints with specified conditions.

Create table1:
SQL> create table emp(empno int(3),empname varchar(20),age
int(3),deptno int(3),salary float(7,2),phno int(5));

Query OK, 0 rows affected (0.11 sec)


Records: 0 Duplicates: 0 Warnings: 0

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL>desc emp;

PRIMARY KEY

Q1: create the department table with the primary key as a table
level constraint.

SQL> create table dept(deptno int(3)primary key,deptname


varchar(10));

Q2: Alter the employee table with the primary key as a column
level constraint.

SQL> alter table emp modify empno int primary key;

Query OK, 0 rows affected (0.11 sec)


Records: 0 Duplicates: 0 Warnings: 0

NOT NULL CONSTRAINT:

Q3:Add employee name as a not null constraint using alter


command

SQL> alter table emp modify empname varchar(10) not null;

Query OK, 0 rows affected (0.11 sec)


Records: 0 Duplicates: 0 Warnings: 0

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

CHECK CONSTRAINT:

Q4: Add Check Constraint For The Column Age

alter table emp modify age int check(age>=18);

Query OK, 0 rows affected (0.11 sec)


Records: 0 Duplicates: 0 Warnings: 0

DEFAULT CONSTRAINT:

Q5:Set salary column as a default constraint

SQL>alter table emp modify salary float default 1000;

Query OK, 0 rows affected (0.05 sec)


Records: 0 Duplicates: 0 Warnings: 0

UNIQUE CONSTRAINT

Q6: create a unique constraint for the column phone number and check
the constraint

alter table emp modify phno int unique;

Query OK, 0 rows affected (0.05 sec)


Records: 0 Duplicates: 0 Warnings: 0

REFERENTIAL CONSTRAINT:FOREIGN KEY)

Q7:

SQL> alter table emp add deptno int(3); Query

OK, 0 rows affected, 1 warning (0.05 sec)


Records: 0 Duplicates: 0 Warnings: 1

SQL> alter table emp add foreign key(deptno) references dept(deptno);

Query OK, 0 rows affected (0.24 sec)


Records: 0 Duplicates: 0 Warnings: 0

Q8) desc emp;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

foreign key

Q10:

insert into emp values(101,’angel’,20,20000,904486322,1);

Query OK, 1 row affected (0.03 sec)

insert into dept values(1,’PROJECT’);

Query OK, 1 row affected (0.03 sec)

insert into dept values(2,’DESIGN’);

Query OK, 1 row affected (0.03 sec)

insert into dept values(3,’HR’);

Query OK, 1 row affected (0.03 sec)

insert into dept values(4,’SOFTWARE’);

Query OK, 1 row affected (0.03 sec)

insert into emp values(101,’angel’,20,1,20000,904486322);

ERROR 1062 (23000): Duplicate entry '101' for key 'emp.PRIMARY'

primary key

insert into emp values(101,’angana’,20,1,30000,904486324);

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

ERROR 1062 (23000): Duplicate entry '101' for key 'emp.PRIMARY'

insert into emp values(102,’angana’,20,1,30000,904486324);

ERROR 1062 (23000): Duplicate entry '102' for key 'emp.PRIMARY'

check

insert into emp values(103,’anu’,16,2,40000,904486326);

ERROR 3819 (HY000): Check constraint 'emp_chk_1' is violated.

insert into emp values(103,’anu’,26,3,40000,904486326);

ERROR 1062 (23000): Duplicate entry '103' for key 'emp.PRIMARY'

not null

insert into emp values(104,null,21,4,40000,904486332);

ERROR 1048 (23000): Column 'empname' cannot be null

insert into emp values(104,’anju’,21,4,40000,904486332);

ERROR 1062 (23000): Duplicate entry '104' for key 'emp.PRIMARY'

unique

insert into emp values(105,’banu’,21,3,50000,904486332);

ERROR 1062 (23000): Duplicate entry '105' for key 'emp.PRIMARY'

insert into emp values(105,’banu’,21,3,50000,904486334);

ERROR 1062 (23000): Duplicate entry '105' for key 'emp.PRIMARY'

dropping constraints

alter table emp drop primary key;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

alter table emp drop foreign key;

Result:
Thus the SQL statements for executing constraints are executed successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 3
WHERE CLAUSE CONDITIONS AND IMPLEMENT
AGGREGATE FUNCTIONS

AIM:

To execute and verify the SQL commands using where clause conditions and
implement aggregate functions.

PROCEDURE:

1. Create the table employee with the corresponding fields.


2. Insert the records in the fields.
3. Implement where clause condition and aggregate functions
4. Verify the records and so for.

Create table 2:

SQL> create table emp(empid int primary key,empname varchar(20),ageint,salary


int,deptno int);
Query OK, 1 row affected (0.06 sec)

SQL> insert into emp values(101,'angel',20,20000,1);


Query OK, 1 row affected (0.06 sec)

SQL> insert into emp values(102,'angena',20,30000,1);


Query OK, 1 row affected (0.02 sec)

SQL> insert into emp values(103,'anu',26,40000,2);


Query OK, 1 row affected (0.02 sec)

SQL> insert into emp


values(104,'anju',21,40000,3); Query OK, 1 row
affected (0.01 sec)

SQL> insert into emp values(105,'banu',21,50000,4);


Query OK, 1 row affected (0.02 sec)
lOMoARcPSD|39705338

Q1. Select the employee who all re above age 21.

SQL> select empname, age from emp where age>=21;

3 rows in set (0.01 sec)


Q2: Display employee name those having salary between 20000 and 40000

SQL> select empname,empid from emp where salary between 20000 and 40000;

Q3:Display the employee details who are in department 1 and 2

SQL> select empname,empid from emp where deptno in(1,2);

Q4: Display the employee names that ends with letter a. SQL>

select empname from emp where empname like '%a';

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Q5: Display the employee names having letter a.


SQL> select empname,empid from emp where empname like '%a%';

Q6: Display the employee names starts with letter a.


SQL> select empname,empid from emp where empname like 'a%';

Q8: display the employee details having employee id greater than 103 and
department number 4.

SQL> select empid,deptno,empname from emp where empid>103 and deptno=4;

Q10: display the employee details that are not in 102 and 104

SQL> select empname,empid from emp where empid not in(102,104);

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Aggregate Functions:

Create table 2:

create table works(empid int,companyname varchar2(20),location


varchar(20),salary int(5),fk_id foreign key(empid) references emp(empid));
Query OK, 0 rows affected (0.19 sec)
Records: 0 Duplicates: 0 Warnings: 0

SQL> insert into works values(101,'infosis','chennai',10000);


Query OK, 1 row affected (0.06 sec)

SQL> insert into works values(102,'wipro','bangalore',20000);


Query OK, 1 row affected (0.03 sec)

SQL> insert into works


values(103,'agile','nagercoil',30000); Query OK, 1 row
affected (0.02 sec)

SQL> insert into works values(104,'accenture','chennai',40000);Query


OK, 1 row affected (0.03 sec)

SQL> select * from works;

Q3:Display the company name which one having more than one employee.
SQL> insert into works values(105,'wipro','bangalore',30000);
Query OK, 1 row affected (0.03 sec)

SQL> select companyname,count(empid) as no_of_emp from works group


by companyname having count(empid)>1;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Q4:Display the employee name having maximum salary

SQL> select max(salary) as maximum from emp;


+---------+
| maximum |
+---------+
| 50000 |
+---------+

Q5: Display the employee name having maximum salary

SQL> select min(salary) as minimum from emp;


+---------+
| minimum |
+---------+
| 20000 |
+---------+

Q6: Display the average salary of employee

select avg(salary) as average from emp;

SQL> select avg(salary) as average from

emp;
+------------+
| average |
+------------+
| 36000.0000 |
+------------+

Q7: Display the employee name who isearning maximum salary


SQL> select empid,empname from emp where salary=(select max(salary)fromemp);
+-------+---------+
| empid | empname |
+-------+---------+
| 105 | banu |
+-------+---------+
Q8: Display the sum of salary of each department
SQL> select deptno,sum(salary)as total from emp group by deptno;
+--------+-------+
| deptno | total |
+--------+-------+
| 1 | 50000 |
| 2 | 40000 |
| 3 | 40000 |
| 4 | 50000 |
lOMoARcPSD|39705338

Q9: Display the sum of salary of each company.

select companyname,sum(salary) as total from works group by companyname;

SQL> select companyname,sum(salary) as total from works group bycompanyname;


+-------------+-------+
| companyname | total |
+-------------+-------+
| infosis | 10000 |
| wipro | 50000 |
| agile | 30000 |
| accenture | 40000 |

Q10: Display company name which one is having less sum of salary compared
to others
SQL> select companyname from works group by companyname having
sum(salary)<=all(select sum(salary)from works group by companyname);
+-------------+
| companyname |
+-------------+
| infosis |
+-------------+

SQL> insert into works values(105,'accenture','chennai',null);


Query OK, 1 row affected (0.05 sec)

Q11: Insert the null record


SQL> select * from works where salary is null;

Q12: Display the not null record from the table.


select * from works where salary is not null;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

order by clause:

Q13: Display the employee in decending order

SQL> select * from emp order by empname desc;

Q15: Display the employee in decending order

SQL> select * from emp order by empname asc;

SQL> select * from emp order by empname;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Result:
Thus the where clause conditions using SQL statements are verified
and executed successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 4 SIMPLE JOIN


OPERATIONS

AIM:
To Query the Database Table and explore Sub queries and simple Join
Operations.

PERFORM THE FOLLOWING:

1. Create table 1 and table 2.


2. Performsub queries using where, fromand select clauses.
3. Performsingle row and multiple rows sub queries.
4. Perform nested sub queries.
5. Performsimple join operations.

SUB-QUERY:
A sub-query is a SQL query nested inside a larger query. A Sub Query can also be called
a Nested/Inner Query.

The sub queries used with:

1. SELECT CLAUSE

2. FROM CLAUSE

3. WHERE CLAUSE

CREATE TABLE 1:

SQL> CREATE TABLE EMP(EMPID INTEGER,EMPNAME VARCHAR(20),AGE


INTEGER,SALARY INTEGER);

QueryOK, 0 rows affected (0.55 sec)

SQL> INSERT INTO EMP VALUES(1,'ASHI',16,10000);

QueryOK, 1 row affected (0.15 sec)

SQL> INSERT INTO EMP VALUES(2,'ANI',18,20000);

QueryOK, 1 row affected (0.03 sec)

SQL> INSERT INTO EMP VALUES(3,'BISMI',17,15000);

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL> SELECT * FROM EMP;

+ + + + +

| EMPID | EMPNAME | AGE | SALARY |

+ + + + +

| 1 | ASHI | 16 | 10000 |

| 2 | ANI | 18 | 20000 |
| 3 | BISMI | 17 | 15000 |

+ + + + +

CREATE TABLE 2:

SQL> CREATE TABLE REPORT(EMPID INTEGER,AGE INTEGER,SALARY


INTEGER);

QueryOK, 0 rows affected (0.08 sec)

SQL> INSERT INTO REPORT VALUES(3,17,15000);

QueryOK, 1 row affected (0.02 sec)

SQL> INSERT INTO REPORT VALUES(1,16,10000);

QueryOK, 1 row affected (0.02 sec)

SQL> INSERT INTO REPORT VALUES(4,16,20000);

QueryOK, 1 row affected (0.01 sec)

SQL> SELECT * FROM REPORT;

+ + + +

| EMPID | AGE | SALARY |

+ + + +

| 3 | 17 | 15000 |

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

| 1 | 16 | 10000 |
| 4 | 16 | 20000 |

+ + + +

3 rows in set (0.00

sec)

SUB-QUERY USING Where Clause:

A sub-query in a WHERE clause can be used to qualify a column against a set of rows.

SYNTAX:

SELECT* FROM table_name1 WHERE column_name1 IN(SELECT


column_name1 FROM table_name2WHERE condition );

SQL> SELECT * FROM REPORT WHERE EMPID IN(SELECT EMPID FROM EMP
WHERE EMPNAME='BISMI');

+ + + +

| EMPID | AGE | SALARY |

+ + + +

| 3 | 17 | 15000 |

+ + + +

1 row in set (0.08 sec)

SUB-QUERY USING FROM CLAUSE:


FROM clause can be used to specify a sub-query expression in SQL. The relation
produced by the sub-query is then used as a new relation on which the outer query
isapplied.

SYNTAX:

SELECT a.column_name1, b.column_name2 FROM table_name1 a, (


SELECT b.column_name2, function(variable) as b.column_name FROM
table_name GROUP BYcolumn_name )b Where Condition;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL> SELECT A.EMPNAME,B.AGE FROM EMP A,(SELECT


EMPID,AVG(AGE)AS AGE FROM REPORT GROUP BY EMPID)B WHERE
A.EMPID=B.EMPID;

+ + +

| EMPNAME | AGE |

+ + +

| ASHI | 16.0000 |

| BISMI | 17.0000 |

+ + +

2 rows in set (0.03 sec)

SQL> SELECT * FROM EMP WHERE SALARY=(SELECT MIN(SALARY) FROM


EMP);

+ + + + +

| EMPID | EMPNAME | AGE | SALARY |

+ + + + +

| 1 | ASHI | 16 | 10000 |

+ + + + +

1 row in set (0.00 sec)

SINGLE ROW SUB QUERY USING HAVING CLAUSE:


The HAVING clause is used to filter out groupsof records. Because it
becomes very useful in filtering on aggregate values such as averages,
summations, and count.

SYNTAX:

SELECT column_name1,function(column_name2) FROM


table_name1 GROUP BY column_name1 HAVINGfunction
(column_name2) > ( SELECTfunction (column_name2) FROM
table_name1 WHERE condition);

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL> SELECT EMPID,MAX(SALARY) FROM EMP GROUP BY EMPID


HAVING MAX(SALARY)>(SELECT MAX(SALARY) FROM EMP WHERE
EMPID=1);

+ + +

| EMPID | MAX(SALARY) |

+ + +

| 2| 20000 |
| 3| 15000 |

+ + +

2 rows in set (0.01 sec)

JOINS:

JOIN USING USING CLAUSE:

The USING clause specifies which columns to test for equalitywhen two tables are
joined.

SYNTAX:

SELECT*FROM table_name1 JOIN table_name2 USING (common_column


name1);

SQL> SELECT * FROM EMP JOIN REPORT USING(EMPID);

+ + + + + + +

| EMPID | EMPNAME | AGE | SALARY | AGE | SALARY |

+ + + + + + +

| 3 | BISMI | 17 | 15000 | 17 | 15000 |

| 1 | ASHI | 16 | 10000 | 16 | 10000 |

+ + + + + + +

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

JOIN USING ON CLAUSE:

ON clause can be used to join columns that have different names. Use the
ON clause to specify conditions or specify columns to join.

SYNTAX:

SELECT*FROM table_name1 JOIN table_name2 ON


(condition_using_common_column_name);

SQL> SELECT A.EMPNAME,A.EMPID,B.AGE,B.SALARY FROM EMP A JOIN


REPORT B ON(A.EMPID=B.EMPID);

+ + + + +

| EMPNAME | EMPID | AGE | SALARY |

+ + + + +

| BISMI | 3 | 17 | 15000 |
| ASHI | 1 | 16 | 10000 |

+ + + + +

2 rows in set (0.00 sec)

Result:
Thus the where clause conditions using SQL statements are verified and
executed successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 5 NATURAL, EQUI AND OUTER JOIN


OPERATIONS

AIM:
To Query the Database Table and explore natural, equi and outer join operations.

PERFORM THE FOLLOWING:

1. Create table 1 and table 2.


2. Performsub queries using natural and outer join operations
3. Analyze the difference of each queries.
4. Report the answers.

CREATE TABLE 1:

SQL> create table employee(ename varchar(20),ecity varchar(20),eno

int(10)); Query OK, 0 rows affected, 1 warning (0.10 sec)

CREATE TABLE 2:

SQL> create table salary(eno int(10),dname varchar(20),esal

int(10));Query OK, 0 rows affected, 2 warnings (0.10 sec)

SQL> desc employee;

+ + + + + + +

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

+ + + + + + +

| ename | varchar(20) | YES | | NULL | |

| ecity | varchar(20) | YES | | NULL | |

| eno | int | YES | | NULL | |

+ + + + + + +

SQL> desc salary;

+ + + + + + +

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

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

+ + + + + + +

| eno | int | YES | | NULL | |

| dname | varchar(20) | YES | | NULL | |

| esal | int | YES | | NULL | |

+ + + + + + +

SQL> insert into employee

values('Ajay','Chennai',11);Query OK, 1 row affected

(0.06 sec)

SQL> insert into employee values('Vijay','Banglore',12);

Query OK, 1 row affected (0.04 sec)

SQL> insert into employee values('Sujay','Chennai',13);

Query OK, 1 row affected (0.03 sec)

SQL> insert into employee values('Jay','Madurai',14);

Query OK, 1 row affected (0.04 sec)

SQL> select* from employee;

+ + + +

| ename | ecity | eno |

+ + + +

| Ajay | Chennai | 11 |

| Vijay| Banglore | 12 |

| Sujay | Chennai | 13 |

| Jay | Madurai | 14 |

SQL> insert into salary

values(11,'IT',20000); Quey OK, 1 row

affected (0.03 sec)

SQL> insert into salary values(12,'CSE',20020);

Query OK, 1 row affected (0.03 sec)


lOMoARcPSD|39705338

SQL> insert into salary

values(13,'IT',20050); Query OK, 1 row

affected (0.03 sec)

SQL> insert into salary values(14,'CSE',20000);

Query OK, 1 row affected (0.03 sec)

SQL> select* from salary;

+ -+ + +

| eno | dname | esal |

+ + + +

| 11 | IT | 20000 |

| 12 | CSE | 20020 |

| 13 | IT | 20050 |

| 14 | CSE | 20000 |

+ + + +

NATURAL JOIN OPERATIONS

A natural join is a type of join operation that creates an implicit join by combining tables
based on columns with the same name and data type

o There is no need to specifythe column names to join.


o The resultant table always contains unique columns.
o It is possible to perform a natural join on more than two tables.
o Do not use the ON clause

Syntax:

SELECT [column_names*] FROM table_name1 NATURAL JOIN table_name2;

SQL> select * from employee natural join salary;

+ + + + + +

| eno | ename | ecity | dname | esal |


lOMoARcPSD|39705338

+ + + + + +

| 11 | Ajay | Chennai | IT | 20000 |

| 12 | Vijay | Banglore | | 20020 |


CSE
| 13 | Sujay | Chennai | IT | 20050 |
| 14 | Jay | Madurai | CSE | 20000 |

+ + + + + +

4 rows in set (0.00 sec)

CROSS JOIN OPERATION:

SQL CROSS JOIN is used to combine all possibilities of the two or more
tablesand returns the result that contains every row from all contributing tables. The
CROSS JOIN is also known as CARTESIAN JOIN, which provides the Cartesian
product of allassociated tables.

Syntax:

SELECT column-lists FROM table1 CROSS JOIN table2;

SQL> select * from employee join salary;

+ + + + + + +

| ename | ecity | eno | eno | dname | esal |

+ + + + + + +

| Jay | Madurai | 14 | 11 | IT | 20000 |

| Sujay | Chennai | 13 | 11 | IT | 20000 |

| Vijay| Banglore | 12 | 11 | IT | 20000 |

| Ajay | Chennai | 11 | 11 | IT | 20000 |


| Jay | Madurai | 14 | 12 | CSE | 20020 |

| Sujay | Chennai | 13 | 12 | CSE | 20020 |

| Vijay | Banglore | 12 | 12 | CSE | 20020 |

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

| Ajay | Chennai | 11 | 12 | CSE | 20020 |

| Jay | Madurai | 14 | 13 | IT | 20050 |

| Sujay | Chennai | 13 | 13 | IT | 20050 |

| Vijay| Banglore | 12 | 13 | IT | 20050 |

| Ajay | Chennai | 11 | 13 | IT | 20050 |

| Jay | Madurai | 14 | 14 | CSE | 20000 |

| Sujay | Chennai | 13 | 14 | CSE | 20000 |

| Vijay| Banglore | 12 | 14 | CSE | 20000 |


| Ajay | Chennai | 11 | 14 | CSE | 20000 |

+ + + + + + +

INNER JOIN OPERATION:

The SQL Inner Join is used to returns only those results from the tables
that match the specified condition and hides other rows and columns. SQL assumes it as
a default Join, so it is optional to use the Inner Join keyword with the query.

Syntax:

SELECT columns FROM table1 INNER JOIN table2 ON condition1


INNER JOIN table3 ON condition2;

SQL> select * from employee inner join salaryon employee.eno=salary.eno;;

+ + + + + + +

| ename | ecity | eno | eno | dname | esal |

+ + + + + + +

| Ajay | Chennai | 11 | 11 | IT | 20000 |

| Vijay | Banglore | 12 | 12 | CSE | 20020 |

| Sujay | Chennai | 13 | 13 | IT | 20050 |

| Jay | Madurai | 14 | 14 | CSE | 20000 |

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

LEFT OUTER JOIN OPERATION:

The LEFT JOIN returns all the rows from the table on the left even if no
matching rows have been found in the table on the right. Where no matches have been
found in the table on the right, NULL is returned.

Syntax:

SELECT column-lists FROM table1 Left outer join table2;

SQL> select * from employee left outer join salary on employee.eno=salary.eno;

+ + + + + + +

| ename | ecity | eno | eno | dname | esal |

+ + + + + + +

| Ajay | Chennai | 11 | 11 | IT | 20000 |

| Vijay | Banglore | 12 | 12 | CSE | 20020 |

| Sujay | Chennai | 13 | 13 | IT | 20050 |

| Jay | Madurai | 14 | 14 | CSE | 20000 |

RIGHT OUTER JOIN OPERATION:

RIGHT JOIN is obviously the opposite of LEFT JOIN. The RIGHT JOIN returns all the
columns from the table on the right even if no matching rows have been found in the
table on the left. Where no matches have been found in the table on the left, NULL is
returned.

Syntax:

SELECT column-lists FROM table1 Right outer join table2;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL> select * from employee right outer join salary on employee.eno=salary.eno;

+ + + + + + +

| ename | ecity | eno | eno | dname | esal |

+ + + + + + +

| Ajay | Chennai | 11 | 11 | IT | 20000 |

| Vijay | Banglore | 12 | 12 | CSE | 20020 |

| Sujay | Chennai | 13 | 13 | IT | 20050 |

| Jay | Madurai | 14 | 14 | CSE | 20000 |

+ + + + + + +

4 rows in set (0.00 sec)

Result:
Thus the SQL commands to execute the natural, equi and outer join
operations are executed and verified successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 6 PROCEDURES AND USER DEFINED FUNCTIONS

AIM:

To create procedures and user defined functions using PL/SQL block.

PERFORM THE FOLLOWING:

1. Create tables.
2. Create procedures and functions.
3. Call procedures and functions to perform listed operations
4. Report the answers.

PROCEDURE:

A procedure (often called a stored procedure) is a collection of pre-compiled


SQL statements stored inside the database. It is a subroutine or a subprogram in the
regular computing language. A procedure always contains a name, parameter lists,
and SQL statements.

Syntax:

CREATE PROCEDURE ProcedureName


BEGIN
SQL Statements
END
1. Write a pl/sql program to find the sum &avg marks of all the student
using procedures.
STUD
RollNo Name M1 M2 M3

Create Table1:

SQL> create table stud(rollno int,name varchar(),m1 int,m2 int,m3 int);

INSERT VALUES INTO THE TABLE:

insert into stud values(1,’abi’,50,60,70);

insert into stud values(2,’bob’,70,60,50);

insert into stud values(3,’tom’,80,60,70);

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Create Procedure:

SQL> delimiter &&

SQL> create procedure mycalc()

-> begin

-> select name,m1+m2+m3 as total,(m1+m2+m3)/3 as aver from stud;

-> end

-> &&

SQL> delimiter ;

->&&

Call Procedure:

SQL> call mycalc();

->&&

Out PUT:

NAME Total Average


Abi 180 60
Bob 180 60
tom 210 70

2. Write a pl/sql programto find the product of 3 numbers in a procedure using in &
out parameter.
Create Procedure:

SQL> delimiter &&

SQL> create procedure myproduct(n1 int,n2 int,n3 int,out result int)

-> begin

-> set result=n1*n2*n3;

-> end

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

-> &&

SQL> delimiter ;

->&&

SQL> call myproduct(3,4,3,@ans);

->&&

SQL> select @ans;

->&&

Output:

@ans
36

USER DEFINED FUNCTIONS

The function which is defined by the user is called a user-defined function. SQL
user-defined functions may or may not have parameters that are optional, butit always
returns a single value that is mandatory. The returned value which is return by the
SQL Function can be of any valid SQL data type.

1. Write a pl/sql programto calculate age in user defined function


Create Table:

SQL> create table employee(empid int primary key,name varchar(50),salary int,dob


date);

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

QueryOK, 0 rows affected (1.61 sec)

Inserting record:

SQL> insert into employee values(1001,'pragya',10000,'2001-02-28');

Query OK, 1 row affected (0.12 sec)

SQL> insert into employee values(1002,'anu',20000,'2002-05-28');

Query OK, 1 row affected (0.08 sec)

SQL> insert into employee values(1003,'bob',30000,'2000-01-18');

Query OK, 1 row affected (0.03 sec)

Create Function:

SQL> DELIMITER &&

SQL> CREATE FUNCTION Func_Calculate_Age(Age date)

-> RETURNS INT DETERMINISTIC

-> BEGIN

-> DECLARE TodayDate DATE;

-> SELECT CURRENT_DATE() INTO TodayDate;

-> RETURN YEAR(TodayDate)-YEAR(Age);

-> END

-> &&

QueryOK, 0 rows affected (0.03 sec)

Calling Function:

SQL> select empid,name,salary,dob,func_calculate_age(dob)as age fromemployee;

-> &&

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Result:

Thus the procedures user defined function were created and executed
successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 7 DCL AND TCL


COMMANDS

AIM:
To create and execute complex transactions and realize DCL and TCL commands.

PERFORM THE FOLLOWING:

1. Create table.
2. Perform DCL and TCL commands.
3. Execute different user privileges.
4. Report the answers.
DCL (Data Control Language):
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.


GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_
USER;
 REVOKE: This command withdraws the user’s access privileges given by
using the GRANT command.
REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

TCL (Transaction Control Language):


Transactions group a set of tasks into a single execution unit. Each transaction
begins with a specific task and ends when all the tasks in the group successfully
complete. If any of the tasks fail, the transaction fails. Therefore, a transaction has only
two results: success or failure.
COMMIT: Commits a Transaction.
COMMIT;
ROLLBACK: Rollbacks a transaction in case of any error occurs.
ROLLBACK to SAVEPOINT_NAME;
SAVEPOINT: Sets a save point within a transaction.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SAVEPOINT SAVEPOINT_NAME;
TCL Exercises:
SQL> select * from employee;
+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anu | 20000 | 2002-05-28 |
| 1003 | bob | 30000 | 2000-01-18 |
+ + + + +
3 rows in set (0.17 sec)

START TRANSACTION:
SQL> start transaction;
QueryOK, 0 rows affected (0.00 sec)

CREATE SAVEPOINT:
SQL> savepoint s1;
QueryOK, 0 rows affected (0.01 sec)

SQL> insert into employee values(1004,'vini',40000,'1999-06-13');


Query OK, 1 row affected (0.10 sec)
SQL> select * from employee;
+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anu | 20000 | 2002-05-28 |
| 1003 | bob | 30000 | 2000-01-18 |
| 1004 | vini | 40000 | 1999-06-13 |
+ + + + +

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

4 rows in set (0.17 sec)


CREATE updated SAVEPOINT:

SQL> savepoint upd;


QueryOK, 0 rows affected (0.00 sec)

UPDATE TABLE

SQL> update employee set name='anupriya' where empid=1002;


Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0

SQL> select * from employee;


+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anupriya | 20000 | 2002-05-28 |
| 1003 | bob | 30000 | 2000-01-18 |
| 1004 | vini | 40000 | 1999-06-13 |
+ + + + -+
4 rows in set (0.00 sec)

CREATE delete SAVEPOINT:

SQL> savepoint del;


QueryOK, 0 rows affected (0.00 sec)

DELETE ROWS FROM TABLE:

SQL> delete from employee where empid=1003;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Query OK, 1 row affected (0.01 sec)


SQL> select * from employee;
+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anupriya | 20000 | 2002-05-28 |
| 1004 | vini | 40000 | 1999-06-13 |
+ + + + +
3 rows in set (0.00 sec)

ROLLBACK TO DELETED SAVEPOINT:

SQL> rollback to del;


QueryOK, 0 rows affected (0.00 sec)

SQL> select * from employee;


+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anupriya | 20000 | 2002-05-28 |
| 1003 | bob | 30000 | 2000-01-18 |
| 1004 | vini | 40000 | 1999-06-13 |
+ + + + +
4 rows in set (0.00 sec)

ROLLBACK TO UPDATE SAVEPOINT:

SQL> rollback to upd;


QueryOK, 0 rows affected (0.00 sec)

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SQL> select * from employee;


+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anu | 20000 | 2002-05-28 |
| 1003 | bob | 30000 | 2000-01-18 |
| 1004 | vini | 40000 | 1999-06-13 |
+ + + + +
ROLLBACK TO S1 SAVEPOINT:

SQL> rollback to s1;


QueryOK, 0 rows affected (0.01 sec)

SQL> select * from employee;


+ + + + +
| empid | name | salary | dob |
+ + + + +
| 1001 | pragya | 10000 | 2001-02-28 |
| 1002 | anu | 20000 | 2002-05-28 |
| 1003 | bob | 30000 | 2000-01-18 |
+ + + + +
3 rows in set (0.17 sec)

COMMIT TRANSACTION:

SQL> commit;
QueryOK, 0 rows affected (0.16 sec)

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

DCL (Data Control Language):


CREATE DATABASE:
SQL>create database employ;
Queryok..
CURRENT USER:

SQL> select user();


+ +
| user() |
+ +
| root@localhost |
+ +
1 row in set (0.28 sec)

SQL> create user 'ajay'@'localhost' identified by 'ajay';


QueryOK, 0 rows affected (1.85 sec)

TO DISPLAY ALL USERS


SQL> select user from SQL.user;
+ +
| user |
+ +
| ajay |
| SQL.infoschema |
| SQL.session |
| SQL.sys |
| root |
+ +
5 rows in set (0.03 sec)

SQL> grant insert on EMPLOY.emp to 'ajay'@'localhost';


QueryOK, 0 rows affected (0.07 sec)

SQL> grant update(eid) on EMPLOY.emp to 'ajay'@'localhost';


QueryOK, 0 rows affected (0.06 sec)

SQL> show grants for 'ajay'@'localhost';


+ +
| Grants for ajay@localhost |
+ +
| GRANT SELECT ON *.* TO `ajay`@`localhost` |
| GRANT INSERT, UPDATE (`eid`) ON `rr`.`emp` TO `ajay`@`localhost` |
+ +

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

2 rows in set (0.00 sec)


LOGIN TO AJAY
SQL> system SQL -u ajay –p
Enter password: **** (Type:ajay)
Welcome to the SQL monitor. Commands end with ; or \g.Your
SQL connection id is 12
Server version: 8.0.32 SQL Community Server - GPL

SQL> select user();


+ +
| user() |
+ +
| ajay@localhost |
+ +
1 row in set (0.00 sec)

SQL> use employ;


Database changed
SQL> select * from emp;
+ + + +
| eid | efname | job |
+ + + +
| 101 | hari | SeniorEng |
| 102 | Rahul | Editor |
+ + + +
2 rows in set (0.02 sec)

SQL> insert into emp values(103,'Gina','Researcher');


Query OK, 1 row affected (0.05 sec)

SQL> update emp set eid=104 where efname='Rahul';


Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0

SQL> update emp set efname='lisha' where eid=101; //Not Granted


ERROR 1143 (42000): UPDATE command denied to user 'ajay'@'localhost' for column
'efname' in table 'emp'

SQL> system SQL -u root –p //Login to Root


Enter password: *****
Welcome to the SQL monitor. Commands end with ; or \g.Your
SQL connection id is 13
Server version: 8.0.32 SQL Community Server - GPL
SQL> select user();
+ +
| user() |

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

+ +
| root@localhost |
+ +
1 row in set (0.00 sec)

Revoke Permission from Ajay user


SQL> revoke update(eid) on employ.emp from 'ajay'@'localhost';
Query OK, 0 rows affected (0.08 sec)

SQL> revoke insert on rr.emp from 'ajay'@'localhost';


Query OK, 0 rows affected (0.04 sec)

SQL> show grants for 'ajay'@'localhost';


+ +
| Grants for ajay@localhost |
+ +
| GRANT SELECT ON *.* TO `ajay`@`localhost` |
+ +
1 row in set (0.00 sec)
SQL> system SQL -u ajay –p //Login to Ajay User
Enter password: ****
Welcome to the SQL monitor. Commands end with ; or \g.Your
SQL connection id is 15
Server version: 8.0.32 SQL Community Server - GPL

SQL> select user();


+ +
| user() |
+ +
| ajay@localhost |
+ +
1 row in set (0.00 sec)

SQL> use rr;


Database changed
INSERT PERMISSION REVOKED

SQL> insert into emp values(108,'naresh','juneng');


ERROR 1142 (42000): INSERT command denied to user 'ajay'@'localhost' for table
'emp'
SQL> system SQL -u root –p
//Login to Root User

Enter password: *****


Welcome to the SQL monitor. Commands end with ; or \g.Your
SQL connection id is 16

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Server version: 8.0.32 SQL Community Server - GPL


SQL> select user();
+ +
| user() |
+ +
| root@localhost |
+ +
1 row in set (0.00 sec)

//To Grant all on Ajay user


SQL>SQL> grant all privileges on *.* to 'ajay'@'localhost' with grant option;
Query OK, 0 rows affected (0.23 sec)

//To Change pwd for ajay user

SQL> alter user 'ajay'@'localhost' identified by


'abcd'; Query OK, 0 rows affected (0.05 sec)

SQL> system SQL -u ajay -p


Enter password: **** (Type abcd)

//To Lock ajay user


SQL> alter user 'ajay'@'localhost' account lock;
Query OK, 0 rows affected (0.04 sec)

SQL> system SQL -u ajay -


p; Enter password: ****
ERROR 3118 (HY000): Access denied for user 'ajay'@'localhost'. Account is locked.
//To Unlock ajay user

SQL> alter user 'ajay'@'localhost' account unlock;


Query OK, 0 rows affected (0.03 sec)

SQL> system SQL -u ajay -p


Enter password: ****

SQL> system SQL -u root -p


Enter password: *****
Welcome to the SQL monitor. Commands end with ; or \g.

SQL> select user();


+ +
| user() |
+ +
| root@localhost |
+ +

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

1 row in set (0.00 sec)

SQL> select user, host from SQL.user;


+ + +
| user | host |
+ + +
| ajay | localhost |
| SQL.infoschema | localhost |
| SQL.session | localhost |
| SQL.sys | localhost |
| root | localhost |
+ + +
5 rows in set (0.01 sec)

//To Drop user


SQL> drop user 'ajay'@'localhost';
QueryOK, 0 rows affected (0.19
sec)

SQL> select user, host from SQL.user;


+ + +
| user | host |
+ + +
| SQL.infoschema | localhost |
| SQL.session | localhost |
| SQL.sys | localhost |
| root | localhost |
+ + +
4 rows in set (0.00 sec)

Result:
Thus the TCL and DCL commands were executed and verified successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 8 TRIGGERS

AIM:

To develop and execute a Trigger for Before and After update, Delete, Insert
operations on a table

Trigger:

A Trigger is a stored procedure that defines an action that the database


automatically takes when some database-related event such as Insert, Update or Delete
occur.

Types Of Triggers:

The various types of triggers are as follows

Before: Before triggers are fired before the DML statement is actually executed.
After: After triggers are fired after the DML statement has finished execution.
For each row: It specifies that the trigger fires once per row.
For each statement: This is the default trigger that is invoked. It specifies that
the trigger fires once per statement.

Variables used in triggers

 :new
 :old

These two variables retain the new and old values ofthe column updated in the database.
The values in these variables can be used in the database triggers for data manipulation.

Snytax:

CREATE TRIGGER <trigger name> <trigger time > <trigger event> ON <table
name> FOR EACH ROW <trigger body>;

Using SQL Triggers

Everytrigger associated with a table has a unique name and function based on
two factors:

1. Time. BEFORE or AFTER a specific row event.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

2. Event. INSERT, UPDATE or DELETE.

Delete Triggers

To delete a trigger, use the DROP TRIGGER statement:

DROP TRIGGER<trigger name>;

Alternatively, use:

DROP TRIGGER IF EXISTS<trigger name>;

Procedure:

1. Create a table called person with name and age for columns.

CREATE TABLE person (name varchar(45), age int);

Insert sample data into the table:

INSERT INTO person VALUES ('Matthew', 25), ('Mark', 20);

Select the table to see the result:

SELECT * FROM person;

2. Create a table called average_age with a column called average:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

CREATE TABLE average_age (average double);

Insert the average age value into the table:

INSERT INTO average_age SELECT AVG(age) FROM person;

Select the table to see the result:

SELECT * FROM average_age;

3. Create a table called person_archive with name, age, and time columns:

CREATE TABLE person_archive


( name varchar(45),
age int,
time timestamp DEFAULT NOW());

Note: The function NOW() records the current time.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Create a BEFORE INSERT Trigger

To create a BEFORE INSERT trigger, use:

CREATE TRIGGER <trigger name> BEFORE INSERT


ON <table name>
FOR EACH ROW
<trigger body>;

The BEFORE INSERT trigger gives control over data modification before
committing into a database table..

BEFORE INSERT Trigger Example

Create a BEFORE INSERT trigger to check the age value before inserting
data into the person table:

delimiter //
CREATE TRIGGER person_bi BEFORE INSERT
ON person
FOR EACH ROW
IF NEW.age < 18 THEN
SIGNAL SQLSTATE '50001' SET MESSAGE_TEXT = 'Person must be older
than 18.';
END IF; //
delimiter ;

Inserting data activates the trigger and checks the value of age before
committing the information:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

INSERT INTO person VALUES ('John', 14);

The console displays the descriptive error message. The data does not
insert into the table because of the failed trigger check.

Create an AFTER INSERT Trigger

Create an AFTER INSERT trigger with:

CREATE TRIGGER <trigger name> AFTER INSERT


ON <table name>
FOR EACH ROW
<trigger body>;

The AFTER INSERT trigger is useful when the entered row generates a
value needed to update another table.

AFTER INSERT Trigger Example

Inserting a new row into the person table does not automatically update the
average in the average_age table. Create an AFTER INSERT trigger on
the person table to update the average_age table after insert:

delimiter //
CREATE TRIGGER person_ai AFTER INSERT
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(age) FROM person); //
delimiter ;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Inserting a new row into the person table activates the trigger:

INSERT INTO person VALUES ('John', 19);

The data successfully commits to the person table and updates


the average_age table with the correct average value.

Create a BEFORE UPDATE Trigger

Make a BEFORE UPDATE trigger with:

CREATE TRIGGER <trigger name> BEFORE UPDATE


ON <table name>
FOR EACH ROW

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

<trigger body>;

The BEFORE UPDATE triggers go together with the BEFORE


INSERT triggers. If any restrictions exist before inserting data, the limits
should be there before updating as well.

BEFORE UPDATE Trigger Example

If there is an age restriction for the person table before inserting data, the age
restriction should also exist before updating information. Without
the BEFORE UPDATE trigger, the age check trigger is easy to
avoid. Nothing restricts editing to a faulty value.

Add a BEFORE UPDATE trigger to the person table with the same body as
the BEFORE INSERT trigger:

delimiter //
CREATE TRIGGER person_bu BEFORE UPDATE
ON person
FOR EACH ROW
IF NEW.age < 18 THEN
SIGNAL SQLSTATE '50002' SET MESSAGE_TEXT = 'Person must be older than
18.';
END IF; //
delimiter ;

Updating an existing value activates the trigger check:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

UPDATE person SET age = 17 WHERE name = 'John';

Updating the age to a value less than 18 displays the error message, and the
information does not update.

Create an AFTER UPDATE Trigger

Use the following code block to create an AFTER UPDATE trigger:

CREATE TRIGGER <trigger name> AFTER UPDATE


ON <table name>
FOR EACH ROW
<trigger body>;

The AFTER UPDATE trigger helps keep track of committed changes to data.
Most often, any changes after inserting information also happen after updating
data.

AFTER UPDATE Trigger Example

Any successful updates to the age data in the table person should also update
the intermediate average value calculated in the average_age table.

Create an AFTER UPDATE trigger to update the average_age table after


updating a row in the person table:

delimiter //
CREATE TRIGGER person_au AFTER UPDATE
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(age) FROM person); //
delimiter ;
lOMoARcPSD|39705338

Updating existing data changes the value in the person table:

UPDATE person SET age = 21 WHERE name = 'John';

Updating the table person also updates the average in the average_age table.

Create a BEFORE DELETE Trigger

To create a BEFORE DELETE trigger, use:

CREATE TRIGGER <trigger name> BEFORE DELETE


ON <table name>
FOR EACH ROW
<trigger body>;

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

The BEFORE DELETE trigger is essential for security reasons. If a parent


table has any children attached, the trigger helps block deletion and prevents
orphaned tables. The trigger also allows archiving data before deletion.

BEFORE DELETE Trigger Example

Archive deleted data by creating a BEFORE DELETE trigger on the


table person and insert the values into the person_archive table:

delimiter //
CREATE TRIGGER person_bd BEFORE DELETE
ON person
FOR EACH ROW
INSERT INTO person_archive (name, age)
VALUES (OLD.name, OLD.age); //
delimiter ;

Deleting data fromthe table person archives the data


into the person_archive table before deleting:

DELETE FROM person WHERE name = 'John';

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Inserting the value back into the person table keeps the log of the deleted data
in the person_archive table:

INSERT INTO person VALUES ('John', 21);

The BEFORE DELETE trigger is useful for logging any table change
attempts.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Create an AFTER DELETE Trigger

Make an AFTER DELETE trigger with:

CREATE TRIGGER <trigger name> AFTER DELETE


ON <table name>
FOR EACH ROW
<trigger body>;

The AFTER DELETE triggers maintain information updates that require the
data row to disappear before making the updates.

AFTER DELETE Trigger Example

Create an AFTER DELETE trigger on the table person to


update the average_age table with the new information:

delimiter //
CREATE TRIGGER person_ad AFTER DELETE
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(person.age) FROM person); //
delimiter ;

Deleting a record from the table person updates the average_age table with
the new average:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Without the AFTER DELETE trigger, the information does not update
automatically.

Result:
Thus the Trigger for Before and After update, Delete, Insert operations were
executed successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 9 VIEWS AND INDEXES

AIM:

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

VIEWS

OBJECTIVE:

 Views Helps to encapsulate complex queryand make it reusable.


 Provides user securityon each view - it depends on your data policy security.
 Using view to convert units - if you have a financial data in US currency, you can
 Create view to convert them into Euro for viewing in Euro currency.

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

SQL COMMANDS

1. COMMAND NAME: CREATE VIEW


COMMAND DESCRIPTION: CREATE VIEW command is used to define a view.

2. COMMAND NAME: INSERT IN VIEW


COMMAND DESCRIPTION: INSERT command is used to insert a new row into the
view.

3. COMMAND NAME: DELETE IN VIEW


COMMAND DESCRIPTION: DELETE command is used to delete a row from the
view.

4. COMMAND NAME: UPDATE OF VIEW


COMMAND DESCRIPTION: UPDATE command is used to change a value in a tuple
without changing all values in the tuple.

5. COMMAND NAME: DROP OF VIEW


COMMAND DESCRIPTION: DROP command is used to drop the view table

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

COMMANDS EXECUTION

CREATION OF TABLE

SQL> create table employee(empid integer,emp_name varchar(20),deptnamevarchar(10),dept_no


integer,DOJ date);
Query OK, 0 rows affected (0.39
sec) 5 rows in set (0.00 sec)

DESCRIPTION OF TABLE:

DISPLAY VIEW:
SQL>SELECT * FROM EMPLOYEE;

SYNTAX FOR CREATION OF VIEW

SQL> CREATE <VIEW> <VIEW NAME> AS SELECT<COLUMN_NAME_1>,


<COLUMN_NAME_2> FROM <TABLE NAME>;

CREATION OF VIEW

SQL> create view empview as select emp_name,empid,deptname,dept_no from


employee;
Query OK, 0 rows affected (0.09 sec)

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

DESCRIPTION OF VIEW

SQL> DESC EMPVIEW;

DISPLAY VIEW:
SQL> SELECT * FROM EMPVIEW;

INSERTION INTO VIEW

INSERT STATEMENT:
SYNTAX:

SQL>INSERT INTO <VIEW_NAME> (COLUMN NAME1,…)VALUES(VALUE1,….);

SQL> INSERT INTO EMPVIEW VALUES('SRI',120,'HR',1);


Query OK, 1 row affected (0.04 sec)
SQL> SELECT * FROM EMPVIEW;

DELETION OF VIEW:

DELETE STATEMENT:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SYNTAX:

SQL> DELETE <VIEW_NMAE>WHERE <COLUMN NMAE> =’VALUE’;


SQL> DELETE FROM EMPVIEW WHERE EMP_NAME='SRI';
Query OK, 1 row affected (0.30
sec) SQL> SELECT * FROM
EMPVIEW;

UPDATE STATEMENT:

SYNTAX:

SQL>UPDATE <VIEW_NAME> SET< COLUMN NAME> = <COLUMN NAME>


<VIEW> WHERE <COLUMNNAME>=VALUE;

SQL> UPDATE EMPVIEW SET EMP_NAME='SRIVIJAY' WHERE EMP_ID=110;


Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0

DROP A VIEW:

SYNTAX:
SQL> DROP VIEW <VIEW_NAME>

EXAMPLE:

SQL> DROP VIEW EMPVIEW;


QueryOK, 0 rows affected (0.08 sec)
lOMoARcPSD|39705338

INDEX

 The CREATE INDEX statement is used to create indexes in tables.


 Indexes allow the database application to find data fast; without reading
the whole table.
 An index can be created in a table to find data more quickly and efficiently.
 The users cannot see the indexes, they are just used to speed
up searches/queries.

Note: Updating a table with indexes takes more time than updating a table without
(because the indexes also need an update). So you should only create indexes on
columns (and tables) that will be frequently searched against.

CREATE INDEX

Syntax

Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name ON table_name (column_name);

SQL> CREATE TABLE PERSON(FIRSTNAME VARCHAR(20),LASTNAME


VARCHAR(20),DEPTNO INTEGER,DEPTNAME VARCHAR(20));
Query OK, 0 rows affected (0.21 sec)

SQL> CREATE INDEX IDX_PNAME ON PERSON(LASTNAME,FIRSTNAME);


Query OK, 0 rows affected (0.30 sec)
Records: 0 Duplicates: 0 Warnings: 0

To access the query plan for the SELECT query, execute the following:

After executing the above statement, the index is created successfully. Now, run
the below statement to see how SQL internally performs this query.

SQL> EXPLAIN SELECT FIRSTNAME,LASTNAME FROM PERSON WHERE


DEPTNAME='CSE';
lOMoARcPSD|39705338

SHOW INDEXES:

DROPPING INDEXES

SQL> DROP INDEX IDX_PNAME ON PERSON;

Query OK, 0 rows affected (0.12 sec)

Records: 0 Duplicates: 0 Warnings:

0 SQL> show indexes from person;

Empty set (0.00 sec)

Result:
Thus the views and indexes created on person table were executed successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

EX: NO: 10
CREATION OF XML DATABASE AND VALIDATION USING
XML SCHEMA

AIM:
To Create a XML database and validation using XML schema.

Procedure:

1. Search liquid xml validator from google.

<!-- schema for first name last name,weight-->


<person>
<first_name>AAA</first_name>
<last_name>XXX</last_name>
<weight scale="digital">55.0</weight>
</person>

<?xml version="1.0">
<xs:schema xmlns:xs="http://www.w3.org/2001/XML Schema">
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="first_name" type="xs:string/>
<xs:element name="last_name" type="xs:string/>
<xs:element name="weight">
<xs:complexType>
<xs:simpleContent>
<xs:extension base="xs:float">
<xs:attribute name="scale"
type="xs:string"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

</xs:schema>

2. Open xml validator link from google.


2. Select xml formatter.
lOMoARcPSD|39705338

3. Select XML TO XSD


Copythe formatted text there.

4. SELECT XML VALIDATOR XSD


Copythe generated text.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

5. Last step select XMLValidator(XSD)

6. Copy first few lines of code in first box and the generated code in the second box.
lOMoARcPSD|39705338

RESULT:
Thus the creation of XML database and validation using XML schema was
executed successfully.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Ex no:11
CREATE DOCUMENT, COLUMN AND GRAPH
BASED DATA USING NOSQL DATABASE
TOOLS

AIM:
To create a document-based NoSQL database using MongoDB, with columns and graphs,
and populate it with sample data.

NOSQL :
NOSQL (Not Only SQL) is a type of database that does not use the traditional relational
model that has been used in traditional SQL databases. Instead, NoSQL databases use a non-
relational approach for data storage and retrieval. They are designed to handle large amounts of
unstructured, semi-structured, and structured data, including text, images, videos, and social
media data.

NoSQL databases are often used in big data and real-time web applications, where high
performance and scalability are essential. Some popular examples of NoSQL databases include
MongoDB, Cassandra, Couchbase, and Apache HBase.

VIEW DATABASE:
In MongoDB, a view is a virtual collection that presents the results of a pre-defined
aggregation pipeline as if it were a collection of documents. Views do not store data
themselves but rather provide a read-only representation of the data in one or more underlying
collections.

QUERY AND OUTPUT:

CREATING DATABASE:
In the mongo shell, you can create a database with the help of the following command. This
command actually switches you to the new database if the given name does not exist and if the
given name exists, then it will switch you to the existing database. Now at this stage, if you use
the show command to see the database list where you will find that your new database is not
present in that database list because, in MongoDB, the database is actually created when you
start entering data in that database.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

SYNTAX:

use database_name

QUERY AND OUTPUT:

CREATING COLLECTION:
In MongoDB, a collection is a grouping of MongoDB documents, similar to a table in a
relational database. To create a collection in MongoDB, you can use the
db.createCollection() method.

SYNTAX:

db.createCollection(name, options)

QUERY AND OUTPUT:

INSERTMANY COMMAND:
insertMany is a method in MongoDB that allows you to insert multiple documents into a
collection at once. The method takes an array of documents as its argument, and inserts each
document as a separate document in the collection.

SYNTAX:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)

QUERY AND

OUTPUT:

DOCUMENT VIEW:

GRAPHICAL VIEW:
Step 1: Open MongoDB Compass Application.

Step 2: Click Connect on the displayed window.


lOMoARcPSD|39705338

Step 3: From the Databases select the database which has the collection you want to
insert document.

Step 4: Click the collection -> ADD DATA -> Insert document. Add fields to the
document and click Insert.

FINDING A SINGLE DOCUMENT:

In MongoDB, we can find a single document using the findOne() method, This method
returns the first document that matches the given filter query expression.

SYNTAX:

db.collection_name.findOne ()

QUERY AND OUTPUT:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

DISPLAYING DOCUMENTS IN A FORMATTED WAY:


In MongoDB, we can display documents of the specified collection in a well-formatted
way using the pretty() method.

SYNTAX:

db.collection_name.find().pretty()

QUERY AND OUTPUT:

GREATER THAN FILTER QUERY:


To get the specific numeric data using conditions like greater than equal or less than
equal use the $gte or $lte operator in the find() method.

SYNTAX:

db.collection_name.find({< key > : {$gte : < value >}})


or
db.collection_name.find({< key > : {$lte : < value >}})

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

QUERY AND OUTPUT:

DELETING THE FIRST DOCUMENT:


In this example, we are deleting the first document from the Student collection by passing an
empty document in the db.collection.deleteOne() method.

SYNTAX:

db.collection_name.deleteOne({})

QUERY AND OUTPUT:

DROPPING A COLLECTION:

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

In MongoDB, a collection is a group of MongoDB documents that are stored together.


Dropping a collection in MongoDB means permanently deleting the entire collection and
all of its contents from the database.

SYNTAX:

db.collection_name.drop()

QUERY AND OUTPUT:

DROP A DATABASE:
In MongoDB, databases hold collections of documents. On a single MongoDB server,
we can run multiple databases. when you install MongoDB some databases are
automatically generated to use. many times you need to delete some database when the
database is no longer used.

db.dropDatabase() the command is used to drop an existing database. This command will
delete the currently selected database. If you have not selected any database, then it will
delete the default ‘test’ database.

SYNTAX:

db.dropDatabase()

QUERY AND OUTPUT:

RESULT:
Thus create a document-based NoSQL database using MongoDB, with columns and graphs,
and populate it with sample data.

Downloaded by Senthil Kumar ([email protected])


lOMoARcPSD|39705338

Ex.No:12
Date : HOSPITAL MANAGEMENT SYSTEM

AIM:
To create a hospital management system using VB as front end and
oracle as back end.

PROGRAM:
FORM 1
Private Sub disp_Click()
Dim k As Integer
Adodc1.Recordset.MoveFirst
Do Until Adodc1.Recordset.EOF
k = Val(Combo1.Text)
If Adodc1.Recordset.Fields(0) = k Then
Text1.Text = Val(Adodc1.Recordset.Fields(0))
Text2.Text = Adodc1.Recordset.Fields(1)
Text3.Text = Adodc1.Recordset.Fields(2)
Text4.Text = Adodc1.Recordset.Fields(3)
Text5.Text = Val(Adodc1.Recordset.Fields(4))
Text6.Text = Adodc1.Recordset.Fields(5)
Text7.Text = Val(Adodc1.Recordset.Fields(6))
Text8.Text = Adodc1.Recordset.Fields(7)
Exit Sub
Adodc1.Recordset.MoveLast
Else
Adodc1.Recordset.MoveNext
End If
Loop
End
Sub
Private Sub Text11_Change()
Text13.Text = Val(Text10.Text) +
Val(Text11.Text) End Sub

Private Sub
update_Click()
Adodc1.Recordset.update
End Sub
Private Sub exit_Click()
End
End Sub
Private Sub Form_Load()
Do Until Adodc1.Recordset.EOF
Combo1.AddItem Adodc1.Recordset.Fields(0)
Adodc1.Recordset.MoveNext
Loop
Text13.Text =
0 End Sub

FORM 2
lOMoARcPSD|39705338

Private Sub Combo1_Change(Text7.Text = Combo1.TextEnd Sub)


lOMoARcPSD|39705338

Private Sub
Combo1_Click() Text7.Text
= Combo1.Text
Adodc2.Recordset.MoveFirst
Do Until Adodc2.Recordset.EOF
If Adodc2.Recordset.Fields(0) = Val(Combo1.Text) Then
Text9.Text = Adodc2.Recordset.Fields(1)
Exit Sub
Else
Adodc2.Recordset.MoveNext
End If
Loop
End
Sub
Private Sub Command1_Click()
Adodc1.Recordset.AddNew
End Sub

Private Sub Command2_Click()


Adodc1.Recordset.MoveNext
End Sub

Private Sub Command3_Click()


Adodc1.Recordset.Update
End Sub

Private Sub Command4_Click()


Adodc1.Recordset.Delete
End Sub

Private Sub Command6_Click()


End
End Sub

Private Sub Form_Load()


Adodc2.Recordset.MoveFirst
Do Until Adodc2.Recordset.EOF
Combo1.AddItem Adodc2.Recordset.Fields(0)
Adodc2.Recordset.MoveNext
Loop
End
Sub

RESULT:

Thus the hospital management system was created successfully

You might also like