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

22cs4001 Dbms Lab Record (2)

This document outlines the structure and objectives of the Database Management System Laboratory course for Computer Science and Engineering students at Hindusthan College of Engineering and Technology. It includes the course objectives, outcomes, program educational objectives, specific objectives, and a detailed description of SQL commands and their usage. Additionally, it provides a list of experiments and practical applications related to database management for the academic year 2023-2024.

Uploaded by

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

22cs4001 Dbms Lab Record (2)

This document outlines the structure and objectives of the Database Management System Laboratory course for Computer Science and Engineering students at Hindusthan College of Engineering and Technology. It includes the course objectives, outcomes, program educational objectives, specific objectives, and a detailed description of SQL commands and their usage. Additionally, it provides a list of experiments and practical applications related to database management for the academic year 2023-2024.

Uploaded by

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

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

22CS4001 – DATABASE MANAGEMENT


SYSTEM LABORATORY

II YEAR / IV SEMESTER – EVEN SEM

NAME OF THE STUDENT :

REGISTER NUMBER :

BRANCH : COMPUTER SCIENCE AND ENGINEERING


YEAR/SEMESTER : II CSE B / IV

1
HINDUSTHAN
COLLEGE OF ENGINEERING AND
TECHNOLOGY COIMBATORE – 641 032
(AN AUTONOMOUS INSTITUTION)

DEPARTMENT OF COMPUTER SCIENCE &


ENGINEERING
Certified that this is the bonafide record of work done
By
………………………………………………………………………………

in the
22CS4001 – DATABASE MANAGEMENT SYSTEM LABORATORY
of this institution, as prescribed by the college for the

IV Semesterduring the Academic year 2023 - 2024


Place: Coimbatore
Date:

Faculty in-Charge Head of the Department

Register Number: ………………………………

Submitted for the End Semester Practical Examination conducted on


……………………………

Internal Examiner External Examiner


2
HINDUSTHAN COLLEGE OF ENGINEERING
DEPARTMENT OF CSE
VISION

To provide an excellence for individuals to develop technologically superior, socially conscious


and nationally responsible citizens.
MISSION
M1: To develop competent Computer Science and Engineering professionals with knowledge in
current technology.
M2: To mould them to attain excellent leadership qualities there by making them excel in their careers.
M3: To inspire and nurture students to come out with innovation and creativity solutions meeting the
societal needs.

PROGRAM EDUCATIONAL OBJECTIVES


PEO1: To acquire knowledge in the latest technologies and innovations and an ability to identify,
analyze, and solve problems in Computer Engineering.

PEO2: To be capable of modeling, designing, implementing, and verifying a computing system to


meet specified requirements for the benefit of society.

PEO3: To possess critical thinking, communication skills, teamwork, leadership skills, and ethical
behaviour necessary to function productively and professionally.

PROGRAM SPECIFIC OBJECTIVES


PSO1: Ability to apply, design, and develop principles of software engineering, networking, and
database concepts for computer-based systems in solving engineering problems.

PSO2: Ability to understand, design, and code engineering problems using programming skills.

PROGRAM OUTCOMES
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems

2. Problem analysis: Identify, formulate, research literature, and analyze complex engineering Problems
reaching substantiated conclusions using first principles of mathematics, natural sciences, and engineering
sciences.

3
3. Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public
health and safety, and the cultural, societal, and environmental considerations

4. Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information to
provide valid conclusions.

5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools including prediction and modeling to complex engineering activities with an understanding
of the limitations.

6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the Professional
engineering practice.

7. Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development

8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.

9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings

10. Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports and
design documentation, make effective presentations, and give and receive clear instructions.

11. Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.

12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.

4
COURSE OBJECTIVES

S.NO DESCRIPTION

1 To understand data definitions and data manipulation commands.

2 To learn the use of nested and join queries

3 To understand views and constraints

4 To understand functions, procedures and procedural extensions of data bases

5 To understand design and implementation of typical database applications

COURSE OUTCOMES

S.NO DESCRIPTION

1 Use typical data definitions and manipulation commands

2 Design applications to test Nested and Join Queries

3 Implement simple applications that use Views

4 Critically analyze the use of Tables, Views, Functions and Procedures

5 Implement applications that require a Front-end Tool

5
CONTENTS
EX. PAGE FACULTY
DATE EXPERIMENT MARKS
NO. NO. SIGN

Data Definition Commands, Data


1 Manipulation Commands for inserting,
deleting, updating and retrieving

Data Control and Transaction Control


2
statements

Database Querying – Simple queries,


3
Nested queries, Sub queries and Joins

4 Integrity Constraints

5 Views, Sequences, Synonyms

Database Programming: Implicit and


6
Explicit Cursors

7 Procedures and Functions

8 Triggers

9 Exception Handling

Development of mini-projects with front


10 end of your choice.

Library Management

6
INTRODUCTION TO SQL COMMANDS

SQL commands are instructions used to communicate with the database to perform specific task
that work with data. SQL commands can be used not only for searching the database but also to
perform various other functions like, for example, you can create tables, add data to tables, or modify
data, drop the table, set permissions for users. SQL commands are grouped into four major categories
depending on their functionality:

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

7
EX.NO : 01 DATA DEFINITION COMMANDS, DATA
DATE : MANIPULATION COMMANDS FOR INSERTING,
DELETING, UPDATING AND RETRIEVING TABLES

AIM

To study the database creation, Data definition commands, Data manipulation commands for
inserting, deleting, updating and retrieving tables from the database.

1. DATA DEFINITION LANGUAGE (DDL): The Data Definition Language (DDL) is used to create
and destroy databases and database objects. These commands will primarily be used by database
administrators during the setup and removal phases of a database project. Let's take a look at the
structure and usage of four basic DDL commands:
1.CREATE 2.ALTER 3. DROP 4. RENAME

1.CREATE:
CREATE TABLE: This is used to create a new relation (table)
Syntax: CREATE TABLE <relation_name/table_name > (field_1 data_type(size),field_2
data_type(size), .. . );
Example:
SQL> CREATE TABLE Student (sno INT (3), sname CHAR (10), class CHAR (5));
SQL> DESC Student;
Output :
Field Type Null Key Default
Sno int YES NULL
Sname char(10) YES NULL
Class char(5) YES NULL

2.ALTER:
a)ALTER TABLE ...ADD...: This is used to add some extra fields into existing relation.
Syntax: ALTER TABLE relation_name ADD (new field_1 data_type(size), new field_2
data_type(size),..);
Example: SQL>ALTER TABLE std ADD (Address CHAR(10));
SQL>DESC Student;
Output :
Field Type Null Key Default
Sno int YES NULL
Sname char(10) YES NULL
Class char(5) YES NULL
Address char(10) YES NULL

b)ALTER TABLE...MODIFY...: This is used to change the width as well as data type of fields of

8
existing relations.
Syntax: ALTER TABLE relation_name MODIFY (field_1 newdata_type(Size), field_2
newdata_type(Size),... field_newdata_type(Size));
Example: SQL>ALTER TABLE student MODIFY(sname VARCHAR(10),class VARCHAR(5));
SQL>DESC Student;
Output :
Field Type Null Key Default
Sno int YES NULL
Sname char(15) YES NULL
Class char(6) YES NULL
Address char(20) YES NULL

c) ALTER TABLE .. DROP ..This is used to remove any field of existing relations.

Syntax: ALTER TABLE relation_name DROP COLUMN (field_name);


Example: SQL>ALTER TABLE student DROP column (sname);
SQL>DESC Student;
Output :
Field Type Null Key Default
Sno int YES NULL
Class char(5) YES NULL
Address char(10) YES NULL

d).ALTER TABLE..RENAME...: This is used to change the name of fields in existing relations.
Syntax: ALTER TABLE relation_name RENAME COLUMN (OLD field_name) to (NEW
field_name);
Example: SQL>ALTER TABLE student RENAME COLUMN sname to stu_name;
SQL>DESC Student;
Output :
Field Type Null Key Default
Sno int YES NULL
Stuname char(10) YES NULL
Class char(5) YES NULL
Address char(10) YES NULL

3).DROP TABLE: This is used to delete the structure of a relation. It permanently deletes the
records in the table.
Syntax: DROP TABLE relation_name;
Example: SQL>DROP TABLE std;
Output : The table Student does not exist.
4).RENAME: It is used to modify the name of the existing database object.
Syntax: RENAME TABLE old_relation_name TO new_relation_name;
Example: SQL>RENAME TABLE Student TO std1;
9
Output :
Now the table Student is renamed to std1.

2).DATA MANIPULATION LANGUAGE (DML): The Data Manipulation Language (DML)


is used to retrieve, insert and modify database information. These commands will be used by all
database users during the routine operation of the database. Let's take a brief look at the basic
DML commands:

1. INSERT 2. UPDATE 3. DELETE


1.INSERT INTO:This is used to add records into a relation. These are three type of

INSERT INTO queries which are as


a) Inserting a single record
Syntax: INSERT INTO < relation/table name>(field_1,field_2……field_n)VALUES(data_1,data_2,
................................................................. data_n);

Example: SQL>INSERT INTO student(sno,sname,class,address)VALUES (1,’Ravi’,’M.Tech’,’Palakol’);


Output:
sno sname class address
1 Ravi M.Tech Palakol

b). Inserting a single record


Syntax: INSERT INTO < relation/table name>VALUES (data_1,data_2,……..data_n);
Example: SQL>INSERT INTO student VALUES (1,’Ravi’,’M.Tech’,’Palakol’);
Output:
sno sname class address
1 Ravi M.Tech Palakol
2 ABC M.E palakol

c). Inserting all records from another relation


Syntax: INSERT INTO relation_name_1 SELECT Field_1,field_2,field_nFROM relation_name_2
WHERE field_x=data;
Example: SQL>INSERT INTO std SELECT sno,sname FROM
studentWHERE name = ‘Ramu‘;

Output:
sno sname
1 Ramu

10
d). Inserting multiple records
Syntax: INSERT INTO relation_name field_1,field_2, ......................... field_n) VALUES
(&data_1,&data_2, ..................................................... &data_n);

Example:SQL>INSERT INTO student (sno, sname, class,address)VALUES


(&sno,’&sname’,’&class’,’&address’);

Enter value for sno: 101


Enter value for name: Ravi
Enter value for class: M.Tech
Enter value for name: Palakol
Output:
sno sname class address
1 Ravi MTech Palakol
2 ABC M.E palakol
3 Rani MTech palakol

1. UPDATE-SET-WHERE: This is used to update the content of a record in a relation.


Syntax:SQL>UPDATE relation name SET Field_name1=data,field_name2=data,WHERE
field_name=data;
Example:SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;
Output:
sno sname class address
1 Kumar M.E Palakol
2 Ravi M.E palakol
3 Rani MTech palakol

2. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.

a) DELETE-FROM: This is used to delete all the records of relation.


Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;
Output:
Student table deleted

b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation.


Syntax: SQL>DELETE FROM relation_name WHERE condition;
Example: SQL>DELETE FROM student WHERE sno = 2;
Output:
sno sname class address
1 Kumar M.E Palakol
2 Ravi M.E palakol
11
5. TRUNCATE: This command will remove the data permanently. But structure will not be removed.
Output:
Table Deleted Permanently

Difference between Truncate & Delete:-


 By using truncate command data will be removed permanently & will not get back where as
by using delete command data will be removed temporally & get back by using roll back
command.

 By using delete command data will be removed based on the condition where as by
using truncate command there is no condition.
 Truncate is a DDL command & delete is a DML command.

Syntax: TRUNCATE TABLE <Table name>


Example: TRUNCATE TABLE student;

 To Retrieve data from one or more tables.

1. SELECT FROM: To display all fields for all records.


Syntax :
SELECT * FROM relation_name;
Example: SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

2. SELECT FROM: To display a set of fields for all records of relation.


Syntax: SELECT a set of fields FROM relation_name;
Example: SQL> select deptno, dname from dept;
DEPTNO DNAME

10 ACCOUNTING
20 RESEARCH
30 SALES
3. SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
12
selected set of records of a relation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Example:SQL> select * FROM dept WHERE deptno<=20;

DEPTNO DNAME LOC


10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:

Thus the above Procedure was successfully created and executed.

13
EX.NO : 02
DATE : DATA CONTROL AND TRANSACTION CONTROL
STATEMENTS

AIM:
To learn and Implement the Data Control Transaction Control Commands

TCL COMMANDS

Transaction Control Language commands are used to manage transactions in the database. These
are used to manage the changes made by DML-statements. It also allows statements to be grouped
together into logical transactions.

Examples of TCL commands –

COMMIT: Commit command is used to permanently save any transaction


into the database.
ROLLBACK: This command restores the database to last committed state.
It is also used with savepoint command to jump to a savepoint
in a transaction.
SAVEPOINT: Savepoint command is used to temporarily save a transaction so that you can rollback
to that point whenever necessary.
Example 1:
 create database school1;
 use school1;
 CREATE TABLE t_school(ID INT, School_Name VARCHAR(40), No_Of_Students INT,
No_Of_Teachers INT, No_Of_Classrooms INT, EmailID VARCHAR(40));
desc t_school;
START TRANSACTION;
 INSERT INTO t_school(ID, School_Name, No_Of_Students, No_Of_Teachers,
No_Of_Classrooms, EmailID) VALUES
(1, "Boys Town Public School", 1000, 80, 12, "[email protected]"),
(2, "Guru Govind Singh Public School", 800, 35, 15, "[email protected]"),
(3, "Delhi Public School", 1200, 30, 10, "[email protected]"),
(4, "Ashoka Universal School", 1110, 40, 40, "[email protected]"),
(5, "Calibers English Medium School", 9000, 31, 50, " [email protected] ");
 SELECT *FROM t_school;

14
ID School_name No_of_Students No_Of_Teachers No_Of_Classrooms EmailID

1 Boys Town 1000 80 12 [email protected]


Public School
Guru Govind
2 Singh Public 800 35 15 [email protected]
School
Delhi Public
1200 30 10 [email protected]
3 School
Ashoka Universal
1100 40 40 [email protected]
4 School
Calibers English
9000 31 50 [email protected]
5 Medium School

COMMIT:
The COMMIT command is the transactional command used to save changes invoked by a
transaction. It saves all the transactions occurred on the database since the last COMMIT or
ROLLBACK.

SYNTAX:
COMMIT;
Example 2:
 CREATE DATABASE t_school 1 row(s) affected
 use t_school 0 row(s) affected
 desc t_school COMMIT 0 row(s) returned
 SET autocommit = 0;
 SAVEPOINT Insertion;
 UPDATE t_school SET Number_Of_Students = 9050 WHERE ID = 5;
 SELECT *FROM t_school;

ID School_name No_of_S No_Of_Teachers No_Of_Classrooms EmailID


tudents
Boys Town Public 1000 80 12 [email protected]
1 School
Guru Govind Singh 800 35 15 [email protected]
2 Public School
Delhi Public School 1200 30 10 [email protected]
3
Ashoka Universal 1100 40 40 [email protected]
4 School
Calibers English 9050 31 50 [email protected]
5 Medium School

15
 SAVEPOINT Updation;
 ROLLBACK TO Insertion;
 SELECT *FROM t_school;

ID School_name No_of_St No_Of_Teachers No_Of_Classrooms EmailID


udents
Boys Town Public 1000 80 12 [email protected]
1 School
Guru Govind 800 35 15 [email protected]
2 Singh Public
School
Delhi Public 1200 30 10 [email protected]
3 School
Ashoka Universal 1100 40 40 [email protected]
4 School
Calibers English 9000 31 50 [email protected]
5 Medium School

DCL (Data Control Language) :


It is used to provide different users access to the stored data. It enables the data administrator to grant or revoke the
required access to act as the database. When DCL commands are implemented in the database, there is no feature to
perform a rollback.

Examples of DCL commands :


 GRANT: allow specified users to perform specified tasks.
 REVOKE: cancel previously granted or denied permissions.
I. GRANT:
GRANT SELECT ON t_school TO Amal;

This command will allow Amal to implement the SELECT queries on the student table. This will
enable the user to read or retrieve information from the student table.
The owner can allow other user to access his object as per his diversion of the permission is called
privilege.

Types of Privilege: 1. System Privilege 2. Object Privilege:


A permission granted to execute the various data definition command like Create Table, Create
Sequence, create session are called System Privilege.

1. System Privilege:
Grant Command is used to give System Privilege to an oracle user.

SYNTAX:
GRANT system privilege TO user;

16
Sample Query:
GRANT CREATE ON t_school TO Amal;
GRANT CREATE ON student TO Amala;
Example 3:
 Create user amal identified by abc123;
 User created
 Select *from t_school

S.NO Staff_ID Staff_Name


1 xxx Malar
2 yyy Rajan
3 zzz amal

 Connect;
Enter user_name:system
Enter password:abc123
Connected
Enter user_name:Amal
Enter password:abc123
Connected

 GRANT SELECT ON t_school TO Amal;


GRANT SUCCEED\

 GRANT SELECT * from system t_school;


 INSERT into system t_school values(4,yzz,Anu)
1 row created
 GRANT SELECT * from system t_school;

S.NO Staff_ID Staff_Name


1 xxx Malar
2 yyy Rajan
3 zzz amal
4 yzz Anu

4 rows selected

2.Object Privilege:
An Object Privilege enables a user to execute some commands on the database object
like table view sequence etc. Some of the object privileges are
i. Alter
ii. Index
iii. Insert
iv. Update
v. Delete
vi. Select
vii. References

Syntax:
Grant object privilege[Object privilege] ON object to user [with grant option]
17
Sample Query:
SQL>Grant select,update,delete on t_school to staff;

UPDATE:
 GRANT UPDATE * from system t_school;

S.NO Staff_ID Staff_Name


1 xxx Malar
2 yyy Rajan
3 zzz amal
4 yzz Anu

4 rows updated
DELETE:
 GRANT DELETE from system t_school where staff_ID – xxx;
1 row deleted
 GRANT SELECT * from system t_school;

S.NO Staff_ID Staff_Name


1 yyy Rajan
2 zzz Amal
3 yzz Anu

II. REVOKE:
Permission granted to a user can also be taken back by the granter. This can be done
by the REVOKE command.

REVOKE SELECT ON student FROM Amal;

This will stop the user Amal from implementing the SELECT query on the student table. The user may
be able to implement other queries in the database.
Syntax:
Revoke object privilege[object privilege] ON object name from user name;
Example:
i. SQL>REVOKE SELECT,INSERT ON t_school from staff;
ii. SQL>REVOKE SELECT ON t_school from rajan;

 Connect;
Enter user_name:system
Enter password:abc123
Connected
Enter user_name:Amal
Enter password:abc123
Connected

 Drop user Amal;


User dropped
18
 REVOKE DELETE on t_school from amal;
Revoke succeed
 REVOKE SELECT,INSERT ON t_school from staff;
 REVOKE SELECT ON t_school from rajan;

ERROR:
Invalid username/password;login denied
Warning:you are no longer connected

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:

Thus the above Procedure was successfully created and executed.

19
EX.NO : 03 DATABASE QUERYING – SIMPLE QUERIES, NESTED
DATE : QUERIES, SUB QUERIES AND JOINS

AIM:

To study and Implement the Database Querying –Simple Queries, Sub Queries and
Joins.

Simple Queries:

1. Aggregate function
2. String function
3. Date function
4. SQL Arithmetic Operators
5. Comparison Operators
6. SQL Logical Operators
7. SQL Set Operators

AGGREGATE FUNCTIONS

Queries using aggregate functions(COUNT,AVG,MIN,MAX,SUM),Group by,Orderby,Having.

(i) Create Employee table containing all Records.


SQL> create table emp(eidnumber INT,ename varchar(10),age INT,salary INT);
Table created.

Output:

eidnmber ename age salary


1 babu 25 50000
2 Logesh 26 40000
3 gowtham 23 40000

(ii) Count number of employee names from employeetable.


SQL> select count(ename) from emp;
Output:

count(ename)
3

(iii) Find the Maximum age from employeetable.


SQL> select max(age) from emp;
Output:
max(age)
26

(iv) SQL> select min(age) from emp;


Output:

min(age) 20
23
(v) Display the Sum of age employeetable.
SQL> select sum(age) from emp;
Output:

sum(age)
74

(vi) Display the Average of age from Employeetable.


SQL> select avg(age) from emp;
Output:

avg(age)
24.6667

(vii) Find grouped salaries of employees.(group by clause)


SQL> select salary from emp group by salary;
Output:
salary
50000
40000

(viii).Find salaries of employee in Ascending Order.(order by clause)


SQL> select ename, salary from emp order by salary;
Output:
ename salary
logesh 40000
gowtham 40000
babu 50000

(ix) HavingClause.
SQL> select ename,salary from emp where age<29 group by ename, salary having
salary<10000;
Output:
ename salary
gowtham 40000

STRING FUNCTIONS
a. Concat: CONCAT returns char1 concatenated with char2. Both char1 and char2 can be any
of the datatypes.
SQL>SELECT CONCAT(‘ORACLE’,’CORPORATION’)FROM DUAL;
Output: ORACLECORPORATION

b. Lower: Returns a character expression after converting uppercase character data to


lowercase.
SQL>SELECT LOWER(‘DBMS’)FROM DUAL;
Output: dbms

21
c. Upper: Returns a character expression with lowercase character data converted to uppercase
SQL>SELECT UPPER(‘dbms’)FROM DUAL;
Output: DBMS

d. Length: Returns the number of characters, rather than the number of bytes, of the given string
expression, excluding trailing blanks.
SQL>SELECT LENGTH(‘DATABASE’)FROM DUAL;
Output: 8

e. Substr: Returns part of a character, binary, text, or image expression.


SQL>SELECT SUBSTR(‘ABCDEFGHIJ’3,4)FROM DUAL;
Output: CDEF

DATE FUNCTIONS
1. Sysdate:
SQL>SELECT SYSDATE FROM DUAL;
Output: 29-MAR-24

2. next_day:
SQL>SELECT NEXT_DAY(SYSDATE,’WED’)FROM DUAL;
Output: 30-MAR-24

3. add_months:
SQL>SELECT ADD_MONTHS(SYSDATE,2)FROM DUAL;
Output: 29-MAY-24

4. last_day:
SQL>SELECT LAST_DAY(SYSDATE)FROM DUAL;
Output: 31-MAR-24

5. to_date:
SQL> select to date (sysdate, "dd\mm\yy") from dual;
Output: 29\03\24

ARITHMETIC OPERATORS
Following are the various arithmetic operators performed on the SQL data:
1. Addition Operator (+)
2. Subtraction Operator (-)
3. Multiplication Operator (+)
4. Division Operator (-)
5. Modulus Operator (+)

We can perform arithmetic operations directly on numbers


Syntax: SELECT operand1 operator operand2;
SELECT 30+10;
22
SELECT 30-10;
SELECT 6*5;
SELECT 30/3;
SLECET 30%7;

Arithmetic Operators in SQL query:

Create Employee_details table, with four columns Emp_Id, Emp_Name, Emp_Salary,


and Emp_Monthlybonus.

Emp Id Emp Name Emp Salary Emp Monthlybonus


101 Tushar 25000 4000
102 Anuj 30000 200

1. SELECT Emp_Salary + 20000 as Emp_New_Salary FROM Employee_details;


OUTPUT:
Emp_New_Salary
45000
50000

2. SELECT Emp_Salary - 5000 as Emp_New_Salary FROM Employee_details;


OUTPUT:
Emp_New_Salary
20000
25000

3. SELECT Emp_Salary * 2 as Emp_New_Salary FROM Employee_details;


OUTPUT:
Emp_New_Salary
50000
60000

4. SELECT Emp_Salary / 2 as Emp_New_Salary FROM Employee_details;


OUTPUT:
Emp_New_Salary
12500.0000
15000.0000

5. SELECT Emp_Salary % Emp_Monthlybonus as Remainder FROM Employee_details;


OUTPUT:
Emp_New_Salary
1000
0

23
Comparison Operators
The Comparison Operators in SQL compare two different data of SQL table and check
whether they are the same, greater, and lesser. The SQL comparison operators are used with
the WHERE clause in the SQL queries

Following are the various comparison operators which are performed on the data stored
in the SQL database tables:

1. SQL Equal Operator (=)


2. SQL Not Equal Operator (!=)
3. SQL Greater Than Operator (>)
4. SQL Greater Than Equals to Operator (>=)
5. SQL Less Than Operator (<)\
6. SQL Less Than Equals to Operator (<=)

Create Employee_details table, with three columns Emp_Id, Emp_Name, and Emp_Salary.

Emp Id Emp Name Emp Salary


201 Abhay 30000
202 Ankit 40000
203 Bheem 30000
204 Ram 29000
205 Sumit 30000

1. SELECT * FROM Employee_details WHERE Emp_Salary = 30000;


OUTPUT:
Emp_id Emp_name Emp_salary
201 Abhay 30000
203 Bheem 30000
205 Sumit 30000

2. SELECT * FROM Employee_details WHERE Emp_Salary != 40000;


OUTPUT:
Emp_id Emp_name Emp_salary
201 Abhay 30000
203 Bheem 30000
204 Ram 29000
205 Sumit 30000

3. SELECT * FROM Employee_details WHERE Emp_Id > 202;


OUTPUT:
Emp_id Emp_name Emp_salary
203 Bheem 30000
204 Ram 29000
205 Sumit 30000

24
4. SELECT * FROM Employee_details WHERE Emp_Id < 204;
OUTPUT:
Emp_id Emp_name Emp_salary
201 Abhay 30000
202 Ankit 40000
203 Bheem 30000

SQL LOGICAL OPERATORS


The Logical Operators in SQL perform the Boolean operations, which give two results True
and False.

Following are the various logical operators which are performed on the data stored in
the SQL database tables:
1. ALL operator
2. AND operator
3. OR operator
4. BETWEEN operator
5. IN operator
6. NOT operator
7. ANY operator
8. LIKE operator

These operators are always used with the following statement:


 SELECT,
 HAVING, and
 WHERE.
Create Employee_details table, which has three columns Emp_Id, Emp_Name,
Emp_Salary, and Emp_City.

Emp Id Emp Name Emp Salary Emp City


201 Abhay 25000 Gurgaon
202 Ankit 25000 Delhi
203 Bheem 30000 Jaipur
204 Ram 29000 Mumbai
205 Sumit 40000 Kolkata

Syntax of AND operator:


SELECT column1, ... , columnN FROM table_Name WHERE condition1 AND condition2 A
ND condition3 AND ....... AND conditionN;
SELECT * FROM Employee_details WHERE Emp_Salary = 25000 AND Emp_City = 'Delhi’;
OUTPUT:
Emp_id Emp_name Emp_salary Emp_City
202 Ankit 25000 Delhi

Syntax of OR operator:

SELECT column1, ... , columnN FROM table_Name WHERE condition1 OR condition2 OR condition
3 OR ....... OR conditionN;

25
SELECT * FROM Employee_details WHERE Emp_Salary = 25000 OR Emp_City = 'Delhi';
OUTPUT:
Emp_id Emp_name Emp_salary Emp_City
202 Ankit 25000 Delhi

Syntax of BETWEEN operator:

SELECT column_Name1, column_Name2 .... , column_Namen FROM table_Name WHERE


Column_name BETWEEN value1 and value2;

SELECT * FROM Employee_details WHERE Emp_Salary BETWEEN 30000 AND 45000;


OUTPUT:
Emp_id Emp_name Emp_salary Emp_City
201 Abhay 30000 Gurgaon
202 Ankit 40000 Delhi
203 Bheem 30000 Jaipur
205 Sumit 30000 Kolkata

SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' ;


OUTPUT:
Emp_id Emp_name Emp_salary Emp_City
201 Abhay 30000 Gurgaon
203 Bheem 30000 Jaipur
204 Ram 29000 Mumbai
205 Sumit 30000 Kolkata

SELECT * FROM Employee_details WHERE Emp_Name LIKE 's%' ;


OUTPUT:
Emp_id Emp_name Emp_salary Emp_City
205 Sumit 30000 Kolkata

SQL SET OPERATORS


The Set Operators in SQL combine a similar type of data from two or more SQL database
tables. It mixes the result, which is extracted from two or more SQL queries, into a single result.

Following are the various set operators which are performed on the similar data
stored in the two SQL database tables:

1. SQL Union Operator


2. SQL Union ALL Operator
3. SQL Intersect Operator
4. SQL Minus Operator

Create Two tables with four columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.
26
Table1: Employee_details1

Emp Id Emp Name Emp Salary Emp City


201 Sanjay 25000 Delhi
202 Ajay 45000 Delhi
203 Saket 30000 Aligarh

Table2 : Employee_details2

Emp Id Emp Name Emp Salary Emp City


203 Saket 30000 Aligarh
204 Saurabh 40000 Delhi
205 Ram 30000 Kerala
201 Sanjay 25000 Delhi

1. SELECT Emp_Name FROM Employee_details1 UNION ALL


SELECT Emp_Name FROM Employee_details2 ;
OUTPUT:
Emp_Name
Sanjay
Ajay
Saket
Saket
Saurabh
Ram
Sanjay

2. SELECT Emp_Name FROM Employee_details1 INTERSECT


SELECT Emp_Name FROM Employee_details2 ;
OUTPUT:
Emp_Name
Saket

3. SELECT Emp_Name FROM Employee_details1 MINUS


SELECT Emp_Name FROM Employee_details2 ;
OUTPUT:
Emp_Name
Sanjay
Ajay

JOINS

PROCEDURE

SQL - Using Joins


The SQL Joins clause is used to combine records from two or more tables in a database. A
JOIN is a means for combining fields from two tables by using values common to each.

There are different types of joins available in SQL −


INNER JOIN − returns rows when there is a match in both tables.
LEFT JOIN − returns all rows from the left table, even if there are no matches in the right
27
table.
RIGHT JOIN − returns all rows from the right table, even if there are no
matches in the left table.
FULL JOIN − returns rows when there is a match in one of the tables.
SELF JOIN − is used to join a table to itself as if the table were two tables, temporarily
renaming at least one table in the SQL statement.
CARTESIAN JOIN − returns the Cartesian product of the sets
of records from the two or more joined tables.

Let us now discuss each of these joins in detail.

SQL - INNER JOINS

The most important and frequently used of the joins is the INNER JOIN. They are also referred
to as an EQUIJOIN.
The INNER JOIN creates a new result table by combining column values of two tables
(table1 and table2) based upon the join-predicate. The query compares each row of table1
with each row of table2 to find all pairs of rows which satisfy the join-predicate. When the
join-predicate is satisfied, column values for each matched pair of rows of A and B are
combined into a result row.
Syntax
SELECT table1.column1, table2.column2... FROM table1 INNER JOIN table2
ON table1.common_field = table2.common_field;

Example
Consider the following two tables.
Table 1 − CUSTOMERS Table is as follows.
+ +
| ID | NAME | AGE | ADDRESS | SALARY |
+ +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00|
+ +

Table 2 − ORDERS Table is as follows.


+ +
| OID | DATE | CUSTOMER_ID | AMOUNT |
+ +
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
+ +

28
Now, let us join these two tables using the INNER JOIN as follows –

SQL>SELECT ID, NAME,AMOUNT, DATE FROM CUSTOMERS INNER JOIN


ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result.


+ +
| ID | NAME | AMOUNT | DATE |
+ +
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+ +

SQL - LEFT JOINS

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the
right table. This means that if the ON clause matches 0 (zero) records in the right table; the
join will still return a row in the result, but with NULL in each column from the right table.
This means that a left join returns all the values from the left table, plus matched values from
the right table or NULL in case of no matching join predicate.

Syntax
SELECT table1.column1, table2.column2... FROM table1 LEFT JOIN table2 ON
table1.common_field = table2.common_field;
Here, the given condition could be any given expression based on your requirement.

Example
Consider the ABOVE two tables,
Now, let us join these two tables using the LEFT JOIN as follows.

SQL>SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN


ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result −


+ +
| ID | NAME | AMOUNT | DATE |
+ +
| 1 | Ramesh | NULL | NULL |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | Kaushik | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | NULL | NULL |
| 6 | Komal | NULL | NULL |
| 7 | Muffy | NULL | NULL |
+ +

SQL - RIGHT JOINS

The SQL RIGHT JOIN returns all rows from the right table, even if there are no matches
29
in the left table. This means that if the ON clause matches 0 (zero) records in the left table;
the join will still return a row in the result, but with NULL in each column from the left
table.
This means that a right join returns all the values from the right table, plus matched values
from the left table or NULL in case of no matching join predicate.

Syntax
SELECT table1.column1, table2.column2... FROM table1 RIGHT JOIN table2
ON table1.common_field = table2.common_field;

Example
Consider the ABOVE two tables,

Now, let us join these two tables using the RIGHT JOIN as follows.

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS
ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

This would produce the following result –


+ +
| ID | NAME | AMOUNT | DATE |
+ +
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | Kaushik | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
+ +

SQL - FULL JOINS

The SQL FULL JOIN combines the results of both left and right outer joins.
The joined table will contain all records from both the tables and fill in NULLs for missing
matches on either side.

Syntax
SELECT table1.column1, table2.column2...
FROM table1 FULL JOIN table2 ON table1.common_field = table2.common_field;

Here, the given condition could be any given expression based on your requirement.

Example
Consider the ABOVE two tables.

Now, let us join these two tables using FULL JOIN as follows.
SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS FULL JOIN
ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

If your Database does not support FULL JOIN (MySQL does not support FULL JOIN),
then you can use UNION ALL clause to combine these two JOINS as shown below.

SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN
ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID UNION ALL SELECT
30
ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON
CUSTOMERS.ID = ORDERS.CUSTOMER_ID

SQL - SELF JOINS

The SQL SELF JOIN is used to join a table to itself as if the table were
two tables; temporarily renaming at least one table in the SQL statement.

Syntax
SELECT a.column_name, b.column_name... FROM table1 a, table1 b WHERE
a.common_field = b.common_field;

Here, the WHERE clause could be any given expression based on your requirement.

Example Consider the ABOVE tableS.


Now, let us join this table using SELF JOIN as follows –

SQL> SELECT a.ID, b.NAME, a.SALARY FROM CUSTOMERS a, CUSTOMERS b


WHERE a.SALARY < b.SALARY;

This would produce the following result −


+ +
| ID | NAME | SALARY |
+ +
| 2 | Ramesh | 1500.00 |
| 2 | kaushik | 1500.00 |
| 1 | Chaitali | 2000.00 |
| 2 | Chaitali | 1500.00 |
| 3 | Chaitali | 2000.00 |
| 6 | Chaitali | 4500.00 |
| 1 | Hardik | 2000.00 |
| 2 | Hardik | 1500.00 |
| 3 | Hardik | 2000.00 |
| 4 | Hardik | 6500.00 |
| 6 | Hardik | 4500.00 |
| 1 | Komal | 2000.00 |
| 2 | Komal | 1500.00 |
| 3 | Komal | 2000.00 |
| 1 | Muffy | 2000.00 |
| 2 | Muffy | 1500.00 |
| 3 | Muffy | 2000.00 |
| 4 | Muffy | 6500.00 |
| 5 | Muffy | 8500.00 |
| 6 | Muffy | 4500.00 |
+ +

SQL - CROSS JOINS


The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records from
two or more joined tables. Thus, it equates to an inner join where the join-condition always
evaluates to either True or where the join-condition is absent from the statement.
Syntax
The basic syntax of the CROSS JOIN is as follows − SELECT table1.column1,
table2.column2... FROM table1, table2 [, table3 ]
31
Example
Consider the ABOVE two tables.

Now, let us join these two tables using CARTESIAN JOIN as follows –
SQL> SELECT ID, NAME AMOUNT, DATE FROM CUSTOMERS, ORDERS;

+ +
| ID | NAME | AMOUNT | DATE |
+ +
| 1 | Ramesh | 3000 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1500 | 2009-10-08 00:00:00 |
| 1 | Ramesh | 1560 | 2009-11-20 00:00:00 |
| 1 | Ramesh | 2060 | 2008-05-20 00:00:00 |
| 2 | Khilan | 3000 | 2009-10-08 00:00:00 |
| 102 | 2009-10-08 00:00:00 | 3 | 3000 |
| 100 | 2009-10-08 00:00:00 | 3 | 1500 |
| 101 | 2009-11-20 00:00:00 | 2 | 1560 |
| 103 | 2008-05-20 00:00:00 | 4 | 2060 |
| 2 | Khilan | 1500 | 2009-10-08 00:00:00 |
| 2 | Khilan | 1560 | 2009-11-20 00:00:00 |
| 2 | Khilan | 2060 | 2008-05-20 00:00:00 |
| 3 | kaushik | 3000 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1500 | 2009-10-08 00:00:00 |
| 3 | kaushik | 1560 | 2009-11-20 00:00:00 |
| 3 | kaushik | 2060 | 2008-05-20 00:00:00 |
| 4 | Chaitali | 3000 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1500 | 2009-10-08 00:00:00 |
| 4 | Chaitali | 1560 | 2009-11-20 00:00:00 |
| 4 | Chaitali | 2060 | 2008-05-20 00:00:00 |
| 5 | Hardik | 3000 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1500 | 2009-10-08 00:00:00 |
| 5 | Hardik | 1560 | 2009-11-20 00:00:00 |
| 5 | Hardik | 2060 | 2008-05-20 00:00:00 |
| 6 | Komal | 3000 | 2009-10-08 00:00:00 |
| 6 | Komal | 1500 | 2009-10-08 00:00:00 |
| 6 | Komal | 1560 | 2009-11-20 00:00:00 |
| 7 | Muffy | 2060 | 2008-05-20 00:00:00 |
+ +

NESTED SUBQUERY
If a Subquery contains another subquery, then the subquery inside another subquery is
called nested subquery.

Table1:
create table Student (Studentid int ,Firstname varchar(200), Lastname varchar(200),
Email varchar(100)):

32
Studentid | Firstname | Lastname | Email

1 | John | Doe | [email protected]


2 | Dhinakar | King | [email protected]
3 | Alice | Johnson | [email protected]

Table2:
create table Course (Courseid int , Coursename nvarchar(250), CourseAdmin int);

Courseid | Coursename | CourseAdmin


1 | Mathematics | 101
2 | Physics | 102
3 | Oracle | 103

Table3:
create table StudentCourse( StudentCourseid int , Studentid int, Courseid int)

StudentCourseid | Studentid | Courseid

1 |1 |3 -- John Doe is enrolled in Oracle


2 |3 |3 -- Alice Johnson is enrolled in Oracle

Query:
select Firstname, lastname from student where studentid in (select studentid from studentcourse
where coursed in (select courseid from course where coursename=’Oracle’);

Output:
Firstname | Lastname

John | Doe
Alice | Johnson

SUBQUERY

STUDENT table
Student(name,rollno,section,location ,phone number)

* | | | | *
| NAME | ROLL_NO | SECTION | LOCATION | PHONE_NUMBER |
* | | | | *
| Ram | 101 | A | Chennai | 9988775566 |
| Raj | 102 | C | Coimbatore | 8877665544 |
| Sasi | 103 | D | Madurai | 7766553344 |
| Ravi | 104 | A | Salem | 8989898989 |
| Sumathi | 105 | B | Kanchipuram | 8989856868 |
| John | 106 | C | Bangalore | 9876543210 |
* | | | | *

33
GRADING

Grade(name,rollno,grade)
+ ---------------------------------------- +
NAME | ROLL_NO | GRADE |
+ +
Ravi | 104 |O |
Sumathi |105 |B |
Raj |102 |O |
Suman |101 |A |
+ +

Query1:
SELECT NAME, LOCATION, PHONE_NUMBER FROM Student WHERE ROLL_NO IN (SELECT
ROLL_NO FROM Grading WHERE GRADE = 'O');

Output
* | | *
| NAME | LOCATION | PHONE_NUMBER |
* | | *
| Ravi | Salem | 8989898989 |
| Raj | Coimbatore | 8877665544 |
* | | *

Query2:

DELETE FROM Student WHERE ROLL_NO IN (SELECT ROLL_NO FROM Grading


WHERE GRADE = 'B');
Output

* | | | | *
| NAME |ROLL_NO |SECTION | LOCATION |PHONE_NUMBER |
* | | | | *
| Ram | 101 | A | Chennai | 9988775566 |
| Raj | 102 | C | Coimbatore | 8877665544 |
| Sasi | 103 | D | Madurai | 7766553344
|
| Ravi | 104 | A | Salem | 8989898989 |
* | | | | *
Query3:

UPDATE Student SET NAME = 'geeks' WHERE ROLL_NO IN (SELECT ROLL_NO FROM
grading WHERE NAME IN ('Raj', 'Ravi'));

34
Output

* | | | | *
| NAME | ROLL_NO | SECTION | LOCATION | PHONE_NUMBER |
* | | | | *
| Ram | 101 | A | Chennai | 9988775566 |
| geeks | 102 | C | Coimbatore | 8877665544 |
| Sasi | 103 | D | Madurai | 7766553344 |
| geeks | 104 | A | Salem | 8989898989 |
* | | | | *

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)

RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:

Thus the above Procedure was successfully created and executed.

35
EX.NO : 04
INTEGRITY CONSTRAINTS
DATE :

AIM: To Study & Implement different types of Integrity constraints

CONSTRAINTS:
Constraints are used to specify rules for the data in a table. If there is any violation between the
constraint and the data action, the action is aborted by the constraint. It can be specified when the table
is created (using CREATE TABLE statement) or after the table is created
(using ALTER TABLE statement).

Constraints are grouped into 3 categories


1. Domain Integrity constraints
Constraints imposed on column. Types of constraints comes under this is
a) Not Null Constraint: Ensures that a column cannot have NULL value.
b) Default Constraint: Provides a default value for a column when none is specified.
c) Check Constraint: Makes sure that all values in a column satisfy certain criteria.

2. Entity integrity constraints


Constraints imposed on each row. Types of constraints comes under this is
d) Unique Constraint: Ensures that all values in a column are different.
e) Primary key Constraint: Used to uniquely identify a row in the table.

3. Referential integrity Constraint: Used to ensure referential integrity of the data

1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record is to be
accepted for storage in the table.

Syntax: CREATE TABLE Table_Name (column_name data_type (size) NOT NULL, );


Example: CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));

OUTPUT:
 mysql> desc student;  mysql> Select * from student;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra | SNO NAME
+-------+----------+------+-----+---------+-------+ 1 BLACKY
| sno | int | NO | | NULL | | 2 KHAN
3 ROBIN
| name | char(10) | YES | | NULL | |
4 JOHN
+-------+----------+------+-----+---------+-------+

 mysql> insert into student values(null,'nithin');


ERROR 1048 (23000): Column 'sno' cannot be null
36
2. DEFAULT : The DEFAULT constraint is used to insert a default value into a column. The
default value will be added to all new records, if no other value is specified.

Syntax: CREATE TABLE Table_Name(col_name1,col_name2,col_name3 DEFAULT ‘<value>’);


Example: CREATE TABLE student (sno INT UNIQUE, name CHAR(10),address
VARCHAR(20) DEFAULT ‘Aurangabad’);
 insert into student1(sno,name)values(1,'BLACKY'),(2,'KHAN'),(3,'ROBIN');
OUTPUT:
SNO NAME ADDRESS
1 BLACKY Aurangabad
2 KHAN Aurangabad
3 ROBIN Aurangabad

3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the constraint,
each row in the table must make the condition either TRUE or unknown (due to a null).
Syntax: CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);
Example: CREATE TABLE student3 (sno INT, name CHAR(10),class CHAR(5),CHECK(class
IN('CSE','CAD','VLSI')));
OUTPUT:
SNO NAME CLASS
1 BLACKY CSE
2 KHAN VLSI
3 JHON CAD
4 ROBIN VLSI
5 DANNY CSE

 mysql> insert into student3(sno,name,class)values(6,'BINU','EEE');


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

4.UNIQUE: The purpose of a unique key is to ensure that information in the column(s) is
unique i.e. a value entered in column(s) defined in the unique constraint must not be repeated across
the column(s). A table may have many unique keys.
Syntax: CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example: CREATE TABLE student4 (sno INT) UNIQUE, name CHAR(10));

OUTPUT:
SNO NAME
1 KHAN
2 JOHN
3 BLACKY
4 DANNY

 mysql> insert into student4(sno,name)values(1,'kavin');


ERROR 1062 (23000): Duplicate entry '1' for key 'student4.sno'
37
5.PRIMARY KEY: A field which is used to identify a record uniquely. A column or combination
of columns can be created as primary key, which can be used as a reference from other tables. A
table contains primary key is known as Master Table.
 It must uniquely identify each record in a table.
 It must contain unique values.
 It cannot be a null field.
 It cannot be multi port field.
 It should contain a minimum no. of fields necessary to be called unique.

Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY,….);
Example: CREATE TABLE faculty (fcode INT PRIMARY KEY, fname CHAR(10));

OUTPUT:
 Select * from faculty;  mysql> DESC FACULTY;
FCODE FNAME +-------+----------+------+-----+---------+-------+
11 JOHN | Field | Type | Null | Key | Default | Extra |
222 DANNY +-------+----------+------+-----+---------+-------+
333 BLACKY | fcode | int | NO | PRI | NULL | |
| fname | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+

6.FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To reference
any primary key column from other table this constraint can be used. The table in which the foreign
key is defined is called a detail table. The table that defines the primary key and is referenced by the
foreign key is called the master table.

Syntax: CREATE TABLE Table_Name(column_name data_type(size)


FOREIGN KEY(column_name) REFERENCES table_name);
Example: CREATE TABLE subject (scode INT PRIMARY KEY, subname CHAR(10), fcode
INT, FOREIGN KEY(fcode) REFERENCES faculty(fcode );

OUTPUT:
SCODE SUBNAME FCODE
4251 JAVA 111
4252 ENGLISH 222
4253 PYTHON 333

 mysql> insert into subject values(4254,'JAVA2',1111);


ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails
(`exp4`.`subject`, CONSTRAINT `subject_ibfk_1` FOREIGN KEY (`fcode`) REFERENCES
`faculty` (`fcode`))

Defining integrity constraints in the alter table command:


Syntax: ALTER TABLE Table_Name ADD PRIMARY KEY (column_name);
Example: ALTER TABLE student ADD PRIMARY KEY (sno);
(OR)
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY(colname)
Example: ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO);
38
mysql> DESC STUDENT;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| sno | int | NO | PRI | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+

Dropping integrity constraints in the alter table command:

Syntax: ALTER TABLE Table DROP constraint_name;


Example: ALTER TABLE student DROP PRIMARY KEY;
(OR)
Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;
Example: ALTER TABLE student DROP CONSTRAINT SN

OUTPUT:
 mysql> DESC STUDENT;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| sno | int | NO | | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

Result: FACULTY SIGNATURE

Thus the above Procedure was successfully created and executed.

39
EX.NO : 05
CREATION OF VIEWS, SYNONYMS, SEQUENCE
DATE :

AIM:

To Study and implement the Creation of Views, Synonyms, Sequence and Indexes.

VIEWS:

A view is the tailored presentation of data contained in one or more table and can also be
said as restricted view to the data in the tables. A view is a “virtual table” or a “stored query”
which takes the output of a query and treats it as a table. The table upon which a view is created is
called as base table.

A view is a logical table based on a table or another view. A view contains no data of its
own but is like a window through which data from tables can be viewed or changed. The tables
on which a view is based are called base tables. The view is stored as a SELECT statement in the
data dictionary

Advantages of a view:
a. Additional level of table security.
b. Hides data complexity.
c. Simplifies the usage by combinig multiple tables into a single table.
d. Provides datas in different perspective.
Example 1:
 create database l;
 use databasel;
 create table student(sno int, sname varchar(20), sdept varchar(20));
 insert student values(1,’kavi’,’cse’);
 insert student values(2,’gomathi’,’cse’);
 insert student values(3,’naveen’,’ece’);
 select * from student;
Output:
sno sname Sdept
1 Kavi Cse
2 Gomathi Cse
3 naveen Ece

 create view sv as select sno,sname,sdept  Insert into sv(sno,sname,sdept) values


from student where sdept = ‘cse’; (4,’ Brij’,’cse’);
 select * from sv;  select * from sv;
Output:
sno sname Sdept Output:
1 kavi Cse sno sname Sdept
2 gomathi cse 1 kavi Cse
2 gomathi Cse
4 Brij cse
40
 insert sv values(5,’kumar’,’ecE’); Output:
 select * from sv;
sno sname Sdept
1 kavi Cse
2 gomathi Cse
4 Brij cse
5 kumar ece
INDEX

Default index is B-Tree index.


 Index is a db objects, provide a fast access path to column that are indexed.
 It contains an entry for each value that appears in the Index columns.
 Indexes are stored separately from actual data.
 Index are independent of the table, it indexes both physically and logically.
 Index do not have activated & deactivated.
 We can use up to 16 COLUMNS as index.
Example 2:
 Create Index idx1 On STUDENT (SNAME) ;
 SHOW INDEXES FROM student;
Output:

 EXPLAIN SELECT sno, sdept FROM student WHERE sname = ‘kavi’;


Output:

 Create Index idx2 On STUDENT (sno) ;


 EXPLAIN SELECT sno, sdept FROM student WHERE sno = 1;
Output:

 CREATE UNIQUE INDEX idx4 ON student(sname);


 insert student values(4,’kavi,’eee’);

SEQUENCE
 Sequence is a DB object that can generate unique sequential value (serial Number).
41
 Its automatic creates sequence.
 Sequence value is often used for PRIMARY KEY’s & UNIQUE KEY’s.
 When sequence is created, we can define its initial value and the increment between its values.
 The maximum value generated by the sequence is 38 digits.
 To generate starting value sequence NEXTVAL should be used.
Example:
 Create database animal;
 Use animal;
 CREATE TABLE Insects ( Id INT UNSIGNED NOT NULL AUTO_INCREMENT,
PRIMARY KEY (id), Name VARCHAR(30) NOT NULL, Type VARCHAR(30) NOT NULL );
 INSERT INTO Insects (Name, Type) VALUES (‘Cockroach’,’Crawling’), (‘Mosquito’,
‘Flying), (‘Spider’ ,’Crawling’), (‘Grasshopper’, ‘Flying’);
 SELECT * FROM Insects;
Output:

 INSERT INTO Insects (Id, Name, Type) VALUES (6,’Bee’,’Flying’), (7,’Ant’, ‘Crawling’);
 SELECT * FROM Insects;
Output:

 INSERT INTO Insects (Name, Type) VALUES (‘Cricket’,’Crawling’);


 SELECT * FROM Insects;
Output:

42
SYNONYM

A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects. We can avoid the entry of SCHEMA. DML
operation performed on synonym will affect the table.
The main functionality of synonym is to access the database objects between different
schemas without using the schema names.

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:

Thus the above Procedure was successfully created and executed.

43
EX.NO : 06 DATABASE PROGRAMMING IMPLICIT AND
DATE : EXPLICIT CURSORS

AIM:
To study the database Programming PL/SQL using implicit and explicit cursors.

Cursor:
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor holds is
referred to as the active set.
There are two types of cursors −
1. Implicit cursors
2. Explicit cursors
a. Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed, when
there is no explicit cursor for the statement. Programmers cannot control the implicit cursors and the
information in it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to be
inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.

The SQL cursor has several useful attributes.


1. %FOUND is true if the most recent SQL operation affected at least one row.
2. %NOTFOUND is true if it didn’t affect any rows.
3. %ROWCOUNT is returns the number of rows affected.
4. %ISOPEN checks if the cursor is open.Select * from customers;

Example 1:
 CREATE TABLE CUSTOMERS( ID INT NOT NULL, NAME VARCHAR (20) NOT
NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2),
PRIMARY KEY (ID) );
/Table Created .
Insert some sample data into the Customers table:

 INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );
 INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );
 INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );
 INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

44
 INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );
 INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (6, 'Komal', 22, 'MP', 4500.00 );

 Select * from customers;


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+

Query:
 DECLARE
total_rows number;
BEGIN
UPDATE customers SET Salary = Salary + 1500;
total_rows := SQL%ROWCOUNT;
dbms_output.put_line(total_rows || ' rows updated.');
END;
Output:
6 rows updated.
PL/SQL procedure successfully completed.
 Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+

b.Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block. It is created on a
SELECT Statement which returns more than one row.

General syntax for creating a cursor:


CURSOR cursor_name IS select_statement;

45
cursor_name – A suitable name for the cursor.
select_statement – A select query which returns multiple rows
How to use Explicit Cursor?
There are four steps in using an Explicit Cursor.
 DECLARE the cursor in the Declaration section.
 OPEN the cursor in the Execution Section.
 FETCH the data from the cursor into PL/SQL variables or records in the Execution Section.
 CLOSE the cursor in the Execution Section before you end the PL/SQL Block.
Syntax:
DECLARE variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Query:
 DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/ Output
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.

46
CURSOR IN MYSQL
Example: 1

 CREATE TABLE tutorials1 ( ID INT PRIMARY KEY, TITLE VARCHAR(100),


AUTHOR VARCHAR(40), DATE VARCHAR(40) );

Now, insert 5 records in tutorials table using INSERT statements –


 Insert into tutorials1 values
(1, 'Java', 'Krishna', '2019-09-01'),
(2, 'Charts', 'Satish', '2019-05-01'),
(3, 'Springs', 'Amit', '2019-05-01'),
(4, 'Android', 'Ram', '2019-03-01'),
(5, 'Cassandra', 'Pruthvi', '2019-04-06');

Create another table to back up the data −


 CREATE TABLE backup ( ID INT, TITLE VARCHAR(100), AUTHOR ARCHAR(40),
DATE VARCHAR(40) );

Following procedure backups the contents of the tutorials table to the backup table using cursors –

 DELIMITER //
CREATE PROCEDURE ExampleProc1()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE tutorialID INTEGER;
DECLARE tutorialTitle, tutorialAuthor,
tutorialDate VARCHAR(20);
DECLARE cur CURSOR FOR SELECT * FROM tutorials;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur;
label: LOOP
FETCH cur INTO tutorialID, tutorialTitle, tutorialAuthor,
tutorialDate;
INSERT INTO backup VALUES(tutorialID, tutorialTitle,
tutorialAuthor, tutorialDate);
IF done = 1 THEN LEAVE label;
END IF;
END LOOP;
CLOSE cur;
END//
DELIMITER ;

You can call the above procedure as shown below –

 CALL ExampleProc;

If you verify the contents of the backup table you can see the inserted records as shown below −
 select * from backup;

47
Output:
The above query produces the following output −
ID TITLE ` AUTHOR DATE
1 Java Krishna 2019-09-01
2 Charts Satish 2019-05-01
3 Springs Amit 2019-05-01
4 Android Ram 2019-03-01
5 Cassandra Pruthvi 2019-04-06

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result
Thus the above Procedure was successfully created and executed.

48
EX.NO : 07
PROCEDURES AND FUNCTIONS
DATE :

AIM:
To Study the creation of procedures and functions.
Description
A procedure is a block that can take parameters (sometimes referred to as arguments) and be
invoked.
Procedures promote reusability and maintainability. Once validated, they can be used in
number of applications. If the definition changes, only the procedure are affected, this greatly
simplifies maintenance.

Modularized program development:


· Group logically related statements within blocks.
· Nest sub-blocks inside larger blocks to build powerful programs.
· Break down a complex problem into a set of manageable well defined logical
modules and implement the modules with blocks.

Procedure and function blocks:


Procedure:
- No return.
- PROCEDURE name IS
Function:
- Returns a value
- FUNCTION name RETURN data-type IS

Syntax for procedure:


Create [or Replace] PROCEDURE procedur_name
(parameter1 [model1] datatype1,
(parameter2 [model2] datatype2, …)
IS|AS PL/SQL Block;

Example 1:
Let us understand how to create a procedure in MySQL through example. First, we need to select a
database that will store the newly created procedure. We can select the database using the below
statement:
 mysql> USE database_name;
Suppose this database has a table named student that contains the following data:
 mysql> select *from student;
+-----+-------+---------+-------+
| sid | sname | address | marks |
+-----+-------+---------+-------+
| 1 | aaa | pune | 81 |
| 2 | bbb | hyd | 75 |
49
| 3 | ccc | buy | 85 |
| 4 | ddd | delhi | 40 |
+-----+-------+---------+-------+
Procedure without Parameter
Suppose we want to display all records of this table whose marks are greater than 70 and count all the
table rows. The following code creates a procedure named get_merit_students:

 DELIMITER &&
CREATE PROCEDURE get_merit_student ()
BEGIN
SELECT * FROM student WHERE marks > 70;
SELECT COUNT(sid) AS Total_Student FROM student;
END &&
DELIMITER ;
If this code executed successfully, we would get the below output:

 CALL get_merit_student_count();
+-----+-------+---------+-------+
| sid | sname | address | marks |
+-----+-------+---------+-------+
| 1 | aaa | pune | 81 |
| 2 | bbb | hyd | 75 |
| 3 | ccc | buy | 85 |
+-----+-------+---------+-------+
3 rows in set (0.00 sec)

+---------------+
| Total_Student |
+---------------+
| 4|
+---------------+
1 row in set (0.04 sec)

Procedure with Parameter


 DELIMITER &&
CREATE PROCEDURE display_max_mark (OUT highestmark INT)
BEGIN
SELECT MAX(marks) INTO highestmark FROM student_info;
END &&
DELIMITER ;

This procedure's parameter will get the highest marks from the student_info table. When we call the
procedure, the OUT parameter tells the database systems that its value goes out from the procedures.
Now, we will pass its value to a session variable @M in the CALL statement as follows:
mysql> CALL display_max_mark(@M);
mysql> SELECT @M;
50
Here is the output:
+------+
| @M |
+------+
| 85 |
+------+
1 row in set (0.00 sec)

Functions:
A function is a named PL/SQL Block which is similar to a procedure. The major difference
between a procedure and a function is, a function must always return a value, but a procedure
may or may not return a value.

General Syntax to create a function is


CREATE [OR REPLACE] FUNCTION function_name [parameters]
RETURN return_datatype;
IS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;

1) Return Type: The header section defines the return type of the function. The return datatype can
be any of the oracle datatype like varchar, number etc.
2) The execution and exception section both should return a value which is of the datatype defined
in the header section.

Sample Function:
The following example function takes a parameter, performs an operation using an SQL function, and
returns the result.
 mysql> CREATE FUNCTION hello (s CHAR(20))
RETURNS CHAR(50) DETERMINISTIC
RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.20 sec)

 mysql> SELECT hello('world');


+----------------+
| hello('world') |
+----------------+
| Hello, world! |
+----------------+
1 row in set (0.01 sec)
Example 2:
51
Create a function called CalcIncome to calculate income.
 mysql>DELIMITER //
CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE income INT;
SET income = 0;
label1: WHILE income <= 3000 DO
SET income = income + starting_value;
END WHILE label1;
RETURN income;
END; //
DELIMITER ;
Query OK, 0 rows affected (0.07 sec)

mysql> SELECT CalcIncome (1000);


+-------------------+
| CalcIncome (1000) |
+-------------------+
| 4000 |
+-------------------+
1 row in set (0.00 sec)

Example 3:
Create another table as shown below −
 CREATE TABLE student ( Name VARCHAR(100), Math INT, English INT, Science
INT, History INT);
Now, insert few records into student table −
 INSERT INTO student values('Raman', 95, 89, 85, 81),('Rahul' , 90, 87, 86, 81),('Mohit', 90, 85,
86, 81),('Saurabh', NULL, NULL, NULL, NULL );
 select * from student2;
+---------+------+---------+---------+---------+
| Name | Math | English | Science | History |
+---------+------+---------+---------+---------+
| Raman | 95 | 89 | 85 | 81 |
| Rahul | 90 | 87 | 86 | 81 |
| Mohit | 90 | 85 | 86 | 81 |
| Saurabh | NULL | NULL | NULL | NULL |
+---------+------+---------+---------+---------+

Following query creates a function with name tbl_Update −


 DELIMITER //
Create Function tbl_Update(S_name Varchar(50), M1 INT,
M2 INT, M3 INT, M4 INT)
RETURNS INT
DETERMINISTIC

52
BEGIN
UPDATE student SET Math = M1, English = M2,
Science = M3, History = M4 WHERE Name = S_name;
RETURN 1;
END //
DELIMITER ;

Call the above created function as shown below −


 Select tbl_update('Saurabh',85,69,75,82);
Output:
mysql> Select tbl_update2('Saurabh',85,69,75,82);
+------------------------------------+
| tbl_update2('Saurabh',85,69,75,82) |
+------------------------------------+
| 1|
+------------------------------------+
1 row in set (0.05 sec)

If you get the records of the table student using the select statement you can observe the modified record
SELECT * from student;
Output:
The above mysql query produces the following output −
+---------+------+---------+---------+---------+
| Name | Math | English | Science | History |
+---------+------+---------+---------+---------+
| Raman | 95 | 89 | 85 | 81 |
| Rahul | 90 | 87 | 86 | 81 |
| Mohit | 90 | 85 | 86 | 81 |
| Saurabh | 85 | 69 | 75 | 82 |
HICET CSE DEPT.CBE-32
+---------+------+---------+---------+---------+ (AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:
Thus the above procedure was successfully created and executed.

53
EX.NO : 08
TRIGGERS
DATE :

AIM
To study and implement the concept of triggers.

DEFINITION

A trigger is a statement that is executed automatically by the system as a side effect of a


modification to the database.

It can either be:


1. Application trigger: Fires whenever an event occurs with a particular application.
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema
or database.
The parts of a trigger are,
 Trigger statement: Specifies the DML statements and fires the trigger body. It also
specifies the table to which the trigger is associated.
 Trigger body or trigger action: It is a PL/SQL block that is executed when the
triggering statement is used.
 Trigger restriction: Restrictions on the trigger can be achieved

The different uses of triggers are as follows,

 To generate data automatically


 To enforce complex integrity constraints
 To customize complex securing authorizations
 To maintain the replicate table
 To audit data modifications

TYPES OF TRIGGERS

The various types of triggers are as follows,

 Before: It fires the trigger before executing the trigger statement.


 After: It fires the trigger after executing the trigger statement.
 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 of the column updated in the database. The
values in these variables can be used in the database triggers for data manipulation.
54
SYNTAX
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

USER DEFINED ERROR MESSAGE


 The package “raise_application_error” is used to issue the user defined error
messages
 Syntax: raise_application_error(error number,‘error message‘);
 The error number can lie between -20000 and -20999.
 The error message should be a character string.
Example 1:
A trigger is a set of SQL statements that run every time a row is inserted, updated, or deleted in a table.
Here's a simple classic example using MySQL trigger syntax: defining a trigger that logs updates to one
table by inserting into another.
 mysql> create table employees ( id bigint primary key auto_increment, first_name varchar(100),
last_name varchar(100));
Query OK, 0 rows affected (0.25 sec)

 mysql> create table hiring (emp_id bigint, hire_date timestamp);


Query OK, 0 rows affected (0.27 sec)

 mysql> create trigger hire_log after insert on employees for each row insert into hiring values
(new.id, current_time());
Query OK, 0 rows affected (0.10 sec)

 mysql> insert into employees (first_name, last_name) values ("Tim", "Sehn");


Query OK, 1 row affected (0.07 sec)
 mysql> select * from employees;
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
| 1 | Tim | Sehn |
+----+------------+-----------+
1 row in set (0.00 sec)
55
 mysql> select * from hiring;
+--------+---------------------+
| emp_id | hire_date |
+--------+---------------------+
| 1 | 2024-05-08 15:59:35 |
+--------+---------------------+
1 row in set (0.00 sec)

Example 2:
Here is a simple example that associates a trigger with a table, to activate for INSERT operations. The
trigger acts as an accumulator, summing the values inserted into one of the columns of the table.
 mysql> CREATE TABLE account (acct_num INT, amount DECIMAL(10,2));
Query OK, 0 rows affected (0.03 sec)

 mysql> CREATE TRIGGER ins_sum BEFORE INSERT ON account


FOR EACH ROW SET @sum = @sum + NEW.amount;
Query OK, 0 rows affected (0.01 sec)
The CREATE TRIGGER statement creates a trigger named ins_sum that is associated with the account
table. It also includes clauses that specify the trigger action time, the triggering event, and what to do
when the trigger activates.
 mysql> SET @sum = 0;
 mysql> INSERT INTO account VALUES(137,14.98),(141,1937.50),(97,-100.00);
 mysql> SELECT *FROM ACCOUNT;
+----------+---------+
| acct_num | amount |
+----------+---------+
| 137 | 14.98 |
| 141 | 1937.50 |
| 97 | -100.00 |
+----------+---------+
 mysql> SELECT @sum AS 'Total amount inserted';
+-----------------------+
| Total amount inserted |
+-----------------------+
| 1852.48 |
+-----------------------+
An UPDATE trigger that checks the new value to be used for updating each row, and modifies the
value to be within the range from 0 to 100. This must be a BEFORE trigger because the value must
be checked before it is used to update the row:
 mysql> delimiter //
 mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON account
56
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;//
mysql> delimiter ;
 mysql> update account set amount=200 where acct_num=137;
 mysql> SELECT *FROM ACCOUNT;
+----------+---------+
| acct_num | amount |
+----------+---------+
| 137 | 100.00 |
| 141 | 1937.50 |
| 97 | -100.00 |
+----------+---------+

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:
Thus the above procedure was successfully created and executed.

57
EX.NO : 09
EXCEPTION HANDLING
DATE :

AIM:
To write a PL/SQL block that handles all types of exceptions.

Concepts Involved:
Exception Handling:
While working with stored procedures in MySQL if an exception or occurs the execution of the procedure
terminates abruptly, to avoid this you need to handle the exceptions in MYSQL.

DECLARE ... HANDLER Statement


MySQL provides a handler to handle the exceptions in the stored procedures. You can handle these
exceptions by declaring a handler using the MySQL DECLARE ... HANDLER Statement.

Syntax
DECLARE handler_action HANDLER
FOR condition_value
Statement

The handler_action
The handler_action is the action to be performed when the given condition(s) are satisfied. You can provide
the following as values for handler actions.

CONTINUE − The current program will continue execution of the procedure.


EXIT − This terminates the execution of the procedure.
UNDO − InnoDB does not support this action.

The condition_value
The condition_value is the condition to be satisfied, you can pass multiple condition values. You can provide
the following as values for condition value.

mysql_error_code − This is an integer literal indicating the error code.


sqlstate_value − This is a 5-character string literal specifying the SQLSTATE value.
condition_name − The name of the user defined condition specified with DECLARE ... CONDITION.
SQLWARNING − Shorthand value for SQLSTATE starts with '01'.
NOT FOUND − Shorthand value for SQLSTATE starts with '02'.
SQLEXCEPTION − Short hand value to specify the exception.

Example
First, create a table called users:

 CREATE TABLE users (


user_id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(50) NOT NULL);

58
Second, define a stored procedure that inserts a new user into the users table:

 BEGIN
DECLARE EXIT HANDLER FOR SQLSTATE '23000'
BEGIN
SELECT 'Error: Duplicate username. Please choose a different username.' AS Message;
END;
INSERT INTO users (username, email) VALUES (p_username, p_email);
SELECT 'User inserted successfully' AS Message;
END //
DELIMITER ;

In the stored procedure, declare an exit handler that is activated when a unique constraint violation occurs, which
is indicated by the SQLSTATE ‘23000’:

Third, insert a new rows into the users table by calling the insert_user stored procedure:

 CALL insert_user('jane','[email protected]');
 CALL insert_user('kavi','[email protected]');

OUTPUT:
+----------------------------+
| Message |
+----------------------------+
| User inserted successfully |
+----------------------------+
1 row in set (0.08 sec)

If you execute the statement again, it’ll return the following error:
mysql> CALL insert_user('kavi','[email protected]');

OUTPUT:
+----------------------------------------------------------------+
| Message |
+----------------------------------------------------------------+
| Error: Duplicate username. Please choose a different username. |

+----------------------------------------------------------------+
1 row in set (0.03 sec) HICET CSE DEPT.CBE-32
(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
EXECUTION AND RESULT
DOCUMENTATION AND VIVA
TOTAL
FACULTY SIGNATURE

Result:
Thus the above procedure was successfully created and executed.
59
EX.NO : 10
SIMPLE OPAC SYSTEMS FOR LIBRARY MANAGEMENT
DATE :

Objective:

To create simple opac system for library management.


In this project, the users will be able to perform the following functionalities Login, View
Categories, Book details, Author details, Book issue, and Book return. This is a library management
software developed using Java and My SQL.

System Requirements:
To execute the below project, you will need the following business requirements:

 MySQL Community Server


 MySQL JDBC Connector
 Java
 Eclipse IDE

System Implementation:
MySql Setup for Library Management System Project in Java:
1. Create a database
create database library;

2. Select the database


use library;

3. Create a book table


create table book ( id int primary key, book_name varchar(25), category varchar(15),
author varchar(25), publisher varchar(25));

4. Create an issue table


create table issue ( member_id int primary key, member_name varchar(25), book_name varchar(25),
date_issue date, date_return date);

5. Create an admin table


create table admin (cust_id varchar(25),password varchar(25));

6. Insert some values in the admin table


insert into admin values("admin1","1234"),("admin2","9876");

List Of Modules:
1. Login Module
2. Category Module
3. Author module
4. Book Module
5. Issue Book Module
6. Return Book Module

1. Login module in library management system project in java


This module helps to make a login page so that the user can enter the user name and password to enter
60
into the library management system in java. Name the file as login.java
package library;
import javax.swing.JOptionPane;
public class Login extends javax.swing.JFrame {
public Login() {
initComponents();
}
@SuppressWarnings("unchecked")
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtusername = new javax.swing.JTextField();
txtpass = new javax.swing.JPasswordField();
jButton2 = new javax.swing.JButton();
.
.
..

if(username.equals("Peter") && pass.equals("123"))


{
Main m = new Main();
this.hide();
m.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(this,"Username and Password do not match");
txtusername.setText("");
txtpass.setText("");
txtusername.requestFocus();
}
}

When the entered user name and password didn’t match the existing records in the database, it will
return the “Username and password do not match”.

61
Once we enter the correct username and password it takes us to the home page of our library
management application.

2. Category Module in library management system in java


We can create a new category in this module by giving the details. Name the file category.java.

package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
public class category extends javax.swing.JFrame {
public category() {
initComponents();
Connect();
table_update();
}
Connection con;
PreparedStatement p;
.
.
.
. javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
…….

java.util.logging.Logger.getLogger(category.class.getName()).log(java.util.logging.Level.SEVERE,
null, ex);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new category().setVisible(true);
}
});
}

62
3. Author module in library management system project in java with source code pdf
In this module, we can create new author profiles. Name the file as author.java.
package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.table.DefaultTableModel;
public class author extends javax.swing.JFrame {
public author() {
initComponents();
Connect();
table_update();
}
..
.
.addGap(29, 29, 29)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(21, Short.MAX_VALUE))
);
}
}
}

4. Book Module for library management system project in java with source code
In this module, we can edit the details of the book. Name the file as book.java.
package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
63
Connect();
Author();
Category();
Publisher();
table_update();
}
Connection con;
PreparedStatement pst;
.
.
.
.
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(92, 92, 92)
.addComponent(jPanel2,
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pack();
setLocationRelativeTo(null);
}
}
}

5. Issue Book Module in simple library management system project in java with source code
In this module, we can issue books to the members. Name the file as issue.java.
package library;
import com.sun.glass.events.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import javax.swing.table.DefaultTableModel;
public class Lend extends javax.swing.JFrame {
public Issue() {
initComponents();
Connect();
Book();
table_update();
64
}
.
.
.
if(rs.next()==false)
{
JOptionPane.showMessageDialog(this,"Member ID not Found");
}
else
{
String productname = rs.getString("name");
txtname.setText(productname.trim());
}
} catch (SQLException ex) {
Logger.getLogger(Lend.class.getName()).log(Level.SEVERE, null, ex);
}
}

6. Return Book Module in library management system code in java


In this module, we can return the book to the members. Name the file return.java.
package library;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
public class Return extends javax.swing.JFrame {
public Return() {
initComponents();
Connect();
.
.
.
.
else
{
txtelp.setText("0");
txtfine.setText("0");
}
txtdate.setText(date.trim());
}
65
} catch (SQLException ex) {
Logger.getLogger(Return.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Conclusion

In this project, we developed a GUI-based project, a Library Management System Project in Java and
MySQL . The users are able to perform the operations such as Login, View Categories, Book
details, Author details, Book issue, and Book return.

HICET CSE DEPT.CBE-32


(AUTONOMOUS INSTITUTION)
RECORD/OBSERVATION MARK

AIM/ALGORITHM/PROCEDURE

CODING/QUERY/DESCRIPTION

COMPILATION/TEST CASES

EXECUTION AND RESULT

DOCUMENTATION AND VIVA

TOTAL

FACULTY SIGNATURE

Result:
Thus the above mini project was successfully created and executed.

66

You might also like