DBMS LAB MANUAL
DBMS LAB MANUAL
NO: 1
CREATE A DATABASE TABLE, ADD CONSTRAINTS (PRIMARY KEY,
UNIQUE, CHECK, NOT NULL), INSERT ROWS, UPDATE AND DELETE
DATE: 20-03-24 ROWS USING SQL DDL AND DML COMMANDS.
AIM
PROCEDURE
Step 1: Start
Step 3: Create a table with necessary attributes and execute DDL and DML commands.
Step 5: Stop
SQL> CREATE TABLE EMP (EMPNO NUMBER (4), ENAME VARCHAR2 (10),
DESIGNATIN VARCHAR2 (10), SALARY NUMBER (8,2));
Table created.
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
EMPNO NUMBER(6)
ENAME VARCHAR2(10)
DESIGNATIN VARCHAR2(10)
SALARY NUMBER(8,2)
1
SQL>ALTER TABLE EMP ADD (DOB DATE, DOJ DATE);
Table altered.
SQL> DESC EMP;
REMOVE / DROP
SQL> ALTER TABLE EMP DROP COLUMN DOJ;
SQL> DESC EMP;
Name Null? Type
Output
2
UNIQUE Constraint
MySQL> CREATE TABLE ShirtBrands(Id INTEGER, BrandName VARCHAR(40) UNIQUE,
Size VARCHAR(30));
MySQL> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Pantaloons', 38), (2,
'Cantabil', 40);
MySQL> INSERT INTO ShirtBrands(Id, BrandName, Size) VALUES(1, 'Raymond', 38), (2,
'Cantabil', 40);
Output
CHECK CONSTRAINT
CHECK (expr)
MySQL> CREATE TABLE Persons ( ID int NOT NULL,Name varchar(45) NOT NULL, Age
int CHECK (Age>=18) );
In the below output, we can see that the first INSERT query executes successfully, but the second
statement fails and gives an error that says: CHECK constraint is violated for key Age.
3
Output
RESULT
4
EXP.NO: 2
CREATE A SET OF TABLES, ADD FOREIGN KEY CONSTRAINTS
AND INCORPORATE REFERENTIAL INTEGRITY
DATE: 27-03-24
AIM
To create a set of tables and add foreign key and referential integrity constraints.
PROCEDURE
Step 1:Start
Step 5: Stop
DEPARTMENT
EMPLOYEES
5
OUTPUT
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constrai
RESULT
6
EXP.NO: 3
QUERY THE DATABASE TABLES USING DIFFERENT ‘WHERE’
CLAUSE CONDITIONS AND ALSO IMPLEMENT AGGREGATE
DATE: 28-03-24 FUNCTIONS
AIM
PROCEDURE
Step 1: Start
Step 4:stop
Syntax:
7
WHERE Clause with OR condition
AGGREGATE FUNCTIONS
8
Output:
Output:
Consider our database has a table named employees, having the following data. Now, we are going
to understand this function with various examples:
Output:
9
MySQL avg() function example
Consider our database has a table named employees, having the following data. Now, we are going
to understand this function with various examples:
Output:
RESULT
10
EXP.NO: 4
QUERY THE DATABASE TABLES AND EXPLORE SUB QUERIES AND
SIMPLE JOIN OPERATIONS
DATE: 03-04-24
AIM:
To execute and verify the SQL commands for Simple JOIN and sub queries.
PROCEDURE
STEP 1: Start
STEP 2: Create the table with its essential attributes.
STEP 3: Insert attribute values into the table
STEP 4: Execute Commands for JOIN operation and extract information from the table.
STEP 5: Execute Commands for Sub queries operation.
STEP 6: Stop
Consider two tables "officers" and "students", having the following data.
Output
11
MYSQL SUBQUERY
RESULT
12
EXP.NO: 5 QUERY THE DATABASE TABLES AND EXPLORE NATURAL, EQUI
AND OUTER JOINS
DATE: 04-04-24
AIM
To write a query to perform natural join ,equi join and outer join.
PROCEDURE
Step 1: Start
Step 3: Perform natural join,equi join and outer join operations with queries
Step 4: Stop
Syntax:
SELECT [column_names | *] FROM table_name1 NATURAL JOIN table_name2;
NATURAL JOIN:
13
MYSQL RIGHT OUTER JOIN
Syntax:
SELECT columns FROM table1 RIGHT [OUTER] JOIN table2 ON table1.column = table2.co
lumn;
Consider two tables "officers" and "students", having the following data.
Output
EQUI JOIN
14
WHERE table_name1.column_name = table_name2.column_name;
MySQL> SELECT cust. customer_name, bal.balance FROM customer AS cust, balance AS bal
WHERE cust.account = bal.account_num;
RESULT
15
EXP.NO: 6 WRITE USER DEFINED FUNCTIONS AND STORED PROCEDURES
IN SQL
DATE: 18-04-24
AIM:
Creating user defined functions and stored procedures by using
Structures Query Language
QUERY:
SQL UDFs
The following example creates a temporary SQL UDF named AddFourAndDivide and
calls it from within a SELECT statement:
);
SELECT
val, AddFourAndDivide(val,2) FROM
UNNEST([2,3,5,8]) AS val;
16
+ + +
| val f0_ |
+ + +
| 2 3.0 |
| 3 3.5 |
| 5 4.5 |
| 8 6.0 |
+ + +
);
You must specify a dataset for the function(mydataset in this example). After you run
the CREATE FUNCTION statement, you can call the function from a query:
SELECT
val,mydataset,AddFourAndDivide(val,2) FROM
UNNEST([2,3,5,8,12])AS val;
17
Templated SQP UDF parameters:
A parameter with a type equal to ANY TYPE can match more than one argument type when
the function is called.
i) If more than one parameter has type ANY TYPE, then BigQuery doesn’t
enforce any type relationship between these arguments
ii) The function return type cannot be ANY TYPE. It must be either omitted,
which means to be automatically determined based on sql_expression, or
an explicit type.
iii) Passing the function arguments of types that are incompatible with the
function definition will result in an error at call time
The following example shows a SQL UDF that uses a templated parameter.
CREATE TEMP FUNCTION AddFourAndDivideAny(x ANYTYPE, y ANYTYPE)
AS(
(x+4) / y
);
SELECT
addFourAndDivideAny(3,4)AS integer_input; addFourAndDivideAny(1.59,3.14)AS
floating_point_input;
+ + +
| integer_input | floating_point_input |
+ + +
| 1.75 | 1.7802547770700636 |
18
+ + +
The next example used a templated parameter to return the last element of an array
of any type:
CREATE TEMP FUNCTION lastArrayElement(arr ANY TYPE) AS(
arr[ORDINAL(ARRAY_LENGTH(arr))]
);
SELEC
T
lastArrayElement(x) AS last_element
FROM(
SELECT[2,3,5,8,13] AS x);
+ +
| last_element |
+ +
| 13 |
+ +
RESULT:
Thus the above sql query has been executed and verified successfully
19
EXP.NO: 7 EXECUTE COMPLEX TRANSACTIONS AND REALIZE DCL AND TCL
COMMANDS
DATE: 18-04-24
AIM
PROCEDURE
Step 1: Start
Step 5: Stop.
DCL COMMANDS
GRANT
REVOKE
1 row created.
20
SQL> SELECT * FROM EMP;
ROLL BACK
Rollback complete.
COMMIT
SQL> COMMIT;
Commit complete.
RESULT
21
EXP.NO: 8 WRITE SQL TRIGGERS FOR INSERT, DELETE, AND UPDATE
OPERATIONS IN A DATABASE TABLE
DATE: 24-04-24
AIM
To create database triggers using PL/SQL code
PROCEDURE
SYNTAX
create or replace trigger trigger name [before/after] {DML
statements} on [table name] [for each row/statement] begin
exception
end;
PROGRAM
SQL>create table poo(rno number(5),name varchar2(10));
Table created.
SQL>insert into poo values (01.‟kala‟);
1 row created.
SQL>select * from poo;
RNO NAME
------ ----------
1 kala
2 priya
SQL>create or replace trigger pool before insert on poo for each row
2 declare
3 rno poo.rno%type
4 cursor c is select rno from poo;
5 begin
22
6 open c;
7 loop;
8 fetch c into rno;
9 if:new.rno=rno then
10 raise_application_error(-20005,‟rno already exist‟);
11 end if;
12 exit when c%NOTFOUND
13 end loop;
14 close c;
15 end;
16 /
Trigger created.
OUTPUT
SQL>insert into poo values(01,‟kala‟)
Insert into poo values (01,‟kala‟)
*
ERROR at line1:
ORA-20005:rno already exist
ORA-06512:”SECONDCSEA.POOL”,line 9
ORA-04088:error during execution at trigger “SECONDCSEA.POOL”
RESULT
Thus the PL/SQL blocks are developed for triggers and the results are verified.
23
EXP.NO: 9 CREATE VIEW AND INDEX FOR DATABASE TABLES WITH A
LARGE NUMBER OF RECORDS
DATE: 01-05-24
AIM
To execute and verify the SQL commands for Views and Indexes.
PROCEDURE
STEP 1: Start
STEP 5: Execute different Commands and extract information from the View.
STEP 6: Stop
CREATION OF TABLE
Table created.
TABLE DESCRIPTION
SQL> DESC EMPLOYEE;
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE
CREATION OF VIEW
SQL> CREATE VIEW EMPVIEW AS SELECT
EMPLOYEE_NAME,EMPLOYEE_NO,DEPT_NAME,DEPT_NO,DATE_OF_JOIN FROM
EMPLOYEE;
view created.
DESCRIPTION OF VIEW
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
24
DISPLAY VIEW
1 ROW CREATED.
DELETION OF VIEW
DELETE STATEMENT
SQL> DELETE FROM EMPVIEW WHERE EMPLOYEE_NAME='SRI';
UPDATE STATEMENT:
1 ROW UPDATED.
25
DROP A VIEW:
VIEW DROPED
CREATE INDEX
MySQL> CREATE DATABASE
indexes;Query OK, 1 row affected (0.01
sec)
USE indexes;
Database changed
MySQL>CREATE TABLE
first_name varchar(50),
last_name varchar(50),
(1, 'John', 'Smith', 'ABC123', 60000), (2, 'Jane', 'Doe', 'DEF456', 65000),
(3, 'Bob', 'Johnson', 'GHI789', 70000), (4, 'Sally', 'Fields', 'JKL012', 75000),
(5, 'Michael', 'Smith', 'MNO345', 80000), (6, 'Emily', 'Jones', 'PQR678', 85000),
(7, 'David', 'Williams', 'STU901', 90000), (8, 'Sarah', 'Johnson', 'VWX234', 95000),
+ + + + + + + + + + +
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered
| 1 | SIMPLE | employees | NULL | ref | salary | salary | 5 | const | 1 | 100.00 |
+ + + + + + + + + + +
RESULT
26
EXP.NO: 10 CREATE AN XML DATABASE AND VALIDATE IT USING XML
SCHEMA
DATE: 09-05-24
Aim
Algorithm
Step 1: Start
Step 4:Create XML Schema for data values and load values
Step 6:Stop
CREATE TABLE
created TIMESTAMP
);
<list>
<personperson_id="1"fname="Kapek"lname="Sainnouine"/>
<personperson_id="2"fname="Sajon"lname="Rondela"/>
<personperson_id="3"><fname>Likame</fname><lname>Örrtmons</lname></person>
<personperson_id="4"><fname>Slar</fname><lname>Manlanth</lname></person>
<person><fieldname="person_id">5</field><fieldname="fname">Stoma</field>
<fieldname="lname">Milu</field></person>
<person><fieldname="person_id">6</field><fieldname="fname">Nirtam</field>
<fieldname="lname">Sklöd</field></person>
<personperson_id="7"><fname>Sungam</fname><lname>Dulbåd</lname></person>
<personperson_id="8"fname="Sraref"lname="Encmelt"/>
</list>
LOAD XML LOCAL INFILE 'c:/db/person.xml' //this is ths location of the xml data file
MySQL> SELECT
Result
28
EXP.NO: 11 CREATE DOCUMENT, COLUMN AND GRAPH BASED DATA USING
NOSQL DATABASE TOOLS.
DATE: 15-05-24
Aim
Algorithm
Step 1:Start
Step 5:Stop
>Connection string:
mongodb://localhost:27017
output:
29
Create collection in mongodb
OUTPUT:
mydbnew>db.details.insertOne({"website":"mywebsite"})
Output:
Db.details.find()
30
Output
PROCEDURE:
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 asdata 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.
31
OUTPUT
Result
32
EXP.NO: 12 DEVELOP A SIMPLE GUI BASED DATABASE APPLICATION AND
INCORPORATE ALL THE ABOVE-MENTIONED FEATURES
DATE: 22-05-24
Aim
Algorithm
Step 1: Start
Step 3:Design Login Screen with User Name and Password fields.
Step 5: Stop
PROGRAM
import tkinter as tk
import
MySQL.connectorfrom
tkinter import *
def submitact():
user = Username.get()
passw = password.get()
logintodb(user, passw)
try:
cursor.execute(savequery)
myresult = cursor.fetchall()
33
# Printing the result of the
# query
for x in myresult:
print(x)
print("Query Executed successfully")
except:
db.rollback()
print("Error occurred")
root = tk.Tk()
root.geometry("300x300")
root.title("DBMS Login Page")
root.mainloop()
Output:
Result
34
EXP.NO: 13
• Bank Entity : Attributes of Bank Entity are Bank Name, Code and Address.
Code is Primary Key for Bank Entity.
• Customer Entity : Attributes of Customer Entity are Customer_id, Name, Phone Number
and Address.
Customer_id is Primary Key for Customer Entity.
• Branch Entity : Attributes of Branch Entity are Branch_id, Name and Address.
Branch_id is Primary Key for Branch Entity.
• Account Entity : Attributes of Account Entity are Account_number, Account_Type and
Balance.
Account_number is Primary Key for Account Entity.
• Loan Entity : Attributes of Loan Entity are Loan_id, Loan_Type and Amount.
Loan_id is Primary Key for Loan Entity.
This bank ER diagram illustrates key information about bank, including entities such as
branches, customers, accounts, and loans. It allows us to understand the relationships between
entities.
35
ER Diagram of Bank Management System :
Relationships are :
36
• Loan availed by Customer => M : N
(Assume loan can be jointly held by many Customers).
One Customer can have more than one Loans and also One Loan can be availed by one
or more Customers, so the relationship between Loan and Customers is many to many
relationship.
NORMALIZATION PROCESS
Database normalization is a stepwise formal process that allows us to decompose
database tables in such a way that both data dependency and update anomalies are minimized. It
makes use of functional dependency that exists in the table and primary key or candidate key in
analyzing the tables. Normal forms were initially proposed called First Normal Form (INF),
Second Normal Form (2NF), and Third Normal Form (3NF). Subsequently, R, Boyce, and
E. F. Codd introduced a stronger definition of 3NF called Boyce-Codd Normal Form. With the
exception of 1NF, all these normal forms are based on functional dependency among the attributes
of a table. Higher normal forms that go beyond BCNF were introduced later such as Fourth Normal
Form (4NF) and Fifth Normal Form (5NF). However, these later normal forms deal with situations
that are very rare.
TRIGGERS
37
UPDATE accounts a SETa.balance=
(CASE WHEN new.withdrawal=1 THEN a.balance-new.amount ELSE
a.balance+new.amountEND) WHERE a.id = new.accountID;
END;
pseudocode, Represents
To ensure the integrity and consistency of data during a transaction (A transaction is a unit of
program that updates various data items, read more about it here), the database system maintains
four properties. These properties are widely known as ACID properties.
Atomicity
This property ensures that either all the operations of a transaction reflect in database or none.
The logic here is simple, transaction is a single unit, it can’t execute partially. Either it executes
completely or it doesn’t, there shouldn’t be a partial execution.
Let’s say first operation passed successfully while second failed, in this case A’s balance would
be 300$ while B would be having 700$ instead of 800$. This is unacceptable in a banking system.
Either the transaction should fail without executing any of the operation or it should process both
the operations. The Atomicity property ensures that.
There are two key operations are involved in a transaction to maintain the atomicity of the
transaction.
Abort: If there is a failure in the transaction, abort the execution and rollback the changes made
by the transaction.
Consistency
Database must be in consistent state before and after the execution of the transaction. This
ensures that there are no errors in the database at any point of time. Application programmer is
responsible for maintaining the consistency of the database.
Example:
A transferring 1000 dollars to B. A’s initial balance is 2000 and B’s initial balance is 5000.
38
Before the transaction:
Total of A+B = 2000 + 5000 = 7000$
The data is consitendct before and after the execution of the transaction so this example
maintains the consistency property of the database.
Isolation
A transaction shouldn’t interfere with the execution of another transaction. To preserve the
consistency of database, the execution of transaction should take place in isolation (that means no
other transaction should run concurrently when there is a transaction already running).
For example account A is having a balance of 400$ and it is transferring 100$ to account B & C
both. So we have two transactions here. Let’s say these transactions run concurrently and both
the transactions read 400$ balance, in that case the final balance of A would be 300$ instead of
200$. This is wrong.
If the transaction were to run in isolation then the second transaction would have read the correct
balance 300$ (before debiting 100$) once the first transaction went successful.
Durability
Once a transaction completes successfully, the changes it has made into the database should
be permanent even if there is a system failure. The recovery-management component of
database systems ensures the durability of transaction.
STORED PROCEDURE
EXEC bank.GetTransactions
@AccountID = 100000,
@StartDate = '4/1/2007',
@EndDate = '4/30/2007'
39