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

DBMS RECORD

The document outlines various SQL operations including DDL and DML commands, focusing on creating and manipulating tables such as 'emp', 'student', and 'books'. It details the use of constraints, selection commands, and PL/SQL programming structures for tasks like finding prime numbers. Each section includes algorithms, SQL queries, and results of executed commands, demonstrating successful implementation of database operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

DBMS RECORD

The document outlines various SQL operations including DDL and DML commands, focusing on creating and manipulating tables such as 'emp', 'student', and 'books'. It details the use of constraints, selection commands, and PL/SQL programming structures for tasks like finding prime numbers. Each section includes algorithms, SQL queries, and results of executed commands, demonstrating successful implementation of database operations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 88

EXP: NO: 01

DATE: 24/08/23 DDL Operations without Constraints

AIM

To create a table called "emp" with necessary columns and then perform the DDL
Operations without Constraints.

EmpNo, EmpName, DOB, Salary, Designation

Algorithm

➢ Create table named as Emp with the required columns.

➢ Alter the table column values.

➢ Delete the created table Emp.

➢ Using the select query view the records.

Queries
1.1 Create table

CREATE TABLE emp

(
empno NUMBER,
empname VARCHAR2(25),
dob DATE,
salary NUMBER,
designation VARCHAR2(20)
);

The EmpNo column and Salary is of type number and will hold a Employee number and
Salary of an Employee.

The EmpName, Designation columns are of type varchar with a maximum length of 25
characters each.

Page |1
The empty "Emp" table will now look like this:

// Describe the table emp

DESC emp;
Alter table

a. ADD

// To alter the table emp by adding new attribute department

ALTER TABLE emp ADD department VARCHAR2(50);


DESC emp;

b. MODIFY

// To alter the table emp by modifying the size of the attribute department
ALTER TABLE emp MODIFY department VARCHAR2(100);

DESC emp;

c. DROP

// To alter the table emp by deleting the attribute department


ALTER TABLE emp DROP(department);
DESC emp;

d. RENAME

// To alter the table name by using rename keyword


ALTER TABLE emp RENAME TO emp1 ;

DESC emp1;

3. DROP

//To delete the table from the database

DROP TABLE emp1;


DESC emp1;

Page |2
OUTPUT

Page |3
Page |4
RESULT

The DDL queries are used successfully to create and delete the table in SQL.

Page |5
EXP: NO: 02
DDL Operations with Constraints
DATE: 24/08/23

AIM

To create a table called "emp" with necessary columns and then perform the DDL
Operations with Constraints.

Constraints Types

✓ NOT NULL
✓ UNIQUE
✓ PRIMARY KEY
✓ FOREIGN KEY
✓ CHECK
✓ DEFAULT

Algorithm

➢ Create table named as STUDENT with the required columns.

➢ Create table with its respective Constraints.

➢ Using CHECK query verify the data in the table.

➢ Using the select query view the records.

Queries
CREATE THE TABLE
// To create a table student

CREATE TABLE student

studentID NUMBER PRIMARY KEY, sname VARCHAR2(30) NOT NULL,


department CHAR(5), sem NUMBER, dob DATE, email_id VARCHAR2(20)
UNIQUE, college VARCHAR2(20) DEFAULT 'MEC'

);

// Describe the table student

Page |6
DESC student;

//To create a table exam

CREATE TABLE exam

examID NUMBER , studentID NUMBER REFERENCES student(studentID),


department CHAR(5) NOT NULL, mark1 NUMBER CHECK (mark1<=100 and
mark1>=0), mark2 NUMBER CHECK (mark2<=100 and mark2>=0), mark3
NUMBER CHECK (mark3<=100 and mark3>=0), mark4 NUMBER CHECK
(mark4<=100 and mark4>=0), mark5 NUMBER CHECK (mark5<=100 and
mark5>=0), total NUMBER, average NUMBER, grade CHAR(1)

);
//Describe the table exam

Desc Exam;

2. ALTER THE TABLE

A. ADD

//To alter the table student by adding new attribute address


ALTER TABLE student ADD address VARCHAR2(100);

DESC student;

//To alter the table student by adding new constraint to the examID attribute
ALTER TABLE exam CONSTRAINT pr PRIMARY KEY (examID);

B. MODIFY

//To alter the table student by modifying the size of the attribute address

ALTER TABLE student MODIFY address VARCHAR2(150);

DESC student;

C.DROP

Page |7
//To alter the table student by deleting the attribute address

ALTER TABLE student DROP(address);

DESC student;
D.RENAME

// To alter the table name by using rename keyword


ALTER TABLE student RENAME TO student1 ;

Table altered

DESC student1;

ALTER TABLE student1 RENAME TO student ;

• Table altered
3. DROP

// To delete the table from the database

DROP TABLE exam;

DESC exam;

Page |8
OUTPUT

Page |9
P a g e | 10
Result:

Thus all the above DDL SQL commands has been executed successfully and the output
was verified.

P a g e | 11
EXP: NO: 03
DML Operations
DATE: 31/08/23

AIM

To create a table named "BOOKS” with necessary columns and then perform the DML
Operations.

BookNo, BookName, Authname, publisher, year..

Algorithm

➢ Create table named as BOOKS with the required columns.


➢ Insert new rows into the table  Delete the specific rows in the table.
➢ Using the select query view the records.

DML Statements

➢ Insert into
➢ Update
➢ Delete

1. Insert into

The INSERT INTO statement is used to insert a new row in a table.

Two form of inserting a new record into the table


a. Direct Substitution
Insert into table_name values(value1, value2,value3, ……….);

b. Specific Column Insertion


Insert into table_name (columnane1, columnname2, columnname3, …..) values
(values1, value2,value3, ………) ;

c. Another form of insertion is Macro Substitution, this query is used to receive values at
runtime.

P a g e | 12
Insert into table_name (Columnname1, columnname2,…..)
values(&columnname1,&columnname2, ….);
2. Update
Update new data into an existing table

Syntax
UPDATE table_name SET column1=value, column2=value2,... WHERE
some_column=some_value;
3. Delete Query

The DELETE query is used to delete rows in a table.

Syntax

Delete from table_name where column1=somevalue;

Queries

1. Create table
SQL>Create table Books (
BookNo Number(5),
BookName varchar2(25),
AuthName varchar2(25),
Publisher varchar2(25),
Year Number(3) );
2. Insert
SQL>Insert into books values (101,‘Professional_C#’,‘Christian_Nagel’,
‘Tata’,2008);
- 1 row created

SQL>Insert into books (bookno,bookname,authname) values


(102,’Programming_in_C’, ‘Kanitkar’);
- 1 row created

SQL>Insert into books (BookNo, BookName, AuthName, Publisher, Year) values


(&BookNo, ’&BookName’, ’&AuthName’, ’&Publisher’, &year);
Enter BookNo : 103

P a g e | 13
Enter BookName : OOPs
Enter AuthName : Balagurusamy
Enter Publisher : Tata
Enter Year : 2009
- 1 row created

SQL>Select * from Books;


3.Update

SQL>Update books set publisher=”Tata” where bookno=102;

- 1 row updated

SQL>Update books set publisher=”Tata”, year=2010 where bookno=102;

- 1 row created

SQL>Select * from books;


4.Delete

SQL>Delete from books where bookno=103


- 1 row deleted
SQL>Select * from books;

➢ Query to delete all rows in the table

SQL>Delete from books;

- All rows deleted

SQL>Select * from books

No rows selected

P a g e | 14
OUTPUT

P a g e | 15
RESULT

The DML queries are used successfully to insert a new row, update existing value and
deleting a row in the table.

P a g e | 16
EXP: NO: 04
Data Query Projection SQL commands
DATE: 31/08/23

AIM

To perform Data Query Projection SQL commands in an existing table named


"Student" with necessary columns.

Algorithm

➢ Create table “Student” with the required columns.


➢ Insert new rows into the table
➢ Using the select query view the records in different ways.

Queries

CREATE TABLE student

(
studentID NUMBER PRIMARY KEY, sname VARCHAR2(30) NOT NULL,
department CHAR(5), sem NUMBER, email_id VARCHAR2(20) UNIQUE, college
VARCHAR2(20) DEFAULT 'MEC'
);
// Describe the table student
DESC student;
1. SELECT ALL COLUMNS

SELECT * FROM student;


2.SELECT MULTICOLUMN

SELECT sname, department, sem FROM student;

3.SELECTION WITH ALIAS COLUMN NAME

SELECT sname “Student_Name”,department,sem FROM student;

4.SELECTION WITH ARITHMETIC OPERATION

SELECT sname,department,sem+1 “sem” FROM student;

P a g e | 17
5.DISTINCT RECORD SELECTION

// To display the college of the student from the table student by avoiding repeated
values.

SELECT DISTINCT college FROM student;


6.SELECTION WITH CONCATENATION

SELECT sname||studentid FROM student;


7.SELECTION WITH WHERE CLAUSE

// To display the records from the table student who belongs to mec college.
SELECT * FROM student WHERE college='SKCET';

SELECT sname, department FROM student WHERE sem=4;

P a g e | 18
OUTPUT

P a g e | 19
P a g e | 20
Result:
Thus all the above Data Query Projection SQL commands has been executed
successfully and the output was verified.

P a g e | 21
EXP: NO: 05
Selection commands Operations
DATE: 07/09/23

AIM

To create a table named "STUDENT" with necessary columns and then perform the
Selection commands Operations.

Selection Commands

✓ Between…and
✓ In
✓ Not in
✓ Like
✓ Relational Operators
✓ Logical Operators

Queries

CREATE TABLE student

(
studentID NUMBER PRIMARY KEY, sname VARCHAR2(30) NOT NULL,
department CHAR(5), sem NUMBER, email_id VARCHAR2(20) UNIQUE, college
VARCHAR2(20) DEFAULT 'MEC'
);
// Describe the table student

DESC student;
1. SELECT ALL COLUMNS

SELECT * FROM student;

// To display the student id, student name and department of the student
whose the semester in between 4 and 8

P a g e | 22
SELECT studentid,sname,department FROM student WHERE sem BETWEEN 4 AND 8;

// To display the student id, student name and department of the student
whose in CSE and IT department

SELECT studentid,sname,department FROM student WHERE department IN (‘CSE’,’IT’);

// To display the student id, student name and department of the student whose
not in CSE department

SELECT studentid,sname,department FROM student WHERE department NOT IN ‘CSE’;

// To display the student id and student name of the student whose name starts letters
'U' from the table

student

SELECT studentid, sname FROM student WHERE sname LIKE 'U%';


// To display the student id and student name of the student whose name end with
'B' from the table student

SELECT studentid, sname FROM student WHERE sname LIKE '%B';

// To display the student id and student name of the student whose name has
letters 'el' from the table student
SELECT studentid, sname FROM student WHERE sname LIKE '%EL%';
// To display the student id, student name of the student whose the student id
greater than 2

SELECT studentid, sname FROM student WHERE studentid > 2;


// To display the student id, student name of the student whose the student id
greater than 105 and cse department

SELECT studentid, sname FROM student WHERE studentid > 2 AND


department=’IT’;

P a g e | 23
OUTPUT

P a g e | 24
P a g e | 25
Result:
Thus all the above Data Query Selection SQL commands has been executed
successfully and the output was verified

P a g e | 26
EXP: NO: 06
DATE: 07/09/23 PL/SQL

PL/SQL

➢ PL/SQL stands for Procedural Language extension of SQL.

➢ PL/SQL is a combination of SQL along with the procedural features of


programming languages.

Structure PL/SQL Program


DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;

Advantages of PL/SQL

• Block Structures: PL SQL consists of blocks of code, which can be nested


within each other.
• Procedural Language Capability: if else and loops statements
• Better Performance: PL SQL engine processes multiple SQL statements
simultaneously as a single block
• Error Handling

Syntax to declare a variable variable_name

datatype [NOT NULL := value ];

variable_name is the name of the variable.

• datatype is a valid PL/SQL datatype.


• NOT NULL is an optional specification on the variable.
• Each variable declaration is a separate statement and must be terminated by a
semicolon.
variable_name:= value;

P a g e | 27
Example
Declare
salary number(5);
Conditional Statement

IF THEN ELSE STATEMENT


IF condition THEN
statement 1;
ELSE statement
2;
END IF;
IF condition1 THEN
statement 1; statement 2;
ELSIF condtion2 THEN
statement 3; ELSE
statement 4;
END IF

Iterative Statement

There are three types of loops in PL/SQL:


• Simple Loop
• While Loop
• For Loop

Simple Loop
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;

While Loop WHILE


<condition>

LOOP statements;

P a g e | 28
END LOOP;

FOR Loop
FOR counter IN val1..val2
LOOP statements; END
LOOP;

val1 - Start integer value.



• val2 - End integer value.
1.Example PL/SQL Code (For Loop)

SQL> set serveroutput on


SQL> declare
2 begin
3 for i in 1..10
4 loop
5 dbms_output.put_line(to_char(i));
6 end loop;
7* end;
8/
2.Example PL/SQL Code (While Loop)

SQL> set serveroutput on


SQL> declare
2 i number:=0;
3 j number:=0;
4 begin
5 while i<=100 loop
6 j:=j+1;
7 i:=i+2;
8 end loop;
9 dbms_output.put_line(to_char(i));
10 end;
11 /

3.Example PL/SQL Code (For Loop – Exit)


SQL> set serveroutput on
SQL> declare
2 a number:=100;

P a g e | 29
3 begin
4 loop
5 a:=a+25;
6 exit when a=250;
7 end loop;
8 dbms_output.put_line(to_char(a));
9 end;
10 /

P a g e | 30
OUTPUT-1:

OUTPUT-2:

P a g e | 31
OUTPUT-3:

Result:
Thus all the above Data Query Selection SQL commands has been executed
successfully and the output was verified

P a g e | 32
EXP: NO: 07
DATE: 09/09/23 PL/SQL find prime number

AIM
To write and execute a program in PL/SQL to find the prime number.

PL/SQL Code for Prime Number

SQL> set serveroutput on

SQL> declare
2 no number(3):=&no;
3 a number(4);
4 b number(2);
5 begin
6 for i in 2..no-1
7 loop
8 a:=no MOD i;
9 if a=0
10 then
11 GOTO out;
12 end if;
13 end loop;
14 <<out>>
15 if a=1
16 then
17 dbms_output.put_line(no||'is a prime');
18 else
19 dbms_output.put_line(no||'is not a prime');
20 end if;
21* end;
22 /

P a g e | 33
OUTPUT:

RESULT

Thus the program to find the given number is prime or not was executed successfully.

P a g e | 34
EXP: NO: 08
DATE: 09/09/23 PL/SQL to Add two numbers

AIM
To write and execute a program in PL/SQL to Add two numbers.

PL/SQL Code for Addition of two Numbers

SQL> set serveroutput on


SQL> declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=a+b;
9 dbms_output.put_line('sum of'||a||'and'||b||'is'||c);
10 end;
11 /

P a g e | 35
OUTPUT:

RESULT

Thus the program to Add two Numbers was executed successfully.

P a g e | 36
EXP: NO: 09
DATE: 14/09/23 PL/SQL to Find greatest among two numbers

AIM
To write and execute a program in PL/SQL to Find greatest among two numbers.

PL/SQL Code to find greatest among three numbers

SQL> set serveroutput on


SQL> declare
2 a number;
3 b number;
4 c number;
5 d number;
6 begin
7 dbms_output.put_line('enter a:');
8 a:=&a;
9 dbms_output.put_line('enter b:');
10 b:=&b;
11 dbms_output.put_line('enter c:');
12 c:=&b;
13 if(a>b)and(a>c) then
14 dbms_output.put_line('A is maximum');
15 elsif(b>a)and(b>c)then
16 dbms_output.put_line('B is maximum');
17 else
18 dbms_output.put_line('C is maximum');
19 end if;
20* end;
21 /

P a g e | 37
OUTPUT:

RESULT

Thus the program to find greatest among three numbers was executed successfully.

P a g e | 38
EXP: NO: 10
Reverse a given number
DATE: 14/09/23

AIM
To write a program to reverse a given number.

PL/SQL Code to Reverse a Number

SQL> set serveroutput on


SQL> declare
2 given_number varchar(5):='1234';
3 str_length number(2);
4 inverted_number varchar(5);
5 begin
6 str_length:=length(given_number);
7 for cntr in reverse 1..str_length
8 loop
9 inverted_number:=inverted_number||substr(given_number,cntr,1);
10 end loop;
11 dbms_output.put_line('the given no is'||given_number);
12 dbms_output.put_line('the inverted number is'|| inverted_number);
13 end;
14 /

P a g e | 39
OUTPUT:

RESULT
Thus the program to Reverse a Number was executed Successfully

P a g e | 40
EXP: NO: 11
DATE: 16/09/23 Sum of odd numbers

AIM
To write a program to calculate the sum of odd numbers.

PL/SQL Code to calculate Sum of ODD Number


SQL> set serveroutput on
SQL> declare
2 n number;
3 sum1 number default 0;
4 endvalue number;
5 begin
6 endvalue:=&endvalue;
7 n:=1;
8 for n in 1..endvalue
9 loop
10 if mod(n,2)=1
11 then
12 sum1:=sum1+n;
13 end if;
14 end loop;
15 dbms_output.put_line('sum ='||sum1);
16 *end;
SQL> /

P a g e | 41
OUTPUT:

RESULT

Thus the program to calculate the sum of odd number was executed successfully.

P a g e | 42
EXP: NO: 12
DATE: 16/09/23 Net pay

AIM
To write a program to calculate the Net pay.

PL/SQL code to calculate the Net Pay


SQL> set serveroutput on
SQL> declare
2 ename varchar2(15);
3 basic number;
4 da number;
5 hra number;
6 pf number;
7 netsalary number;
8 begin
9 ename:=&ename;
10 basic:=&basic;
11 da:=basic*(41/100);
12 hra:=basic*(15/100);
13 if(basic<3000)
14 then
15 pf:=basic*(5/100);
16 elsif(basic>=3000 and basic<=5000)
17 then
18 pf:=basic*(7/100);
19 elsif(basic>=5000 and basic<=8000)
20 then
21 pf:=basic*(8/100);
22 else
23 pf:=basic*(10/100);
24 end if;
25 netsalary:=basic+da+hra-pf;
26 dbms_output.put_line('employee name:'||ename);
27 dbms_output.put_line('providend fund:'||pf);
28 dbms_output.put_line('net salary:'||netsalary);
29 *end;

P a g e | 43
30 /
OUTPUT:

RESULT
Thus the program to calculate the Net Pay was executed successfully

P a g e | 44
EXP: NO: 13
DATE: 21/09/23 Calculate area and record values

AIM
To write a program to calculate the area and to record the values.

Program to Calculate the Area and Recording the values


SQL> set serveroutput on
SQL> declare
2 pi constant number(4,2):=3.14;
3 radius number(5);
4 area number(14,2);
5 begin
6 radius:=3;
7 while radius<=7
8 loop
9 area:=pi*power(radius,2);
10 insert into areas values(radius,area);
11 radius:=radius+1;
12 end loop;
13 end;
14 /

P a g e | 45
OUTPUT:

RESULT
Thus the program to Calculate the Area and Recording the values was executed
successfully.

P a g e | 46
EXP: NO: 14
DATE: 21/09/23 Cursor program

AIM
To access the tables using the Cursor program.

SQL> create table student(cname varchar2(20),sal number);

Table created.

SQL> desc student;


SQL> insert into student(cname,sal) values('&cname',&sal);
SQL> select * from student;
SQL> set serveroutput on;
SQL> declare
2 cursor emp_cur is select cname,sal from ssss;
3 name ssss.cname%type;
4 salary ssss.sal%type;
5 begin
6 open emp_cur;
7 dbms_output.put_line('name salary');
8 dbms_output.put_line('-----------');
9 loop
10 fetch emp_cur into name,salary;
11 exit when(emp_cur%notfound);
12 dbms_output.put_line(name||' '||salary);
13 end loop;
14 close emp_cur;
15 end;
16 /
SQL> CREATE OR REPLACE FUNCTION FIND
2 (cnam in varchar2)
3 RETURN number
4 is
5 cid number;
6 cursor c1

P a g e | 47
7 is
8 select cno from ttt where cname=cnam;
9 begin
10 open c1;
11 fetch c1 into cid;
12 if c1%notfound then
13 cid:=9999;
14 end if;
15 close c1;
16 return cid;
17 end; 18 /
Function created.

SQL> select * from ttt;


CNO CNAME MARK
---------- ------------- ----------
1 cts 99
2 tcs 55
3 ibm 89

SQL> select FIND('tcs') from dual;


FIND('TCS')
-----------
2
SQL> select FIND('ibm') from dual;
FIND('IBM')
-----------
3
SQL> select FIND('hcl') from dual;
FIND('HCL')
-----------
9999

P a g e | 48
OUTPUT:

P a g e | 49
RESULT
Thus the program for cursor was created in PL/SQL and executed successfully.

P a g e | 50
EXP: NO: 15
DATE: 05/10/23 Package in PL/SQL

AIM

To create a package in PL/SQL.

PACKAGE
Creating a Package:
SQL> create or replace package emp_objects
2 as
3 cursor emp_list return employee1%rowtype;
4 function seniors(dept in varchar2) return varchar2;
5 procedure high_sal(dept in number, eno out empl.eno%type, ename out
empl.name%type);
6 end; 7 /
Package created.
Creating a Package Body
SQL> create or replace package body emp_objects as
2 cursor emp_list return employee1%rowtype is select * from employee1;
3 function seniors(dept in varchar2) return varchar2 is
4 cursor a is select * from employee1 where dt_join=(select min(dt_join) from
employee1 where deptid=dept); 5 a_var a%rowtype;
6 begin
7 open a;
8 fetch a into a_var;
9 if a%notfound then
10 return' No employees in the dept.';
11 else
12 return a_var.empno||','||a_var.name;
13 end if;
14 end;
15 procedure high_sal(dept in number, eno out empl.eno%type, ename out
empl.name%type) is
16 cursor a is select eno, name from empl where basic=(select max(basic) from empl
where deptno=dept);
17 begin
18 open a;
19 fetch a into eno, ename;

P a g e | 51
20 close a;
21 end;
22 end emp_objects;
23 /
Package body created.
Calling the Package
declare
eno employee1.empno%type;
ename
employee1.name%type; a_var
employee1%rowtype; name
varchar2(30); begin
for c in emp_objects.emp_list loop
emp_objects.high_sal(a_var.deptid, eno, ename);
dbms_output.put_line(a_var.deptid||' '||eno||'
'||ename); end loop;
for a1 in (select dept from departments)
loop
name:=senior(a1.dept);
dbms_output.put_line(a1.dept||' '||name);
end loop;
end;
/
SQL> @ packfunc;
d1 102,kenneth d2
101,erich d3
105,clive
d4 106,robin

PL/SQL procedure successfully completed.

RESULT
Thus the package was created in PL/SQL and executed successfully.

P a g e | 52
EXP: NO: 16
DATE: 12/10/23 PL/SQL to implement the Trigger

AIM
To write a program in PL/SQL to implement the Trigger.
TRIGGER
TRIGGER WITH BEFORE UPDATE
Create Table
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.
Inserting Records
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

P a g e | 53
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;

P a g e | 54
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

TRIGGER WITH AFTER UPDATE


Create Table

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.

Inserting Records
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_
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

P a g e | 55
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_
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_
new 1: insert into orders30(order_id,quantity,cost_per_item) values(102,5,30)

1 row created.

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);

P a g e | 56
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 trigger was created in PL/SQL and executed successfully.

P a g e | 57
EXP: NO: 17
DATE: 14/10/23 PL/SQL to implement the Exception concept

AIM
To write the program in PL/SQL to implement the Exception concept.

EXCEPTIONS

Pre-defined Exception:
declare
ename employee.ename%type;
begin select ename into ename from
employee;
dbms_output.put_line('Employee
Name'); exception
when too_many_rows then
dbms_output.put_line('Multiple rows assigned to a single
variable'); end;
/
SQL> @ build_excep;
Multiple rows assigned to a single variable

PL/SQL procedure successfully completed.

User-Define Exception :
Checking the Integrity Constraing Violation:
declare
not_null_vio exception;
pragma exception_init(not_null_vio,-
1400); ename varchar2(15); dept
varchar2(5); designation varchar2(10);
basic number(8,2); begin

P a g e | 58
ename:='&emp_name';
dept:='&department';
designation:='&designation';
basic:=&basic; insert into
employee
(ename,dept,designation,basic)
values(ename,dept,designation,basic);
exception
when not_null_vio then dbms_output.put_line('Violation of Integrity constraint-not
null value needed!!!');
end;
/
SQL> @ excep;

Enter value for emp_name: aruna


old 9: ename:='&emp_name';
new 9: ename:='aruna'; Enter
value for department: 103 old
10: dept:='&department'; new
10: dept:='103';
Enter value for designation: leader
old 11:
designation:='&designation'; new
11: designation:='leader'; Enter
value for basic: 30000 old 12:
basic:=&basic; new 12:
basic:=30000;
Violation of Integrity constraint-not null value needed!!!
PL/SQL procedure successfully completed.

Comparing Employees Designation:


declare
incorrect_desig exception; new_desig
employee.designation%type;
begin
new_desig:= '&new_desig'; if
new_desig not in('analyst','leader') then
raise incorrect_desig;

P a g e | 59
end if; exception when incorrect_desig then
dbms_output.put_line('You have entered the wrong
designation'); dbms_output.put_line('Valid values are
analyst, leader'); dbms_output.put_line(to_char(sqlcode));
dbms_output.put_line(sqlerrm); end;
/
Enter value for new_desig: manager
old 5: new_desig:= '&new_desig';
new 5: new_desig:= 'manager'; You
have entered the wrong designation
Valid values are analyst, leader
1
User-Defined Exception

PL/SQL procedure successfully completed.

RESULT

Thus exception was created in PL/SQL and executed successfully.

P a g e | 60
EXP: NO: 18
DATE: 19/10/23 Aggregate Functions

AIM

To create a table named "Employee" with necessary columns and then perform
the Aggregate Functions.

Types

Order By
Group By
Aggregate Functions

SQL> select * from cust;


ORDER BY
========
SQL> select cname from cust order by cname desc;
SQL> select cname,caccno,cbalance from cust order by cbalance desc,cname asc;
GROUP BY
=========
SQL> select max(cbalance),cacctype from cust group by cacctype;
AGGREGATE FUNCTIONS
SQL> select count(*) from cust;
SQL> select count(distinct cname) from cust;
SQL>select sum(cbalance) as totbal,avg(cbalance) as average from cust where
cacctype='savings';
SQL> select max(cbalance),min(cbalance) from cust;

P a g e | 61
OUTPUT

P a g e | 62
RESULT
Thus the queries for Aggregate functions are executed successfully.

P a g e | 63
EXP: NO: 19
DATE: 26/10/23 Extract Data from Multiple Tables using SQL Joins

AIM

To extract Data from Multiple Tables using SQL Joins.


Joins
Joins help in extracting data from two or more tables based on some condition
specified in the WHERE clause.
Different kinds of Joins
✓ Self Joins
✓ Cartesian Products
✓ Equi-Joins
✓ Outer Joins

Self Join
A self join is a join of a table to itself. The same table appear twice after the
FROM clause.

Cartesian Product
If in the joins statement you forget to put the WHERE condition or intentionally
don’t write the WHERE clause at all, the result will be Cartesian product

Equi-Join
Equi comes because of the use of Equal sign (=) in the join condition.
The query containing Equijoin will give you total number of records equal to
or less than the number of records of the one table among all the tables in the query,
having least number of records in it.

// Table Creation - cseitstudent


CREATE TABLE cseitstudent
(
studentID NUMBER PRIMARY KEY, sname
VARCHAR(30),
department CHAR(5), sem NUMBER
);

P a g e | 64
// Table Creation - placement
CREATE TABLE placement
(
PlacementID NUMBER PRIMARY KEY, StudentID NUMBER,
department CHAR(5), Company VARCHAR2(30), salary NUMBER
);

// Display the values in the table as rows

SELECT * FROM cseitstudent;

SELECT * FROM placement;

// INNER JOIN

SELECT * FROM cseitstudent INNER JOIN Placement ON


cseitstudent.studentID=placement.StudentID;

//LEFT OUTER JOIN


SELECT * FROM cseitstudent LEFT OUTER JOIN placement ON
cseitstudent.studentID=placement.studentID;

SELECT cseitstudent.sname,placement.placementID, placement.company


FROM cseitstudent
LEFT OUTER JOIN placement
ON cseitstudent.studentID=placement.studentID;
//RIGHT OUTER JOIN

SELECT *
FROM cseitstudent
RIGHT OUTER JOIN placement
ON cseitstudent.studentID=placement.studentID;
SELECT cseitstudent.sname,placement.placementID, placement.company
FROM cseitstudent RIGHT OUTER JOIN placement
ON cseitstudent.studentID = placement.studentID;
//FULL OUTER JOIN

P a g e | 65
SELECT * FROM cseitstudent
FULL OUTER JOIN placement
ON cseitstudent.studentID=placement.studentID;
SELECT cseitstudent.sname,placement.placementID, placement.company FROM
cseitstudent

FULL OUTER JOIN placement


ON cseitstudent.studentID=placement.studentID;
//SELF JOIN

Returns rows by comparing the values of the same table.

//TABLE CREATION

CREATE TABLE employee


(
empid NUMBER, empname VARCHAR2(25), reportingid NUMBER
);

//DISPLAYS VALUES IN THE TABLE

Select * from employee;


SELECT e1.empid, e1.empname, e2.empname AS HeadName
FROM employee e1, employee e2
WHERE e1.reportingid=e2.empid;

//EQUI JOIN

SELECT * FROM cseitstudent, placement WHERE


cseitstudent.studentID=placement.studentID;

// NON EQUI JOIN

SELECT cseit.studentID, cseit.sname FROM cseitstudent cseit, placement placed


WHERE cseit.studentID>placed.studentID;

P a g e | 66
OUTPUT

P a g e | 67
P a g e | 68
Result:

Thus all the above Joins SQL commands has been executed successfully and
the output was verified.

P a g e | 69
EXP: NO: 20
Subquery and Nested Subqueries
DATE: 02/11/23

AIM
To create table and to perform subquery and nested subqueries.

//Create a table employee1

CREATE TABLE employee1


(
empno NUMBER, empname VARCHAR2(255), salary NUMBER,
designation
VARCHAR2(20)
);

SELECT * FROM employee1 WHERE designation =


(SELECT designation FROM employee1 WHERE empname='RAJESH');
SELECT * FROM employee1 WHERE salary <
(SELECT salary FROM employee1 WHERE empname='SIVA');
SELECT studentID, sname FROM cseitstudent WHERE studentID IN
(SELECT studentID FROM placement);
SELECT studentID, sname FROM cseitstudent WHERE studentID NOT IN (SELECT
studentID FROM placement);
SELECT studentID, company, salary FROM placement WHERE SALARY < SOME
(23000, 28000);

// EXISTS

SELECT * FROM placement WHERE EXISTS (


SELECT * FROM placement WHERE salary>20000);
// NOT EXISTS

SELECT * FROM employee1 WHERE


NOT EXISTS (SELECT * FROM employee1 WHERE salary>20000 );

P a g e | 70
OUTPUT

P a g e | 71
Result:
Thus all the above SQL nested queries has been executed successfully and the
output was verified.

P a g e | 72
EXP: NO: 21
DATE: 04/11/23 Set Operations

AIM
To create tables named "Author" and “Publisher” with necessary columns and
then to perform Set operations.

Set Operations
The set operations union, intersect, and except operate on relations and
correspond to the relational algebra operations È, Ç, -.
Each of the above operations automatically eliminates duplicates.

CREATE TABLE student


(
studentID NUMBER PRIMARY KEY, sname VARCHAR2(30) NOT NULL,
department CHAR(5), sem NUMBER, email_id VARCHAR2(20) UNIQUE, college
VARCHAR2(20)
DEFAULT 'MEC'
);
// View the table student

Select * from student;


// Consider the tables Student

CREATE TABLE exam


(
examID NUMBER, studentID NUMBER REFERENCES student(studentID),
department CHAR(5) NOT NULL, mark1 NUMBER CHECK (mark1<=100 and
mark1>=0), mark2 NUMBER CHECK (mark2<=100 and mark2>=0), mark3
NUMBER CHECK (mark3<=100 and mark3>=0), mark4 NUMBER CHECK
(mark4<=100 and mark4>=0), mark5 NUMBER CHECK (mark5<=100 and
mark5>=0), total NUMBER, average NUMBER, grade CHAR(1)

);

P a g e | 73
Select * from exam;
// To display student id using union - displays all values without duplicates from
student and exam

SELECT studentid FROM student


UNION
SELECT studentid FROM exam;
// To display student id using union all - displays all values with duplicates from
student and exam

SELECT studentid FROM student UNION ALL SELECT studentid FROM exam;

// To display student id using intersect - displays common values in both the


tables without duplicates from student and exam

SELECT studentid FROM student

INTERSECT
SELECT studentid FROM exam;
// To display student id using minus - displays the values that minus the student
id of student from exam

SELECT studentid FROM student


MINUS
SELECT studentid FROM exam;

STUDENTID

102

P a g e | 74
OUTPUT

P a g e | 75
Result:
Thus all the above SQL Set Operation queries has been executed successfully and
the output was verified.

P a g e | 76
EXP: NO: 22
DATE: 09/11/23 View table with necessary columns

AIM

To create a view for a table named “BookView” with necessary columns.

1)View Creation:

SQL> create view bookview(title,author,publisher,price) as select title, author,


publisher, price from book;

View created.
SQL> select * from bookview;
SQL> create view bookv (title, author, price) as select title, author, price from book
where price between 100 and 300; View created.
SQL> select * from bookv;
2)Record Insertion:
SQL> insert into bookv (title,author,price) values('&title','&author',&price);
SQL> select * from bookv;
SQL> select * from bookview;
3)Record Deletion:
SQL> delete from bookview where
author='kumar'; 1 row deleted.
SQL> delete from bookview where publisher='TATA';
1 rows deleted.
SQL> select * from bookview;
4)View Deletion:
SQL> drop view bookv; View
dropped.
SQL> select * from bookv;
select * from bookv

P a g e | 77
OUTPUT

P a g e | 78
RESULT
Thus a view was created for a table and some operations are done with the help of
view on the table.

P a g e | 79
EXP: NO: 23
DATE: 16/11/23 STUDENT INFORMATION SYSTEM

AIM

To create a table and to report student information system.


Query
//Table creation

CREATE TABLE exam


(
id NUMBER, name VARCHAR2(15), gen VARCHAR2(6), dep VARCHAR2(10),
yr NUMBER, sems VARCHAR2(10), sub1 NUMBER, sub2 NUMBER, sub3
NUMBER, tot NUMBER, cg NUMBER, rest VARCHAR2(10)
);
//Form design
//Code
using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data;
using System.Drawing; using System.Linq; using System.Text;
using System.Windows.Forms; using Oracle.DataAccess.Client; namespace exam
{
public partial class Form1 : Form
{
OracleConnection conn = new OracleConnection("Data Source=XE;User
Id=system;Password=password;");
OracleCommand cmd;
public Form1()
{
InitializeComponent();

private void Form1_Load(object sender, EventArgs e)

P a g e | 80
{

dept.Items.Add("IT");
dept.Items.Add("CSE");
dept.Items.Add("ECE");
dept.Items.Add("EEE");
dept.Items.Add("MECH");
sem.Items.Add("I");
sem.Items.Add("II");
sem.Items.Add("III");
sem.Items.Add("IV");
sem.Items.Add("V");
sem.Items.Add("VI");
sem.Items.Add("VII");
sem.Items.Add("VIII");
year.Items.Add("1");
year.Items.Add("2");
year.Items.Add("3");
year.Items.Add("4");

}
private void save_Click(object sender, EventArgs e)
{ try
{
String g;
if (male.Checked ==
true) g = "male";
else
g="femal
e";
conn.Open();
cmd = new OracleCommand("Insert into

P a g e | 81
exam(id,name,gen,dep,yr,sems,sub1,sub2,sub3,tot,cg,rest) values('" +
regno.Text + "','" + name.Text + "','"+dept.Text+"','"+g+"','"+year.Text+"',
'"+sem.Text+"','"+m1.Text+"','"+m2.Text+"','"+m3.Text+"',
'"+total.Text+"','"+cgpa.Text+"','"+res.Text+"')", conn);

MessageBox.Show("Records Inserted
Successfully");
cmd.ExecuteNonQuery();
conn.Close();
}

catch (Exception ex)


{
MessageBox.Show(ex.Message);
}
}

private void select_Click(object sender, EventArgs e)


{
conn.Open();
cmd = new OracleCommand("select * from exam",
conn); OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["id"].ToString() == regno.Text)
{
string sname= dr["name"].ToString(); if
(dr["gen"].ToString() == "male")
Convert.ToBoolean(male.Checked =
true); else
Convert.ToBoolean(female.Checked =
true); string sdept= dr["dep"].ToString();
string syear= dr["yr"].ToString();

P a g e | 82
string ssem = dr["sems"].ToString(); string sm1 =
dr["sub1"].ToString(); string sm2=
dr["sub2"].ToString(); string sm3 =
dr["sub3"].ToString(); string stot= dr["tot"].ToString();
string scgpa = dr["cg"].ToString(); string sres=
dr["rest"].ToString(); name.Text = sname;
dept.Text=sdept;
year.Text=syear;
sem.Text=ssem;
m1.Text=sm1; m2.Text=sm2;
m3.Text=sm3; total.Text=stot;
cgpa.Text=scgpa; res.Text = sres;
}
} dr.Close();
cmd.Dispose();
conn.Dispose();
}
{
MessageBox.Show(ex.Message);
}
}

private void exit_Click(object sender, EventArgs e)


{ this.Close();
}

private void calc_Click(object sender, EventArgs e)


{
String rest;
int mar1, mar2, mar3, t; float c;
mar1 = int.Parse(m1.Text); mar2 =
int.Parse(m2.Text); mar3 = int.Parse(m3.Text); t =
mar1 +mar2 + mar3;

P a g e | 83
c = (t)/29 ;
if (mar1>=50 && mar2>=50 && mar3 >= 50)
rest = "Pass";
else
rest = "Fail"; total.Text =
t.ToString(); cgpa.Text =
c.ToString(); res.Text = rest;
}

private void report_Click(object sender, EventArgs e)


{
Form2 f=new Form2();
f.Show();
}
}
}

private void update_Click(object sender, EventArgs e)


{ try
{
conn.Open();
cmd = new OracleCommand(" UPDATE exam set name='" + name.Text + "'
WHERE id = '" + regno.Text + "'", conn);
MessageBox.Show("Records updated Successfully");
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

P a g e | 84
}

private void delete_Click(object sender, EventArgs e)


{
try
{
conn.Open();
cmd = new OracleCommand(" DELETE from exam WHERE id = '" +
regno.Text + "'", conn); MessageBox.Show("Records deleted Successfully");
cmd.ExecuteNonQuery();
conn.Close() }

//SELECT
//INSERT
//Select
//Delete
//Select
//Report

P a g e | 85
OUTPUT:

P a g e | 86
P a g e | 87
Result:
Thus the above Student Information System Application has been created
successfully using SQL queries and the output was verified.

P a g e | 88

You might also like