DBMS Lab Manual Editing New

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 44

Ex. No.

: 1 DDL & DML COMMANDS


Date :

AIM :
To study and perform the Data Definition Language commands and Data Manipulation Language
commands.
PROCEDURE :
DDL COMMANDS IN SQL :
• CREATE Command
• DROP Command
• ALTER Command
• TRUNCATE Command
• RENAME Command

1) CREATE : The CREATE TABLE statement is used to create a new table in a database.
Syntax :
SQL> CREATE TABLE <table name>(fieldname1 datatype,fieldname2 datatype,…..,fieldname-n
datatype);
Example :
SQL>create table customer (name varchar2(20),street varchar2(20),city varchar2(20));
Table created.

2) DISPLAY
Syntax :
SQL> desc <tablename>;
Example :
SQL> desc customer;
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(20)
STREET VARCHAR2(20)
CITY VARCHAR2(20)
3) ALTER : To alter the definition of a table in one of these ways:
• To add a column
• To add an integrity constraint
• To redefine a column(datatype,size,default value)
• To explicitly allocate an extent syntax
Syntax :
SQL>alter table<table name> add/modify (columnname datatype(size));
Example:
SQL>alter table customer add (phoneno number(10));
Table altered.
SQL> desc customer;
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(20)
STREET VARCHAR2(20)
CITY VARCHAR2(20)
PHONENO NUMBER(10)
Example :
SQL>alter table customer modify (name varchar2(30));
Table altered.
SQL> desc customer;
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(30)
STREET VARCHAR2(20)
CITY VARCHAR2(20)
PHONENO NUMBER(10)

4) RENAME : RENAME tablename to new tablename


Syntax :
SQL>rename <table name>to <new name>;
Example :
SQL>rename customer to cust;
Table renamed.
SQL>desc cust;
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(30)
STREET VARCHAR2(20)
CITY VARCHAR2(20)
PHONENO NUMBER(10)

5) TRUNCATE : Delete all the records in the table retaining its structure.
Syntax :
SQL>alter table <table name> drop(columname);
Example :
SQL>alter table cust drop(street varchar2(20));
Table altered.
SQL>desc cust;
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(30)
CITY VARCHAR2(20)
PHONENO NUMBER(10)

6) DROP : This command is used to drop the table.


Syntax :
SQL>drop table <table name>;
Example :
SQL>drop table cust;
Table dropped.
SQL>desc cust;
Error
ORA-04043:object cust doesnot exists.
DML COMMANDS IN SQL:
• SELECT Command
• INSERT Command
• UPDATE Command
• DELETE Command
CREATE :
SQL > create table cust(cname varchar2(15),cid number(5),caddr char(10),caccno number(5),
cacctype varchar2(10),cbalance float, Primary key(cid),unique(cname), unique(caccno),
check(cbalance>=1000));
SQL> desc cust;
Name Null? Type
----------------------------------------- -------- ----------------------------
CNAME VARCHAR2(15)
CID NOT NULL NUMBER(5)
CADDR CHAR(10)
CACCNO NUMBER(5)
CACCTYPE VARCHAR2(10)
CBALANCE FLOAT(126)

INSERT : The INSERT INTO statement is used to insert new records in a table.
SQL> insert into cust values('Anitha',01,'Chennai',1001,'savings',15000);
1 row created.
SQL> insert into cust values('jone',02,'Pondy',1002,'savings',25000);
1 row created.
SQL> insert into cust values('david',03,'Salem',1003,'fd',36200);
1 row created.
SQL> insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance);
Enter value for cname: ann
Enter value for cid: 04
Enter value for caddr: Salem
Enter value for caccno: 1009
Enter value for cacctype: 5000
Enter value for cbalance: 5000
Old 1: insert into cust values('&cname',&cid,'&caddr',&caccno,'&cacctype',&cbalance)
New 1: insert into cust values('ann',04,'Salem',1009,'RD',5000)
1 row created.
SQL> insert into cust values('roselin',02,'trichy',1007,'savings',27000);
1 row created.

SELECT : The SELECT statement is used to select data from a database. The data returned is stored in a
result table called the result set.
SQL> select * from cust;
CNAME CID CADDR CACCNO CACCTYPE CBALANCE
--------------- ---------- ---------- ---------- ---------- ------------------- ----------------
Anitha 1 Chennai 1001 savings 15000
jone 2 Pondy 1002 savings 25000
david 3 Salem 1003 fd 36200
ann 4 Salem 1009 RD 5000
roselin 5 Trichy 1007 savings 27000
5 rows selected.

UPDATE : The UPDATE statement is used to modify the existing records in a table.
SQL>update cust set caccno=1111 where cname='david';
1 row updated
SQL> select * from cust;
CNAME CID CADDR CACCNO CACCTYPE CBALANCE
--------------- ---------- ---------- ---------- ---------- --------------------------------------
Anitha 1 Chennai 1001 savings 15000
jone 2 Pondy 1002 savings 25000
david 3 Salem 1111 fd 36200
ann 4 Salem 1004 checkings 5000
roselin 5 Trichy 1005 checkings 10000
5 rows selected.
DELETE : The DELETE statement is used to delete exsting records in a table.
SQL>delete from cust where cacctype='fd';
3 rows deleted
SQL> select * from cust;
CNAME CID CADDR CACCNO CACCTYPE CBALANCE
--------------- ---------- ---------- ---------- ---------- -------------------------------------
Anitha 1 Chennai 1001 savings 15000
jone 2 Pondy 1002 savings 25000
ann 4 Salem 1004 checkings 5000
roselin 5 Trichy 1005 checkings 10000
4 rows selected.

CREATE : To create a table , the basic structure to hold user data specifying this information:
• Column definitions
• Integrity constraints
• An optional cluster
• Data from an arbitrary query syntax.

CONSTRAINTS :
• NOT NULL every record must have a value for the column
• UNIQUE value for each record must be distinct
• CHECK checks to make sure the condition is satisfied
• PRIMARY KEY defines the primary key of the table

SQL PRIMARY KEY CONSTRAINT :


The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain
UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the
table, this primary key can consist of single or multiple columns (fields).

SQL PRIMARY KEY on ALTER TABLE


SQL> create table persons(id int,firstname varchar(20),lastname varchar(20),age int);
SQL> desc persons;
To create a PRIMARY KEY constraint on the "ID" column when the table is already created, use the
following SQL:
Syntax :
SQL> ALTER TABLE Persons ADD PRIMARY KEY (ID);
SQL> desc persons;

DROP a PRIMARY KEY Constraint : To drop a PRIMARY KEY constraint, use the following SQL,
Syntax :
SQL> ALTER TABLE persons DROP PRIMARY KEY;
SQL> desc persons;

SQL UNIQUE Constraint


The UNIQUE constraint ensures that all values in a column are different. Both
the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of
columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you canhave
many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "ID" column when the table is already created, use the
followingSQL:
Syntax :
SQL>ALTER TABLE Persons ADD UNIQUE (ID);
SQL>INSERT INTO persons values(1,’ajay’,’kumar’,18);
SQL>INSERT INTO persons values(1,’john’,’son’,18);

DROP a UNIQUE Constraint : To drop a UNIQUE constraint, use the following SQL,
Syntax :
SQL>ALTER TABLE Persons DROP UNIQUE(id);
SQL>INSERT INTO persons values(1,’john’,’son’,18);
SQL>SELECT * FROM persons;

SQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a column. If you define
a CHECK constraint on a column it will allow only certain values for this column. If you definea
CHECK constraint on a table it can limit the values in certain columns based on values in other columns in
the row.

SQL CHECK on ALTER TABLE : To create a CHECK constraint on the "Age" column when the table is
already created, use the followingSQL,
Syntax :
SQL>ALTER TABLE Persons ADD CHECK (Age>=18);
SQL>INSERT INTO persons values(2,’suthan’,’raj’,17);

SQL NOT NULL Constraint


By default, a column can hold NULL values. The NOT NULL constraint enforces a column to NOT
accept NULL values. This enforces a field to always contain a value, which means that you cannot insert a
new record, or update a record without adding a value to this field.

SQL NOT NULL on ALTER TABLE : To create a NOT NULL constraint on the "Age" column when
the "Persons" table is already created,use the following SQL,
Syntax :
SQL> ALTER TABLE Persons MODIFY Age int NOT NULL;
SQL> desc persons;

RESULT
Thus the database was created and the SQL queries are written to retrieve information from the
database.
Ex.No.: 2 FOREIGN KEY CONSTRAINTS
Date :

AIM :
To Create a set of tables, add foreign key constraints and incorporate referential integrity

DESCRIPTION :
SQL FOREIGN KEY CONSTRAINT
The FOREIGN KEY constraint is used to prevent actions that would destroy links between
tables. FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in
another table. The table with the foreign key is called the child table, and the table with the primary key is called
the referenced or parent table. The FOREIGN KEY constraint prevents invalid data from being inserted into
the foreign key column, because it has to be one of the values contained in the parent table.

SQL FOREIGN KEY on CREATE TABLE


SQL>create table personsfk(personid int not null,firstname varchar(20),lastname varchar(20),age
int,primary key(personid));

SQL>create table orders (orderid int not null,ordernumber int not null,personid int,primary key
(orderid),constraint fk_personorder foreign key (personid) references persons(personid));

DROP a FOREGN KEY CONSTRAINT :


SQL>alter table orders drop constraint fk_personorder;

SQL FOREIGN KEY on ALTER TABLE

SQL>create table ordersnew(ordered int,ordernumber int,personid int,primary key (personid);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on
multiple columns, use the following SQL syntax:
SQL>alter table orders add constraint fk_personorder foreign key (personid) references persons
(personid);

RESULT
Thus the database was created and the SQL queries are written to retrieve information from the
database.
Ex.No.: 3 AGGREGATE FUNCTIONS
Date :

AIM :
To write a Query the database tables using different ‘where’ clause conditions and also
implement aggregate functions.

DESCRIPTION :
The SQL WHERE Clause : The WHERE clause is used to filter records. It is used to extract only those
records that fulfill a specified condition.
Syntax
SELECT column1, column2, … FROM table_name WHERE condition;

The WHERE clause is not only used in SELECT statements, it is also used in UPDATE, DELETE,
etc.!
Operators in The WHERE Clause
The following operators can be used in the WHERE clause:

Operator Description Example

= Equal SELECT * FROM Products WHERE Price = 18;

> Greater than SELECT * FROM Products WHERE Price > 30;

< Less than SELECT * FROM Products WHERE Price < 30;
>= Greater than or equal SELECT * FROM Products WHERE Price >= 30;

<= Less than or equal SELECT * FROM Products WHERE Price <= 30;

<>, != Not equal. SELECT * FROM Products WHERE Price <> 18;

SELECT * FROM Products WHERE Price BETWEEN


BETWEEN Between a certain range
50 AND 60;

LIKE Search for a pattern SELECT * FROM Customers WHERE City LIKE 's%';

To specify multiple possible SELECT * FROM Customers WHERE City IN


IN
values for a column ('Paris','London');
MySQL sum() function : The MySQL sum() function is used to return the total summed value of an
expression. It returns NULL if the result set does not have any rows. It is one of the kinds of aggregate
functions in MySQL.
Syntax :
SQL>SELECT SUM(aggregate_expression) FROM tables [WHERE conditions];
Consider our database has a table named employees, having the following data. Now, we are going
to understand this function with various examples:
⚫ MySQL sum() function with WHERE clause- This example is used to return the result based
on the condition specified in the WHERE clause.
⚫ MySQL sum() function with GROUP BY clause- We can also use the SUM() function with
the GROUP BY clause to return the total summed value for each group.
⚫ MySQL sum() function with HAVING clause- The HAVING clause is used to filter the group
with the sum() function in MySQL.
⚫ MySQL sum() function with DISTINCT clause- MySQL uses the DISTINCT keyword
to remove the duplicate rows from the column name. This clause can also be used with
sum() function to return the total summed value of a Unique number of records present in
the table.

Exercise :
1. Create a table which has the following fieldsCustomerID, CustomerName, ContactName,
Address,City, PostalCode, Country.

SQL> CREATE TABLE CUSTOMER(CustomerID number, CustomerName varchar2(15),


Contactnumber number, Address varchar2(15), City varchar2(15), PostalCode number);

SQL> Insert into customer values(1,’ajay’,8548493883,’main street’,’chennai’,629001);


SQL> Insert into customer values(2,’kumar’,9823456778,’east street’,’mexico’,20018);
SQL> Insert into customer values(3,’john’,7658280234,’stapley street’,’mexico’,29001);

2. Write a SQL statement selects all the customers from the country "Mexico", in the Customers" table:
SQL>SELECT * FROM Customers WHERE City='Mexico';
SQL>SELECT * FROM Customers WHERE CustomerID=1;
SQL>Create table employees(empid number,empname varchar(20),age number,city varchar(20),
occupation varchar(20), workinghours number);
SQL>Insert into employees values(1,’ajay’,26,’chennai’,’manager’,10);
SQL>Insert into employees values(2,’kumar’,32,’chennai’,’testing’,14);
SQL>Insert into employees values(3,’john’,32,’delhi’,’testing’,16);
SQL>Insert into employees values(4,’godson’,26,’delhi’,’developer’,11);
SQL>Insert into employees values(5,’suthan’,34,’mumbai’,’developer’,12);
SQL>Insert into employees values(6,’swaraj’,34,’mumbai’,’team leader’,18);
SQL>Insert into employees values(7,’jeswin’,37,’goa’,’team leader’,20);
SQL>Insert into employees values(8,’gladson’,29,’delhi’,’developer’,11);

3. Execute the following query that uses the COUNT(expression) function to calculates the total
number of employees name available in the table:
SQL>SELECT COUNT(emp_name) FROM employees;

4. Execute the following statement that returns all rows from the employee table and WHERE
clause specifies the rows whose value in the column emp_age is greater than 32:
SQL>SELECT COUNT(*) FROM employees WHERE emp_age>32;

5. This statement uses the COUNT(distinct expression) function that counts the Non-Null and distinct
rows in the column emp_age:
SQL>SELECT COUNT(DISTINCT emp_age) FROM employees;

MySQL Count() Function with GROUP BY Clause


6. We can also use the count() function with the GROUP BY clause that returns the count of the
element in each group. For example, the following statement returns the number of employee in each
city:
SQL>SELECT city, COUNT(*) FROM employees GROUP BY city;

MySQL Count() Function with HAVING and ORDER BY Clause


7. Execute the following statement that gives the employee name who has at least two age same and
sorts them based on the count result
SQL>SELECT emp_age, COUNT(*) FROM employees GROUP BY emp_age HAVING
COUNT(*)>=2 ORDER BY COUNT(*);

8. Execute the following query that calculates the total number of working hours of all employees in
the table:
SQL>SELECT SUM(working_hours) AS "Total working hours" FROM employees;

9. Execute the following query to calculate the total working hours of employees whose
working_hours >= 12.
SQL>SELECT SUM(working_hours) AS "Total working hours" FROM employees WHERE
working_hours>=12;

10. Write a statement calculates the total working hours of each employee by using the SUM() function
with the GROUP BY clause, as shown in the following query:
SQL> SELECT occupation, SUM(working_hours) AS "Total working hours" FROM employees
GROUP BY occupation;

11. Execute the following statement that calculates the working hours of all employees, grouping them
based on their occupation and returns the result whose Total_working_hours>24.
SQL> SELECT occupation, SUM(working_hours) Total_working_hours FROM employees
GROUP BY occupation HAVING SUM(working_hours)>24;

12. Execute the following query that removes the duplicate records in the working_hours column of
the employee table and then calculates the sum:
SQL>SELECT occupation,SUM(DISTINCT working_hours) Total_working_hours FROM
employees GROUP BY occupation;

VIVA Questions
1. What are aggregate functions in MySQL?
2. Which clause is used with an aggregate functions?
3. How do you write aggregate function in SQL?
4. Why are aggregate functions called so?
5. Is sum an aggregate function in SQL?
6. What is the syntax of Count() function and sum() function ?

RESULT
Thus the database was created and the SQL queries are written to retrieve information from the
database.
Ex.No.: 4 SUB QUERIES AND SIMPLE JOIN OPERATIONS
Date :

AIM :
To write sub queries and join queries in SQL and practice them.
PROCEDURE :
A) SUB QUERIES
SQL> create Table account (accno number(5), brname varchar2(20), balance number(10), Primary
key(accno));
Table created.
SQL > select * from account;
ACCNO BRNAME BALANCE
----------- -------------- ----------------
100 chennai 1000
101 trichy 12000
102 tuticorin 300000
104 madurai 23000
105 nzt 3400
106 tuty 6000
SQL > create Table branch (brname varchar2(20), brcity varchar2(20), assets number(10), Primary
key(brname)) ;
Table created.
SQL > select * from branch;
BRNAME BRCITY BALANCE
--------------- ---------- ----------------
nzt tuticorin 30000
millerpuram tuticorin 50000
kk nagar tirinelveli 900000
ss nagar maduari 57600
sk nagar theni 8000
spic tuticorin 360000
SQL > create table Customer (cname varchar2(15), cstreet varchar2(20), ccity varchar2(10),
Primary key(cname));
SQL > select * from customer;
CNAME CSTREET CCITY
--------------- ---------- ----------
dbi kk st tuty
kalai ss road chennai
ponni north st theni
tarani south st dindugal
ann west st tuty
vimal main road nagercoil
SQL > create Table loan (loanno number(5), brname varchar2(20), amount number(10), Primary
key(loanno)) ;
Table created.
SQL > select * from loan;
LOANNO BRNAME AMOUNT
--------------- --------------- --------------
1 nzt 23000
5 KK nagar 3000
6 tuticorin 25000
8 madurai 29000
9 nzt 3400
10 teni 6000

SQL > create Table depositor (cname varchar2(15), accno number(10));


Table created
SQL > select * from depositor;
CNAME ACCNO
--------------- ----------
kalai 104
pinky 101
silvia 100
alagu 102
sibu 105
jerlin 103
6 rows selected.
SQL > create Table borrower (cname varchar2(15), loanno number(10));
Table created
SQL > select * from borrower;
CNAME LOANNO
--------------- ----------
pinky 1
silvia 5
kavi 6
priya 8
selm 9
kiruba 10
6 rows selected.

SET MEMBERSHIP
1. IN : Find all customers who have both an account and a loan at the bank.
SQL > select distinct cname from borrower where cname in (select cname from depositor);
CNAME
---------------
kalai
pinky
silvia

2. NOT IN : Find all customers who have a loan at the bank but do not have account at the bank.
SQL > select distinct cname from borrower where cname not in (select cname from depositor);
CNAME
---------------
kavi
priya
sibu
kiruba

SET COMPARISON
1. SOME : Find the names of all branches that have assets greater than that of at least one branch located
in “tuticorin”
SQL > select brname from branch where assets>some (select assets from branch where
brcity=’tuticorin’;
BRNAME
---------------
nzt
millerpuram
kk nagar
ss nagar
spic
5 rows selected

2. ALL : Find the names of all branches that have assets grater than that of each branch located in “tuticorin”
SQL > select brname from branch where assets>all (select assets from branch where
brcity=’tuticorin’;
BRNAME
---------------
kk nagar
1 rows selected

3. COMPARISON OPERATOR : Find the names of all branches that have assets greater than those of
atleast one branch located in “tuticorin”
SQL>select distinct t.brname from branch as t, branch as s where t.assets>s.assets and
brcity=’tuticorin’;
BRNAME
---------------
nzt
millerpuram
kk nagar
ss nagar
spic
5 rows selected

TEST FOR EMPTY RELATION


1. EXISTS : Find all customers who have both an account and a loan at the bank.
SQL>select distinct cname from borrower where exists (select * from depositor where
depositor.cname=borrower.cname);
CNAME
---------------
kalai
pinky
silvia

B) JOIN QUERIES
Create order table
SQL>Create Table orders(orderid varchar(20),customerid varchar(20),orderdate varchar(20));
SQL>Insert into orders(orderid, customerid,orderdate) values(10308,2,’10 march 2023’)
SQL>Insert into orders(orderid, customerid,orderdate) values(10309,3,’12 march 2023’)
SQL>Insert into orders(orderid, customerid,orderdate) values(10310,27,’14 march 2023’)
Create customer table
SQL>Create Table customers(custmerid varchar(20),customername varchar(20),contactnumber
number(20),country varchar(20));
SQL>Insert into customers(customerid,customername,contactnumber,country) values (1,john,
98345343339,germany);
SQL>Insert into customers(customerid,customername,contactnumber,country) values (2,johan,
8902323239,mexico);
SQL>Insert into customers(customerid,customername,contactnumber,country) values (3,joyal,
7434342290,mexicos);
SQL>SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;
ORDERID CUSTOMERNAME ORDERDATE
----------------------------------------------------------------------------
2 johan 2023-02-19
3 joyal 2023-02-17

RESULT :
Thus the nested queries and join queries were studied and executed.
Ex.No.: 5 NATURAL, EQUI AND OUTER JOINS
Date :

AIM :
To Query the database tables and explore natural, equi and outer joins.

PROCEDURE :
Table-1: department
SQL>create table department(dept_name varchar(20),manager_name varchar(255));
Table-2: employee
SQL>create table employee(emp_id int,emp_name varchar(20),dept_name varchar(255));
Inserting Values : Add value into the tables as follows.
SQL>insert into department(dept_name,manager_name) values ( "it", "rohan");
SQL>insert into department(dept_name,manager_name) values ( "sales", "rahul");
SQL>insert into department(dept_name,manager_name) values ( "hr", "tanmay");
SQL>insert into department(dept_name,manager_name) values ( "finance", "ashish");
SQL>insert into department(dept_name,manager_name) values ("marketing", "samay");

SQL>insert into employee(emp_id, emp_name, dept_name) values (1, "sumit", "hr");


SQL>insert into employee(emp_id, emp_name, dept_name) values (2, "joel", "it");
SQL>insert into employee(emp_id, emp_name, dept_name) values (3, "biswa", "marketing");
SQL>insert into employee(emp_id, emp_name, dept_name) values (4, "vaibhav", "it");
SQL>insert into employee(emp_id, emp_name, dept_name) values (5, "sagar", "sales");

Verifying Inserted Data: This is our data inside the table as follows.
SQL>SELECT * FROM EMPLOYEE;
Output :

EMP_ID EMP_NAME DEPT_NAME

1 SUMIT HR

2 JOEL IT

3 BISWA MARKETING
EMP_ID EMP_NAME DEPT_NAME

4 VAIBHAV IT

5 SAGAR SALES

SQL>SELECT * FROM DEPARTMENT;


Output :

DEPT_NAME MANAGER_NAME

IT ROHAN

SALES RAHUL

HR TANMAY

FINANCE ASHISH

MARKETING SAMAY

Query to implement SQL Natural Join :


SQL> select * from employee natural join department;
Output :

EMP_ID EMP_NAME DEPT_NAME MANAGER_NAME

1 SUMIT HR TANMAY

2 JOEL IT ROHAN

3 BISWA MARKETING SAMAY

4 VAIBHAV IT ROHAN
EMP_ID EMP_NAME DEPT_NAME MANAGER_NAME

5 SAGAR SALES RAHUL

1. EQUI JOIN : EQUI JOIN creates a JOIN for equality or matching column(s) values of the relative
tables. EQUI JOIN also create JOIN by using JOIN with ON and then providing the names of the columns
with their relative tables to check equality using equal sign (=).
SQL>Create table account (accno number,brname varchar(20),balance number);
ACCNO BRNAME BALANCE CNAME ACCNO
--------------- ---------- --------------- ---------- - --------
100 chennai 1000 kalai 104
101 trichy 12000 pinky 101
102 tuticorin 30000 silvia 100
104 madurai 23000 alagu 102
105 nzt 3400 sibu 105
SQL>Create table depositor(cname varchar(20),accno number);
CNAME ACCNO
----------------------------
Kalai 104
Pinky 101
Silvia 100
Alagu 102
Sibu 105
Raja 1009
SQL > select * from account,depositor where account.accno=depositor.accno;

2. NON EQUI JOIN : NON EQUI JOIN performs a JOIN using comparison operator other than equal(=)
sign like >, <, >=, <= with conditions.
SQL > select d.cname, a.accno from depositor d account a where a.balance between 23000 and 35000
and a.accno=d.accno;
CNAME ACCNO
--------------- ----------
Alagu 102
kalai 104
2 rows selected.

3. LEFT OUTER JOIN : Returns all records from the left table, and the matched records from the right table
SQL > select account.accno,depositor.cname from account left join depositor on account.accno=
depositor.accno order by account.accno;

4. RIGHT OUTER JOIN : Returns all records from the right table, and the matched records from the left
table
SQL > select account.accno,depositor.cname from account right join depositor on account.accno=
depositor.accno order by account.accno;

5. FULL OUTER JOIN : Returns all records when there is a match in either left or right table
SQL > select depositor.cname,account.accno from depositor full outer join account on
account.accno=depositor.accno order by depositor.cname;

RESULT :
Thus the natural and equi join queires were studied and executed.

Ex.No. : 6 FUNCTIONS AND PROCEDURES


Date :

AIM :
To write a PL/SQL program to implement the concept of procedure and function.
PL/SQL – Procedures :
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram can be invoked
by another subprogram or program which is called the calling program.
A subprogram can be created −
• At the schema level
• Inside a package
• Inside a PL/SQL block
At the schema level, subprogram is a standalone subprogram. It is created with the CREATE
PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be deleted with
the DROP PROCEDURE or DROP FUNCTION statement.
A subprogram created inside a package is a packaged subprogram. It is stored in the database and can
be deleted only when the package is deleted with the DROP PACKAGE statement. We will discuss packages
in the chapter 'PL/SQL - Packages'.PL/SQL subprograms are named PL/SQL blocks that can be invoked with
a set of parameters.
PL/SQL provides two kinds of subprograms −
• Functions − These subprograms return a single value; mainly used to compute and return a
value.
• Procedures − These subprograms do not return a value directly; mainly used to perform an
action.
PROCEDURE :
A procedure returns the control but not any value to calling function or code
SQL> create table stud(rno number(2),mark1 number(3),mark2 number(3),total number(3),primary
key(rno));
Table created.

SQL> desc stud;


Name Null? Type
----------------------------------------- -------- ----------------------------
RNO NOT NULL NUMBER(2)
MARK1 NUMBER(3)
MARK2 NUMBER(3)
TOTAL NUMBER(3)

SQL> select * from stud;


RNO MARK1 MARK2 TOTAL
---------- ------------ ---------- ----------
1 80 85 0
2 75 84 0
3 65 80 0
4 90 85 0

PROGRAM :
SQL> create procedure studd(rnum number) is
2 m1 number;
3 m2 number;
4 total number;
5 begin
6 select mark1,mark2 into m1,m2 from stud where rno=rnum;
7 if m1<m2 then
8 update stud set total=m1+m2 where rno=rnum;
9 else
10 dbms_output.put_line(‘Student failed’);
11 end if;
12 end;
13 /
Procedure created.

SQL> exec studd(1);


PL/SQL procedure successfully completed.
SQL> select * from stud;
RNO MARK1 MARK2 TOTAL
---------- ---------- ---------- ----------
1 80 85 165
2 75 84 0
3 65 80 0
4 90 85 0

SQL> exec studd(4);


PL/SQL procedure successfully completed.

SQL> select * from stud;


RNO MARK1 MARK2 TOTAL
---------- ---------- ---------- ----------
1 80 85 165
2 75 84 0
3 65 80 0
4 90 85 175
SQL> exec studd(2);
PL/SQL procedure successfully completed.

SQL> exec studd(3);


PL/SQL procedure successfully completed.

SQL> select * from stud;


RNO MARK1 MARK2 TOTAL
---------- ---------- ---------- ----------
1 80 85 165
2 75 84 159
3 65 80 145
4 90 85 175

EFUNCTIONS
A function returns a value and control to calling function or code.
PROCEDURE :
a) Function1:
SQL> create table stud(rno number(2),mark1 number(3),mark2 number(3),total number(3), primary
key(rno));
Table created.

SQL> desc stud;


Name Null? Type
------------------ ---------------- -------------------
RNO NOT NULL NUMBER(2)
MARK1 NUMBER(3)
MARK2 NUMBER(3)
TOTAL NUMBER(3)

SQL> select * from stud;


RNO MARK1 MARK2 TOTAL
---------- ---------- ---------- ------------------
1 80 85 0
2 75 84 0
3 65 80 0
4 90 85 0

SQL> create or replace function stude(rnum number) return number is


2 total number;
3 m1 number;
4 m2 number;
5 begin
6 select mark1,mark2 into m1,m2 from stud where rno=rnum;
7 total:=m1+m2;
8 return total;
9 end;
10 /
Function created.
SQL> select stude(2) from dual;
STUDE(2)
----------
159

b) Function2 :
SQL> create table purchase (icode number(3),iname varchar2(13),price number(6),quantity
number(3), rate number(8),primary key(icode),unique(iname));
Table created.

SQL> desc purchase;


Name Null? Type
----------------------------------------- -------- ----------------------------
ICODE NOT NULL NUMBER(3)
INAME VARCHAR2(13)
PRICE NUMBER(6)
QUANTITY NUMBER(3)
RATE NUMBER(8)

SQL> select * from purchase;


ICODE INAME PRICE QUANTITY RATE
---------- -------------------- ---------- ------------------- ----------
100 PenSet 20 10 0
101 ParkerPen 60 10 0
102 180pg Note 24 10 0
103 80pg Note 10 25 0
104 StickFile 10 20 0

SQL> create or replace function pur(itmcd number) return number is


2 qt number;
3 pr number;
4 rate number;
5 begin
6 select price,quantity into pr,qt from purchase where icode=itmcd;
7 rate:=qt*pr;
8 return rate;
9 end;
10 /
Function created.

SQL> select pur(102) from dual;


PUR(102)
-----------
240

RESULT :
Thus the PL/SQL program for implementing the concept of functions is executed and output was
verified successfully.

Ex.No.: 7 DCL AND TCL COMMANDS


Date :

AIM :
To execute complex transactions and realize DCL and TCL commands.
DCL Commands
DCL commands are used to grant and take back authority from any database user
Example :
SQL>connect system;
Enter password: csi
Connected.
USER CREATION
Syntax :
SQL>create user <user name> identified by <password>;
Example :
SQL> create user tom identified by jerry;
User created.
Connect system
Enter password:csi
Connected
CONNECTION
SQL>grant connect,resource to tom;
Grant succeeded.
SQL>connect tom;
Enter password: *****
Connected.
Table Creation
Connect system
Enter password:csi
Connected
SQL>Create table cust(id number,name varchar(20));
SQL>Insert into cust values(1,’ajay’);
SQL>Insert into cust values(2,’john’);
GRANTING PRIVILEGES
SQL>grant select,insert on cust to scott;
Grant succeeded.

REVOKING PRIVILEGES
SQL>revoke select,insert on cust from scott;
Revoke succeeded.

TRANSACTION CONTROL LANGUAGE


TCL commands can only use with DML commands like INSERT, DELETE and UPDATE only.These
operations are automatically committed in the database that's why they cannot be used while creating tables
or dropping them.
Here are some commands that come under TCL:
• COMMIT
• ROLLBACK
• SAVEPOINT

COMMIT COMMAND : COMMIT command is used to permanently save any transaction into the database.
To avoid that, we use the COMMIT command to mark the changes as permanent. Following is commit
command's syntax, COMMIT;
SQL>commit;
Committ completed.
SQL>insert into cust values(7,’rajesh’);
SQL> select * from cust;

ROLLBACK : This command restores the database to last commited state. It is also used with SAVEPOINT
command to jump to a savepoint in an ongoing transaction. Following is rollback command's syntax,
SQL>rollback;
Rollback completed.
SQL> select * from cust;

SAVEPOINT COMMAND : SAVEPOINT command is used to temporarily save a transaction so that you
can rollback to that point whenever required.
SQL>SAVEPOINT savepoint_name;

Let’s use some SQL queries on the above table and see the results.
SQL>INSERT INTO cust VALUES(5, 'Rahul');
SQL>COMMIT;
SQL>UPDATE cust SET name = 'Abhijit' WHERE id = '5';
SQL>SAVEPOINT A;
SQL>INSERT INTO cust VALUES(6, 'Chris');
SQL>SAVEPOINT B;
SQL>INSERT INTO cust VALUES(9, 'Bravo');
SQL>SAVEPOINT C;
SQL>Select * from cust;
SQL>ROLLBACK TO B;
SQL>Select * from cust;

RESULT :
Thus the DCl and TCL commands were studied and executed

EX.NO.: 8 TRIGGERS
Date :
AIM :
To write a PL/SQL program to implement the concept of triggers.

PROCEDURE :
PL/SQL - Triggers
In this chapter, we will discuss Triggers in PL/SQL. Triggers are stored programs, which are automatically
executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of
the following events −
• A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
• A database definition (DDL) statement (CREATE, ALTER, or DROP).
• A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Learn About Different Type Of Triggers In Oracle
Overview
Database triggers are specialized stored programs. Oracle engine allows the definition of the procedures,
which are implicitly executed when an insert, update, or delete is issued in a table from SQL or through the
Application, and the trigger automatically executes a DML statement. They are not called directly, but are
triggered by the events in the database. They run between the time, when you issue a command and the time,
you perform the database management system action. You can write the triggers in PL/SQL.
Introduction
PL/SQL Type of Triggers are based on how they are triggered.
Before Triggers : These triggers are fired before the SQL statement trigger (INSERT, UPDATE,DELETE)
is executed. The execution of the triggering SQL statement is stopped, depending on the various conditions
to be fulfilled in the BEFORE trigger.
After Triggers : These triggers are fired after the triggering SQL statement (INSERT, UPDATE,DELETE)
is executed. The triggering SQL statement is executed first, followed by the code of the trigger.
Row Trigger : The triggers are fired for each and every record, which is inserted or updated or deleted from
a table.
Statement Trigger : The trigger is fired for each row of the DML operation, being performed on a table. We
cannot access the column values for the records being inserted, updated, deleted on the table nor the individual
records.

a) TRIGGER WITH BEFORE UPDATE


SQL> create table orders(order_id number(5),quantity number(4),cost_per_item number(6,2),total_cost
number(8,2),updated_date date,updated_by varchar2(10));
Table created.
SQL> insert into orders(order_id,quantity,cost_per_item) values (&order_id,&quantity,
&cost_per_item);
Enter value for order_id: 1
Enter value for quantity: 4
Enter value for cost_per_item: 20
old 1: insert into orders(order_id,quantity,cost_per_item) values(&order_id,&quantity,&cost_per_it
new 1: insert into orders(order_id,quantity,cost_per_item) values(1,4,20)
1 row created.
SQL> /
Enter value for order_id: 2
Enter value for quantity: 5
Enter value for cost_per_item: 30
old 1: insert into orders(order_id,quantity,cost_per_item) values(&order_id,&quantity,&cost_per_it
new 1: insert into orders(order_id,quantity,cost_per_item) values(2,5,30)
1 row created.
SQL> /
Enter value for order_id: 3
Enter value for quantity: 6
Enter value for cost_per_item: 25
old 1: insert into orders(order_id,quantity,cost_per_item) values(&order_id,&quantity,&cost_per_it
new 1: insert into orders(order_id,quantity,cost_per_item) values(3,6,25)
1 row created.
SQL> select * from orders;
ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST UPDATED_D UPDATED_BY
---------- ---------- ------------- ---------- --------- ----------
1 4 20
2 5 30
3 6 25

TRIGGER SCRIPT
SQL> create or replace trigger orders_before_update
2 before update
3 on orders
4 for each row
5 declare
6 v_username varchar2(10);
7 begin
8 select user into v_username from dual;
9 :new.updated_date:=sysdate;
10 :new.updated_by:=v_username;
11 end;
12 /
Trigger created.

SQL> update orders set total_cost=3000 where order_id=2;


1 row updated.

SQL> select * from orders;


ORDER_ID QUANTITY COST_PER_ITEM TOTAL_COST UPDATED_D
UPDATED_BY
---------- ---------- ------------- ---------- --------- ----------
1 4 20
2 5 30 3000 19-SEP-07 CSE3101
3 6 25

b) TRIGGER WITH AFTER UPDATE


SQL> create table orders30(order_id number(5),quantity number(4),cost_per_item number(6,2),
total_cost number(8,2));
Table created.
SQL> create table orders_audit(order_id number,quantity_before number,quantity_after number,
username varchar2(20));
Table created.
SQL> insert into orders30(order_id,quantity,cost_per_item) values(&order_id,&quantity,
&cost_per_item);
Enter value for order_id: 100
Enter value for quantity: 5
Enter value for cost_per_item: 10
old 1: insert into orders30(order_id,quantity,cost_per_item) values(&order_id,&quantity,
&cost_per_ item);
new 1: insert into orders30(order_id,quantity,cost_per_item) values(100,5,10)
1 row created.
SQL> /
Enter value for order_id: 101
Enter value for quantity: 4
Enter value for cost_per_item: 20
old 1: insert into orders30(order_id,quantity,cost_per_item) values(&order_id,&quantity,
&cost_per_ item);
new 1: insert into orders30(order_id,quantity,cost_per_item) values(101,4,20)
1 row created.
SQL> /
Enter value for order_id: 102
Enter value for quantity: 5
Enter value for cost_per_item: 30
old 1: insert into orders30(order_id,quantity,cost_per_item) values(&order_id,&quantity,
&cost_per_ item);
new 1: insert into orders30(order_id,quantity,cost_per_item) values(102,5,30)
1 row created.

TRIGGER SCRIPT
SQL> create or replace trigger orders_after_update
2 after update
3 on orders30
4 for each row
5 declare
6 v_username varchar2(10);
7 begin
8 select user into v_username
9 from dual;
10 insert into orders_audit
11 (order_id,
12 quantity_before,
13 quantity_after,
14 username)
15 values
16 (:new.order_id,
17 :old.quantity,
18 :new.quantity,
19 v_username);
20 end;
21 /
Trigger created.
SQL> update orders30 set quantity=25 where order_id=101;
1 row updated.

SQL> select *from orders_audit;


ORDER_ID QUANTITY_BEFORE QUANTITY_AFTER USERNAME
---------- --------------- -------------- ---------------------------------------------------------
101 4 25 CSE3090

RESULT :
Thus the PL/SQL program for implementing trigger is executed and the output was verified
successfully.
Ex.No.: 9 VIEW AND INDEX
Date :
AIM :
To write queries on views and indexes.

PROCEDURE :
A view is nothing more than a SQL statement that is stored in the database with an associated name.
A view is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one or
many tables which depends on the written SQL query to create a view.
Views, which are a type of virtual tables allow users to do the following −Structure data in a way that
users or classes of users find natural or intuitive.Restrict access to the data in such a way that a user can see
and (sometimes) modify exactly what they need and no more.Summarize data from various tables which can
be used to generate reports.

TABLE CREATION
SQL>create table customer(cname varchar(20),street varchar(20));
SQL>insert into customer values(‘ajay’,’north street’);
SQL>insert into customer values(‘godson’,’east street’);
SQL>insert into customer values(‘madhan’,’church street’);
SQL>insert into customer values(‘vijay’,’west street’);
SQL>select * from customer;
1. Create a view from single table containing all columns from the base table.
SQL>create view view1 as select * from customer;
SQL>select * from view1;
2. Create a view from single table with selected columns.
SQL>create view view2 as select cname,street from customer;
SQL>select * from view2;
TABLE CREATION
SQL>create table depositor(accno number,brname varchar(20));
SQL>insert into depositor values(101,’nazareth’);
SQL>insert into depositor values(102,’sattankulam’);
SQL>insert into depositor values(103,’mudhalur’);
SQL>select * from depositor;
SQL>create table account(accno number,cname varchar(20));
SQL>insert into account values(101,’ajay’);
SQL>insert into account values(102,’godson’);
SQL>insert into account values(105,’darwin’);
SQL>select * from account;
3. Create a view from two tables with selected columns.
SQL>create view xyz as select brname,cname from depositor d, account a where d.accno=a.accno;
SQL>select * from xyz;
TABLE CREATION
SQL>create table borrower(loanno number,brname varchar(20));
SQL>insert into borrower values(1001,’nazareth’);
SQL>insert into borrower values(1002,’sattankulam’);
SQL>insert into borrower values(1003,’mudhalur’);
SQL>select * from borrower;
SQL>create table loan(loanno number,cname varchar(20));
SQL>insert into loan values(1001,’ajay’);
SQL>insert into loan values(1002,’godson’);
SQL>insert into loan values(1005,’darwin’);
SQL>select * from account;
4. Create a view from two or more tables with union operator.
SQL> create view lmn as select brname,cname from depositor,account where depositor.accno=
account.accno union select brname,cname from borrower,loan where borrower.loanno=loan.loanno;
SQL> select * from lmn;
5.Create a view from another view.
SQL>create view view3 as select cname from xyz where brname=’nazareth’;
6. Check all DML commands with above views.
SQL> insert into view1 values (‘darwin’,’church street’);
1 row created;
SQL>update view1 set street=’main road’ where cname like ‘ajay’;
1 row updated.
Note: Update command does not works for all queries on views.
SQL>delete from view1 where cname like ‘godson’;
1 row deleted.
7. Drop view which you generated.
SQL>drop view view1;
View dropped;

SQL CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables. Indexes are used to retrieve data from
the database more quickly than otherwise. The users cannot see the indexes, they are just used to speed up
searches/queries.
TABLE CREATION
SQL>create table persons(firstname varchar(20),lastname varchar(20));
SQL>insert into persons values(‘ajay’,’kumar’);
SQL>insert into persons values(‘jenish’,’john’);
SQL>insert into persons values(‘god’,’son’);
Syntax :
SQL>CREATE INDEX index_name ON table_name (column1, column2, ...);
Example :
create index sp1 on persons ( firstname, lastname);
• When should indexes be created:
o A column contains a wide range of values.
o A column does not contain a large number of null values.
o One or more columns are frequently used together in a where clause or a join condition.
• When should indexes be avoided:
o The table is small
o The columns are not often used as a condition in the query
o The column is updated frequently
Confirming Indexes: You can check the different indexes present in a particular table given by the user or
the server itself and their uniqueness.
Syntax :
select * from USER_INDEXES;
It will show you all the indexes present in the server, in which you can locate your own tables
too.
Removing an Index: Remove an index from the data dictionary by using the DROP INDEX command.
Syntax :
DROP INDEX index;
DROP INDEX sp1;

RESULT :
Thus the program to implement view and indexes was studied and executed successfully.

Ex No.: 10 Create an XML database and validate it using XML schema


Date :
AIM :
To use Java based XSD validator to validate students.xml against the students.xsd.

DESCRIPTION :
An XML document with correct syntax is called "Well Formed".
Rules for well formed XML
• It must begin with the XML declaration.
• It must have one unique root element.
• All start tags of XML documents must match end tags.
• XML tags are case sensitive.
• All elements must be closed.
• All elements must be properly nested.
• All attributes values must be quoted.
• XML entities must be used for special characters.
To help you syntax-check your XML, we have created an XML validator. A "valid" XML document must be
well formed (satisfy all the basic syntax condition).

Steps to validate XML against XSD


• Copy the XSDValidator.java file to any location, say E: > java
• Copy the students.xml to same location E: > java
• Copy the students.xsd to same location E: > java.
• Compile XSDValidator.java using console. Make sure you have JDK 1.8 onwards
installed on your machine and classpaths are configured.
students.xml
<?xml version = "1.0"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
<nickname>Dinkar</nickname>
<marks>85</marks>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
<nickname>Vinni</nickname>
<marks>95</marks>
</student>
<student rollno = "593">
<firstname>Jasvir</firstname>
<lastname>Singh</lastname>
<nickname>Jazz</nickname>
<marks>90</marks>
</student>
</class>
Students.xsd
<?xml version = "1.0"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = 'class'>
<xs:complexType>
<xs:sequence>
<xs:element name = 'student' type = 'StudentType' minOccurs = '0'
maxOccurs = 'unbounded' />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "StudentType">
<xs:sequence>
<xs:element name = "firstname" type = "xs:string"/>
<xs:element name = "lastname" type = "xs:string"/>
<xs:element name = "nickname" type = "xs:string"/>
<xs:element name = "marks" type = "xs:positiveInteger"/>
</xs:sequence>
<xs:attribute name = 'rollno' type = 'xs:positiveInteger'/>
</xs:complexType>
</xs:schema>

XSDValidator.java
import java.io.File;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.xml.sax.SAXException;
public class XSDValidator {
public static void main(String[] args) {
if(args.length !=2){
System.out.println("Usage : XSDValidator <file-name.xsd> <file-name.xml>" );
} else {
boolean isValid = validateXMLSchema(args[0],args[1]);
if(isValid){
System.out.println(args[1] + " is valid against " + args[0]);
} else {
System.out.println(args[1] + " is not valid against " + args[0]);
}
}
}
public static boolean validateXMLSchema(String xsdPath, String xmlPath){
try {
SchemaFactory factory =
SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = factory.newSchema(new File(xsdPath));
Validator validator = schema.newValidator();
validator.validate(new StreamSource(new File(xmlPath)));
} catch (IOException e){
System.out.println("Exception: "+e.getMessage());
return false;
}catch(SAXException e1){
System.out.println("SAX Exception: "+e1.getMessage());
return false;
}
return true;
}
}
Output :

RESULT :
Thus the Create an XML database and validate it using XML schema was executed successfully.

You might also like