DBMS Unit 4
DBMS Unit 4
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 ……………………………………………….............
EX.
DATE NAME OF THE EXPERIMENT PAGE STAFF SIGN
NO
NO.
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:
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:
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));
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.
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.
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)
SELECT COMMANDS
Selects all rows from the table
Syntax: Select * from tablename;
Example: Select * from IT;
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;
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)
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
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
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.
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.
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.
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.
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
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
ONAME OID
----------------- -------------
chair 2005
table 2006
chair 2007
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
CNAME CID
--------------- ----------
jones 506
hayden 508
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
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
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
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
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
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;
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:
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’.
6. Determine the max and min salary and rename the column as max_salary and min_salary.
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.
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");
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
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;
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
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;
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
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);
4 Karthik AP 1 15000
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:
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
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
SQL> create table ititems(itemid number(3), actualprice number(5), ordid number(4), prodid number(4));
Table created.
1 row created.
1 row created.
1 row created.
Procedure created.
Procedure created.
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. /
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.
2. last day
3. Months between
4. next_day
5. round
This function returns the date, which is rounded to the unit specified by the format model.
CHARACTER FUNCTIONS
replace (char,search select replace(“jack and jue”,”j”,”bl”) from black and blue
string, replace string); dual;
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.
2. to_date()
Syntax: to_date(d,[format]);
This function converts character to date data format specified in the form character.
Miscellaneous Functions
1.uid - This function returns the integer value (id) corresponding to the user currently logged in.
3. nyl - The null value function is mainly used in the case where we want to consider null values as zero.
COUNT FUNCTION
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.
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:
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.
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
SQL Commands:
DCL Commands
GRANT COMMAND
<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.
[ 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:
COMMIT: Commit;
Queries
Tables Used
Ans.
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.
Revoke succeeded.
Q4. Develop a query to revoke some privileges of employees table from departments table
Ans.
Revoke succeeded.
Ans.
Savepoint created.
1 row created.
1 row created.
Commit complete
Executable SQL Commands using MySQL:
SQL Queries :
Table used
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
Types of Triggers
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;
The package "raise_application_error" is used to issue the user defined error messages
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.
*
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’;
*
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’
*
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’
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);
ERROR at line 1:
ERROR at line 1:
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:
(c) Simplifies the usage by combining multiple tables into a single table.
3.Types of view:
SQL Commands:
Syntax
Create [or replace] view <view name> [column alias names] as <query> [with <options> conditions];
Queries
Tables Used
Q1. The organization wants to display only the details of the employees those who are ASP. (Horizontal
portioning)
Solution:
Ans.
SQL> create view empview as select * from emp where job=’ASP’;
View created.
Solution:
Ans.
View created.
Ans.
DEPT TABLE
EMP TABLE
EMPVIEW VIEW
EMPVIEW1 VIEW
Ans.
Ans.
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:
Index created.
Index created.
Drop Index:
Index dropped.
Index dropped.
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)
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:
Procedure:
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.
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.
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.
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.
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.
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.
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:
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.
"info":{
"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.",
"info":{
"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]",
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]",
"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
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.
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.
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
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.
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 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.
-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.
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.
-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).
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.
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
Aim:
To develop a Simple Gui based Database Application and Incorporate all the above-Mentioned Features.
Output:
BANKING SYSTEM
Program:
Output:
Result:
Thus the above source code for develop a Simple Gui based Database Application and Incorporate all the above-
Mentioned Features executed successfully.