DBMS LAB MANUAL
DBMS LAB MANUAL
LIST OF EXPERIMENTS:
1. Create a database table, add constraints (primary key, unique, check, Not null), insert rows,
update and delete rows using SQL DDL and DML commands.
2. Create a set of tables, add foreign key constraints and incorporate referential integrity.
3. Query the database tables using different ‘where’ clause conditions and also implement
aggregate functions.
4. Query the database tables and explore sub queries and simple join operations.
5. Query the database tables and explore natural, equi and outer joins.
6. Write user defined functions and stored procedures in SQL.
7. Execute complex transactions and realize DCL and TCL commands.
8. Write SQL Triggers for insert, delete, and update operations in a database table.
9. Create View and index for database tables with a large number of records.
10. Create an XML database and validate it using XML schema.
11. Create Document, column and graph based data using NOSQL database tools.
12. Develop a simple GUI based database application and incorporate all the above-mentioned
features CS3481 Database Management Systems Lab Manual
13. Case Study using any of the real life database applications from the following list
a) Inventory Management for a EMart Grocery Shop
b) Society Financial Management
c) Cop Friendly App – Eseva
d) Property Management – eMall
e) Star Small and Medium Banking and Finance
Build Entity Model diagram. The diagram should align with the business and
functional goals stated in the application.
Apply Normalization rules in designing the tables in scope.
Prepared applicable views, triggers (for auditing purposes), functions for enabling
enterprise grade features.
Build PL SQL / Stored Procedures for Complex Functionalities, ex EOD Batch
Processing for calculating the EMI for Gold Loan for each eligible Customer.
● Ability to showcase ACID Properties with sample queries with appropriate settings
Aim:
To understand Sql and create database table, add constraints (PRIMARY KEY, UNIQUE,
CHECK, NOT NULL), insert rows, update and delete rows using SQL DDL and DML commands.
SQL
Structured Query Language(SQL) as we all know is the database language by the use of which we can
perform certain operations on the existing database and also we can use this language to create a
database. SQL uses certain commands like Create, Drop, Insert, etc. to carry out the required tasks.
These SQL commands are mainly categorized into five categories as:
DDL – Data Definition Language
DQL – Data Query Language
DML – Data Manipulation Language
DCL – Data Control Language
TCL – Transaction Control Language
DDL (Data Definition Language):
DDL or Data Definition Language actually consists of the SQL commands that can be used to
define the database schema. It simply deals with descriptions of the database schema and is used to create
and modify the structure of database objects in the database. DDL is a set of SQL commands used to
create, modify, and delete database structures but not data. These commands are normally not used by a
general user, who should be accessing the database via an application.
List of DDL commands:
CREATE: This command is used to create the database or its objects (like table, index, function, views,
store procedure, and triggers).
DROP: This command is used to delete objects from the database.
ALTER: This is used to alter the structure of the database.
TRUNCATE: This is used to remove all records from a table, including all spaces allocated for the
records are removed.
COMMENT: This is used to add comments to the data dictionary.
RENAME: This is used to rename an object existing in the database.
SELECT
12.mysql> select * from Employee1;
DELETE
14.mysql> delete from Employee1 Where Age='28';
Query OK, 1 row affected (0.01 sec)
DROP COLUMNS:
15. .mysql> ALTER TABLE Employee1 DROP COLUMN Age;
Query OK, 0 rows affected (0.27 sec)
Records: 0 Duplicates: 0 Warnings: 0
RESULT:
Thus the table was created in MySQL and the various command has been executed successfully.
The table with the foreign key is called the child table, and the table with the primary key is called the
referenced or parent table.
The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the parent table.
3. mysql> CREATE TABLE customer ( ID INT NOT NULL , Name varchar(50) NOT NULL, City
varchar(50) NOT NULL, PRIMARY KEY (ID) );
Query OK, 0 rows affected (0.26 sec)
4. mysql> CREATE TABLE contact (ID INT,Customer_Id INT, Customer_Info varchar(50) NOT
NULL, Type varchar(50) NOT NULL, INDEX par_ind (Customer_Id), CONSTRAINT
fk_customer FOREIGN KEY (Customer_Id) REFERENCES customer(ID));
Query OK, 0 rows affected (0.24 sec)
5. mysql> describe customer;
Result:
Thus the table was created in MySQL and various command by adding Foreign Key has been
executed successfully.
EX.NO:3 QUERY THE DATABASE TABLES USING DIFFERENT ‘WHERE’
DATE: CLAUSE CONDITIONS AND ALSO IMPLEMENTAGGREGATE
FUNCTIONS.
AIM:
★ COUNT
★ SUM
★ AVERAGE
★ MAX
★ MIN
COUNT() function
The SQL COUNT function returns the number of rows in a table satisfying the criteria specified in the
WHERE clause. It sets on the number of rows or non NULL column values.
SUM() function
The SQL AGGREGATE SUM() function returns the sum of all selected column.
AVG() function
The SQL AVG function calculates the average value of a column of numeric type.It returns the average
of all non NULL values.
MAX() function
The aggregate function SQL MAX() is used to find the maximum value or highest value of a certain
column or expression.
MIN() function
The aggregate function SQL MIN() is used to find the minimum value or lowest value of a column or
expression. This function is useful to determine the smallest of all selected values of a column.
Queries to use Aggregate Function
1. create database third1;
Query OK, 1 row affected (0.21 sec)
2. use third1;
Database changed
3. mysql> create table student1(studentName varchar(25), StudentId int,Age int, Address
Varchar(25), Department varchar(25), Fees int);
Query OK, 0 rows affected (0.12 sec)
4. mysql> describe student1;
8. mysql> insert into student1 values("Raja", 104, 29, "Thanjavur", "Mech", 39000);
Query OK, 1 row affected (0.03 sec)
9. mysql> insert into student1 values("Suja", 105, 12, "Thanjavur", "Eighth", 15000);
Query OK, 1 row affected (0.02 sec)
10. mysql> select * from student1;
AGGREGATE FUNCTIONS
11. mysql> select avg(fees) result from student1;
RESULT
Thus the database creation using aggregation function commands has been completed successfully.
EX.NO :4 QUERY THE DATABASE TABLES AND EXPLORE SUB
DATE: QUERIES AND SIMPLE JOIN OPERATIONS.
AIM:
To create a table and execute Sub queries and Joins.
SUBQUERIES AND JOINS
The JOIN statement is used to join the data of two or more tables and bring out the result as a single
set of records. The joins are very useful when you have a relationship between two tables using the
primary-foreign key.
The sub queries are also used to join the data of two or more tables. A sub query is also called an inner
query or a nested query. A sub query is basically a query inside the query.
Note that, in the JOIN statement, only a single SELECT statement is present with the names of
multiple tables. Whereas, in the sub query, there is another query with the SELECT statement present
apart from the outer SELECT statement. That means, there can be multiple select statements present in
the sub queries.
Sub queries and join statements can be used alternatively. However, sometimes the sub query becomes
the only option to get the result. However, a join statement can be replaced with a very long sub query.
Note that, before the JOIN statement was introduced in MySQL, only sub query was the option to write
the complex logic. That means, everything that we write using the JOIN, can be written using the sub
query.
SUB-QUERIES
1.mysql> create database four;
Query OK, 1 row affected (0.75 sec)
2. mysql> use four;
Database changed
3. mysql> create table product (product_id int primary key, product_name
varchar(25),product_price int);
Query OK, 0 rows affected (0.06 sec)
4. mysql> desc product;
11. mysql> create table sale(sales_id int not null primary key auto_increment,product_id
int,sales_year int,sales_amount int);
Query OK, 0 rows affected (0.10 sec)
12. mysql> desc sale;
20. mysql> SELECT * FROM product WHERE product_id=(SELECT product_id FROM sale
WHERE sales_amount>=15000 AND product_id=product.product_id);
21. mysql> SELECT * FROM product WHERE product_id=(SELECT product_id FROM sale
WHERE sales_amount>=19000 AND product_id=product.product_id);
22. mysql> SELECT * FROM product WHERE product_id IN (SELECT product_id FROM
sale);
23. mysql> SELECT * FROM product WHERE product_id NOT IN (SELECT product_id
FROM sale);
Empty set (0.00 sec)
JOIN QUERY
24. mysql> SELECT p.product_id,p.product_name,p.product_price FROM product p JOIN
sale ON p.product_id=sale.product_id WHERE sales_amount>=3000;
25. mysql> SELECT DISTINCT p.product_id,p.product_name,p.product_price FROM
product p JOIN sale ON p.product_id=sale.product_id;
RESULT:
Thus the query to implement Subqueries and joins in database has been successfully executed.
EX.NO 5 QUERY THE DATABASE TABLES AND EXPLORE NATURAL, EQUI
AND OUTER JOINS.
AIM:
To create a table and execute the natural, equi and outer joins.
DESCRIPTION:
JOIN OPERATIONS INNER JOIN/ NATURAL JOIN/ JOIN:
It is a binary operation that allows us to combine certain selections and a Cartesian product into one
operation. Inner Join
An Inner Join returns only the rows in both tables that match the join condition.
Equi Join
An Equi Join returns all the rows in both tables where the specifiedcolumns are equal.
Syntax of Equi Join
SELECT table1.column1, table2.column2
FROM table1
INNER JOIN table2
ON table1.columnX = table2.columnY;
Natural Join
A Natural Join is a type of Join that matches columns with the same name in both tables.
Syntax of Natural Join
SELECT table1.column1, table2.column2
FROM table1
NATURAL JOIN table2;
Outer Join
An Outer Join in DBMS returns all the rows from one table and the matching rows from the
other table. If there is no match, NULL values are returned for the missing rows.
FROM table1
ON table1.columnX = table2.columnY;
Query:
To perform a Left Outer Join, we can join the two tables on the ID column.
SELECT Table1.Name, Table2.Address
FROM Table1
ON Table1.ID = Table2.ID;
FROM table1
ON table1.columnX = table2.columnY;
16. mysql> SELECT Table1.Name, Table2.Address FROM Table1 INNER JOIN Table2 ON
Table1.ID = Table2.ID;
17. mysql> SELECT Table1.ID, Table1.Name, Table1.Age, Table2.Address, Table2.Salary FROM
Table1 NATURAL JOIN Table2;
18. mysql> SELECT Table1.Name, Table2.Address FROM Table1 LEFT JOIN Table2 ON
Table1.ID = Table2.ID;
19. mysql> SELECT Table1.Name, Table2.Address FROM Table1 RIGHT JOIN Table2 ON
Table1.ID = Table2.ID;
RESULT
Thus the relationship between databases has been implemented using join operation.
AIM:
To write MYSQL programs that executes the concept of procedures.
DEFINITION:
A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a
specific task. They are essentially sub-programs.
Procedures and functions are made up of,
• Declarative part
• Executable part
• Optional exception handling part
These procedures and functions do not show the errors.
KEYWORDS AND THEIR PURPOSES REPLACE:
It recreates the procedure if it already exists.
PROCEDURE: It is the name of the procedure to be created.
ARGUMENT: It is the name of the argument to the procedure. Paranthesis can be omitted if no
arguments are present.
IN: Specifies that a value for the argument must be specified when calling the procedure ie. used to
pass values to a sub-program. This is the default parameter.
OUT: Specifies that the procedure passes a value for this argument back to it’s calling environment
after execution ie. used to return values to a caller of the sub-program.
INOUT: Specifies that a value for the argument must be specified when calling the procedure and
that procedure passes a value for this argument back to it’s calling environment after execution.
RETURN: It is the datatype of the function’s return value because every function must return a
value, this clause is required.
SYNTAX:
CREATE
[DEFINER = user]
PROCEDURE [IF NOT EXISTS] sp_name ([proc_parameter[,...]])
[characteristic ...] routine_body
CREATE
[DEFINER = user]
FUNCTION [IF NOT EXISTS] sp_name ([func_parameter[,...]])
RETURNS type
[characteristic ...] routine_body
proc_parameter:
[ IN | OUT | INOUT ] param_name type
func_parameter:
param_name type
type:
Any valid MySQL data type
characteristic: {
COMMENT 'string'
| LANGUAGE SQL
| [NOT] DETERMINISTIC
| { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
| SQL SECURITY { DEFINER | INVOKER }
}
routine_body:
Valid SQL routine statement
1. mysql> create database six;
Query OK, 0 rows affected (0.60 sec)
Result:
The MYSQL queries to create procedures and functions were executed and their
respective outputs were verified.
EX.NO 7 DCL AND TCL COMMANDS IN MYSQL
AIM:
To create the database creation and execute the DML and TCL Commands
GRANT
REVOKE
GRANT
Syntax:
REVOKE
REVOKE is used for taking back permission, which is given to the user.
Syntax:
REVOKE object_privileges ON table_name FROM user1, user2,… userN
Transaction Control Language
TCL manages the issues and matters related to the transactions in any database. They are used to rollback
or commit the changes in the database. Here are some commands that come under TCL:
COMMIT
ROLLBACK
COMMIT
The COMMIT command is used to save all the transactions to the database.
Syntax:
COMMIT;
ROLLBACK
The rollback command is used to undo transactions that have not already been saved to the database.
Syntax:
ROLLBACK;
RESULT:
Thus the queries to perform DCL and TCL were created, executed and their respective
outputs were verified.
EX.NO 8 TRIGGERS IN MYSQL
AIM
To study and implement the concepts 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. 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
TRIGGERS - SYNTAX
CREATE [OR REPLACE] TRIGGER trigger_ nameBEFORE|AFTER
[INSERT,UPDATE,DELETE[COLUMNNAME..]
ON table_name
Referencing[OLDASOLD|NEWAS NEW]
FOREACHROW|FOREACHSTATEMENT [ WHEN Condition]
DECLARE
[declaration_section
variable declarations;constantdeclarations;
]
BEGIN
[executable_section
PL/SQLexecute/subprogram body
] EXCEPTION
[exception_section
PL/SQLExceptionblock ]
5. mysql> CREATE TABLE test3(a3 INT NOT NULL AUTO_INCREMENT PRIMARY KEY);
Query OK, 0 rows affected (0.08 sec)
7. mysql> delimiter |
8. mysql> CREATE TRIGGER testref BEFORE INSERT ON test1
-> FOR EACH ROW
-> BEGIN
-> INSERT INTO test2 SET a2 = NEW.a1;
-> DELETE FROM test3 WHERE a3 = NEW.a1;
-> UPDATE test4 SET b4 = b4 + 1 WHERE a4 = NEW.a1;
-> END;
-> |
Query OK, 0 rows affected (0.01 sec)
9. mysql> delimiter ;
10. mysql> INSERT INTO test3 (a3) VALUES
-> (NULL), (NULL), (NULL), (NULL), (NULL),
-> (NULL), (NULL), (NULL), (NULL), (NULL);
Query OK, 10 rows affected (0.04 sec)
Records: 10 Duplicates: 0 Warnings: 0
11. mysql> INSERT INTO test4 (a4) VALUES
-> (0), (0), (0), (0), (0), (0), (0), (0), (0), (0);
Query OK, 10 rows affected (0.03 sec)
Records: 10 Duplicates: 0 Warnings: 0
12. mysql> INSERT INTO test1 VALUES
-> (1), (3), (1), (7), (1), (8), (4), (4);
Query OK, 8 rows affected (0.05 sec)
Records: 8 Duplicates: 0 Warnings: 0
13. mysql> SELECT * FROM test1;
RESULT
Thus the View and index for database tables has been executed successfully.
EX.NO 10 XML DOCUMENT CREATION AND VALIDATION
Aim
To create a XML database file and Validate the Schema .
Algorithm
Step 1: Start
Step 2:Open MySQL command prompt(version.5.5)
Step 3:Create new database as bookstore and use it.
Step 4:Create XML Schema for data values and load values
Step 5:Validate XML using ExtractValue function.
Step 6:Stop
CREATE TABLE
Result
Thus the XML Database schema is created and Validated.
EX.NO 11 CREATE DOCUMENT, COLUMN AND GRAPH BASED
DATA USING NOSQL DATABASE TOOLS.
AIM
To Create Document,column and Graph using NOSQL Tools.
ALGORITHM
Step 1:Start
Step 2:Create Database in MongoDB
Step 3:Create Collection and Document in MongoDB
Step 4:Display all document
Step 5:Stop
1. use <database_name>command
2. mydbnew>db.details.insertOne({"website":"mywebsite"})
Display all documents
3. Mydbnew>Db.details.find()
PROCEDURE:
Step 1: Log into MongoDB Atlas.
To access the MongoDB Charts application, you must be logged into Atlas
If you have an Atlas Project with clusters containing data you wish to visualize,
Step 3: Select the project from the Context dropdown in the left navigation pane.
Step 4: Create an Atlas cluster. The MongoDB Charts application makes it easy to connect
Collections in your cluster as data sources. Data sources reference specific collections and
charts views that you can access in the Chart Builder to visualize the data in those collections
or charts views.
Step 5: Launch the MongoDB Charts application. In Atlas, click Charts in the navigation bar.
RESULT:
Thus the Creation of Document, column and graph based data using NOSQL database
tools was successfully created, executed and verified.
EX.NO 12 GUI BASED DATABASE APPLICATIONS
Aim
To develop a program in python to implement the GUI based application
Algorithm
Step 1: Start
Step 2: Import necessary files to perform database operations
Step 3:Design Login Screen with User Name and Password fields. Step 4: Check with appropriate conditions
to login.
Step 5: Stop
PROGRAM
import tkinter as tk import MySQL.connector from tkinter import *
def submitact():
user = Username.get() passw = password.get()
print(f"The name entered by you is {user} {passw}") logintodb(user, passw)
def logintodb(user, passw):
# If password is enetered by the # user
if passw:
db = MySQL.connector.connect(host ="localhost", user = user,
password = passw, db ="College")
cursor = db.cursor()
# If no password is enetered by the # user
else:
db = MySQL.connector.connect(host ="localhost", user = user,
db ="College") cursor = db.cursor()
# A Table in the database
savequery = "select * from STUDENT"
try:
cursor.execute(savequery) myresult = cursor.fetchall()
# Printing the result of the # query
for x in myresult: print(x)
print("Query Executed successfully")
except:
db.rollback() print("Error occurred")
Result
Thus the simple GUI application has been created and executed successfully.
AIM:
To create a mini project named Inventory Control System.
DESCRIPTION:
Inventory Control System is a project which allows to maintain the stocks and sell the products and
update the stock.
It has three forms
• Main Menu form
• Stock Form.
• Sales Form
Main Menu Form :
It allows to choose the option whether stock entry or sales entry.
Stock Form:
It allows to enter the product id, product name, quantity, unit price and reorder value.
Sales Form:
It allows to sell the product by choosing the product id and specifying the sales quantity. It checks
whether the sales quantity is less than or equal to available quantity and also checks whether the
remaining quantity after sales is lesser than reorder level. If so, it disallows sales.
The information entered is stored in the database.
DATABASE
TABLES:STOCK TABLE
CREATE TABLE
stock(
Prodid INT PRIMARY KEY, prodname VARCHAR2(50), quantity INT,
unitprice INT, reorder int
);
SALES TABLE
CREATE TABLE
sale(
prodid INT REFERENCES stock(prodid),
prodname VARCHAR2(50), unitprice INT,
50
salesqty INT,
datetime VARCHAR2(50)
);
SAMPLE CODING:
STOCK ENTRY:
package conn;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import
javax.swing.JOptionPane;
import oracle.jdbc.OraclePreparedStatement;import oracle.jdbc.OracleResultSet;
public class stockentry extends javax.swing.JFrame {
Connection conn=null; OraclePreparedStatement pst=null; OracleResultSet rs=null;
private void btnInsert_clickActionPerformed(java.awt.event.ActionEvent evt) {
//TODO add your handling code here: try
{
private void
{
//TODO add your handling code here:Try
{
Date d = new Date();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy 'at' HH:mm:ss a");
String date = DATE_FORMAT.format(d); int i=Integer.parseInt(txt_salesqty.getText());
Class.forName("oracle.jdbc.OracleDriver") Connectionconn=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "hemesh", “123");
String sql="update stock set quantity=quantity-'"+i+"' where prodid=?"; PreparedStatement
pst=conn.prepareStatement(sql);
pst.setString(1,jComboBox1.getSelectedItem().toString());pst.executeUpdate();
Stringsql1="Insertintosale(prodid,prodname,unitprice,salesqty,datetime) values(?,?,?,?,?)";
PreparedStatement pst1=conn.prepareStatement(sql1);
pst1.setInt(1,Integer.parseInt(jComboBox1.getSelectedItem().toString())); pst1.setString(2,
txt_prodname.getText());
pst1.setInt(3,Integer.parseInt( txt_unitprice.getText())); pst1.setInt(4,
Integer.parseInt(txt_salesqty.getText())); pst1.setString(5,date);
pst1.execute();
JOptionPane.showMessageDialog(null, "Sucessfully Inserted");
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
//TODO add your handling code here:try
{
Class.forName("oracle.jdbc.OracleDriver");
Connectionconn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1 521
:XE", "hemesh", "123");
String sql="select * from stock where prodid=?"; PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, jComboBox1.getSelectedItem().toString()); ResultSet rs=pst.executeQuery();
if(rs.next())
{
txt_prodname.setText(rs.getString("prodname")
);
txt_unitprice.setText(rs.getString("unitprice")); txt_salesqty.setText(rs.getString("salesqty"));
}
}
}
public void additems()
{
try
{
Class.forName("oracle.jdbc.OracleDriver"); Connectionconn=
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "hemesh", 123"); String
sql="select prodid from stock"; PreparedStatement pst=conn.prepareStatement(sql);ResultSet
rs=pst.executeQuery();
while(rs.next())
{
}
jComboBox1.addItem(rs.getInt("prodid"));
}
}
RESULT:
Thus the mini project of Inventory control system using E-mart grocery shop project has been
successfully completed.