DBMS LAB MANUAL
DBMS LAB MANUAL
AIM:
Creation of a database and writing SQL commands to retrieve information from the
database.
QUERIES:
//Create table
CREATE TABLE emp
(
empno INT,
empname VARCHAR(255),
DOB DATE,
salary INT,
designation VARCHAR(20)
);
// Insert values
INSERT INTO emp(empno,empname, DOB, designation) VALUES(100,'John', ‘21-
Apr-1996’, 50000,'Manager');
INSERT INTO emp(empno,empname, DOB, designation) VALUES(101,'Greg', ‘20-
July-1994’, 2500,'Clerk');
-2 rows inserted
// Display values
SELECT * FROM emp;
Page | 1
EMPNO EMPNAME DOB SALARY DESIGNATION
100 John 21-Apr-1996 50000 Manager
101 Greg 20-July-1994 2500 Clerk
// Modify values
UPDATE emp SET salary = salary + 1000;
SELECT * FROM emp;
EMPNO EMPNAME DOB SALARY DESIGNATION
100 John 21-Apr-1996 51000 Manager
101 Greg 20-July-1994 3500 Clerk
// Delete values
DELETE FROM emp WHERE empno = 100;
-1 row deleted.
DDL STATEMENTS
• CREATE TABLE
• ALTER TABLE
• DROP TABLE
Page | 2
SYNTAX:
1. Create Table
2. Alter Table
The ALTER TABLE statement is used to add, delete, or modify columns in an existing table
a. To Add a column
3. Drop Table
QUERIES:
- Table Created
DESC emp;
EMPNAME VARCHAR 25 - - - - - -
DOB DATE 7 - - - - - -
SALARY INT 11 - - - - - -
DESIGNATION VARCHAR 20 - - - - - -
a. ADD
- Table Altered
DESC emp;
Column Data Type Length Precision Scale Primary Key Nullable Default
Comment
EMPNO INT 11 - - - - -
-
EMPNAME VARCHAR 25 - - - - -
-
Page | 4
DOB DATE 7 - - - - -
-
SALARY INT 11 - - - - -
-
DESIGNATION VARCHAR 20 - - - - -
-
DEPARTMENT VARCHAR2 50 - - - - -
-
b. MODIFY
// To alter the table emp by modifying the size of the attribute department
DESC emp;
Column Data Type Length Precision Scale Primary Key Nullable Default
Comment
EMPNO INT 11 - - - - -
-
EMPNAME VARCHAR 25 - - - - -
-
DOB DATE 7 - - - - -
-
SALARY INT 11 - - - - -
-
DESIGNATION VARCHAR 20 - - - - -
-
DEPARTMENT VARCHAR 100 - - - - -
-
c. DROP
- Table Altered
DESC emp;
EMPNAME VARCHAR 25 - - - - - -
DOB DATE 7 - - - - - -
SALARY INT 11 - - - - - -
DESIGNATION VARCHAR 20 - - - - - -
d. RENAME
- Table Altered
DESC emp1;
3. DROP
DESC emp1;
Object to be described could not be found.
Page | 6
CONSTRAINT TYPES:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
QUERIES:
DESC student;
Page | 7
SEM INT 22 - - - - -
-
DOB DATE 7 - - - - -
-
EMAIL_ID VARCHAR 20 - - - - -
-
COLLEGE VARCHAR 20 - - - -
'MEC' -
DESC exam;
Column Data Type Length Precision Scale Primary Key Nullable Default
Comment
EXAMID INT 22 - - - - - -
STUDENTID INT 22 - - - - - -
DEPARTMENT VARCHAR 5 - - - - - -
MARK1 INT 22 - - - - - -
MARK2 INT 22 - - - - - -
MARK3 INT 22 - - - - - -
MARK4 INT 22 - - - - - -
MARK5 INT 22 - - - - - -
TOTAL INT 22 - - - - - -
AVERAGE INT 22 - - - - - -
GRADE VARCHAR 1 - - - - - -
- Table Altered
DESC student;
Column Data Type Length Precision ScalePrimary Key NullableDefault
Comment
STUDENTID INT 22 - - 1 - - -
SNAME VARCHAR 30 - - - - - -
DEPARTMENT VARCHAR 5 - - - - -
-
SEM INT 22 - - - - -
-
DOB DATE 7 - - - - -
-
EMAIL_ID VARCHAR 20 - - - - -
-
COLLEGE VARCHAR 20 - - - -
'MEC' -
ADDRESS VARCHAR 100 - - - - -
-
B. MODIFY
//To alter the table student by modifying the size of the attribute address
- Table Altered
DESC student;
Column Data Type Length Precision Scale Primary Key Nullable Default
Comment
STUDENTID INT 22 - - 1 - -
-
SNAME VARCHAR 30 - - - - -
-
DEPARTMENT VARCHAR 5 - - - -
- -
Page | 9
SEM INT 22 - - - - -
-
DOB DATE 7 - - - - -
-
EMAIL_ID VARCHAR 20 - - - - -
-
COLLEGE VARCHAR 20 - - - -
'MEC' -
ADDRESS VARCHAR 150 - - - - -
-
C. DROP
- Table Altered
DESC student;
Column Data Type Length Precision Scale Primary Key Nullable Default
Comment
STUDENTID INT 22 - - 1 -
- -
SNAME VARCHAR 30 - - - -
- -
DEPARTMENT VARCHAR 5 - - - -
- -
SEM INT 22 - - - -
- -
DOB DATE 7 - - - -
- -
EMAIL_ID VARCHAR 20 - - - -
- -
COLLEGE VARCHAR 20 - - - -
'MEC' -
D. RENAME
Page | 10
- Table Altered
DESC student1;
- Table Altered
3. DROP
- Table dropped
DESC exam;
RESULT:
Page | 11
Ex.No:2
CREATION OF EMPLOYEE DATABASE WITH CONSTRAINTS
Date:
AIM:
QUERIES:
DESC student;
DESIGNATION VARCHAR 50 - - - - -
-
DOB DATE 7 - - - - -
-
EMAIL_ID VARCHAR 20 - - - - -
-
Page | 12
COLLEGE VARCHAR 20 - - - -
'MEC' -
Create a table ‘Employee’ with the following details (Column level constraints)
QUERIES:
Create table Employee(Empno Number(5) Primary key, Empname Varchar2(20)
,Designation Varchar2(10), Date_of_join Date, Salary Number(9,2) constraint csk NOT
NULL, Depno Number(2) Reference Department (Deptno));
SQL>descs employee;
NAME Type
Empno Number(5)
Empname Varchar2(20)
Designation Varchar2(10)
Date_of_join Date
Salary Number(9,2) NOTNULL
Depno Number(2)
2.Create another table called ‘Department’ with the following structure(Column level
constraints)
Depno Number(2) Primary key
Depname Varchar2(15)
Deplocation Varchar2(10)
Ans:
Page | 13
SQL>Create table department (deptno Number(2) Primary key , Depname Varchar2(15),
Deplocation Varchar2(10));
SQL>desc department;
Name Type
Depno Number(2) Primary key
Depname Varchar2(15)
Deplocation Varchar2(10)
i. Display the number of employees in each department with the department numbers in
descending order
SQL>select deptno, count(empname)from department groupby department orderby desc;
RESULT:
Thus the Employee database with constraints were performed and executed successfully.
Page | 14
Ex.No:3 QUERY THE DATABASE TABLES USING DIFFERENT ‘WHERE
Date: CLAUSE CONDITIONS AND ALSO IMPLEMENT AGGREGATE
FUNCTIONS
AIM:
Creation of a database and execute Aggregate Functions to retrieve information from the
database.
QUERIES:
➢ ORDER BY
➢ GROUP BY
➢ AGGREGATE FUNCTIONS
▪ Table Created
DESC student;
Page | 15
SNAME VARCHAR 30 - - - - -
-
DEPARTMENT CHAR 5 - - - - -
-
SEM INT 22 - - - - -
-
DOB DATE 7 - - - - -
-
EMAIL_ID VARCHAR 20 - - - - -
-
COLLEGE VARCHAR 20 - - - -
'MEC' -
1. ORDER BY
// To display the department, sem and student name from the table student based on
department in ascending order.
// To display the department, sem and student name from the table student based on
department in descending order.
SELECT department, sem, sname FROM student ORDER BY department DESC, sem
DESC, sname DESC;
2. GROUP BY
DEPARTMENT SUM_DEPARTMENT
CSE 430
IT 1346
3. AGGREGATE FUNCTIONS
STUDENTS_REGISTERED
4
// 2. MAX - displays the maximum value
RANK_1
90.8
LAST_RANK
86
DEPARTMENT SUM_DEPARTMENT
CSE 430
Page | 17
IT 1346
DEPARTMENT AVERAGE
IT 448.66667
CSE 430
RESULT:
Databases are created and SQL queries are retrieved information successfully.
Page | 18
Ex.No:4 QUERY THE DATABASE TABLES AND EXPLORE SUB QUERIES
Date: AND SIMPLE JOIN OPERATIONS
AIM:
Creation of a database and execute SQL Joins to retrieve information from the database.
QUERIES:
JOIN TYPES
1. INNER JOIN
2. SELF JOIN
-Table Created
-Table Created
Page | 19
// Inserting values into cseitstudent table
- 5 row(s) inserted
- 5 row(s) inserted
Page | 20
1 104 IT infosys 25000
2 105 CSE Wipro 22000
3 204 MECH HYUNDAI 30000
4 102 IT Infosys 25000
5 103 CSE Infosys 25000
// INNER JOIN
SELECT *
FROM cseitstudent
INNER JOIN Placement
ON cseitstudent.studentID=placement.StudentID;
//SELF JOIN
//TABLE CREATION
Page | 21
CREATE TABLE employee
(
empid INT,
empname VARCHAR(25),
reportingid INT
);
- Table Created
// EXISTS
// NOT EXISTS
SELECT * FROM employee1 WHERE
NOT EXISTS (SELECT * FROM employee1 WHERE salary>20000 );
no data found
RESULT:
Databases are created and SQL queries are retrieved information successfully.
Page | 23
Ex.No:5 QUERY THE DATABASE TABLES AND EXPLORE NATURAL ,
Date: EQUI AND OUTER JOIN OPERATIONS
AIM:
Creation of a database and execute SQL Joins to retrieve information from the database.
QUERIES:
JOIN TYPES
1. OUTER JOIN
a. LEFT OUTER JOIN
b. RIGHT OUTER JOIN
c. CROSS OUTER JOIN
2. EQUI JOIN
3. NON EQUI JOIN
-Table Created
-Table Created
- 5 row(s) inserted
- 5 row(s) inserted
SELECT *
FROM cseitstudent
LEFT OUTER JOIN placement
ON cseitstudent.studentID=placement.studentID;
SELECT *
FROM cseitstudent
RIGHT OUTER JOIN placement
ON cseitstudent.studentID=placement.studentID;
SELECT *
FROM cseitstudent
FULL OUTER JOIN placement
ON cseitstudent.studentID=placement.studentID;
//EQUI JOIN
STUDENTID SNAME
105 eshwar
105 eshwar
105 eshwar
104 nirmal
104 nirmal
103 sheela
// EXISTS
Page | 28
SELECT * FROM placement WHERE EXISTS (
SELECT * FROM placement WHERE salary>20000);
// NOT EXISTS
SELECT * FROM employee1 WHERE
NOT EXISTS (SELECT * FROM employee1 WHERE salary>20000 );
no data found
// NATURAL JOIN
Syntax :
We will perform the natural join query by using the following syntax.
SELECT *
FROM TABLE1
NATURAL JOIN TABLE2;
Step-1:Creating Database :
create database saran;
Step-2: Using the database :
To use this database as follows.
use saran;
Page | 29
Step-3: Reference tables into the database :
This is our tables in the geeks database as follows.
Table-1: department –
Create Table department
(
DEPT_NAME Varchar(20),
MANAGER_NAME Varchar(255)
);
Table-2: employee –
Create Table employee
(
EMP_ID int,
EMP_NAME Varchar(20),
DEPT_NAME Varchar(255)
);
Step-4: Inserting values :
Add value into the tables as follows.
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "IT",
"ROHAN");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "SALES",
"RAHUL");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "HR",
"TANMAY");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES ( "FINANCE",
"ASHISH");
INSERT INTO DEPARTMENT(DEPT_NAME,MANAGER_NAME) VALUES
("MARKETING", "SAMAY");
1 SUMIT HR
2 JOEL IT
3 BISWA MARKETING
4 VAIBHAV IT
5 SAGAR SALES
SELECT * FROM DEPARTMENT;
Output :
DEPT_NAME MANAGER_NAME
IT ROHAN
SALES RAHUL
HR TANMAY
FINANCE ASHISH
MARKETING SAMAY
Page | 31
Output :
EMP_ID EMP_NAME DEPT_NAME MANAGER_NAME
1 SUMIT HR TANMAY
2 JOEL IT ROHAN
4 VAIBHAV IT ROHAN
RESULT:
Databases are created and SQL queries are retrieved information successfully.
Page | 32
Ex.No:6
USER DEFINED FUNCTIONS AND STORED PROCEDURES IN SQL
Date:
AIM:
Creation 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:
CREATE TEMP FUNCTION AddFourAndDivide(x INT64, y INT64)
RETURNS FLOAT64
AS (
(x + 4) / y
);
SELECT
val, AddFourAndDivide(val, 2)
FROM
UNNEST([2,3,5,8]) AS val;
Page | 33
CREATE FUNCTION mydataset.AddFourAndDivide(x INT64, y INT64)
RETURNS FLOAT64
AS (
(x + 4) / y
);
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;
A parameter with a type equal to ANY TYPE can match more than one argument type when the
function is called.
• If more than one parameter has type ANY TYPE, then BigQuery doesn't enforce any type
relationship between these arguments.
• 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.
• 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.
SELECT
addFourAndDivideAny(3, 4) AS integer_input,
addFourAndDivideAny(1.59, 3.14) AS floating_point_input;
Page | 34
This example produces the following output:
+----------------+-----------------------+
| integer_input | floating_point_input |
+----------------+-----------------------+
| 1.75 | 1.7802547770700636 |
+----------------+-----------------------+
The next example uses 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))]
);
SELECT
lastArrayElement(x) AS last_element
FROM (
SELECT [2,3,5,8,13] AS x
);
RESULT:
Databases are created user defined function and procedure in SQL queries are retrieved
information successfully.
Page | 35
Ex.No:7
Execute Complex transactions and realize DCL and TCL Commands
Date:
AIM:
DESCRIPTION:
The DCL language is used for controlling the access to the table and hence securing the Database.
DCL is used to provide certain privileges to a particular user. Privileges are rights to be allocated.
The privilege commands are namely,
• Grant
• Revoke
• Commit
• Savepoint
• Rollback
GRANT COMMAND: It is used to create users and grant access to the database. It requires
database administrator (DBA) privilege, except that a user can change their password. A user can
grant access to their database objects to other users.
REVOKE COMMAND: Using this command , the DBA can revoke the granted database
privileges from the user.
SAVEPOINT: It is used to temporarily save a transaction so that you can rollback to that point
whenever necessary
ROLLBACK: It restores the database to last commited state. It is also use with savepoint command
to jump to a savepoint in a transaction.
COMMANDS
Page | 36
Consider the following tables namely “DEPARTMENTS” and “EMPLOYEES” Their schemas
are as follows ,
SQL> Grant select , update , insert on departments to abcde with grant option; Grant succeeded.
SQL> Revoke select , update , insert on departments from abcde; Revoke succeeded.
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
Page | 37
SQL> commit; Commit complete.
NAME ID
Anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
indu 11
janani 13
Page | 38
9 rows selected.
NAME ID
anu 1
brindha 2
chinthiya 3
divya 4
ezhil 5
fairoz 7
hema 9
indu 11
8 rows selected.
NAME ID
anu 1
brindha 2
chinthiya 3
divya 4
Page | 39
ezhil 5
fairoz 7
hema 9
RESULT:
Thus the creation of database with various constraints and the SQL queries to retrieve
information from the database using DCL statements has been implemented and the output was
verified successfully.
Page | 40
Ex.No:8 SQL TRIGGERS FOR INSERT, DELETE, AND UPDATE
Date: OPERATIONS IN DATABASE TABLE
AIM:
To Create a SQL triggers for insert, delete and update operations in database table
TRIGGER
SYNTAX:
EXAMPLE-1:
TRIGGER CREATION :
Page | 41
SELECT-EMP_AUDIT
SELECT –EMP:
RESULT:
Page | 42
Ex.No:9 CREATE VIEW AND INDEX FOR DATABASE TABLES WITH
Date: LARGE NUMBER OF RECORDS
Aim:
Syntax :
DEFINITION:
A view, is a logical table based on one or more tables or views. A view contains no data
itself. The tables upon which a view is based are called base tables.
SYNTAX:
AS
<Query Expression>
QUERY:
OUTPUT:
QUERY:
OUTPUT:
Page | 43
1 rows inserted.
1 rows inserted.
1 rows inserted.
QUERY:
OUTPUT:
QUERY:
OUTPUT:
1 bala IT
2 rupesh IT
QUERY:
OUTPUT:
1 rows inserted.
QUERY:
OUTPUT:
1 bala IT
2 rupesh IT
Page | 44
7 anand IT
QUERY:
OUTPUT:
1 rows updated.
QUERY:
OUTPUT:
1 bala IT
5 rupesh IT
7 anand IT
QUERY:
OUTPUT:
1 rows deleted
QUERY:
OUTPUT:
1 bala IT
7 art IT
QUERY:
Page | 45
OUTPUT:
DEFINITION:
SYNTAX:
Create index:
Drop Index:
QUERY:
OUTPUT:
QUERY:
OUTPUT:
Result:
Thus, the SQL queries using views were successfully executed and
verified.
Page | 46
Ex.No:10 CREATE AN XML DATABASE AND VALIDATE IT USING XML
Date: SCHEMA.
Aim:
Query:
DECLARE
l_schema CLOB;
BEGIN
<xs:element name="item">
<xs:complexType>
<xs:sequence>
<xs:element ref="title"/>
<xs:element ref="note" minOccurs="0"/>
<xs:element ref="quantity"/>
<xs:element ref="price"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
<xs:element ref="orderperson"/>
<xs:element ref="shipto"/>
<xs:element ref="item" maxOccurs="unbounded"/>
</xs:sequence>
<xs:attribute ref="orderid" use="required"/>
</xs:complexType>
</xs:element>
</xs:schema>';
END;
/
We can check the schema details using the USER_XML_SCHEMAS view.
Page | 48
SELECT schema_url FROM user_xml_schemas;
SCHEMA_URL
--------------------------------------------------------------------------------
my_schema.xsd
SQL>
With the schema registered, we can now validate XML documents against it.
BEGIN
DBMS_XMLSCHEMA.deleteschema(
schemaurl => 'my_schema.xsd',
delete_option => DBMS_XMLSCHEMA.delete_cascade_force);
END;
/
Validate XML Document (SCHEMAVALIDATE)
In the following PL/SQL example, we create an XMLTYPE from some XML in a CLOB, then
call the SCHEMAVALIDATE member procedure to test the XML against the XML schema.
DECLARE
l_xml CLOB;
l_xmltype XMLTYPE;
BEGIN
END;
/
SQL>
To see an example of a validation failure, rename the "name" tag to "name1". This is not part of
the XML schema, so it will fail the validation.
DECLARE
l_xml CLOB;
l_xmltype XMLTYPE;
BEGIN
END;
/
DECLARE
*
ERROR at line 1:
ORA-30937: No schema definition for 'name1' (namespace '##local') in parent
'/shiporder/shipto'
ORA-06512: at "SYS.XMLTYPE", line 354
ORA-06512: at line 29
SQL>
Validate XML Document (XMLISVALID)
CREATE TABLE t1 (
id NUMBER,
xml XMLTYPE
);
COMMIT;
Now we can use the XMLISVALID function in SQL to test against the registered XML Schema.
It returns a "1" if the XML is valid, and "0" if it isn't.
SELECT id,
XMLISVALID(xml, 'my_schema.xsd') AS is_valid
FROM t1;
ID IS_VALID
---------- ----------
1 1
2 0
Page | 52
SQL>
Result:
Page | 53
Ex.No:11 CREATE DOCUMENT, COLUMN AND GRAPH BASED DATA
Date: USING NOSQL DATABASE TOOLS
Aim:
To write NoSQL queries using Column Graph based data commands to manage the database.
Query:
The examples on this page use the inventory collection. Populate the inventory collection
with the following documents:
{ "item": "journal", "qty": 25, "size": { "h": 14, "w": 21, "uom": "cm" }, "status": "A" },
{ "item": "notebook", "qty": 50, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "A" },
{ "item": "paper", "qty": 100, "size": { "h": 8.5, "w": 11, "uom": "in" }, "status": "D" },
{ "item": "planner", "qty": 75, "size": { "h": 22.85, "w": 30, "uom": "cm" }, "status": "D" },
{ "item": "postcard", "qty": 45, "size": { "h": 10, "w": 15.25, "uom": "cm" }, "status": "A" }
Compass
To select all documents in the collection, pass an empty document as the query filter
parameter to the query bar. The query filter parameter determines the select criteria:
Page | 54
This operation uses a filter predicate of {}, which corresponds to the following SQL statement:
For more information on the MongoDB Compass query bar, see Query Bar.
Page | 55
To specify equality conditions, use <field>:<value> expressions in the query filter document:
Compass
The following example selects from the inventory collection all documents where
the status equals "D":
Copy the following filter into the Compass query bar and click Find:
{ status: "D" }
Compass
This operation uses a filter predicate of { status: "D" }, which corresponds to the following SQL
statement:
Page | 56
Specify Conditions Using Query Operators
A query filter document can use the query operators to specify conditions in the following form:
Compass
The following example retrieves all documents from the inventory collection where status equals
either "A" or "D":
Copy the following filter into the Compass query bar and click Find:
Compass
Page | 57
NOTE
Although you can express this query using the $or operator, use the $in operator rather than
the $or operator when performing equality checks on the same field.
The operation uses a filter predicate of { status: { $in: [ "A", "D" ] } }, which corresponds to the
following SQL statement:
Page | 58
Refer to the Query and Projection Operators document for the complete list of MongoDB query
operators.
A compound query can specify conditions for more than one field in the collection's documents.
Implicitly, a logical AND conjunction connects the clauses of a compound query so that the query
selects the documents in the collection that match all the conditions.
The following example retrieves all documents in the inventory collection where
the status equals "A" and qty is less than ($lt) 30:
Copy the following filter into the Compass query bar and click Find:
Compass
The operation uses a filter predicate of { status: "A", qty: { $lt: 30 } }, which corresponds to the
following SQL statement:
Page | 59
Specify OR Conditions
Using the $or operator, you can specify a compound query that joins each clause with a
logical OR conjunction so that the query selects the documents in the collection that match at least
one condition.
Copy the following filter into the Compass query bar and click Find:
Compass
Page | 60
The operation uses a filter predicate of { $or: [ { status: 'A' }, { qty: { $lt: 30 } } ] }, which
corresponds to the following SQL statement:
In the following example, the compound query document selects all documents in the collection
where the status equals "A" and either qty is less than ($lt) 30 or item starts with the
character p:
Copy the following filter into the Compass query bar and click Find:
Compass
Page | 61
status: 'A',
$or: [
SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")
Result:
Page | 62
Ex.No:12
DEVELOP A SIMPLE GUI BASED DATABASE APPLICATION
Date:
AIM:
To develop a simple GUI based database application for Personal Information System.
DESCRIPTION:
DATABASE:
FORMS:
Page | 63
➔ TO INSERT THE RECORD CLICK SAVE
Page | 64
➔ TO SEARCH ENTER THE PERSONAL NUMBER AND CLICK SEARCH
Page | 65
➔ TO DELETE ENTER THE PERSONAL NUMBER AND CLICK DELETE
Page | 66
➔ TO MODIFY ENTER THE PERSONAL NUMBER AND CLICK SEARCH THEN PERFORM
UPDATIONS AND CLICK MODIFY
Page | 67
Page | 68
➔ TO CLEAR THE BOX CLICK THE CLEAR BUTTON
Page | 69
➔ AFTER CLICKING THE CLEAR BUTTON
Page | 70
➔ TO EXIT PRESS THE EXIT BUTTON
CODING:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Oracle.DataAccess.Client;
namespace PersonelInformationSystem
{
public partial class Form1 : Form
{
public Form1()
{
Page | 71
InitializeComponent();
}
//CONNECTIVITY CODING
OracleConnection conn;
private void Form1_Load(object sender, EventArgs e)
{
string oradb = "Data Source=XE;User Id=art;Password=123;";
conn = new OracleConnection(oradb);
conn.Open();
}
//CLEAR FUNCTION
private void Clear()
{
txtPID.Text = "";
txtName.Text = "";
txtFather.Text = "";
txtDOB.Text = "";
rdoMale.Checked = false;
rdoFemale.Checked = false;
txtAddress.Text = "";
txtMark.Text = "";
txtMobile.Text = "";
txtEmail.Text = "";
}
//INSERTION CODING
// Do NOT change the order of the parameter and values
private void btnSave_Click(object sender, EventArgs e)
{
string gender = " ";
if (rdoMale.Checked)
{
gender = "Male";
}
else if (rdoFemale.Checked)
{
gender = "Female";
}
DateTime dt = Convert.ToDateTime(txtDOB.Text);
string sql = "INSERT INTO sankar.personaldetail
(pid,name,father,dob,gender,address,mark,mobile,email) VALUES
(:pid,:name,:father,:dob,:gender,:address,:mark,:mobile,:email)";
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.Parameters.Add("pid", txtPID.Text);
cmd.Parameters.Add("name", txtName.Text);
cmd.Parameters.Add("father", txtFather.Text);
Page | 72
cmd.Parameters.Add("dob", dt);
cmd.Parameters.Add("gender", gender);
cmd.Parameters.Add("address", txtAddress.Text);
cmd.Parameters.Add("mark", txtMark.Text);
cmd.Parameters.Add("mobile", txtMobile.Text);
cmd.Parameters.Add("email", txtEmail.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("inserted sucessfully");
Clear();
}
//UPDATION CODING
// Do NOT change the order of the parameter and values
private void btnEdit_Click(object sender, EventArgs e)
{
string gen = " ";
if (rdoMale.Checked)
{
gen = rdoMale.Text;
}
else if (rdoFemale.Checked)
{
gen = rdoFemale.Text;
}
DateTime dt = Convert.ToDateTime(txtDOB.Text);
//DELETION CODING
private void btnDelete_Click(object sender, EventArgs e)
Page | 73
{
OracleCommand cmd = new OracleCommand("DELETE FROM sankar.personaldetail
WHERE
pid=:pid", conn);
cmd.Parameters.Add("pid", txtPID.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Message deleted succesfully");
Clear();
}
//CLEAR CODING
private void btnClear_Click(object sender, EventArgs e)
{
Clear();
}
//SEARCH CODING
private void btnSearch_Click(object sender, EventArgs e)
{
OracleCommand cmd = new OracleCommand("SELECT * FROM sankar.personaldetail
WHERE
pid=:pid1", conn);
cmd.Parameters.Add("pid1", txtPID.Text);
OracleDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
txtPID.Text = dr["pid"].ToString();
txtName.Text = dr["name"].ToString();
txtFather.Text = dr["father"].ToString();
txtDOB.Text = dr["dob"].ToString();
if (dr["gender"].ToString() == "Male")
{ rdoMale.Checked = true; }
else
{ rdoFemale.Checked = true; }
txtAddress.Text = dr["address"].ToString();
txtMark.Text = dr["mark"].ToString();
txtMobile.Text = dr["mobile"].ToString();
txtEmail.Text = dr["email"].ToString();
}
else
{
MessageBox.Show("Record not found ");
}
}
//EXIT CODING
private void btnExit_Click(object sender, EventArgs e)
Page | 74
{
Close(); } } }
RESULT:
Page | 75
Ex.No:13
Case Study (Inventory Management for a EMart Grocery Shop)
Date:
Aim:
Description:
Inventory control system helps in monitoring the sales and various stocks available
DATABASE:
STOCK TABLE
-----------
prodid INT PRIMARY KEY, prodname VARCHAR2(50), quantity INT, unitprice INT,
reorderlevel INT
);
SALES TABLE
------------
prodid INT REFERENCES stock(prodid), salesqty INT, amount INT, salesdate DATE
);
Page | 76
FORMS:
Page | 77
CODING FOR SALES FORM:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Oracle.DataAccess.Client;
namespace inventory1
{
public partial class sales : Form
{
public sales()
{
Page | 78
InitializeComponent();
}
OracleConnection conn;
private void sales_Load(object sender, EventArgs e)
{
string oradb = "Data Source=172.18.1.6;User Id=cselab;Password=cselab;";
conn = new OracleConnection(oradb);
conn.Open();
Page | 79
}
public Boolean validate()
{
String sel1 = "select quantity,reorderlevel,prodname from cselab.stock where
prodid=:prodid";
OracleCommand cmd = new OracleCommand(sel1, conn);
cmd.Parameters.Add("prodid", cmboPid.SelectedItem);
OracleDataReader dr = cmd.ExecuteReader();
int relevel = 0;
int qty = 0;
if (dr.Read())
{
qty = int.Parse(dr["quantity"].ToString());
relevel = int.Parse(dr["reorderlevel"].ToString());
}
int sqty = int.Parse(txtSalesqty.Text);
if (sqty > qty) // Insuficient stock
{
return true;
}
int afterSale = qty - sqty;
if (afterSale < relevel)
{
MessageBox.Show("Stock level is low. Please order the item " +
dr["prodname"].ToString());
}
return false;
}
private void txtSalesqty_Validated(object sender, EventArgs e)
{
int amt = getAmount();
txtAmt.Text = amt.ToString();
}
private int getAmount()
{
string sel = "SELECT unitprice FROM cselab.stock WHERE prodid=:prodid";
OracleCommand cmd = new OracleCommand(sel, conn);
cmd.Parameters.Add("prodid", cmboPid.SelectedItem);
OracleDataReader dr = cmd.ExecuteReader();
Page | 80
int uprice = 0;
if (dr.Read())
{
uprice = int.Parse(dr["unitprice"].ToString());
}
int sqty = int.Parse((txtSalesqty.Text).ToString());
int amt = uprice * sqty;
return amt;
}
public void updatestock()
{
string upd = "update cselab.stock set quantity=quantity-:salesqty where prodid=:prodid";
OracleCommand cmd = new OracleCommand(upd, conn);
cmd.Parameters.Add("salesqty", txtSalesqty.Text);
cmd.Parameters.Add("prodid", cmboPid.SelectedItem);
cmd.ExecuteNonQuery();
}
void clear()
{
cmboPid.Text = "";
txtSalesqty.Text = "";
txtAmt.Text = "";
txtSalesdate.Text = "";
}
Page | 81
using System.Text;
using System.Windows.Forms;
using Oracle.DataAccess.Client;
namespace inventory1
{
public partial class stock : Form
{
public stock()
{
InitializeComponent();
}
OracleConnection conn;
Boolean IsExist;
}
private void btnStock1_Click(object sender, EventArgs e)
{
if (IsExist)
{
String upd = "update cselab.stock set quantity=quantity + :qty where prodid=:prodid";
OracleCommand cmd2 = new OracleCommand(upd, conn);
cmd2.Parameters.Add("qty", txtQty.Text);
Page | 82
cmd2.Parameters.Add("prodid", txtPid.Text);
cmd2.ExecuteNonQuery();
MessageBox.Show("Quantity is updated");
clear();
}
else
{
String ins = "INSERT INTO cselab.stock(prodid, prodname, quantity, unitprice,
reorderlevel) values(:prodid, :prodname, :quantity, :unitprice, :reorderlevel)";
OracleCommand cmd = new OracleCommand(ins, conn);
cmd.Parameters.Add("prodid", txtPid.Text);
cmd.Parameters.Add("prodname", txtPname.Text);
cmd.Parameters.Add("quantity", txtQty.Text);
cmd.Parameters.Add("unitprice", txtPrice.Text);
cmd.Parameters.Add("reorderlevel", txtReorder.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Entry is made in the stock");
clear(); ;
}
}
private void btnXit_Click(object sender, EventArgs e)
{
Close();
}
private void txtPid_Validated(object sender, EventArgs e)
{
String sel = "Select prodid,prodname,unitprice,reorderlevel from cselab.stock where
prodid=:prodid";
OracleCommand cmd1 = new OracleCommand(sel, conn);
cmd1.Parameters.Add("prodid", txtPid.Text);
String pid = txtPid.Text;
OracleDataReader dr = cmd1.ExecuteReader();
IsExist = false;
if (dr.Read())
{
txtPname.Text = dr["prodname"].ToString();
txtPrice.Text = dr["unitprice"].ToString();
txtReorder.Text = dr["reorderlevel"].ToString();
txtPname.Enabled = false;
Page | 83
txtPrice.Enabled = false;
txtReorder.Enabled = false;
IsExist = true;
}
}
}
}
RESULT:
Page | 84
ADDITIONAL PROGRAM
AIM:
To write a PL/SQL block to find whether the given number is odd or even.
PROGRAM:
declare
n number:=&n;
begin
if mod(n,2)=0
then
dbms_output.put_line('number is even');
else
dbms_output.put_line('number is odd');
end if;
end;
/
Output
Enter value for n: 7
old 2: n number:=&n;
new 2: n number:=7;
number is odd
RESULT:
Thus the program to find whether the given number is odd or even by using PL/SQL has
been executed successfully.
Page | 85
Ex. No: 14.b Factorial of a Number
AIM:
To write a PL/SQL block to find the factorial of a given number.
PROGRAM:
DECLARE
fact number :=1;
n number := &1;
BEGIN
while n > 0 loop
fact:=n*fact;
n:=n-1;
end loop;
dbms_output.put_line(fact);
END;
Output
Consider 5 has given
120
RESULT:
Thus the program to find the factorial of a given number by using PL/SQL has been
executed successfully.
Page | 86
Ex. No: 14.c Leap Year or Not
AIM:
To write a PL/SQL block to find whether the given year is leap year or not.
PROGRAM:
DECLARE
year NUMBER := 2012;
BEGIN
IF MOD(year, 4)=0
AND
MOD(year, 100)!=0
OR
MOD(year, 400)=0 THEN
dbms_output.Put_line(year || ' is leap year ');
ELSE
dbms_output.Put_line(year || ' is not leap year.');
END IF;
END;
Output
2012 is leap year
RESULT:
Thus, the program to find whether the given year is leap year or not by using PL/SQL
has been executed successfully.
Page | 87
Ex. No: 14.d Fibonacci Series
AIM:
To write a PL/SQL block to generate Fibonacci series.
PROGRAM:
declare
a number := 0;
b number := 1;
temp number;
n number := 10;
i number;
begin
dbms_output.put_line('fibonacci series is :');
dbms_output.put_line(a);
dbms_output.put_line(b);
for i in 2..n
loop
temp:= a + b;
a := b;
b := temp;
dbms_output.put_line(temp);
end loop;
end;
Output
fibonacci series is : 0 1 1 2 3 5 8 13 21 34
RESULT:
Thus the program to generate Fibonacci series by using PL/SQL has been executed
successfully.
Page | 88
Ex. No: 14.e Reverse a Number
AIM:
To write a PL/SQL block to reverse a number.
PROGRAM:
DECLARE
num number;
reverse_num number:=0;
begin
num:=98765;
while num>0
loop
reverse_num:=(reverse_num*10) + mod(num,10);
num:=trunc(num/10);
end loop;
dbms_output.put_line(' Reversed number is : '|| reverse_num);
Output
Reversed number is: 56789
RESULT:
Thus, the program to reverse a number by using PL/SQL has been executed successfully.
Page | 89