0% found this document useful (0 votes)
5 views

DBMS Unit 4

The document is a record notebook for the Database Management System Laboratory for the academic year 2024-2025. It includes a bonafide certificate, an index of experiments, and detailed procedures for various SQL commands and database operations, such as creating tables, adding constraints, and executing DML commands. The document serves as a practical guide for students to perform database-related tasks and understand SQL syntax and integrity constraints.

Uploaded by

rameshkumar.m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DBMS Unit 4

The document is a record notebook for the Database Management System Laboratory for the academic year 2024-2025. It includes a bonafide certificate, an index of experiments, and detailed procedures for various SQL commands and database operations, such as creating tables, adding constraints, and executing DML commands. The document serves as a practical guide for students to perform database-related tasks and understand SQL syntax and integrity constraints.

Uploaded by

rameshkumar.m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

DEPARTMENT OF ADVANCED COMPUTING SCIENCES

RECORD NOTE BOOK 2024 – 2025

244DS1A24PD – Database Management System Laboratory

NAME OF THE STUDENT :

REGISTER NUMBER :

DEPARTMENT :

YEAR :

SEMESTER :
BONAFIDE CERTIFICATE
Name : …………………………………
Reg. No : …………………………………
Branch : …………………………………

Certified that this is the bonafide record of work done by the above
student in the ……………………………………………….............

……………………....... laboratory during the year 2024-2025.

Head of the Department Lab in-Charge

Submitted for the practical examination held on ………………………

Internal Examiner External Examiner


INDEX

EX.
DATE NAME OF THE EXPERIMENT PAGE STAFF SIGN
NO
NO.

Create a database table, add constraints (primary


key, unique, check, Not null), insert rows, update
and delete rows using SQL DDL and DML
1 Commands.

Create a set of tables, add foreign key constraints


2. and incorporate referential integrity.

Query the database tables using different ‘where’


Clause Conditions and also Implement aggregate
3 functions.
Query the database tables and explore sub queries
and simple join operations.
4

Query the database tables and explore natural,


5 equi and outer joins

Write user defined functions and stored


6 procedures in SQL.

Execute complex transactions and realize DCL


and TCL commands.
7
Write SQL Triggers for insert, delete and update
operations in a database table.
8

Create view and index for database tables with a


9 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.
Create a Database Table, Add Constraints (Primary Key, Unique, Check, Not Null),
EXP. NO: 1
Insert Rows, Update and Delete Rows using SQL DDL and DML Commands.
DATE:

Aim:

To create a Database Table, Add Constraints (Primary Key, Unique, Check, Not Null), Insert Rows, Update
and Delete Rows using SQL DDL and DML Commands.

Procedure:

DATA DEFINITION LANGUAGE (DDL) COMMANDS


1. DDL COMMAND
- It is used to communicate with database. DDL is used to:
✓ Create an object
✓ Alter the structure of an object
✓ To drop the object created.
2. The commands used are: Create, Alter, Drop, Truncate

3. INTEGRITY CONSTRAINT
An integrity constraint is a mechanism used by oracle to prevent invalid data entry into the table. It has
enforcing the rules for the columns in a table. The types of the integrity constraints are:
(a) Domain Integrity (b) Entity Integrity (c) Referential Integrity
(a) Domain Integrity
This constraint sets a range and any violations that take place will prevent the user from performing the
manipulation that caused the breach. It includes:
Not Null constraint:
While creating tables, by default the rows can have null value the enforcement of not null constraint in a table
ensure that the table contains values.
Principle of null values:
✓ Setting null value is appropriate when the actual value is unknown, or when a value would not be
meaningful.
✓ A null value is not equivalent to a value of zero.
✓ A null value will always evaluate to null in any expression.
✓ When a column name is defined as not null, that column becomes a mandatory i.e., the user has to
enter data into it.
✓ Not null Integrity constraint cannot be defined using the alter table command when the table contain
rows.
Check Constraint
Check constraint can be defined to allow only a particular range of values. When the manipulation violates this
constraint, the record will be rejected. Check condition cannot contain sub queries.

b) Entity Integrity
Maintains uniqueness in a record. An entity represents a table and each row of a table represents an instance of
that entity. To identify each row in a table uniquely we need to use this constraint. There are 2 entity
constraints:

Unique key constraint


It is used to ensure that information in the column for each record is unique, as with telephone or drivers
license numbers. It prevents the duplication of value with rows of a specified column in a set of column. A
column defined with the constraint can allow null value.
If unique key constraint is defined in more than one column i.e., combination of column cannot be specified.
Maximum combination of columns that a composite unique key can contain is 16.

Primary Key Constraint


A primary key avoids duplication of rows and does not allow null values. It can be defined on one or more
columns in a table and is used to uniquely identify each row in a table. These values should never be changed
and should never be null.
A table should have only one primary key. If a primary key constraint is assigned to more than one column or
combination of column is said to be composite primary key, which can contain 16 columns.

c) Referential Integrity
It enforces relationship between tables. To establish parent-child relationship between 2 tables having a
common column definition, we make use of this constraint. To implement this, we should define the column in
the parent table as primary key and same column in the child table as foreign key referring to the
corresponding parent entry.

Foreign key
A column or combination of column included in the definition of referential integrity, which would refer to a
referenced key.

Referenced key
It is a unique or primary key upon which is defined on a column belonging to the parent table.
SQL Commands:

Create Table
➢ It is used to create a table
Syntax:
Create table tablename (column_name1 data_type constraints, column_name2 data_type constraints ...)
Example:
Create table Emp ( EmpNo number(5), EName VarChar(15), Job Char(10) constraint unique, DeptNo
number(3) CONSTRAINT FKey2 REFERENCES DEPT(DeptNo));
Create table stud (sname varchar2(20) not null, rollno number(10) not null, dob date not null);

Rules
1. Oracle reserved words cannot be used.
2. Underscore, numerals, letters are allowed but not blank space.
3. Maximum length for the table name is 30 characters.
4. Different tables should not have same name.
5. We should specify a unique column name.
6. We should specify proper data type along with width.
7. We can include "not null" condition when needed. By default it is,null".

Alter Table
Alter command is used to
1. Add a new column.
2. Modify the existing column definition.
3. To include or drop integrity constraint.
Syntax:
Alter table tablename add/modify (attribute datatype(size));
Example:
1. Alter table emp add (phone_no char (20));
2. Alter table emp modify(phone_no number (10));
3. ALTER TABLE EMP ADD CONSTRAINT Pkey1 PRIMARY KEY (EmpNo);
Drop Table
It will delete the table structure provided the table should be empty.
Example: drop table prog20;
Here prog20 is table name

Truncate Table
If there is no further use of records stored in a table and the structure has to be retained then the records alone
can be deleted.
Syntax:
TRUNCATE TABLE <TABLE NAME>;
Example: Truncate table stud;

DESC
This is used to view the structure of the table.
Example: desc emp;
Name Null? Type
-------------------------------------------
EmpNo NOT NULL number(5)
ENameVarChar(15)
Job NOT NULL Char(10)
DeptNo NOT NULL number(3)
PHONE NO number (10)

DOMAIN INTEGRITY
Example:
Create table cust(custid number(6) not null, name char(10));
Alter table cust modify (name not null);

CHECK CONSTRAINT
Example
Create table student (regno number (6), mark number (3) constraint b check (mark>=0 and mark <=100));
Alter table student add constraint b2 check (length(regno<=4));
ENTITY INTEGRITY
(a) Unique key constraint
Example
Create table cust(custid number(6) constraint uni unique, name char(10));
Alter table cust add(constraint c unique(custid));

(b) Primary Key Constraint


Example
Create table stud(regno number(6) constraint primary key, name char(20));

Queries:
Q1. Create a table called EMP with the following structure.
Name Type
---------------- --------------------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
JOB VARCHAR2(10)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)
Allow NULL for all columns except ename and job.

Solution:
1. Understand create table syntax.
2. Use the create table syntax to create the said tables.
3. Create primary key constraint for each table as understand from logical table structure.
Ans.
SQL> create table emp(empno number(6),ename varchar2(20)not null job varchar2(10) not null, deptno
number(3), sal number(7,2));
Table created.

Q2. Add a column experience to the emp table. experience numeric null allowed.
Solution:
1. Learn alter table syntax.
2. Define the new column and its data type.
3. Use the alter table syntax.
Ans.
SQL> alter table emp add(experience number(2));
Table altered.
Q3. Modify the column width of the job field of emp table.
Solution:
1. Use the alter table syntax.
2. Modify the column width and its data type.
Ans.
SQL> alter table emp modify(job varchar2(12));
Table altered.
SQL> alter table emp modify(job varchar(13));
Table altered.

Q4. Create dept table with the following structure.


Name Type
------------------ -------------------------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(10)
LOC VARCHAR2(10)
Deptno as the primarykey
Solution:
1. Understand create table syntax.
2. Decide the name of the table.
3. Decide the name of each column and its data type.
4. Use the create table syntax to create the said tables.
5. Create primary key constraint for each table as understand from logical table structure.
Ans.
SQL> create table dept(deptno number(2) primary key.dname varchar2(10),loc varchar2(10));
Table created.

Q5. Create the empl table with ename and empno, add constraints to check the empno value while
entering (i.e) empno> 100.
Solution:
1. Learn alter table syntax.
2. Define the new constraint [columns name type]
3. Use the alter table syntax for adding constraints.
Ans.
SQL> create table empl(ename varchar2(10),empno number(6) constraint check(empno>100));
Table created.
Q6. Drop a column experience to the emp table.
Solution:
1. Learn alter table syntax. Use the alter table syntax to drop the column.
Ans.
SQL> alter table emp drop column experience;
Table altered.

Q7. Truncate the emp table and drop the dept table
Solution:
1. Learn drop, truncate table syntax.
Ans.
SQL> truncate table emp;
Table truncated.
SQL> drop table dept;
Table dropped.

DATA MANIPULATION LANGUAGE (DML) COMMANDS

1.DML COMMAND
DML commands are the most frequently used SQL commands and is used to query and manipulate the
existing database objects. Some of the commands are Insert, Select, Update, Delete
2.Insert Command
This is used to add one or more rows to a table. The values are separated by commas and the data types char
and date are enclosed in apostrophes. The values must be entered in the same order as they are defined.
3.Select Commands
It is used to retrieve information from the table. it is generally referred to as querying the table. We can either
display all columns in a table or only specify column from the table.
4.Update Command
It is used to alter the column values in a table. A single column may be updated or more than one column
could be updated.
5.Delete command
After inserting row in a table we can also delete them if required. The delete command consists of a from
clause followed by an optional where clause.
(c) SQL Commands
INSERT COMMAND
Inserting a single row into a table
Syntax: insert into <table name> values (value list)
Example: insert into s values(“S3","sup3","blore",10)

Inserting more than one record using a single insert commands


Syntax: insert into <table name> values (&coll, &col2, ....)
Example: insert into stud values(&reg, &name, &percentage);

Skipping the fields while inserting


insert into <tablename(coln names to which datas to be inserted)> values (list of values);
Other way is to give null while passing the values.

SELECT COMMANDS
Selects all rows from the table
Syntax: Select * from tablename;
Example: Select * from IT;

The retrieval of specific columns from a table


It retrieves the specified columns from the table
Syntax: Select column_namel,.....,column_namen from table name;
Example: Select empno, empname from emp;

Elimination of duplicates from the select clause


It prevents retrieving the duplicated values. Distinct keyword is to be used.
Syntax: Select DISTINCT coll, col2 from table name;
Example: Select DISTINCT job from emp;

Select command with where clause


To select specific rows from a table we include “where" clause in the select command. It can appear only after
the "from" clause.
Syntax: Select column_namel, .....,column_namen from table name where condition;
Example: Select empno, empname from emp where sal>4000;
Select command with order by clause
Syntax: Select column_namel, .....,column_namen from table name where conditionorder by colmnname;
Example: Select empno, empname from emp order by empno;

Select command to create a table


Syntax: create table tablename as select * from existing_tablename;
Example: create table empl as select * from emp;

Select command to insert records:


Syntax: insert into tablename (select columns from existing_tablename);
Example: insert into empl (select * from emp);

UPDATE COMMAND
Syntax: update tablename set field=values where condition;
Example: Update emp set sal = 10000 where empno =135;

DELETE COMMAND
Syntax: Delete from table where conditions;
Example: delete from emp where empno =135;

Queries
Q1. Insert a single record into dept table.
Solution:
1. Decide the data to add in dept.
2. Add to dept one row at a time using the insert into syntax.
Ans.
SQL> insert into dept values (1,”TT”, “Tholudur");
1 row created.

Q2. Insert more than a record into emp table using a single insert command.
Ans.
SQL> insert into emp values(&empno,'&ename','&job',&deptno,&sal);
Enter value for empno: 1
Enter value for ename:Mathi
Enter value for job: AP
Enter value for deptno: 1
Enter value for sal: 10000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(1,'Mathi','AP',1,10000)
1 row created.
SQL> /
Enter value for empno: 2
Enter value for ename: Arjun
Enter value for job: ASP
Enter value for deptno: 2
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(2, 'Arjun','ASP',2,12000)
1 row created.
SQL> /
Enter value for empno: 3
Enter value for ename: Gugan
Enter value for job: ASP
Enter value for deptno: 1
Enter value for sal: 12000
old 1: insert into emp values(&empno,'&ename','&job',&deptno,&sal)
new 1: insert into emp values(3,'Gugan','ASP',1,12000)
1 row created.

Q3. Update the emp table to set the salary of all employees to Rs15000/- who are working as ASP
Ans.
SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL


-------------------------------------------------------------------
1. Mathi AP 1 10000
2. Arjun ASP 2 12000
3. Gugan ASP 1 12000

SQL> update emp set sal=15000 where job=’ASP’;


2 rows updated.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
--------------------------------------------------------------------------
1. Mathi AP 1 10000
2. Arjun ASP 2 15000
3. Gugan ASP 1 15000

Q4.Create a pseudo table employee with the same structure as the table emp and insert rows into the
table using select clauses.
Ans.
SQL> create table employee as select * from emp;
Table created.
SQL> desc employee;
Name Null? Type
------------------------------------------------------------------------
EMPNO NUMBER(6)
ENAME NOT NULL VARCHAR2(20)
JOB NOT NULL VARCHAR2(13)
DEPTNO NUMBER(3)
SAL NUMBER(7,2)

Q5. Select employee name, job from the emp table


Ans.
SQL> select ename, job from emp;
ENAME JOB
--------------------------------------------------------
Mathi AP
Arjun ASP
Gugan ASP
Karthik Prof
Akalya AP
Suresh Lect
6 rows selected.
Q6: Delete only those who are working as lecturer
Ans.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
------------------------------------------------------------
1. Mathi AP 1 10000
2. Arjun ASP 2 15000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000
5. Akalya AP 1 10000
6. Suresh Lect 1 8000
6 rows selected.

SQL> delete from emp where job='lect';


1 row deleted.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
------------------------------------------------------------
1. Mathi AP 1 10000
2. Arjun ASP 2 15000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000
5. Akalya AP 1 10000

Q7. List the records in the emp table orderby salary in ascending order.
Ans.
SQL> select * from emp order by sal;
EMPNO ENAME JOB DEPTNO SAL
------------------------------------------------------------
1. Mathi AP 1 10000
5. Akalya AP 1 10000
2. Arjun AP 2 15000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000
Q8. List the records in the emp table order by salary in descending order.
Ans.
SQL> select * from emp order by sal desc;
EMPNO ENAME JOB DEPTNO SAL
----------------------------------------------------------------
4 Karthik Prof 2 30000
2 Arjun ASP 2 15000
3 Gugan ASP 1 15000
1 Mathi AP 1 10000
5 Akalya AP 1 10000

Q9. Display only those employees whose deptno is 30.


Solution:
1. Use SELECT FROM WHERE syntax.
Ans.
SQL> select * from emp where deptno=1;
EMPNO ENAME JOB DEPTNO SAL
----------------------------------------------------------------
1 Mathi AP 1 10000
3 Gugan ASP 1 15000
5 Akalya AP 1 10000

Q10. Display deptno from the table employee avoiding the duplicated values.
Solution:
1. Use SELECT FROM syntax..
2. Select should include distinct clause for the deptno.
Ans.
SQL> select distinct deptno from emp;
DEPTNO
-------------
1
2
Executed SQL Commands using MySQL:

CREATE DATABASE

ENTITY INTEGRITY

a). Unique key consntraint.


Example:-

Create table cust(custid number(6) constraint uni unique, name char(10));

Alter table cust add(constraint c unique (custid));

b). Primary key constraint.

SQL Queries :-
1. Create a table called EMP with the following structure.
2. Add a column experience to the emp table, experience numeric null allowed.

3. Modify the column width of the job field of emp table.


SQL> alter table emp modify (job vrchar2(12));
Table altered.
SQL> alter table emp modify(job varchar(13));
Table altered.

4. Create dept table with the following structure.

5. Create the emp1 table with ename and empno, add constraints to check the empno value entering (i.e)
empno>100.
6.Drop a column experience to the emp table.

7. Truncate the emp table and drop the dept table.

INSERT COMMAND
SQL Command.
1. Insert a single record into dept table.
2. Insert more than a record into emp table using a single insert command.

3.Update the emp table to set the salary of all employees to Rs 15000/- who are working as ASP.

4.Create a pseudo table employee with the same structure as the table emp and insert rows into the table
using select clauses.
5. Select employee name, job from the emp table.

6. Delete only those who are working as lecturer.

7. List the records in the emp table orderly salary in ascending order.
8. List the records in the emp table order by salary in descending order.

9. Display only those employee whose deptno is 30.

10. Display deptno from the table employee avoiding the duplicated values.

Result:
Thus the above SQL queries using DDL and DML Commands executed successfully.
EXP. NO: 2
Create a set of tables, add foreign key constraints and incorporate referential
DATE:
integrity.

Aim:
To study the various constraints available in the SQL query language.

Procedure:
DOMAIN INTEGRITY CONSTRAINTS
NOT NULL CONSTRAINT
SQL> create table empl (ename varchar2(30) not null, eid varchar2(20) not null);
Table created.
SQL> insert into empl values ('abcde',11);
1 row created.
SQL> insert into empl values ('fghij',12);
1 row created.
SQL> insert into empl values (‘klmno',null);
insert into empl values ('klmno',null)
*
ERROR at line 1:
ORA-01400: cannot insert NULL into ("ITA". "EMPL". "EID")
SQL> select * from empl;
ENAME EID
-------------- ----------
abcde 11
fghij 12
12

CHECK AS A COLUMN CONSTRAINT


SQL> create table depts (dname varchar2(30) not null, did number(20) not null check (did<10000));
Table created.
SQL> insert into depts values ('sales',9876);
1 row created.
SQL> insert into depts values (‘marketing’,5432);
1 row created.
SQL> insert into depts values ('accounts',789645);
insert into depts values ('accounts,789645)
*
ERROR at line 1:
ORA-02290: check constraint (ITA.SYS_C003179) violated
SQL> select * from depts;
DNAME DID
-------------- -----------
sales 9876
marketing 5432

CHECK AS A TABLE CONSTRAINT


SQL> create table airports (aname varchar2(30) not null, aid number(20) not null, acity varchar2(30) check(
acity in ('chennai', 'hyderabad', 'bangalore')));
Table created.
SQL> insert into airports values( 'abcde', 100,'chennai');
1 row created.
SQL> insert into airports values( 'fghij', 101, ‘hyderabad’);
1 row created.
SQL> insert into airports values('klmno', 102, 'bangalore');
1 row created.
SQL> insert into airports values( 'pqrst', 103,'mumbai');
insert into airports values( 'pqrst', 103, 'mumbai') *
ERROR at line 1:
ORA-02290: check constraint (ITA.SYS_C003187) violated

SQL> select * from airports;

ANAME AID ACITY


------------- --------- ---------------
abcde 100 chennai
fghij 101 hyderabad
klmno 102 bangalore
ENTITY INTEGRITY CONSTRAINTS
UNIQUE AS A COLUMN CONSTRAINT

SQL> create table book (bname varchar2(30) not null, bid number(20) not null unique);
Table created.
SQL> insert into book values ('fairy tales', 1000);
1 row created.
SQL> insert into book values (‘bedtime stories',1001);
1 row created.
SQL> insert into book values ('comics', 1001);
insert into book values ('comics', 1001)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003130) violated
SQL> select * from book;
BNAME BID
--------------- ----------------
fairy tales 1000
bedtime stories 1001

UNIQUE AS A TABLE CONSTRAINT


SQL> create table orders(oname varchar2(30) not null, oid number(20) not null, unique(oname,oid));
Table created.
SQL> insert into orders values ('chair', 2005);
1 row created.
SQL> insert into orders values ('table', 2006);
1 row created.
SQL> insert into orders values ('chair',2007);
1 row created.
SQL> insert into orders values ('chair', 2005);
insert into orders values ('chair', 2005)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003152) violated
SQL> select * from orders;

ONAME OID
----------------- -------------
chair 2005
table 2006
chair 2007

PRIMARY KEY AS A COLUMN CONSTRAINT

SQL> create table custo ( cname varchar2(30) not null, cid number(20) not null primary key);
Table created.
SQL> insert into custo values ('jones', 506);
1 row created.
SQL> insert into custo values (‘hayden',508);
1 row created.
SQL> insert into custo values ('ricky',506);
insert into custo values ('ricky',506)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003165) violated

SQL> select * from custo;

CNAME CID
--------------- ----------
jones 506
hayden 508

PRIMARY KEY AS A TABLE CONSTRAINT

SQL> create table branches( bname varchar2(30) not null, bid number(20) not null,primary key(bname,bid));
Table created.
SQL> insert into branches values ('anna nagar', 1005);
1 row created.
SQL> insert into branches values ('adyar',1006);
1 row created.
SQL> insert into branches values ('anna nagar',1007);
1 row created.
SQL> insert into branches values ('anna nagar', 1005);
insert into branches values ('anna nagar', 1005)
*
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003173) violated
SQL> select * from branches;
BNAME BID
-------------- ----------
anna nagar 1005
adyar 1006
anna nagar 1007

REFERENTIAL INTEGRITY CONSTRAINTS


TO CREATE 'DEPTS' TABLE
SQL> create table depts(city varchar2(20), dno number(5) primary key);
Table created.
SQL> insert into depts values('chennai', 11);
1 row created.
SQL> insert into depts values(‘hyderabad’, 22);
1 row created.

TO CREATE 'SEMP' TABLE


SQL> create table semp(ename varchar2(20), dno number(5) references depts(dno));
Table created.
SQL> insert into semp values('x', 11);
1 row created.
SQL> insert into semp values(‘y’,22);
1 row created.
SQL> select * from semp;
ENAME DNO
------------ -----------
x 11
Y 22

ALTER TABLE
SQL> alter table semp add(address varchar2(20));
Table altered..
SQL> update semp set address='10 gandhi road' where dno=11;
1 row updated.
SQL> update semp set address='12 m.g. road' where dno=22;
1 row updated.
SQL > select * from semp;
ENAME DNO ADDRESS
x 11 10 gandhi road
y 22 12 m.g. road
SQL> select city, ename from depts, s2emp where depts.dno = s2emp.dno;
CITY ENAME
------------- ------------
Chennai x
Hyderabad y

Executed SQL Commands using MySQL:

DOMAIN INTEGRITY COMNSTRIANTS

NOT NULL CONSTRAINT


CHECK AS A COLUMN CONSNTRAINT

CHECK AS A TABLE CONSNTRAINT

ENTITY INTEGRITY CONSTRAINT


UNIQUE AS A COLUMN CONSTRAINT
UNIQUE AS A TABLE CONSTRAINT

PRIMARY KEY AS COLUMN CONSTRIANT

PRIMARY KEY AS TABLE CONSTRIANT


REFERENTIAL INTEGRITY CONSTRAINT
TO CREATE ‘DEPTS’ TABLE

TO CREATE ‘SEMP’ TABLE

ALTER TABLE

Result:
Thus the various constraints were implemented and the tables were created using the respective constraints.
EXP. NO: 3 Query the Database Tables using Different 'Where' Clause Conditions and also
Implement Aggregate Functions
DATE:

Aim:
To query the database tables using different 'Where' clause conditions and also implement aggregate functions.

Procedure:
AGGREGATE FUNCTIONS

AVG (N): It returns average value of n ignoring null values.


SQL> select avg(spocket) result from studs;
RESULT
-----------
400

MIN (EXPR): It returns minimum value of the expression.


SQL> select min(spocket) result from studs;
RESULT
-----------
100

COUNT (EXPR): It returns the number of rows where expression is not null.
SQL> select count(spocket) result from studs;
RESULT
-----------
4
SQL> select count(spocket) result from studs where sarea=’anna nagar’;
RESULT
-----------
2

COUNT(*): It returns the number of rows in the table including the duplicates and those with null values.
SQL> select count(*) result from studs;
RESULT
-----------
4
MAX (EXPR): It returns maximum value of the expression.
SQL> select max(spo ket) result from studs;
RESULT
-----------
750
SUM(N): It returns sum of values of n.
SQL> select sum(spocket) result from studs;
RESULT
-----------
1600

GROUP BY CLAUSE
The group by clause is another section of the select statement. This optional class tells oracle to group rows
based on distinct values that exists for specified columns.
HAVING CLAUSE
The having clause can be used in conjunction with the group by clause. Having imposes a condition on the
group by clause, which further filters the groups created by the group by clause.

NUMERIC FUNCTIONS
SQL> select abs(-20) result from dual;
RESULT
-----------
20

SQL> select power (2,10) result from dual;


RESULT
-----------
1024

SQL> select round(15.359,2) result from dual;


RESULT
-----------
15.36

SQL> select sqrt (36) result from dual;


RESULT
-----------
6
SPECIAL OPERATORS
In/not in - used to select a equi from a specific set of values
Any - used to compare with a specific set of values
Between/not between-used to find between the ranges
Like/not like-used to do the pattern matching

Queries
Q1. Display all the details of the records whose employee name starts with _A.
Solution:
1. Use SELECT FROM WHERE syntax.
2. Select should include all in the given format.
3. From should include employee
4. where should include condition on empname like “A%",
Ans.
SQL> select * from emp where ename like 'A%';
EMPNO ENAME JOB DEPTNO SAL
----------------------------------------------------------------
2 Arjun ASP 2 15000
5 Akalya AP 1 10000

Q2. Display all the details of the records whose employee name does not starts with _A.
Ans.
SQL> select * from emp where ename not like 'A%';
EMPNO ENAME JOB DEPTNO SAL
----------------------------------------------------------------
1. Mathi AP 1 10000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000

Q3. Display the rows whose salary ranges from 15000 to 30000.
Ans.
SQL> select * from emp where sal between 15000 and 30000;
EMPNO ENAME JOB DEPTNO SAL
----------------------------------------------------------------
2. Arjun ASP 2 15000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000
Q4. Calculate the total and average salary amount of the emp table.
Ans.
SQL> select sum(sal), avg(sal) from emp;
SUM(SAL) AVG(SAL)
-------------- ------------------
80000 16000

Q5: Count the total records in the emp table.


Ans.
SQL>select * from emp;

EMPNO ENAME JOB DEPTNO SAL


----------------------------------------------------------------
1. Mathi ASP 1 10000
2. Arjun ASP 2 15000
3. Gugan ASP 1 15000
4. Karthik Prof 2 30000
5. Akalys AP 1 10000

SQL> select count(*) from emp;


COUNT(*)
---------------
5

Q6. Determine the max and min salary and rename the column as max_salary and min_salary.
Solution:
1. Use the MIN & MAX aggregate function in select clause.
2. Rename the column as min_sal&max_sal.
Ans.
SQL> select max(sal) as max_salary, min(sal) as min_salary from emp;

MAX_SALARY MIN SALARY


-------------------- ------------------
30000 10000
Q7. Display the month between-1-jun-10land 1-aug-10 in full.
Ans.
SQL>Select month between (“1-jun-2010","1-aug-2010") from dual;

Q8. Display the last day of that month in-05-Oct-091.


Ans.
SQL> Select last day ('1-jun-2009’) from dual;
LAST_DAY(
-----------------
30-JUN-09

Q9. Find how many job titles are available in employee table.
Solution:
1. Use select from clause.
2. Use count function to get the result.
Ans.
SQL> select count(job) from emp;
COUNT(JOB)
------------------
4
SQL> select count(distinct job) from emp;
COUNT(DISTINCTJOB)
-------------------------------
2
Q10. What is the difference between maximum and minimum salaries of employees in the organization?
Solution:
1. Use select from clause.
2. Use function max(),min() and find the difference between them to get the result.
Ans.
SQL> select max(sal), min(sal) from emp;
MAX(SAL) MIN(SAL)
-------------- -----------------
20000 10000
Executed SQL Commands using MySQL:

CREATE THE TABLE

SQL commands:
1. Display all the details of the records whose employee name starts with _A’.

2. Display all the details of the records whose employee name does not starts with _A’.

3. Display the rows whose salary ranges from 15000 to 30000.


4. Calculate the total and average salary amount of the emp table.

5. Count the total records in the emp table.

6. Determine the max and min salary and rename the column as max_salary and min_salary.

7. Display the month between –1-jun-10|| and 1-aug-10 in full.

8. Display the last day of that month in –05-oct-09||.

Result:
Thus the above SQL commands using different ‘where’ clause conditions and also implement aggregate
functions executed successfully.
EXP. NO: 4
Query the Database Tables and Explore Sub Queries and Simple Join Operations
DATE:

Aim:
To write the SQL commands to query the database tables and explore sub queries and simple join operations.

Procedure:
1.Nested Queries: Nesting of queries one within another is known as a nested queries.
Sub queries: The query within another is known as a sub query. A statement containing sub query is called
parent statement. The rows returned by sub query are used by the parent statement.

2.Types
1. Sub queries that return several values
Sub queries can also return more than one value. Such results should be made use along with the operators in
and any.
2. Multiple queries
Here more than one sub query is used. These multiple sub queries are combined by means of "and" & "or"
keywords.
3. Correlated sub query
A sub query is evaluated once for the entire parent statement whereas a correlated sub query is evaluated once
per row processed by the parent statement.

3.Relating Data through Join Concept


The purpose of a join concept is to combine data spread across tables. A join is actually performed by the
"where" clause which combines specified rows of tables.
Syntax:
select columns from tablel, table2 where logical expression;
Types of Joins:
1.Simple Join 2.Self Join 3.Outer Join 4.Inner Join

4.Simple Join
(a) Equi-join: A join, which is based on equalities, is called equi- join.
(b) Non Equi-join: It specifies the relationship between Table Aliases
Table aliases are used to make multiple table queries shorted and more readable. We give an alias name to the
table in the "from" clause and use it instead of the name throughout the query
5.Self join: Joining of a table to itself is known as self-join. It joins one row in a table to another. It can
compare each row of the table to itself and also with other rows of the same table.

6.Outer Join: It extends the result of a simple join. An outer join returns all the rows returned by simple join
as well as those rows from one table that do not match any row from the table. The symbol (+) represents outer
join.
Inner join: Inner join returns the matching rows from the tables that are being joined.

SQL Commands:

Nested Queries
Example: select ename, eno, address where salary>(select salary from employee whereename = "jones");

1. Subqueries that return several values


Example: select ename, eno from employee where salary <any (select salary from employee where deptno
=”10");
2. Correlated subquery
Example: select * from emp x where x.salary> (select avg(salary) from emp where deptno = x.deptno);

Simple Join
(a) Equi-join
Example: select * from item, cust where item.id = cust.id;
(b) Non Equi-join
Example: select * from item, cust where item.id<cust.id;

Self join
Example: select * from emp x, emp y where x.salary>= (select avg(salary) from x.emp where x.deptno =
y.deptno);

Outer Join
Example: select ename, job, dname from emp, dept where emp.deptno (+) = dept.deptno;
Queries
Q1. Display all employee names and salary whose salary is greater than minimum salary of the
company and job title starts with M.
Solution:
1. Use select from clause.
2. Use like operator to match job and in select clause to get the result.
Ans.
SQL> select ename, sal from emp where sal>(select min(sal) from emp where job like 'A%');
ENAME SAL
---------------- ---------
Arjun 12000
Gugan 20000
Karthik 15000

Q2. Issue a query to find all the employees who work in the same job as Arjun.
Ans.
SQL> select * from emp;
EMPNO ENAME JOB DEPTNO SAL
-----------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

SQL> select ename from emp where job = (select job from emp where ename='Arjun');
ENAME
-------------
Arjun
Gugan

Q3. Issue a query to display information about employees who earn more than any employee in dept 1.
Ans.
SQL> select * from emp where sal>(select max(sal) from emp where empno=1);
EMPNO ENAME JOB DEPTNO SAL
-----------------------------------------------------------------------------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000
JOINS
Tables used
SQL> select * from emp;
----------------------------------------------------------------- ---------
EMPNO ENAME JOB DEPTNO SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

SQL> select * from dept;

DEPTNO DNAME LOC


-----------------------------------------------------------
1 ACCOUNTING NEWYORK
2 RESEARCH DALLAS
3 SALES CHICAGO
4 OPERATIONS BOSTON

EQUI-JOIN
Q4. Display the employee details, departments that the departments are same in both the emp and dept.
Solution:
1. Use select from clause.
2. Use equi join in select clause to get the result.
Ans.
SQL> select * from emp, dept where emp.deptno = dept.deptno;

EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC


-----------------------------------------------------------------------------------------------------------------------------------
1 Mathi AP 1 10000 1 ACCOUNTING NEWYORK
2 Arjun ASP 2 12000 2 RESEARCH DALLAS
3 Gugan ASP 2 20000 2 RESEARCH DALLAS
4 Karthik AP 1 15000 4 OPERATIONS BOSTON
NON-EQUIJOIN
Q5. Display the employee details, departments that the departments are not same in both the emp and
dept.
Solution:
1. Use select from clause.
2. Use non equi join in select clause to get the result.
Ans.
SQL> select * from emp,dept where emp.deptno!=dept.deptno;

EMPNO ENAME JOB DEPTNO SAL DEPTNO DNAME LOC


-----------------------------------------------------------------------------------------------------------------------------------
2 Arjun ASP 2 12000 1 ACCOUNTING NEWYORK
3 Gugan ASP 2 20000 1 ACCOUNTING NEWYORK
1 Mathi AP 1 10000 2 RESEARCH DALLAS
4 Karthik AP 1 15000 2 RESEARCH DALLAS
1 Mathi AP 1 10000 3 SALES CHICAGO
2 Arjun ASP 2 12000 3 SALES CHICAGO
3 Gugan ASP 2 20000 3 SALES CHICAGO
4 Karthik AP 1 15000 3 SALES CHICAGO
1 Mathi AP 1 10000 4 OPERATIONS BOSTON
2 Arjun ASP 2 12000 4 OPERATIONS BOSTON
3 Gugan ASP 2 20000 4 OPERATIONS BOSTON
4 Karthik AP 1 15000 4 OPERATIONS BOSTON

12 rows selected.
Executed SQL Commands using MySQL:
SQL Queries:-
1. Display all employee names and salary whose salary is greater than minimum salary of the company
and job title starts with _M’.

2.Issue a query to find all the employee who work in the same job as arjun.

3. Issue a query to display information about employee who earn more than any employee in dept 1.
JOIN
TABLE USED

EQUI – JOIN
4. Display the employee details, departments that the departments are same in both the emps and dept

NON - EQUIJOIN
5. Display the employee details,department that the department are not same in both the emps and dept.

Result:
Thus the above SQL commands for query the database tables and explore sub queries and simple join
operations executed successfully.
EXP. NO: 5
Query the Database Tables and Explore Natural, Equi and Outer Joins
DATE:

Aim:

To write the SQL commands to query the database tables and explore Natural, Equi and Outer Joins.

Procedure:

LEFTOUT-JOIN

Tables Used

SQL> select * from stud1;

Regno Name Mark1 Mark2 Result


-----------------------------------------------------------------
101 john 89 80 pass
102 Raja 70 80 pass
103 Sharin 70 90 pass
104 sam 90 95 pass

SQL> select * from stud2;

NAME GRA
----------------------
john s
raj s
sam a
sharin a

Q1. Display the Student name and grade by implementing a left outer join.
Ans.
SQL> select stud1.name,grade from stud1 left outer join stud2 on stud1.name=stud2.name;

NAME GRA
----------------------
john s
raj s
sam a
sharin a
smith null
RIGHTOUTER-JOIN

Q2. Display the Student name, register no, and result by implementing a right outer join.

Ans.

SQL> select stud1.name, regno, result from stud1 right outer join stud2 on stud 1.name = stud2.name;

Name Regno Result


----------------------------------------
john 101 pass
raj 102 pass
sam 103 pass
sharin 104 pass

Rollno Name Markl Mark2 Total


----------------------------------------------------------------
1 sindu 90 95 185
2 arul 90 90 180

FULLOUTER-JOIN

Q3. Display the Student name register no by implementing a full outer join.
Ans.
SQL> select stud1.name, regno from stud1 full outer join stud2 on (stud1.name=stud2.name);

Name Regno
--------------------------
john 101
raj 102
sam 103
sharin 104

SELFJOIN

Q4. Write a query to display their employee names.


Ans.
SQL> select distinct ename from emp x, dept y where x.deptno = y.deptno;

ENAME
------------
Arjun
Gugan
Karthik
Mathi
Q5. Display the details of those who draw the salary greater than the average salary.

Ans.

SQL> select distinct * from emp x where x.sal>= (select avg(sal) from emp);

EMPNO ENAME JOB DEPTNO SAL


--------------------------------------------------------------------------

3 Gugan ASP 2 20000

4 Karthik AP 1 15000

11 Kavitha designer 12 17000

Executed SQL Commands using MySQL:

LEFTOUT – JOIN
TABLES USED
1. Display the Student name and grade by implementing a left outer join.

RIGHTOUTER – JOIN
2. Display the Student name, register no, and result by implementing a right outer join.

Result:
Thus the above SQL commands for query the database tables and explore Natural, Equi and Outer Joins
executed successfully.
EXP. NO: 6
Write user Defined Functions and Stored Procedures in SQL
DATE:

Aim:

To write user Defined Functions and Stored Procedures in SQL.

Procedure:

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., it is 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., it is 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 data type of the function’s return value because every function must return a value, this
clause is required.
PROCEDURES-SYNTAX

create or replace procedure <procedure name> (argument {in,out,inout} datatype)


{is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram body;
exception
exception PL/SQL block;
end;

CREATING THE TABLE 'ITITEMS' AND DISPLAYING THE CONTENTS

SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4));

Table created.

SQL> insert into ititems values(101, 2000, 500, 201);

1 row created.

SQL> insert into ititems values(102, 3000, 1600, 202);

1 row created.

SQL> insert into ititems values(103, 4000, 600, 202);

1 row created.

SQL> select * from ititems;

ITEMID ACTUALPRICE ORDID PRODID


---------------------------------------------------------------
101 2000 500 201
102 3000 1600 202
103 4000 600 202

PROGRAM FOR GENERAL PROCEDURE - SELECTED RECORD'S PRICE IS INCREMENTED


BY 500, EXECUTING THE PROCEDURE CREATED AND DISPLAYING THE UPDATED TABLE

SQL> create procedure itsum(identity number, total number) is price number;


2. null_price exception;
3. begin
4. select actualprice into price from ititems where itemid=identity;
5. if price is null then
6. raise null_price;
7. else
8. update ititems set actualprice=actualprice+total where itemid=identity;
9. end if;
10. exception
11. when null_price then
12. dbms_output.put_line(‘price is null’);
13. end;
14. /

Procedure created.

SQL> exec itsum(101, 500);

PL/SQL procedure successfully completed.

SQL> select * from ititems;

ITEMID ACTUALPRICE ORDID PRODID


---------------------------------------------------------------
101 2500 500 201
102 3000 1600 202
103 4000 600 202

PROCEDURE FOR 'IN' PARAMETER - CREATION, EXECUTION

SQL> set serveroutput on;

SQL> create procedure yyy (a IN number) is price number;


2 begin
3 select actualprice into price from ititems where itemid=a;
4 dbms_output.put_line('Actual price is ' || price);
5 if price is null then
6 dbms_output.put_line('price is null’);
7 end if;
8 end;
9/

Procedure created.

SQL> exec yyy(103);

Actual price is 4000

PL/SQL procedure successfully completed.


PROCEDURE FOR 'OUT' PARAMETER - CREATION, EXECUTION

SQL> set serveroutput on;

SQL> create procedure zzz (a in number, b out number) is identity number;


2. begin
3. select ordid into identity from ititems where itemid=a;
4. if identity<1000 then
5. b:=100;
6. end if;
7. end;
8. /

Procedure created.

SQL> declare
2. a number;
3. b number;
4. begin
5. zzz(101,b);
6. dbms_output.put_line(‘The value of b is ‘|| b);
7. end;
8. /

The value of b is 100

PL/SQL procedure successfully completed.

PROCEDURE FOR 'INOUT' PARAMETER - CREATION, EXECUTION

SQL> create procedure itit (a inout number) is


2. begin
3. a:=a+1;
4. end;
5. /

Procedure created.

SQL> declare
2. a number:=7;
3. begin
4. itit(a);
5. dbms_output.put_line(‘The updated value is '||a);
6. end;
7. /
FUNCTIONS

DATE FUNCTION

1. Add_month

This function returns a date after adding a specified date with specified number of months.

Syntax: Add_months(d,n); where d-date n-number of months

Example: Select add_months(sysdate,2) from dual;

2. last day

It displays the last date of that month.

Syntax: last day (d); where d-date

Example: Select last_day (“1-jun-2009") from dual;

3. Months between

It gives the difference in number of months between dl & d2.

Syntax: month_between (d1,d2); where d1 & d2 -dates

Example: Select month_between (“1-jun-2009","1-aug-2009") from dual;

4. next_day

It returns a day followed the specified date.

Syntax: next_day (d,day);

Example: Select next_day (sysdate, "wednesday") from dual;

5. round

This function returns the date, which is rounded to the unit specified by the format model.

Syntax: round (d,[fmt]); where d- date, [fmt] - optional.

By default date will be rounded to the nearest day

Example: Select round (to_date(“1-jun-2009","dd-mm-yy"),"year") from dual;


Select round (“1-jun-2009","year") from dual;
NUMERICAL FUNCTIONS

Command Query Output

Abs(n) Select abs(-15) from dual; 15

Ceil(n) Select ceil(55.67) from dual; 56

Exp(n) Select exp(4) from dual; 54.59

Floor(n) Select floor(100.2) from dual; 100

Power(m,n) Select power(4,2) from dual; 16

Mod(m,n) Select mod(10,3) from dual; 1

Round(m,n) Select round(100.256,2) from dual; 100.26

Trunc(m,n) Select trunc(100.256,2) from dual; 100.23

Sqrt(m,n) Select sqrt(16) from dual; 4

CHARACTER FUNCTIONS

Command Query Output

initcap(char); select initeap("hello") from dual; Hello

lower (char); select lower (“HELLO") from dual; hello

upper (char); select upper (“hello") from dual; HELLO

ltrim (char,[set]); select ltrim (“cseit",”cse") from dual; select it

rtrim (char[set]); rtrim (“cseit",”it") from dual; cse

replace (char,search select replace(“jack and jue”,”j”,”bl”) from black and blue
string, replace string); dual;

substr (char,m,n); select substr (“information", 3, 4) from dual; Form


CONVERSION FUNCTION

1. to_char()

Syntax: to_char(d,[format]);

This function converts date to a value of varchar type in a form specified by date format. If format is neglected
then it converts date to varchar2 in the default date format.

Example: select to_char (sysdate, "dd-mm-yy") from dual;

2. to_date()

Syntax: to_date(d,[format]);

This function converts character to date data format specified in the form character.

Example: select to_date(“aug 15 2009","mm-dd-yy") from dual;

Miscellaneous Functions

1.uid - This function returns the integer value (id) corresponding to the user currently logged in.

Example: select uid from dual;

2. user - This function returns the logins user name.

Example: select user from dual;

3. nyl - The null value function is mainly used in the case where we want to consider null values as zero.

Syntax: nvl(exp1, exp2)

If expl is null, return exp2. If expl is not null, return expl.

Example: select custid, shipdate, nvl(total,0) from order;

4. vsize: It returns the number of bytes in expression.

Example: select vsize(“tech") from dual;


GROUP FUNCTIONS

A group function returns a result based on group of rows.

1. avg - Example: select avg (total) from student;

2. max - Example: select max (percentage1) from student;

3. min - Example: select min (marks1) from student;

4. sum - Example: select sum(price) from product;

COUNT FUNCTION

In order to count the number of rows, count function is used.

1. count(*) - It counts all, inclusive of duplicates and nulls.

Example: select count(*) from student;

2. count(col_name) - It avoids null value.

Example: select count(total) from order;

3. count(distinct col_name) - It avoids the repeated and null values.

Example: select count(distinct ordid) from order;

Executed SQL commands using MySQL:

SQL Queries:-
Creating the table ‘ititems’ and displaying the contents.
PROGRAM FOR GENERAL PROCEDURE – SELCTED RECORD’S PRICE IS INCREMENTED
BY 500, EXECUTING THE PROCEDURE CREATE AND DISPLAYING THE UPDATED TABLE.
mysql > exec itsum(101,500);
2. null_price exception;
3. begin
4. select actualprice into price from ititems where itemid=identity;
5. if price is null then
6. raise null_price;
7. else
8. update ititems set actualprice=actualprice+total where itemid=identity;
9. end if;
10. exception
11. when null_price then
12. dbms_output.put_line(‘price is null’);
13. end;
14./
Procedure created.

PL/SQL procedure successfully completed.


mysql > select * from items;

PROCEDURE FOR “N” PARAMETER – CREATION, EXECUTION


mysql> set serveroutput on;
mysql> create procedure yyy (a IN number) is price number;
2. begin
3. select actualprice into price from ititems where itemid=a;
4. dbms_output-put_line(‘Actual price is’ || price);
5. if price is null then
6. dbms_output.put_line(‘price is null’);
7. end if;
8. end;
9. /
Procedure created.
mysql> exec yyy(103);
Actual price is 4000
PL/SQL procedure successfully completed.
PROCEDURE FOR ‘OUT’ PARAMETER – CREATION
mysql> set serceroutput on;
mysql> create procedure zzz(a in number, b out number) is identity number;
2. begin
3. select ordid into identity from ititems where itemid=a;
4. if identity <1000 then
5. b:=100;
6. end if;
7. end;
8. /
Procedure created.
mysql> declare
2. a number;
3. b number;
4. begin;
5. zzz(101,b);
6. dbms_output.put_line(‘The value of b is’ || b);
7. end;
8. /
The value of b is 1—
PL/SQL procedure successfully completed.

PROCEDURE FOR ‘INPUT’ PARAMETER – CREATION, EXECUTION.


mysql> create procedure itit(a inout number) is
2. begin
3. a:=a+1;
4. end;
5. /
Procedure created.
mysql> declare
2. a number :=7;
3. begin
4. itit(a);
5. dbms_output.put_line(‘The update value is ‘||a);
6. end;
7. /

Result:

Thus the above SQL commands for user Defined Functions and Stored Procedures in SQL executed
successfully.
EXP. NO: 7
Execute Complex Transactions and Realize DCL and TCL Commands
DATE:

Aim:

To write the SQL commands to execute complex transactions and realize DCL and TCL Commands.

Procedure:

Data Control Language (DCL), Transaction Control Language (TCL) Commands

1.DCL COMMAND

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.

2. The privilege commands are namely, Grant and Revoke

3.The various privileges that can be granted or revoked are, Select, Insert, Delete, Update, References,
ExecuteAll

4.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.

5.REVOKE COMMAND: Using this command, the DBA can revoke the granted database privileges from
the user.

6.TCL COMMAND

COMMIT: command is used to save the Records.

ROLL BACK: command is used to undo the Records.

SAVE POINT command is used to undo the Records in a particular transaction

SQL Commands:

DCL Commands

GRANT COMMAND

Grant <database_priv [database_priv…..]> to <user_name> identified by <password> [, password.....];

Grant <object_priv> | All on <object> to <user | public> [ With Grant Option];


REVOKE COMMAND

Revoke <database_priv> from <user [, user ] >;

Revoke <object_priv> on <object> from <user | public >;

<database_priv> -- Specifies the system level privileges to be granted to the users or roles. This includes create
/ alter /delete any object of the system.

<object_priv> -- Specifies the actions such as alter / delete / insert / references / execute / select / update for
tables.

<all> -- Indicates all the privileges.

[ With Grant Option ] - Allows the recipient user to give further grants on the objects.

The privileges can be granted to different users by specifying their names or to all users by using the "Public"
option.

TCL COMMANDS

Syntax:

SAVEPOINT: SAVEPOINT <SAVE POINT NAME>;

ROLLBACK: ROLL BACK <SAVE POINT NAME>;

COMMIT: Commit;

Queries

Tables Used

Consider the following tables namely "DEPARTMENTS" and "EMPLOYEES"

Their schemas are as follows,

Departments (dept_no, dept_name, dept_location);

Employees (emp_id, emp_name, emp_salary);


Q1. Develop a query to grant all privileges of employees table into departments table

Ans.

SQL> Grant all on employees to departments;

Grant succeeded.

Q2. Develop a query to grant some privileges of employees table into departments table

Ans.

SQL> Grant select, update, insert on departments to departments with grant option;

Grant succeeded.

Q3. Develop a query to revoke all privileges of employees table from departments table

Ans.

SQL> Revoke all on employees from departments;

Revoke succeeded.

Q4. Develop a query to revoke some privileges of employees table from departments table

Ans.

SQL> Revoke select, update, insert on departments from departments;

Revoke succeeded.

Q5. Write a query to implement the save point

Ans.

SQL> SAVEPOINT S1;

Savepoint created.

SQL> select * from emp;


EMPNO ENAME JOB DEPTNO SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan AP 1 15000
4 Karthik Prof 2 30000
SQL> INSERT INTO EMP VALUES(5,’Akalya’, ‘AP’,1,10000);

1 row created.

SQL> select * from emp;


EMPNO ENAME JOB DEPTNO SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan AP 1 15000
4 Karthik Prof 2 30000
5 Akalya AP 1 10000

Q6. Write a query to implement the rollback.


Ans.
SQL> rollback s1;

SQL> select * from emp;


EMPNO ENAME JOB DEPTNO SAL
---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 15000
3 Gugan AP 1 15000
4 Karthik Prof 2 30000

SQL> INSERT INTO EMP VALUES(5,'Akalya', 'AP',1,10000);

1 row created.

Q7. Write a query to implement the commit


Ans.
SQL> COMMIT;

Commit complete
Executable SQL Commands using MySQL:
SQL Queries :
Table used

1. DEVELOP A QUERY TO GRANT ALL PRIVILEGES OF EMPLOYEES TABLE INTO


DEPARTMENTS TABLE.
mysql> Grant all on employees to deptments;
Grant succeeded.

2. DEVELOP A QUERY TO GRANT SOME PRIVILEGES OF EMPLOYEES TABLE INTO


DEPARTMENTS TABLE.
mysql> Grant select, update, insert on department to departments with grant option.
Grant succeeded.

3. DEVELO[ A QUERY TO REVOKE ALL PRIVILEGES TO EMPLOYEES TABLE FROM


DEPARTMENT TABLE.
mysql > Revoke all on employees from departments;
Revoke succeeded.

4. DEVELOP A QUERY TO REVOKE SOME PRIVILEGES PF EMPLOYEES TABLE FROM


DEPARTMENTS TABLE.
mysql > Revoke select, update, insert on departments from departments;
Revoke succeeded.

5. WRITE A QUERY TO IMPLEMENT THE SAVE POINT.


6. WRITE A QUERY TO IMPLEMENT THE ROLLBACK.
mysql > rollback s1;
mysql> select * from emp;

7. WRITE A QUERY TO IMPLEMENT THE COMMIT .


mysql> COMMIT;
Commit complete.

Result:

Thus the above SQL commands for complex transactions and realize DCL and TCL Commands executed
successfully.
EXP. NO: 8
Write SQL Triggers for Insert, Delete, and Update Operations in a Database Table
DATE:

Aim:

To write SQL Triggers for Insert, Delete, and Update Operations in a Database Table.

Procedure:

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

Types of Triggers

The various types of triggers are as follows,

➢ Before: It fires the trigger before executing the trigger statement.


➢ After: It fires the trigger after executing the trigger statement.
➢ For each row: It specifies that the trigger fires once per row.
➢ For each statement: This is the default trigger that is invoked. It specifies that the trigger fires once
per statement.
Variables used in Triggers
➢ :new
➢ :old

These two variables retain the new and old values of the column updated in the database. The values in these
variables can be used in the database triggers for data manipulation

TRIGGERS - SYNTAX

create or replace trigger triggername [before/after] {DML statements} on [tablename] [for each row/statement]
begin
--------------------------
--------------------------
--------------------------
exception
end;

USER DEFINED ERROR MESSAGE

The package "raise_application_error" is used to issue the user defined error messages

Syntax: raise_application_error(error number, ‘error message’);

The error number can lie between -20000 and -20999.


The error message should be a character string.

TO CREATE A SIMPLE TRIGGER THAT DOES NOT ALLOW INSERT UPDATE AND DELETE
OPERATIONS ON THE TABLE

SQL> create trigger ittrigg before insert or update or delete on itempls for each row
2. begin
3. raise_application_error(-20010,’You cannot do manipulation’);
4. end;
5. /

Trigger created.

SQL> insert into itempls values(‘aaa’,14,34000);

insert into itempls values(‘aaa’,14,34000)

*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger 'STUDENT.ITTRIGG'
SQL> delete from itempls where ename=’xxx’;

delete from itempls where ename=’xxx’

*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger ‘STUDENT.ITTRIGG’

SQL> update itempls set eid=15 where ename=’yyy’;

update itempls set eid=15 where ename=’yyy’

*
ERROR at line 1:
ORA-20010: You cannot do manipulation
ORA-06512: at "STUDENT.ITTRIGG", line 2
ORA-04088: error during execution of trigger ‘STUDENT.ITTRIGG’

TO DROP THE CREATED TRIGGER

SQL> drop trigger ittrigg;

Trigger dropped.

TO CREATE A TRIGGER THAT RAISES AN USER DEFINED ERROR MESSAGE AND DOES
NOT ALLOW UPDATION AND INSERTION

SQL> create trigger ittriggs before insert or update of salary on itempls for each row
2. declare
3. triggsalitempls.salary%type;
4. begin
5. select salary into triggsal from itempls where eid=12;
6. if(:new.salary>triggsal or :new.salary<triggsal) then
7. raise_application_error(-20100,’Salary has not been changed’);
8. end if;
9. end;
10. /

Trigger created.
SQL> insert into itempls values (‘bbb’,16,45000);

insert into itempls values (‘bbb’,16,45000)

ERROR at line 1:

ORA-04098: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

SQL> update itempls set eid=18 where ename=’zzz’;

update itempls set eid=18 where ename=’zzz’

ERROR at line 1:

ORA-04298: trigger 'STUDENT.ITTRIGGS' is invalid and failed re-validation

Result:

Thus the above SQL Triggers for Insert, Delete, and Update Operations in a Database Table executed
successfully.
EXP. NO: 9
Create view and Index for Database Tables with a large number of Records
DATE:

Aim:

To write SQL commands to create view and index for database tables with a large number of records.

Procedure:

VIEWS

1.Views:

A view is the tailored presentation of data contained in one or more table and can also be said as restricted
view to the data’s in the tables. A view is a "virtual table" or a "stored query" which takes the output of a query
and treats it as a table. The table upon which a view is created is called as base table.

A view is a logical table based on a table or another view. A view contains no data of its own but is like a
window through which data from tables can be viewed or changed. The tables on which a view is based are
called base tables. The view is stored as a SELECT statement in the data dictionary.

2.Advantages of a view:

(a) Additional level of table security.

(b) Hides data complexity.

(c) Simplifies the usage by combining multiple tables into a single table.

(d) Provides data's in different perspective.

3.Types of view:

Horizontal -> enforced by where cause

Vertical -> enforced by selecting the required columns

SQL Commands:

Creating and dropping view:

Syntax

Create [or replace] view <view name> [column alias names] as <query> [with <options> conditions];

Drop view <view name>;


Example:

Create or replace view empview as select * from emp;

Drop view empview;

Queries

Tables Used

SQL> select * from emp;

EMPNO ENAME JOB DEPTNO SAL


---------------------------------------------------------------------------
1 Mathi AP 1 10000
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
4 Karthik AP 1 15000

Q1. The organization wants to display only the details of the employees those who are ASP. (Horizontal
portioning)

Solution:

1. Create a view on emp table named managers

2. Use select from clause to do horizontal portioning

Ans.
SQL> create view empview as select * from emp where job=’ASP’;

View created.

SQL> select * from empview;

EMPNO ENAME JOB DEPTNO SAL


---------------------------------------------------------------------------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
Q2. The organization wants to display only the details like empno, empname, deptno, deptname of the
employees. (Vertical portioning)

Solution:

1. Create a view on emp table named general

2. Use select from clause to do vertical portioning

Ans.

SQL> create view empview1 as select ename, sal from emp;

View created.

Q3. Display all the views generated.

Ans.

SQL> select * from tab;

TNAME TABTYPE CLUSTERID


---------------------------------------------------------------

DEPT TABLE

EMP TABLE

EMPVIEW VIEW

EMPVIEW1 VIEW

Q4. Execute the DML commands on the view created.

Ans.

SQL> select * from empview;

EMPNO ENAME JOB DEPTNO SAL


---------------------------------------------------------------------------
2 Arjun ASP 2 12000
3 Gugan ASP 2 20000
Q5. Drop a view.

Ans.

SQL> drop view empview1;

View dropped.

Indexes

➢ An index can be created in a table to find data more quickly and efficiently.
➢ The users cannot see the indexes; they are just used to speed up searches/queries.
➢ Updating a table with indexes takes more time than updating a table without; because the indexes
also need an update. So we should only create indexes on columns (and tables) that will be frequently
searched against.

Syntax:

Create Index:

CREATE INDEX index_name ON table_name (column_name)

SQL> create table splr(sname varchar(10),sid number(10),scity varchar(10));


Table created.

SQL> insert into splr values(‘hcl’,01,’chennai’);


1 row created.

SQL> insert into splr values(‘dell’,04,’madurai’);


1 row created.

SQL> insert into splr values(‘HP’,02,’kovai’);


1 row created.

SQL> insert into splr values(‘Lenovo’,03, ‘trichy’);


1 row created.

SQL> select * from splr;

SNAME SID SCITY


------------ -------- ----------------
hcl 1 chennai
dell 4 madurai
HP 2 kovai
Lenovo 3 trichy
SQL> create index sp1 on splr(sid);

Index created.

SQL> create index sp2 on splr(sid,scity);

Index created.

Drop Index:

SQL> drop index sp1;

Index dropped.

SQL> drop index sp2;

Index dropped.

Executed SQL Commands using MySQL:

SQL QUERIES
TABLE USED

1. The organization wants to display only the details of the employees those who are ASP.(Horizontal
portioning)
2. The Organization wants to display only the details like empno, empname, deptno, deptname of the
employees.(Vertical portioning)

3. Display all the views generated.

SQL> SELECT * FROM TAB;


TNAME TABTYPE CLUSTERID
---------------------------------------------------------
DEPT TABLE
EMP TABLE
EMPVIEW VIEW
EMPVIEW1 VIEW

4. Execute the DML commands on the view created.

5. Drop a view.
SYNTAX:
CREATE INDEX:
CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN_NAME)

DROP INDEX:
SQL> DROP INDEX SP1;
INDEX DROPPED.
SQL> DROP INDEX SP2;
INDEX DROPPED.

Result:

Thus the above SQL commands for create view and index for database tables with a large number of records
executed successfully.
EXP. NO: 10
Create an XML Database and Validate it using XML Schema
DATE:

Aim:

To create an XML Database and Validate it using XML Schema.

Procedure:

Create and Register an XML schema

Step 1: Create an XML schema

We now need to create an XML schema using the XML Schema Editor in DWB. This section will walk you
through creating a new XML Schema from scratch.
(Note: The example user has already created the XML Schema.)

1. Expand the Data Development Project in the Data Project Explorer. Locate the folder named XML
Schema Documents. Right-click on the XML Schema Documents folder and find New.

2. After you click on New, you see a popup window titled "Create XML Schema." The parent folder is
the name of your data development project. In the File Name textbox, create a name for your XML
Schema document, You can name the XML Schema document any name you choose; however, it
MUST have the .xsd extension.
3. Click Finish, and you should get the screen shown below. Notice that the .xsd file opens up and you see
code. Look at the bottom of the pane for the .xsd file and you should see two tabs, one labeled Source
and the other labeled Graph. You are in Source view, and what you see is the basic XML code
template.
Step 2: Adding XML Elements

You could, if you wanted to, write the code to create your XML Schema Document, but DWB has a Graph
option that allows you to create it graphically using various icons. It is pretty COOL! This is the one we
will use for this lab.

1. Click on the Graph tab.


Before going any further, I want to show you the finished XML Schema Document graphically so that
you have some idea of what you are going to be building. Look at the figure below. On the right
side, you should see the Outline pane. It shows the tree structure of the schema. Remember that this
is the finished product that you will build.

2. Let's start working on it. Right-click in the Elements pane. Click on Add Element.

3. You will now have the "root" element of your XML document, which is named
NewGlobalElement.
4. Rename the root element from NewGlobalElement to customerinfo. Note: Sometimes, you are able
to immediately change the name; if you can't, right-click on NewGlobalElement and find Refactor
and then Rename.
5. Once the root element has been renamed, right-click on the customerinfo element, select Set Type,
and then select New Complex Type.

6.Double-click on the customerinfo element and you will get an element hierarchy.
The box to the right of the customerinfo box, the one with the 3 dots that also has the cursor pointing to
it, is called a sequence box. If you right click on the sequence box, you will see an Add Element
choice. This is where you add the elements that belong or go under the root element customerinfo.
Remember that customerinfo is a Complex Type.

7. Right-click the sequence box (... box). Click Add Element.

Next, you will add the elements.


8. You can immediately change NewElement to name. If you don't do it right away, then right-click
on the element and choose Refactor and then Rename. Notice that the data type is String.

9. To add the address elements, repeat the previous two steps.


After you rename the element to address, notice that it is a String type. The address element will
further contain other elements, so it must be a Complex type.

10. Change the “type” from string to anonymous.

11. Add the element balance (use a lowercase B). Set the type to decimal. Use Set Existing Type to
change the type.
Now, we will add the elements under the address element.

12. Click on the + sign to the right of the address element. You should get a sequence box.
13. Now add street, city, state, and zip to the address element. Follow the same process you used to
create name, address, and balance.

Step 2: XML Schema Registration

In this step, there is one more thing to do. We need to register the XML Schema with the XSR-XML
Schema Repository. This is done in the DWB. The registration is necessary so that the database can
decompose (shred) and validate XML data. Once this is done you will be able to view and manage
XML schemas and documents in the XSR.

1. Close the graphical XML Schema editor.

2. In the Data Project Explorer Pane, make sure that you have expanded your data development
project tree.

3.Locate the XML Schema Documents folder and click on the + sign next to it.
You should see your XML Schema.
I am going to use the one that I just created named NanaLiuNewXMLSchema.

4.Right-click on your schema and look for Register an XML Schema.


5. Click on Register an XML Schema.

You should notice that the name of the schema you highlighted (the one you just created) is in the
"XML schema name" text box.
If you try to change the name, you may be prompted to reconnect to the database by a User ID and
Password dialog box.
Don't worry if you don't get the login prompt.
6.Click Next. You should get the "Register an XML Schema" dialog.
Notice that it is asking for a "Schema location.cx."

In the box labeled "XML schema documents and dependencies," you should see a path reference to
your U:\ drive and workspace and Schema.

7. Simply click on the path (U:\), and that path will then appear in the Schema location box.
8. Click Finish. It might take 30 seconds or more to register.

Possible reasons for XSR Registration Errors:

A. Remember when we first started this lab, we talked about a possible XSR Registration error that may
occur when the system is IPLed (restarted) after maintenance downtime and the DeVry "Bind" has not
yet run. Well, if this BIND procedure has not run or fails, then you will NOT be able to register your
XML Schema..

B. The other possible reason for XSR Registration failure is that you have not completed all of the steps
correctly.

C. If you get an error, take a screenshot of your error message, review the lab steps, and consult your
instructor for assistance.
It is important to know that these types of errors are common in the industry, so you are getting direct
industry experience.

9.. When your XSR Registration is successful you will see a message:

"Register successful."

Result:

Thus the above steps for create an XML Database and Validate it using XML Schema created successfully.
EXP. NO: 11
Create Document, Column and Graph Based Data using Nosql Database Tools
DATE:

Aim:

To create Document, Column and Graph Based Data using Nosql Database Tools

Procedure:

Document based data

A document database is a type of nonrelational database that is designed to store and query data as JSON-like
documents. Document databases make it easier for developers to store and query data in a database by using the
same document-model format they use in their application code. The flexible, semistructured, and hierarchical
nature of documents and document databases allows them to evolve with applications needs. The document
model works well with use cases such as catalogs, user profiles, and content management systems where each
document is unique and evolves over time. Document databases enable flexible indexing, powerful ad hoc
queries, and analytics over collections of documents.

In the following example, a JSON-like document describes a book.


[
{
"year": 2013,

"title":"Turn It Down, Or Else!",

"info":{

"directors": [ "Alice Smith", "Bob Jones"],

"release_date":"2013-01-18T00:00:00Z",

"rating": 6.2,

"genres":["Comedy", "Drama"],

"image_url"

"http://ia.media-imdb.com/images/N/O9ERWAU7FS797AJ7LU8HN09AMUP908RL1o5JF90EWR7
LJKQ7@@_V1_SX400_.jpg",

"plot" : "A rock band plays their music at high volumes, annoying the neighbors.",

"actors": ["David Matthewman", "Jonathan G. Neff"]


}
},
{
"year": 2015,
"title": "The Big New Movie",

"info":{

"plot": "Nothing happens at all.",

"rating": 0
}
}
]

The following is an example of a document that might appear in a document database like MongoDB. This
sample document represents a company contact card, describing an employee called Sammy:

{
"_id": "sammyshark",

"firstName": "Sammy",

"lastName": "Shark",

"email": "[email protected]",

"department": "Finance"
}

Notice that the document is written as a JSON object. JSON is a human-readable data format that has become
quite popular in recent years. While many different formats can be used to represent data within a document
database, such as XML or YAML, JSON is one of the most common choices. For example, MongoDB adopted
JSON as the primary data format to define and manage data.

All data in JSON documents are represented as field-and-value pairs that take the form of field: value. In the
previous example, the first line shows an id field with the value sammyshark. The example also includes fields
for the employee's first and last names, their email address, as well as what department they work in.

Field names allow you to understand what kind of data is held within a document with just a glance. Documents
in document databases are self-describing, which means they contain both the data values as well as the
information on what kind of data is being stored. When retrieving a document from the database, you always
get the whole picture.

The following is another sample document representing a colleague of Sammy's named Tom, who works in
multiple departments and also uses a middle name:

{
"_id": "tomjohnson";

"firstName": "Tom",

"middleName": "William",
"lastName": "Johnson",

"email": "[email protected]",

"department": ["Finance", "Accounting"]


}

This second document has a few differences from the first example. For instance, it adds a new field called
middleName. Also, this document's department field stores not a single value, but an array of two values:
"Finance" and "Accounting".

Let's imagine the contact card must store information about social media accounts the employee uses and add
them as nested objects to the document:

{
"_id": "tomjohnson",

"firstName": "Tom",

"middleName": "William",

"lastName": "Johnson",

"email": "[email protected]",

"department": ["Finance", "Accounting"],

"socialMediaAccounts": [

{
"type": "facebook",

"username": "tom_william_johnson_23"

},
{

"type": "twitter",

"username": "@tomwilliamjohnson23"
}
]
}

A new field called social Media Accounts appears in the document, but instead of a single value, it refers to an
array of nested objects describing individual social media accounts. Each of these accounts could be a document
on its own, but here they're stored directly within the contact card. Once again, there is no need to change the
database structure to accommodate this requirement. You can immediately save the new document to the
database.
Column based data

COLUMN BASED SYSTEMS

The Columnar Data Model of NoSQL is important. NoSQL databases are different from SQL databases. This is
because it uses a data model that has a different structure than the previously followed row-and-column table
model used with relational database management systems (RDBMS). NoSQL databases are a flexible schema
model which is designed to scale horizontally across many servers and is used in large volumes of data.

Columnar Data Model of NoSQL:

Basically, the relational database stores data in rows and also reads the data row by row, column store is
organized as a set of columns. So if someone wants to run analytics on a small number of columns, one can read
those columns directly without consuming memory with the unwanted data. Columns are somehow are of the
same type and gain from more efficient compression, which makes reads faster than before.

Working of Columnar Data Model:

In Columnar Data Model instead of organizing information into rows, it does in columns. This makes them
function the same way that tables work in relational databases. This type of data model is much more flexible
obviously because it is a type of NoSQL database.

The below example will help in understanding the Columnar data model:

Row-Oriented
ID Name Grade GPA
001 John Senior 4.00
002 Karen Freshman 3.67
003 Bill Junior 3.33

Column-Oriented

Name ID Grade ID GPA ID


John 001 Senior 001 4.00 001
Karen 002 Freshman 002 3.67 002
Bill 003 Junior 003 3.33 003

Columnar Data Model uses the concept of keyspace, which is like a schema in relational models.

More specifically, column databases use the concept of keyspace, which is sort of like a schema in relational
models. This keyspace contains all the column families, which then contain rows, which then contain columns.
It's a bit tricky to wrap your head around at first but it's relatively straightforward.
By taking a quick look, we can see that a column family has several rows. Within each row, there can be several
different columns, with different names, links, and even sizes (meaning they don't need to adhere to a standard).
Furthermore, these columns only exist within their own row and can contain a value pair, name, and a timestamp.

If we take a specific row as an example:

The Row Key is exactly that: the specific identifier of that row and is always unique. The column contains the
name, value, and timestamp, so that's straightforward. The name/value pair is also straight forward, and the
timestamp is the date and time the data was entered into the database.

Some examples of column-store databases include Casandra, CosmoDB, Bigtable and HBase.

Graph based data

GRAPH DATABASES

A graph database is a type of database used to represent the data in the form of a graph. It has three components:
nodes, relationships, and properties. These components are used to model the data. The concept of a Graph
Database is based on the theory of graphs. It was introduced in the year 2000. They are commonly referred to
NoSql databases as data is stored using nodes, relationships and properties instead of traditional databases. A
graph database is very useful for heavily interconnected data. Here relationships between data are given priority
and therefore the relationships can be easily visualized. They are flexible as new data can be added without
hampering the old ones. They are useful in the fields of social networking, fraud detection, AI Knowledge graphs
etc.

The description of components are as follows:

-Nodes: represent the objects or instances. They are equivalent to a row in database. The node basically acts as
a vertex in a graph. The nodes are grouped by applying a label to each member.

-Relationships: They are basically the edges in the graph. They have a specific direction, type and form
patterns of the data. They basically establish relationship between nodes.

-Properties: They are the information associated with the nodes.

Some examples of Graph Databases software are Neo4j, Oracle NoSQL DB, Graph base etc. Out of which
Neo4j is the most popular one.

In traditional databases, the relationships between data is not established. But in the case of Graph Database, the
relationships between data are prioritized. Nowadays mostly interconnected data is used where one data is
connected directly or indirectly. Since the concept of this database is based on graph theory, it is flexible and
works very fast for associative data. Often data are interconnected to one another which also helps to establish
further relationships. It works fast in the querying part as well because with the help of relationships we can
quickly find the desired nodes. join operations are not required in this database which reduces the cost. The
relationships and properties are stored as first-class entities in Graph Database.

Graph databases allow organizations to connect the data with external sources as well. Since organizations
require a huge amount of data, often it becomes cumbersome to store data in the form of tables. For instance, if
the organization wants to find a particular data that is connected with another data in another table, so first join
operation is performed between the tables, and then search for the data is done row by row. But Graph database
solves this big problem. They store the relationships and properties along with the data. So if the organization
needs to search for a particular data, then with the help of relationships and properties the nodes can be found
without joining or without traversing row by row. Thus the searching of nodes is not dependent on the amount
of data.

Types of Graph Databases:

-Property Graphs: These graphs are used for querying and analyzing data by modelling the relationships among
the data. It comprises of vertices that has information about the particular subject and edges that denote the
relationship. The vertices and edges have additional attributes called properties.

-RDF Graphs: It stands for Resource Description Framework. It focuses more on data integration. They are
used to represent complex data with well defined semantics. It is represented by three elements: two vertices, an
edge that reflect the subject, predicate and object of a sentence. Every vertex and edge is represented by
URI(Uniform Resource Identifier).

When to Use Graph Database?


• Graph databases should be used for heavily interconnected data.
• It should be used when amount of data is larger and relationships are present.
• It can be used to represent the cohesive picture of the data.

Working of Graph and Graph Databases

Graph databases provide graph models. They allow users to perform traversal queries since data is connected.
Graph algorithms are also applied to find patterns, paths and other relationships this enabling more analysis of
the data. The algorithms help to explore the neighboring nodes, clustering of vertices analyze relationships and
patterns. Countless joins are not required in this kind of database.

Graph databases are generally straightforward in how they're structured though. They primarily are composed
of two components:
❖ The Node: This is the actual piece of data itself. It can be the number of viewers of a youtube video, the
number of people who have read a tweet, or it could even be basic information such as people's names, addresses,
and so forth.
❖The Edge: This explains the actual relationship between two nodes. Interestingly enough, edges can also have
their own pieces of information, such as the nature of the relation between two nodes. Similarly, edges might
also have directions describing the flow of said data.

The information used in graph databases can be essentially anything, and as you can see from the structure
above, are pretty simple to plot out and to understand at a fundamental level. In fact, a lot of modern graph
databases are starting to include this sort of quick visualization that doesn't require complex database language
knowledge, with a good recent example being MongoDB.

Taking a look at a more specific example, as you can see in the image above, graph databases can not only
describe the complex relationship between a group people but also their interests, likes, their friendships, and
businesses. Of course, the sky (and hardware) is the limit here, and you can get pretty complex when building a
graph database.

Example of Graph Database:


• Recommendation engines in E commerce use graph databases to provide customers with accurate
recommendations, updates about new products thus increasing sales and satisfying the customer's
desires.
• Social media companies use graph databases to find the "friends of friends" or products that the user's
friends like and send suggestions accordingly to user.
• To detect fraud Graph databases play a major role. Users can create graph from the transactions between
entities and store other important information. Once created, running a simple query will help to identify
the fraud.

Result:

Thus the above procedure for Document, Column and Graph Based Data using Nosql Database Tools created
successfully.
EXP. NO: 12 Develop a Simple Gui based Database Application and Incorporate all

DATE: the above-Mentioned Features

Aim:

To develop a Simple Gui based Database Application and Incorporate all the above-Mentioned Features.

PROGRAM FOR FORM 1

Private Sub emp_Click()


Form2.Show
End Sub
Private Sub exit_Click()
Unload Me
End Sub
Private Sub salary_Click()
Form3.Show
End Sub

PROGRAM FOR FORM 2

Private Sub add_Click()


Adodc1.Recordset.AddNew
MsgBox "Record added"
End Sub
Private Sub clear_Click()
Text1.Text=""
Text2.Text = ""
Text3.Text=""
Text4.Text=""
Text5.Text=""
Text6. Text=""
End Sub
Private Sub delete_Click()
Adodc1.Recordset.Delete
MsgBox "Record Deleted"
If Adodc1.Recordset.EOF= True Then
Adodc1.Recordset.MovePrevious
End If
End Sub
Private Sub exit_Click()
Unload Me
End Sub
Private Sub main_Click()
Form1.Show
End Sub
Private Sub modify_Click()
Adodcl.Recordset.Update
End Sub
PROGRAM FOR FORM 3

Private Sub add_Click()


Adodc1.Recordset.AddNew
MsgBox "Record added"
End Sub
Private Sub clear_Click()
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text6.Text = ""
End Sub
Private Sub delete_Click()
Adodc1.Recordset.Delete
MsgBox "Record Deleted"
If Adodcl.Recordset.EOF= True Then
Adodc1.Recordset.MovePrevious
End If
End Sub
Private Sub exit_Click()
Unload Me
End Sub
Private Sub main_Click()
Form1.Show
End Sub
Private Sub modify_Click()
Adodc1.Recordset.Update
End Sub

Output:
BANKING SYSTEM

Facilities required to do the experiment:

SI.No Facilities required Quantity


1 System 1
2 Operating System Windows XP
3 Front end VB / VC++ / JAVA
4 Back end Oracle11g, my SQL, DB2

Procedure for doing the experiment

Step No. Details of the step


1. Create the DB for banking system source request the using SQL
2. Establishing ODBC connection
3. Click add button and select oracle in ORA home 90 click finished
4. A window will appear give the data source name as oracle and give the user id as scott
5. Now click the test connection a window will appear with server and user name give user as scott
and password tiger Click ok
6. VISUAL BASIC APPLICATION:-
• Create standard exe project in to and design ms from in request format
• To add ADODC project select component and check ms ADO data control click ok
• Now the control is added in the tool book
• Create standard exe project in to and design ms from in request format

7. ADODC CONTEOL FOR ACCOUNT FROM:-


Click customs and property window and window will appear and select ODBC data source name
as oracle and click apply as the some window.

Program:

CREATE A TABLE IN ORACLE

SQL>create table account(Cname varchar(20),accno number(10),balance number);


Table Created

SQL> insert into account values('&cname',&accno,&balance);


Enter value for cname: Mathi
Enter value for accno: 1234
Enter value for balance: 10000
old1: insert into account values(‘&cname’,&accno,&balance)
new1: insert into emp values(‘Mathi’,1234,10000)
1 row created.
SOURCE CODE FOR FORM1

Private Sub ACCOUNT_Click()


Form2.Show
End Sub
Private Sub EXIT_Click())
Unload Me
End Sub
Private Sub TRANSACTION_Click()
Form3.Show
End Sub

SOURCE CODE FOR FORM 2

Private Sub CLEAR_Click()


Text1.Text = ""
Text2.Text = ""
Text3.Text =""
End Sub
Private Sub DELETE_Click()
Adodc1.Recordset.DELETE
MsgBox "record deleted"
Adodc1.Recordset.MoveNext
If Adodc1.Recordset.EOF= True Then
Adodc1.Recordset.MovePrevious
End If
End Sub
Private Sub EXIT_Click()
Unload Me
End Sub
Private Sub HOME_Click()
Form1.Show
End Sub
Private Sub INSERT_Click()
Adodcl.Recordset.AddNew
End Sub
Private Sub TRANSACTION_Click()
Form3.Show
End Sub
Private Sub UPDATE_Click()
Adodcl.Recordset.UPDATE
MsgBox "record updated successfully"
End Sub
SOURCE CODE FOR FORM 3

Private Sub ACCOUNT_Click()


Form2.Show
End Sub
Private Sub CLEAR_Click()
Text1.Text =””
Text2.Text =””
End Sub
Private Sub
DEPOSIT_Cli
ck() Dim s As
String
s = InputBox("enter the amount to be deposited") Text2.Text = Val(Text2.Text) + Val(s)
A = Text2.Text
MsgBox "CURRENT BALANCE IS Rs" +Str(A)
Adodcl.Recordset.Save Adode1.Recordset.UPDATE
End Sub
Private Sub EXIT_Click()
Unload Me
End Sub
Private Sub HOME_Click()
Form1.Show
End Sub
Private Sub WITHDRAW_Click() Dim s As String
s = InputBox("enter the amount to be deleted") Text2.Text = Val(Text2.Text) - Val(s)
A = Text2.Text
MsgBox "current balance is Rs" + Str(A)
Adodc1.Recordset.Save Adodc1.Recordset.UPDATE
EndSub

Output:
Result:

Thus the above source code for develop a Simple Gui based Database Application and Incorporate all the above-
Mentioned Features executed successfully.

You might also like