0% found this document useful (0 votes)
29 views34 pages

DBMS Lab Record

The document outlines various SQL operations, including Data Definition Language (DDL) and Data Manipulation Language (DML) commands for creating, altering, and managing database tables. It details the creation of tables with foreign key constraints, the use of different WHERE clause conditions, aggregate functions, subqueries, and JOIN operations for data retrieval. The results indicate successful execution of all SQL commands and queries demonstrated throughout the exercises.

Uploaded by

malarvizhi k
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)
29 views34 pages

DBMS Lab Record

The document outlines various SQL operations, including Data Definition Language (DDL) and Data Manipulation Language (DML) commands for creating, altering, and managing database tables. It details the creation of tables with foreign key constraints, the use of different WHERE clause conditions, aggregate functions, subqueries, and JOIN operations for data retrieval. The results indicate successful execution of all SQL commands and queries demonstrated throughout the exercises.

Uploaded by

malarvizhi k
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/ 34

EX.

NO:1a DATA DEFINITION LANGUAGE


DATE:

AIM:

To implement database creation and do the operations in database using Data Definition Language.

ALGORITHM:
Step 1: Create table by using create table command with column name, data type and size.
Step 2: Display the table by using desc command.
Step 3: Add any new column with the existing table by alter table command.
Step 4: Modify the existing table with modify command.
Step 5: Delete the records in files by truncate.
Step 6: Delete the Entire table by drop command.

1) CREATE DATABASE & TABLE

Syntax:

create database databasename;


create table table_name( column1 datatype, column2 datatype, column3 datatype,
..... columnN datatype);

Example:

create database acet;

use acet;

create table employee(id int,name varchar(100),age int,address varchar(100),salary float,

PRIMARY KEY (id));

Query OK, 0 rows affected (0.10 sec)

2) DESCRIBING THE TABLE

Syntax:
desc table_name;

Example:
desc employee;
3) ALTER TABLE

Syntax:
alter table table_name add column_name datatype;

Example:
alter table employee add dept varchar(10);

desc employee;

4) RENAME
To rename column name
Syntax:
alter table table_name rename column existing _name to new_name;

Example:
alter table employee rename column address to addr;
table employee altered.

To rename table name


Syntax:
alter table table_name rename to new_table_name;

Example:
alter table employee rename to empl;
Query OK, 0 rows affected (0.02 sec)
select * from employee;
ORA-00942: table or view does not exist
00942. 00000 - "table or view does not exist"
*Cause:
*Action:
Error at Line: 21 Column: 15

5) TRUNCATE

Syntax:
truncate table table_name;

Example:
truncate table emp;
select * from empl;

no data found

6) DROP TABLE

Syntax:
drop table table_name;

Example:

drop table empl;


table customers dropped.

select * from empl;


ORA-00942: table or view does not exist

RESULT:
Thus the queries to implement data definition commands are executed successfully.
EX.NO:1b DATA MANIPULATION LANGUAGE
DATE:

AIM:
To implement and execute a query for manipulating & storing data items in a database using Structured
Query Language commands

ALGORITHM:
Step 1: Create table by using create table command.
Step 2: Insert values into the table
Step 3: Delete any records from the table
Step 4: Update any values in the table.
Step 5: Display the values from the table by using select command.

1) CREATE A TABLE

create table student(id int,Name varchar(30) NOT NULL,Department varchar(10), UNIQUE (id));

desc student;

2) INSERT
Syntax:
insert into table_name values(column1,column2,….);
Example:
insert into student values(1,'ABC','CSE');
insert into student values(2,'DEF','CSE');
select * from student;

To insert NULL values to column:


The following syntax is used to insert NULL value to the column.

insert into student values(3,'null','CSE');


select * from student;
To insert default value to the column:
The following syntax is used to insert default value to the table.
Syntax:
insert into table_name values(column1,column2,…);

Example:
insert into student values(3,’alex’,default);
1 rows inserted.
select * from student;

To insert data using select statement:


The following syntax is used insert all the values from another table using select statement.
Syntax:
insert into table_name1 select * from table_name2;

Example:
create table stud(id int,Name varchar(30),Department varchar(10));
insert into stud select * from student;

3) UPDATE
Syntax:
update table_name set column1 = value1, column2 = value2. .. , columnn = valuen
where [condition];
Example: (single column)

update stud set Department='ECE' where id=3;


1 rows updated.
Example: (multiple column)

update stud set Name=’XYZ’,Department='CIVIL' where id=2;

4) DELETE

Syntax: (delete particular row)


delete from table_name where condition;

Example:
delete from stud where id=2;

Syntax:
delete from table_name;

Example:
delete from stud;
select * from stud;

no data found

RESULT:
Thus, a query for manipulating & storing data items in a database using
Structured Query Language commands were implemented and executed successfully.
EX.NO:2 CREATE SET OF TABLES ADD FOREIGN KEY CONSTRAINT AND
DATE: INCORPORATE REFERENTIAL INTEGRITY

Aim:
To create a set of tables in SQL with a foreign key constraint to ensure referential integrity between them.
Algorithm:
Step 1: Create the parent table with a primary key.
Step 2: Create the child table with a foreign key that references the primary key of the parent table.
Step 3: Ensure referential integrity by setting constraints like ON DELETE CASCADE
Step 4: Insert data into the parent table first.
Step 5: Insert data into the child table referencing the parent table’s primary key.
Step 6: Test referential integrity by attempting to delete or update records.

Query:
-- Step 1: Create the Parent Table (Department)
CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL);

-- Step 2: Create the Child Table (Employee) with Foreign Key Constraint
CREATE TABLE Employee (
EmpID INT PRIMARY KEY,
EmpName VARCHAR(50) NOT NULL,
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID) ON DELETE CASCADE);

-- Step 3: Insert values into the Department table


INSERT INTO Department (DeptID, DeptName) VALUES (1, 'HR'), (2, 'IT');

-- Step 4: Insert values into the Employee table


INSERT INTO Employee (EmpID, EmpName, DeptID) VALUES (101, 'Alice', 1), (102, 'Bob', 2);

-- Step 5: Check Referential Integrity


DELETE FROM Department WHERE DeptID = 1;

-- This will delete 'HR' and also Alice (due to ON DELETE CASCADE)

SELECT * FROM Employee;


SELECT * FROM Department;
OUTPUT :

RESULT:
Thus, to create a set of tables add foreign key constraint and incorporate referential integrity were
implemented and executed successfully.
EX.NO:3 DATABASE TABLES WITH DIFFERENT 'WHERE CLAUSE' CONDITIONS
DATE:

Aim:
To query database tables using different WHERE clause conditions and apply aggregate functions
to perform calculations on data.

Algorithm:
Step 1: Create two tables: Department (parent) and Employee (child) with a foreign key constraint.
Step 2: Insert sample data into both tables.
Step 3: Use different WHERE conditions to filter data:

 Equality (=)
 Range (BETWEEN)
 Pattern matching (LIKE)
 Multiple conditions (AND, OR)
 Null checking (IS NULL, IS NOT NULL)

Step 4: Implement aggregate functions (COUNT, SUM, AVG, MAX, MIN, GROUP BY).
Step 5: Execute queries and verify results.

Query:

Step 1: Create Tables


CREATE TABLE Department (
DeptID INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL);

CREATE TABLE Employee (


EmpID INT PRIMARY KEY,
EmpName VARCHAR(50) NOT NULL,
Salary INT,
DeptID INT,
FOREIGN KEY (DeptID) REFERENCES Department(DeptID));

Step 2: Insert Sample Data

INSERT INTO Department (DeptID, DeptName) VALUES


(1, 'HR'),
(2, 'IT'),
(3, 'Finance');

INSERT INTO Employee (EmpID, EmpName, Salary, DeptID)


VALUES
(101, 'Alice', 50000, 1),
(102, 'Bob', 60000, 2),
(103, 'Charlie', 45000, 1),
(104, 'David', 70000, 3),
(105, 'Eve', NULL, 2); -- Employee with NULL salary
Step 3: Queries with WHERE Conditions and Aggregate Functions
1. Filter Employees by Department (Equality =)
SELECT * FROM Employee WHERE DeptID = 1;
+-------+---------+--------+--------+
| EmpID | EmpName | Salary | DeptID |
+-------+---------+--------+--------+
| 101 | Alice | 50000 | 1|
| 103 | Charlie | 45000 | 1|
+-------+---------+--------+--------+

2. Find Employees with Salary Between 45,000 and 65,000 (BETWEEN)


SELECT * FROM Employee WHERE Salary BETWEEN 45000 AND 65000;

+-------+---------+--------+--------+
| EmpID | EmpName | Salary | DeptID |
+-------+---------+--------+--------+
| 101 | Alice | 50000 | 1 |
| 102 | Bob | 60000 | 2 |
| 103 | Charlie | 45000 | 1 |
+-------+---------+--------+--------+

3. Find Employees with Names Starting with 'A' (LIKE)


SELECT * FROM Employee WHERE EmpName LIKE 'A%';

+-------+---------+--------+--------+
| EmpID | EmpName | Salary | DeptID |
+-------+---------+--------+--------+
| 101 | Alice | 50000 | 1 |
+-------+---------+--------+--------+

4. Employees in HR or IT (IN Operator)


SELECT * FROM Employee WHERE DeptID IN (1, 2);

+-------+---------+--------+--------+
| EmpID | EmpName | Salary | DeptID |
+-------+---------+--------+--------+
| 101 | Alice | 50000 | 1 |
| 103 | Charlie | 45000 | 1 |
| 102 | Bob | 60000 | 2 |
| 105 | Eve | NULL | 2|
+-------+---------+--------+--------+

5. Find Employees with Salary Greater Than 50,000 (>)


SELECT * FROM Employee WHERE Salary > 50000;
+-------+---------+--------+--------+
| EmpID | EmpName | Salary | DeptID |
+-------+---------+--------+--------+
| 102 | Bob | 60000 | 2 |
| 104 | David | 70000 | 3 |
+-------+---------+--------+--------+
Step 4: Aggregate Functions with WHERE Clause
6. Count the Total Employees (COUNT)
SELECT COUNT(*) AS TotalEmployees FROM Employee;

+----------------+
| TotalEmployees |
+----------------+
| 5|
+----------------+

7. Find the Average Salary (AVG)


SELECT AVG(Salary) AS AvgSalary FROM Employee WHERE Salary IS NOT NULL;

+------------+
| AvgSalary |
+------------+
| 56250.0000 |
+------------+

8. Count Employees in Each Department (GROUP BY)


SELECT DeptID, COUNT(*) AS EmployeeCount
FROM Employee
WHERE DeptID IS NOT NULL
GROUP BY DeptID;

+--------+---------------+
| DeptID | EmployeeCount |
+--------+---------------+
| 1| 2|
| 2| 2|
| 3| 1|
+--------+---------------+

RESULT:
Thus the SQL query the database tables with different 'where clause' conditions also implement
aggregate function areexecuted successfully.
EX.NO:4 SIMPLE QUERIES, SUB QUERIES, JOINS
DATE:

Aim:

To query database tables using subqueries and JOIN operations for efficient data retrieval.

Algorithm:
Step 1: Create two tables: Category (parent) and Product (child) with a foreign key constraint.
Step 2: Insert sample data into both tables.
Step 3: Use subqueries: Retrieve data using a nested query and correlated subqueries.
Step 4: Perform JOIN operations

Queries:
Step 1: Create Tables
CREATE TABLE Category (
CategoryID INT PRIMARY KEY,
CategoryName VARCHAR(50) NOT NULL);

CREATE TABLE Product (


ProductID INT PRIMARY KEY,
ProductName VARCHAR(50) NOT NULL,
Price INT,
CategoryID INT,
FOREIGN KEY (CategoryID) REFERENCES Category(CategoryID));

Step 2: Insert Sample Data


INSERT INTO Category (CategoryID, CategoryName) VALUES
(1, 'Electronics'),
(2, 'Furniture'),
(3, 'Clothing');
INSERT INTO Product (ProductID, ProductName, Price, CategoryID)
VALUES
(101, 'Laptop', 75000, 1),
(102, 'Table', 12000, 2),
(103, 'Smartphone', 40000, 1),
(104, 'Sofa', 25000, 2),
(105, 'T-shirt', 500, 3);

Step 3: Subqueries
1. Retrieve Products Belonging to the Most Expensive Category (Subquery in WHERE)

SELECT * FROM Product


WHERE CategoryID = (SELECT CategoryID FROM Product ORDER BY Price DESC LIMIT 1);
+-----------+-------------+-------+------------+
| ProductID | ProductName | Price | CategoryID |
+-----------+-------------+-------+------------+
| 101 | Laptop | 75000 | 1|
| 103 | Smartphone | 40000 | 1|
+-----------+-------------+-------+------------+
2. Find Categories with More Than One Product (Subquery in HAVING)

SELECT CategoryID FROM Product


GROUP BY CategoryID
HAVING COUNT(*) > 1;

+------------+
| CategoryID |
+------------+
| 1|
| 2|
+------------+
3. Find the Most Expensive Product Using a Subquery

SELECT * FROM Product


WHERE Price = (SELECT MAX(Price) FROM Product);

+-----------+-------------+-------+------------+
| ProductID | ProductName | Price | CategoryID |
+-----------+-------------+-------+------------+
| 101 | Laptop | 75000 | 1|
+-----------+-------------+-------+------------+

Step 4: JOIN Operations


4. Retrieve Products with Their Category Names (INNER JOIN)

SELECT Product.ProductID, Product.ProductName, Product.Price, Category.CategoryName


FROM Product
INNER JOIN Category ON Product.CategoryID = Category.CategoryID;
+-----------+-------------+-------+--------------+
| ProductID | ProductName | Price | CategoryName |
+-----------+-------------+-------+--------------+
| 101 | Laptop | 75000 | Electronics |
| 102 | Table | 12000 | Furniture |
| 103 | Smartphone | 40000 | Electronics |
| 104 | Sofa | 25000 | Furniture |
| 105 | T-shirt | 500 | Clothing |
+-----------+-------------+-------+--------------+

5. Retrieve All Categories and Their Products (LEFT JOIN)

SELECT Category.CategoryName, Product.ProductName, Product.Price


FROM Category
LEFT JOIN Product ON Category.CategoryID = Product.CategoryID;
+--------------+-------------+-------+
| CategoryName | ProductName | Price |
+--------------+-------------+-------+
| Electronics | Smartphone | 40000 |
| Electronics | Laptop | 75000 |
| Furniture | Sofa | 25000 |
| Furniture | Table | 12000 |
| Clothing | T-shirt | 500 |
+--------------+-------------+-------+

6. Retrieve All Products and Their Categories (RIGHT JOIN)

SELECT Product.ProductName, Product.Price, Category.CategoryName


FROM Product
RIGHT JOIN Category ON Product.CategoryID = Category.CategoryID;

+-------------+-------+--------------+
| ProductName | Price | CategoryName |
+-------------+-------+--------------+
| Smartphone | 40000 | Electronics |
| Laptop | 75000 | Electronics |
| Sofa | 25000 | Furniture |
| Table | 12000 | Furniture |
| T-shirt | 500 | Clothing |
+-------------+-------+--------------+

RESULT:
Thus the SQL commands to execute simple queries, sub queries and joins areexecuted
successfully.
EX.NO:5 NATURAL, EQUI AND OUTER JOIN
DATE:

Aim :
To write DQL Commands to join, Restrict and Retrieve information from one or more
tables execute it and verify the same.

Algorithm:

1. Write a query to display empid,name,deptid,deptname and location


for allemployees and verify it.

SQL> select
employee.empid,employee.name,employee.depid,department.deptname,depa
rtment.location from employee,department where
employee.depid=department.depid;

EMPID NAME DEPID DEPTNAME LOCATION

a123 ragu CS000 COMPUTER_SCIENCE CHENNAI


a124 rama CS000 COMPUTER_SCIENCE CHENNAI
a125 ram EE000 ELECT_ELECTRO MUMBAI
a128 sag EE000 ELECT_ELECTRO MUMBAI
c128 dinesh EC000 ELECT_COMM DELHI
d124 abc EC000 ELECT_COMM DELHI

6 rows selected.

2. Write a query to display the “dinesh” depid and deptname and verify it.

SQL> select e.empid,e.name,e.depid,d.deptname from employee e,department d


wheree.depid=d.depid and e.name='dinesh';

EMPID NAME DEPID DEPTNAME

c128 dinesh EC000 ELECT_COMM

Selecting Rows with Non-Equijoin using table Aliases:


[Other Conditions such as >=, <= and BETWEEN, AND ]

1. Write a query to display the name,salary and deptname of all employees


whosesalary is greater than 10000 and verify it.

SQL> select e.name,e.salary,d.deptname from employee e,department d where


e.salary>10000and e.depid=d.depid;

NAME SALARY DEPTNAME

ragu 200000 COMPUTER_SCIENCE


rama 200000 COMPUTER_SCIENCE
ram 30000 ELECT_ELECTRO
Selecting Rows using Outer Joins:[ Left Outerjoin,Right Outerjoin using ”+” symbol ]

1. Write a query to display the name, depid and deptname of all


employees.Make surethat employees without department are included as well and
verify it.

SQL> select e.name,e.depid,d.deptname from employee e,department d where e.depid


=d.depid(+);

NAME DEPID DEPTNAME

rama CS000 COMPUTER_SCIENCE


ragu CS000 COMPUTER_SCIENCE
sag EE000 ELECT_ELECTRO
ram EE000 ELECT_ELECTRO
abc EC000 ELECT_COMM
dinesh EC000 ELECT_COMM
www

7 rows selected.
2. Write a query to display the name, salary,depid and deptname of all employees.
Makesure that departments without employees are included as well and verify.

SQL> select e.name,e.salary,e.depid,d.deptname from employee e,department


d where e.depid(+)=d.depid;

NAME SALARY DEPID DEPTNAME

ragu 200000 CS000 COMPUTER_SCIENCE


rama 200000 CS000 COMPUTER_SCIENCE
ram 30000 EE000 ELECT_ELECTRO
sag 10000 EE000 ELECT_ELECTRO
dinesh 10000 EC000 ELECT_COMM
abc 5000 EC000 ELECT_COMM
MECHANICAL
CHEMICAL
8 rows selected
d

RESULT:
Thus the SQL commands to execute natural, equi and outer joins areexecuted successfully.
EX.NO:6 PROCEDURES AND FUNCTIONS
DATE:

AIM:
To implement and execute Procedures in Oracle Database using Procedural Language
concepts.

ALGORITHM:

Step 1: Connect to the database.


Step 2: Create a table.
Step 3: Create a stored procedure.
Step 4: Execute the stored procedure.
Step 5: Verify the results.
Step 6: Disconnect from the database.

QUERY:

Create the Procedures

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);
-- Drop the procedure if it already exists
DROP PROCEDURE IF EXISTS AddEmployee;

-- Create the stored procedure


DELIMITER //

CREATE PROCEDURE AddEmployee (


IN p_EmployeeID INT,
IN p_FirstName VARCHAR(50),
IN p_LastName VARCHAR(50),
IN p_Department VARCHAR(50),
IN p_Salary DECIMAL(10, 2)
)
BEGIN
INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary)
VALUES (p_EmployeeID, p_FirstName, p_LastName, p_Department, p_Salary);
END //

DELIMITER ;
-- Call the procedure to add a new employee
CALL AddEmployee(1, 'John', 'Doe', 'Sales', 50000.00);

-- Call the procedure to add another employee


CALL AddEmployee(2, 'Jane', 'Smith', 'HR', 55000.00);

-- Select data from Employees table to verify the inserted records


SELECT * FROM Employees;
OUTPUT:

Create the Function

-- Drop the function if it already exists


DROP FUNCTION IF EXISTS CalculateTotalPrice;

-- Create the function


DELIMITER //

CREATE FUNCTION CalculateTotalPrice (


p_Price DECIMAL(10, 2),
p_TaxRate DECIMAL(5, 2)
)
RETURNS DECIMAL(10, 2)
DETERMINISTIC
BEGIN
RETURN p_Price + (p_Price * p_TaxRate / 100);
END //

DELIMITER ;
-- Calculate the total price of an item with a price of 100 and a tax rate of 5%
SELECT CalculateTotalPrice(100, 5) AS TotalPrice;

OUTPUT:

RESULT:
Thus the PL/SQL procedures and functions are executed successfully
EX.NO.7 TRANSACTION CONTROL AND DATA CONTROL STATEMENTS
DATE:

AIM:
To implement Transaction Control statements using structured Query Language

ALGORITHM:

Step 1: Create table by using create table command.


Step 2: Insert values into the table
Step 3: Commit the table
Step 4: Insert or Update any values in the table.
Step 5: Rollback the table
Step 6: Insert or Update any values in the table.
Step 7: Fix a save point
Step 8: Repeat step 6 and 7
Step 9: Rollback to any save point

1) CREATE A TABLE

create table employeepersonaldetails(id int primary key,name varchar(30) not null,age int not
null,mobilenumber int not null unique);

insert into employeepersonaldetails values(1,'Ajay',20,9876543210);


insert into employeepersonaldetails values(2,'Brindha',20,9874563210);
insert into employeepersonaldetails values(3,'Kumaran',20,9673443210);
select * from employeepersonaldetails;

commit;

Statement executed

insert into employeepersonaldetails values(4,'Archana',20,9876543410);


rollback;

insert into employeepersonaldetails values(5,'Braham',20,9878953210);

savepoint a;

savepoint created

insert into employeepersonaldetails values(6,'Srimathi',20,9678953210);

savepoint b;

rollback to a;

RESULT:
Thus Transaction Control and Data Control statements using structured Query Language is
executed successfully
EX.NO:8 TRIGGERS
DATE:

Aim:
To implement PL/SQL triggers and do the operations in database automatically.

Algorithm:
Step 1: Create Logs Table: Table to store log entries for insert, update, and delete actions.
Step 2: Create Main Table: Replace TableName and columns with your actual table name and
columns.
Step 3: Define Triggers: Create triggers for insert, update, and delete operations.
Step 4: Test the Triggers: Perform insert, update, and delete operations to test the triggers.
Step 5: Verify Logs: Retrieve logs to verify that the triggers are working as expected.
Query:

-- 1. Create Tables
CREATE TABLE ProductLogs (
LogID INT PRIMARY KEY AUTO_INCREMENT,
ActionType VARCHAR(10),
ProductID INT,
ProductName VARCHAR(100),
ActionDate TIMESTAMP
);

CREATE TABLE Products (


ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
CategoryID INT,
SupplierID INT,
Price DECIMAL(10, 2),
StockQuantity INT
);

-- 2. Insert Sample Data


INSERT INTO Products (ProductID, ProductName, CategoryID, SupplierID, Price, StockQuantity)
VALUES
(1, 'Coca Cola', 1, 1, 1.50, 100),
(2, 'Pepsi', 1, 2, 1.40, 150),
(3, 'Lays Chips', 2, 1, 2.50, 200);

-- 3. Define Triggers
DELIMITER //

CREATE TRIGGER after_insert_products


AFTER INSERT ON Products
FOR EACH ROW
BEGIN
INSERT INTO ProductLogs (ActionType, ProductID, ProductName, ActionDate)
VALUES ('INSERT', NEW.ProductID, NEW.ProductName, NOW());
END;
//

CREATE TRIGGER after_update_products


AFTER UPDATE ON Products
FOR EACH ROW
BEGIN
INSERT INTO ProductLogs (ActionType, ProductID, ProductName, ActionDate)
VALUES ('UPDATE', NEW.ProductID, NEW.ProductName, NOW());
END;
//

CREATE TRIGGER after_delete_products


AFTER DELETE ON Products
FOR EACH ROW
BEGIN
INSERT INTO ProductLogs (ActionType, ProductID, ProductName, ActionDate)
VALUES ('DELETE', OLD.ProductID, OLD.ProductName, NOW());
END;
//

DELIMITER ;

-- 4. Test Triggers
INSERT INTO Products (ProductID, ProductName, CategoryID, SupplierID, Price, StockQuantity)
VALUES
(4, 'Sprite', 1, 2, 1.60, 120);

UPDATE Products SET Price = 1.55 WHERE ProductID = 1;

DELETE FROM Products WHERE ProductID = 2;

-- 5. Verify Logs
SELECT * FROM ProductLogs;

OUTPUT:

+-------+------------+-----------+-------------+---------------------+
| LogID | ActionType | ProductID | ProductName | ActionDate |
+-------+------------+-----------+-------------+---------------------+
| 1 | INSERT | 4 | Sprite | 2025-02-06 12:30:00 |
| 2 | UPDATE | 1 | Coca Cola | 2025-02-06 12:31:00 |
| 3 | DELETE | 2 | Pepsi | 2025-02-06 12:32:00 |
+-------+------------+-----------+-------------+---------------------+

RESULT:
Thus the SQL triggers are executed successfully.
EX.NO:9 VIEWS AND INDEX
DATE:

AIM:

To write a DDL command to create views to restrict data access from one or more tables,execute
it and verify the same.

Creating views:

1. Create a view that contains employee id as “ID_NUMBER”, employee name as


“NAME”and salary as ”SALARY” for each employee in department 90.

SQL> create view vw_emp80(id,name,salary) as select empid,name,salary from employee


wheredeptid=90;

OUTPUT:

View created.
SQL> select * from vw_emp80;

ID NAME SALARY

s203 vidhya 29000


2. To create a view to set the salary Rs.15000/- to the employee id ‘a102’ in thevw_dept_salary and verify
the result in vw_emp12_sal and employees table.

SQL> update vw_emp12 set salary=15000 where

empid='a102';1 row updated.

To Verify: SQL> select * from vw_emp12;

SNO NAME SALARY DESIG LAST EMPID DEPTID HIRE_DATE

1 monica 15000 rep a a102 102 13-MAR-08


Creating Index
Create table
CREATE TABLE Colleges ( college_id INT PRIMARY KEY,college_code
VARCHAR(20),NOT NULL college_name VARCHAR(50));
create index
CREATE INDEX college_index ON Colleges(college_code);

college_id college_code college_name


empty

RESULT:
Thus the PL/SQL program for implementing views and index has been successfully executed.
EX.NO:10 XML SCHEMA
DATE:

AIM:

To implement XML Database and validate it using XML Schema.

PROGRAM:
create database acet;
use acet;
CREATE TABLE Students (
ID INT PRIMARY KEY AUTO_INCREMENT,
StudentData TEXT NOT NULL
);

INSERT INTO Students (StudentData)


VALUES
('<student><name>John Doe</name><age>21</age><department>Computer
Science</department></student>'),
('<student><name>Jane Smith</name><age>22</age><department>Electrical
Engineering</department></student>');

SELECT ID, ExtractValue(StudentData, '/student/name') AS StudentName FROM Students;

SELECT
ID,
ExtractValue(StudentData, '/student/name') AS Name,
ExtractValue(StudentData, '/student/age') AS Age,
ExtractValue(StudentData, '/student/department') AS Department
FROM Students;

OUTPUT

RESULT:
Thus the XML Database and validate it using XML Schema is executed successfully.
EX.NO:11 NOSQL DATABASE TOOLS
DATE

Aim:
To Create a Document, column and graph based data using NOSQL database tools.

Procedure:

Document-Based Database (MongoDB)

Step 1: Install MongoDB

1. Go to the MongoDB download page and download the Community Server version for your
operating system.
2. Follow the installation instructions specific to your OS.

Step 2: Start MongoDB

1. Open a terminal or command prompt.


2. Run the following command to start the MongoDB server:

bash

mongod

This command starts the MongoDB daemon process.

Step 3: Connect to MongoDB

1. Open another terminal or command prompt.


2. Run the following command to connect to the MongoDB server:

bash

mongo

Step 4: Execute Queries

1. Insert Document:

use mydatabase;
db.mycollection.insertOne({
name: "John Doe",
age: 30,
address: {
street: "123 Main St",
city: "Example City"
}
});

2. Find Documents:

db.mycollection.find({ age: { $gt: 25 } });


3. Update Document:

db.mycollection.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
);

4. Delete Document:

db.mycollection.deleteOne({ name: "John Doe" });

OUTPUT:

{
"acknowledged" : true,
"insertedId" : ObjectId("67a43ba0eab1610044ec0fc4")
}
{ "_id" : ObjectId("67a43ba0eab1610044ec0fc4"), "name" : "John Doe", "age" : 30,
"address" : { "street" : "123 Main St", "city" : "Example City" } }
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
{ "acknowledged" : true, "deletedCount" : 1 }

RESULT
Thus the Document, column and graph based data using NOSQL database has been successfully
executed.
EX.NO:12 GUI BASED DATABASE APPLICATIONS
DATE:

AIM:
To implement an online exam registration page with database connectivity using php

ALGORITHM:

STEP 1: Develop a webpage which includes all the fields for registering for an online exam
STEP 2: Develop a PHP page which receives the values that are given as an input in the registration page
STEP 3: Connect the registration page with the PHP page
STEP 4: Receive the values from registration page
STEP 5: Establish a connection with the database
STEP 6: Store the received values in the database

PROGRAM:

Registration.html

<html>
<body bgcolor="lightblue">
<p><center>REGISTRATION FORM</center></p>
<form action="Registration.php" method="post">
<center><pre><b> Student name: <input type="text" name="n" value=" ">
Register Number: <input type="text" name="reg" value=" ">
CGPA: <input type="text" name="cgpa" value=" ">
YEAR: <input type="text" name="y" value=" ">
Branch: <input type="text" name="branch" value=" ">
<input type="submit" name="button" value="SUBMIT">
</b></center></pre>
</body>
</html>

Registration.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Online_exam";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
/*else
echo "Connection established";*/

$Name=$_POST['n'];
$RegNo=$_POST['reg'];
$CGPA=$_POST['cgpa'];
$Year=$_POST['y'];
$Branch=$_POST['branch'];
/*echo $Name;
echo $RegNo;
echo $CGPA;
echo $Year;
echo $Branch;*/
$sql = "CREATE TABLE regDetails(Name varchar(30) not null, RegNo int(15) not null,CGPA float
not null, Year varchar(5) not null, Branch varchar(5) not null)";

if ($conn->query($sql) === TRUE)


{
echo "Table regDetails created successfully";
}
else
{
echo "Error creating table: " . $conn->error;
}
$sql = "INSERT INTO regDetails (Name,RegNo,CGPA,Year,Branch)
VALUES ('$Name',$RegNo,$CGPA,'$Year','$Branch')";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

RESULT:
Thus the real life database application for exam registration has been successfully executed.
EX.NO:13 DATABASE DESIGN USING ER MODELING, NORMALIZATION AND
DATE : IMPLEMENTATION FOR ANY APPLICATION

AIM:
The aim of this project is to design and implement an Inventory Management System for an EMart
grocery shop using a relational database.
ALGORITHM:

STEP 1: Design database


STEP 2: Create database tables
STEP 3: Insert sample data
STEP 4: Implement views, triggers, and functions
STEP 5: Develop stored procedures
STEP 6: Ensure ACID properties

PROCEDURE:

-- 1. Create Tables
CREATE TABLE Category (
CategoryID INT PRIMARY KEY,
CategoryName VARCHAR(100) NOT NULL
);

CREATE TABLE Supplier (


SupplierID INT PRIMARY KEY,
SupplierName VARCHAR(100) NOT NULL,
ContactName VARCHAR(100),
ContactEmail VARCHAR(100)
);

CREATE TABLE Product (


ProductID INT PRIMARY KEY,
ProductName VARCHAR(100) NOT NULL,
CategoryID INT,
SupplierID INT,
Price DECIMAL(10, 2),
StockQuantity INT,
FOREIGN KEY (CategoryID) REFERENCES Category(CategoryID),
FOREIGN KEY (SupplierID) REFERENCES Supplier(SupplierID)
);

CREATE TABLE Customer (


CustomerID INT PRIMARY KEY,
CustomerName VARCHAR(100) NOT NULL,
ContactName VARCHAR(100),
ContactEmail VARCHAR(100)
);

CREATE TABLE `Order` (


OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
TotalAmount DECIMAL(10, 2),
FOREIGN KEY (CustomerID) REFERENCES Customer(CustomerID)
);
CREATE TABLE OrderDetails (
OrderID INT,
ProductID INT,
Quantity INT,
UnitPrice DECIMAL(10, 2),
PRIMARY KEY (OrderID, ProductID),
FOREIGN KEY (OrderID) REFERENCES `Order`(OrderID),
FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
);

CREATE TABLE Inventory (


ProductID INT PRIMARY KEY,
StockQuantity INT,
LastUpdated DATE,
FOREIGN KEY (ProductID) REFERENCES Product(ProductID)
);

-- 2. Insert Sample Data


INSERT INTO Category (CategoryID, CategoryName) VALUES (1, 'Beverages'), (2, 'Snacks');

INSERT INTO Supplier (SupplierID, SupplierName, ContactName, ContactEmail) VALUES


(1, 'Supplier A', 'Contact A', '[email protected]'),
(2, 'Supplier B', 'Contact B', '[email protected]');

INSERT INTO Product (ProductID, ProductName, CategoryID, SupplierID, Price, StockQuantity)


VALUES
(1, 'Coca Cola', 1, 1, 1.50, 100),
(2, 'Pepsi', 1, 2, 1.40, 150),
(3, 'Lays Chips', 2, 1, 2.50, 200);

INSERT INTO Customer (CustomerID, CustomerName, ContactName, ContactEmail) VALUES


(1, 'Customer A', 'Contact A', '[email protected]'),
(2, 'Customer B', 'Contact B', '[email protected]');

INSERT INTO `Order` (OrderID, CustomerID, OrderDate, TotalAmount) VALUES


(1, 1, '2025-02-06', 3.00);

INSERT INTO OrderDetails (OrderID, ProductID, Quantity, UnitPrice) VALUES


(1, 1, 2, 1.50);

INSERT INTO Inventory (ProductID, StockQuantity, LastUpdated) VALUES


(1, 100, '2025-02-06'),
(2, 150, '2025-02-06'),
(3, 200, '2025-02-06');

-- 3. Views
CREATE VIEW CurrentInventory AS
SELECT ProductID, ProductName, StockQuantity
FROM Product
JOIN Inventory ON Product.ProductID = Inventory.ProductID;

-- 4. Triggers
CREATE TRIGGER UpdateInventoryOnOrder
AFTER INSERT ON OrderDetails
FOR EACH ROW
BEGIN
UPDATE Inventory
SET StockQuantity = StockQuantity - NEW.Quantity
WHERE ProductID = NEW.ProductID;
END;
-- 5. Functions
CREATE FUNCTION CalculateTotalOrderAmount(OrderID INT)
RETURNS DECIMAL(10, 2)
BEGIN
DECLARE total DECIMAL(10, 2);
SELECT SUM(Quantity * UnitPrice) INTO total
FROM OrderDetails
WHERE OrderID = OrderID;
RETURN total;
END;

-- 6. Stored Procedures
CREATE PROCEDURE CalculateEMIForGoldLoan()
BEGIN
DECLARE customer_id INT;
DECLARE loan_amount DECIMAL(10, 2);
DECLARE interest_rate DECIMAL(5, 2) DEFAULT 10.0;
DECLARE emi DECIMAL(10, 2);

DECLARE cur CURSOR FOR


SELECT CustomerID, LoanAmount
FROM GoldLoan
WHERE Status = 'Active';

OPEN cur;
FETCH cur INTO customer_id, loan_amount;

WHILE SQLSTATE = '00000' DO


SET emi = (loan_amount * interest_rate / 100) / 12;
UPDATE GoldLoan
SET EMI = emi
WHERE CustomerID = customer_id;

FETCH cur INTO customer_id, loan_amount;


END WHILE;

CLOSE cur;
END;

-- 7. Demonstrating ACID Properties

-- Atomicity
START TRANSACTION;
INSERT INTO `Order` (CustomerID, OrderDate, TotalAmount) VALUES (2, 2, '2025-02-06', 2.80);
INSERT INTO OrderDetails (OrderID, ProductID, Quantity, UnitPrice) VALUES (2, 2, 2, 1.40);
COMMIT;

-- Consistency
ALTER TABLE OrderDetails ADD CONSTRAINT fk_order FOREIGN KEY (OrderID) REFERENCES
`Order`(OrderID);

-- Isolation
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
-- Perform operations
COMMIT;
-- Durability
START TRANSACTION;
-- Perform operations
COMMIT;

OUTPUT:
+-----------+-------------+--------------+
| ProductID | ProductName | StockQuantity|
+-----------+-------------+--------------+
|1 | Coca Cola | 100 |
|2 | Pepsi | 150 |
|3 | Lays Chips | 200 |
+-----------+-------------+--------------+

+-----------+--------------+-------------+
| ProductID | StockQuantity| LastUpdated |
+-----------+--------------+-------------+
|2 | 148 | 2025-02-06 |
+-----------+--------------+-------------+

+------------------------------+
| CalculateTotalOrderAmount(1) |
+------------------------------+
| 3.00 |
+------------------------------+

RESULT:
Thus normalization has been implemented for student database successfully.
EX.NO:14 EXPLICIT CURSORS
DATE :

AIM:
To demonstrate the use of explicit cursors in SQL for database programming.

ALGORITHM:

STEP 1: Connect to the database.

STEP 2: For explicit cursor: Declare an explicit cursor for the SELECT statement, open the cursor,
fetch rows from the cursor, display them in a loop, and close the cursor.

STEP 3: Disconnect from the database.

QUERY:
-- Create Employees table
CREATE TABLE IF NOT EXISTS Employees (
EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Department VARCHAR(50),
Salary DECIMAL(10, 2)
);

-- Insert sample data into Employees table


INSERT INTO Employees (EmployeeID, FirstName, LastName, Department, Salary) VALUES
(1, 'John', 'Doe', 'Sales', 50000.00),
(2, 'Jane', 'Smith', 'HR', 55000.00),
(3, 'Alice', 'Johnson', 'IT', 60000.00),
(4, 'Bob', 'Brown', 'Marketing', 45000.00);

-- Verify data
SELECT * FROM Employees;
-- Drop the procedure if it already exists
DROP PROCEDURE IF EXISTS ShowEmployees;

-- Create the procedure


DELIMITER //

CREATE PROCEDURE ShowEmployees()


BEGIN
DECLARE done INT DEFAULT 0;
DECLARE emp_id INT;
DECLARE emp_firstname VARCHAR(50);
DECLARE emp_lastname VARCHAR(50);
DECLARE emp_dept VARCHAR(50);
DECLARE emp_salary DECIMAL(10, 2);

-- Declare cursor
DECLARE employee_cursor CURSOR FOR
SELECT EmployeeID, FirstName, LastName, Department, Salary FROM Employees;

-- Declare NOT FOUND handler


DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
-- Open cursor
OPEN employee_cursor;

-- Loop through the cursor


read_loop: LOOP
FETCH employee_cursor INTO emp_id, emp_firstname, emp_lastname, emp_dept,
emp_salary;
IF done THEN
LEAVE read_loop;
END IF;
-- Display the fetched data
SELECT CONCAT('EmployeeID: ', emp_id, ', Name: ', emp_firstname, ' ', emp_lastname, ',
Department: ', emp_dept, ', Salary: ', emp_salary) AS EmployeeDetails;
END LOOP;

-- Close cursor
CLOSE employee_cursor;
END //

DELIMITER ;

-- Call the procedure


CALL ShowEmployees();

OUTPUT:

RESULT:
Thus explicit cursors in SQL database programming has been implemented successfully.

You might also like