22cs4001 Dbms Lab Record (2)
22cs4001 Dbms Lab Record (2)
REGISTER NUMBER :
1
HINDUSTHAN
COLLEGE OF ENGINEERING AND
TECHNOLOGY COIMBATORE – 641 032
(AN AUTONOMOUS INSTITUTION)
PEO3: To possess critical thinking, communication skills, teamwork, leadership skills, and ethical
behaviour necessary to function productively and professionally.
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
COURSE OUTCOMES
S.NO DESCRIPTION
5
CONTENTS
EX. PAGE FACULTY
DATE EXPERIMENT MARKS
NO. NO. SIGN
4 Integrity Constraints
8 Triggers
9 Exception Handling
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.
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.
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);
2. DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.
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.
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;
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
TOTAL
FACULTY SIGNATURE
Result:
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.
14
ID School_name No_of_Students No_Of_Teachers No_Of_Classrooms EmailID
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;
15
SAVEPOINT Updation;
ROLLBACK TO Insertion;
SELECT *FROM t_school;
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.
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
Connect;
Enter user_name:system
Enter password:abc123
Connected
Enter user_name:Amal
Enter password:abc123
Connected
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;
4 rows updated
DELETE:
GRANT DELETE from system t_school where staff_ID – xxx;
1 row deleted
GRANT SELECT * from system t_school;
II. REVOKE:
Permission granted to a user can also be taken back by the granter. This can be done
by the REVOKE command.
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
ERROR:
Invalid username/password;login denied
Warning:you are no longer connected
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
TOTAL
FACULTY SIGNATURE
Result:
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
Output:
count(ename)
3
min(age) 20
23
(v) Display the Sum of age employeetable.
SQL> select sum(age) from emp;
Output:
sum(age)
74
avg(age)
24.6667
(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
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
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 (+)
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:
Create Employee_details table, with three columns Emp_Id, Emp_Name, and Emp_Salary.
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
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
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
Following are the various set operators which are performed on the similar data
stored in the two SQL database tables:
Create Two tables with four columns Emp_Id, Emp_Name, Emp_Salary, and Emp_City.
26
Table1: Employee_details1
Table2 : Employee_details2
JOINS
PROCEDURE
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|
+ +
28
Now, let us join these two tables using the INNER JOIN as follows –
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.
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;
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
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.
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
Table2:
create table Course (Courseid int , Coursename nvarchar(250), CourseAdmin int);
Table3:
create table StudentCourse( StudentCourseid int , Studentid int, Courseid int)
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:
* | | | | *
| 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 |
* | | | | *
RECORD/OBSERVATION MARK
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
TOTAL
FACULTY SIGNATURE
Result:
35
EX.NO : 04
INTEGRITY CONSTRAINTS
DATE :
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).
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.
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
+-------+----------+------+-----+---------+-------+
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
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
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.
OUTPUT:
SCODE SUBNAME FCODE
4251 JAVA 111
4252 ENGLISH 222
4253 PYTHON 333
OUTPUT:
mysql> DESC STUDENT;
+-------+----------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| sno | int | NO | | NULL | |
| name | char(10) | YES | | NULL | |
+-------+----------+------+-----+---------+-------+
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
TOTAL
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
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:
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.
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
TOTAL
FACULTY SIGNATURE
Result:
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.
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:
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 );
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.
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
46
CURSOR IN MYSQL
Example: 1
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 ;
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
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
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.
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)
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.
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)
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 |
+---------+------+---------+---------+---------+
52
BEGIN
UPDATE student SET Math = M1, English = M2,
Science = M3, History = M4 WHERE Name = S_name;
RETURN 1;
END //
DELIMITER ;
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
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
TYPES OF TRIGGERS
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)
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)
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
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.
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.
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.
Example
First, create a table called users:
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:
System Requirements:
To execute the below project, you will need the following business requirements:
System Implementation:
MySql Setup for Library Management System Project in Java:
1. Create a database
create database library;
List Of Modules:
1. Login Module
2. Category Module
3. Author module
4. Book Module
5. Issue Book Module
6. Return Book Module
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.
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);
}
}
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.
AIM/ALGORITHM/PROCEDURE
CODING/QUERY/DESCRIPTION
COMPILATION/TEST CASES
TOTAL
FACULTY SIGNATURE
Result:
Thus the above mini project was successfully created and executed.
66