0% found this document useful (0 votes)
47 views91 pages

DBMS Lab Manual

Here are the key points about transaction control language (TCL) commands: - TCL commands are used to manage transactions in a database. Transactions allow multiple SQL statements to be executed together as a single unit. - COMMIT commits the changes made by the current transaction and makes them permanent in the database. - ROLLBACK rolls back or cancels the changes made by the current transaction and restores the database to its original pre-transaction state. - SAVEPOINT establishes a point inside a transaction to which we can roll back if needed. - RELEASE removes a previously established savepoint. Some examples: - Start a transaction: BEGIN WORK; - Commit the transaction:

Uploaded by

VETRI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views91 pages

DBMS Lab Manual

Here are the key points about transaction control language (TCL) commands: - TCL commands are used to manage transactions in a database. Transactions allow multiple SQL statements to be executed together as a single unit. - COMMIT commits the changes made by the current transaction and makes them permanent in the database. - ROLLBACK rolls back or cancels the changes made by the current transaction and restores the database to its original pre-transaction state. - SAVEPOINT establishes a point inside a transaction to which we can roll back if needed. - RELEASE removes a previously established savepoint. Some examples: - Start a transaction: BEGIN WORK; - Commit the transaction:

Uploaded by

VETRI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

SQL (STRUCTURED QUERY LANGUAGE):

SQL is a language for storing, manipulating and retrieving the data stored in a relational
database. It was one of the first commercial languages for Edgar F.Codd’s relational model. It
become a standard of the American National Standards Institute (ANSI) in 1986 and of the
International Organization for Standards (ISO) in 1987.
FACILITIES OF SQL:
• Defining views on the database.
• Specifying security and authorization.
• Defining integrity constraints.
• Specifying transaction controls.
SQL DATA TYPES:
DATA TYPE DESCRIPTION STORAGE
char(size) Fixed width character One byte per character
string. Maximum 8,000 allowed
characters
varchar(size) Variable width character One byte per
string. Maximum 8,000 character stored
characters
number(size) Number value with the Two bytes
maximum number of
digits specified in
parenthesis
date Stores year, month and Four bytes
day values. Default format
is DD-MON-YY.
float(n) Floating point to atleast N Four bytes
digits
time Stores Three bytes
hours:minutes:second
decimal A floating point number Five-Seventeen bytes
allows to specify the
maximum number and
how many digits after the
decimal place.
Ex. No. 1 DATA DEFINITION LANGUAGE

Aim:

To execute the data definition language commands.

Data Definition Language:(DDL)

It defines the database structure or schema.

CREATE:

It is used to create a table with necessary attributes.

SYNTAX:

create table tablename(columnname1 datatype,columnname2 datatype,….columnnamen


datatype);

Example:

create table student(name char(15),regno number(20));

DESC:

It is used to display the design of the table.

SYNTAX:

desc tablename;

EXAMPLE:

desc student;

ALTER:

It is used to modify the definition (structure) of a table in three ways:

1. Add
2. Modify
3. Drop
ADD:
It is used to add a column in a table.

SYNTAX:

alter table tablename add columnname datatype;


EXAMPLE:

alter table student add mark1 number(2);

alter table student add mark2 number(2);

alter table student add percentage number(2);

alter table student add city char(10);

MODIFY:

It is used to modify the datatype of a table.

SYNTAX:

alter table tablename modify columnname datatype;

EXAMPLE:

alter table student modify percentage float(2);

DROP:

It is used to delete a column in the table.

SYNTAX:

alter table tablename drop(columnname);

EXAMPLE:

alter table student drop city;

RENAME:

It is used to rename the tablename.

SYNTAX:

rename tablename to newtablename;

EXAMPLE:

rename student to student1;

TRUNCATE:

It is used to delete the records of the table;


SYNTAX:

truncate table tablename;

EXAMPLE:

truncate table student;

DROP:

It is used to delete the entire table.

SYNTAX:

drop table tablename;

EXAMPLE:

drop table student;

TABLE CREATION:

SQL> create table student(name char(30),registernumber number(12));

OUTPUT:

Table created.

ALTER(ADD):

SQL> alter table student add cgpa number(2);

OUTPUT: Table

altered.

ALTER(MODIFY):

SQL> alter table student modify cgpa float;

OUTPUT: Table

altered.

DESCRIPTION:

SQL> desc student;


OUTPUT:

Name Null? Type

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

NAME CHAR(30)

REGISTERNUMBER NUMBER(12)

CGPA FLOAT(126)

AGE NUMBER(2)

ALTER(DROP):

SQL> alter table student drop(age);

OUTPUT: Table

altered.

DESCRIPTION:

SQL> desc student;

OUTPUT:

Name Null? Type

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

NAME CHAR(30)

REGISTERNUMBER NUMBER(12)

CGPA FLOAT(126)

RENAME:

SQL> rename student to studentdetails;

OUTPUT:

Table renamed.

DROP:

SQL> truncate table studentdetails;

OUTPUT:
Table truncated.

DROP:

SQL> drop table studentdetails;

OUTPUT:

Table dropped.

Result:

Thus the Data Definition language Quries was performed and implemented
successfully.
Ex.No.2 D A T A M A NI P UL AT I O N L A NG U AG E

Aim:

To execute the data manipulation language commands.

Data Definition Language :( DDL)

DML enable users to access or manipulate data as organized by the appropriate data
model. The types of access are:

• Retrieval of information stored in the database.


• Insertion of new information in to the database.
• Deletion of new information from the database.
• Modification of information from the database.
INSERT:

It is used to insert a new data into the database.

SYNTAX:

insert into tablename values(value1,value2,….valuen);

Example:

insert into student values(‘Jeni’,25,100);

insert into student values(‘Anie’,27,75);

insert into student values(‘Anish’,28,87);

DELETE:

It is used to delete a record from the database based on the condition.

SYNTAX:

delete from tablename where condition;

Example:

delete from student where id=27;

UPDATE:

It is used to change the old data to the required new value.


SYNTAX:

updatetablename set columnname=value where condition;

Example:

updatestudent set marks=90 where id=28;

SELECT:

It is used to display a whole database or a particular column;

SYNTAX:

DISPLAY WHOLE DATABASE:

select * from tablename;

DISPLAY PARTICULAR COLUMN:

select columnname1,columnname2 from tablename;

Example:

select * from student;

select marks from student;

DATA MANIPULATION LANGUAGE:

TABLE CREATION:

SQL> create table accounts(customerid number,customername char(20),age number(2),balance


number,loanamount number);

OUTPUT: Table

created.

DESCRIPTION:

SQL> desc accounts;

OUTPUT:

Name Null? Type

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

CUSTOMERID NUMBER
CUSTOMERNAME CHAR(20)

AGE NUMBER(2)

BALANCE NUMBER

LOANAMOUNT NUMBER

INSERTION:

SQL> insert into accounts values(20,'sindu',18,1000,12000);

OUTPUT:

1 row created.

INSERTION:

SQL> insert into accounts values(21,'sneha',19,1200,1231);

OUTPUT:

1 row created.

INSERTION:

SQL> insert into accounts values(23,'swapna',19,100,10000);

OUTPUT:

1 row created.

INSERTION:

SQL> insert into accounts values(22,'ashish',18,10000,122000);

OUTPUT:

1 row created.

DISPLAY:

SQL> select * from accounts;

OUTPUT:

CUSTOMERID CUSTOMERNAME AGE BALANCE LOANAMOUNT

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

20 sindu 18 1000 12000


21 sneha 19 1200 1231

23 swapna 19 100 10000

22 ashish 18 10000 122000

DELETION:

SQL> delete from accounts where loanamount>10000;

OUTPUT:

2 rows deleted.

QUERY:

SQL> select * from accounts;

OUTPUT:

CUSTOMERID CUSTOMERNAME AGE BALANCE LOANAMOUNT

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

21 sneha 19 1200 1231

23 swapna 19 100 10000

UPDATION:

SQL> update accounts set customerid=25 where customerid=23;

OUTPUT:

1 row updated.

DISPLAY:

SQL> select * from accounts;

OUTPUT:

CUSTOMERID CUSTOMERNAME AGE BALANCE LOANAMOUNT

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

21 sneha 19 1200 1231

25 swapna 19 100 10000


DISPLAY:
SQL> select customerid,customername,loanamount from accounts;

OUTPUT:

CUSTOMERID CUSTOMERNAME LOANAMOUNT

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

21 sneha 1231

25 swapna 10000

Result:

Thus the Data Manipulation language Quries was performed and implemented
successfully.
Ex.No.3 T C L A N D DC L C O M M A N D S

Aim:
To execute the transaction control language and data control language commands.

TRANSACTION CONTROL LANGUAGE :( TCL)


Transaction Control Language (TCL) commands are used to manage transactions in
database. These are used to manage the changes made by DML statements. It also allows
statements to be grouped together into logical transactions.
COMMIT:
It allows a user to record the changes permanently into the database. Prior to the
execution of a COMMIT command, all changes made to the rows of a table are stored in a database
buffer or main memory. If the user quits the database before committing the changes, no data
will be written to the database files and the changes will be lost.
SYNTAX:
commit;
Example:
commit;
ROLLBACK:
It restores the database to last committed state. The changes made to a table have not
been committed; the user can cancel all the intermediate changes made to a table by issuing a
ROLLBACK statement.
SYNTAX:
rollback;
rollback to savepointname;
Example: rollback;
rollback to A;

A B C rollback;
a1 b1 c1
a2 b2 c2
a3 b3 c3

A B C
SAVEPOINT:
It allows the user to undo only a part of the current transaction by allowing the user to go
back to a particular point in time.
SYNTAX:
savepoint savepointname;
Example:
savepoint A;

A B C
a1 b1 c1
Savepoint A;
a2 b2 c2
a3 b3 c3

Insert new tuple

A B C
a1 b1 c1 Savepoint B;

a2 b2 c2
a3 b3 c3
a4 b4 c4

Delete first row

A B C
a2 b2 c2
Savepoint C;
a3 b3 c3
a4 b4 c4

A B C
a1 b1 c1
Rollback to A;
a2 b2 c2
a3 b3 c3
DATA CONTROL LANGUAGE (DCL):
DCL is used to create roles, permissions, and referential integrity as well it is used to
control access to database by securing it.
GRANT:
Gives user’s access privileges to database
SYNTAX:
GRANT (object privilege) on tablename to username;
EXAMPLE:
grant insert on account to A;
REVOKE :Withdraws user’s access privileges to database given with the GRANT command.
SYNTAX:
REVOKE (object privilege) on tablename from username;
EXAMPLE:
revoke select on accountdetails from A;
COMMENT:
It is used to create a comments about the table in the data dictionary.
SYNTAX:
comment on table tablename is ‘comment line’
EXAMPLE:

comment on table accountdetails is ‘accountbanking’;


Tansaction Control Language:
Table Creation:
SQL> create table pen(name char(10),id number(15));
Output:
Table created.
Query:
SQL> insert into pen values('fathima',10);
Output:
1 row created.
Query:
SQL> insert into pen values('noor',11);
Output:
1 row created.
Query:
SQL> rollback;
Output:
Rollback complete.
Query:
SQL> insert into pen values('shahtaj',13);
Output:
1 row created.
Query:
SQL> insert into pen values('sultana',14);
Output:
1 row created.
Query:
SQL>savepoint s1;
Output:
Savepoint created.
Query:
SQL> insert into pen values('manhar',15);
Output:
1 row created.
Query:
SQL> insert into pen values('parveen',16);
Output:
1 row created.
Query:
SQL>savepoint s2;
Output:
Savepoint created.
Query:
SQL> insert into pen values('ghosu',17);
Output:
1 row created.
Query:
SQL> select * from pen;
Output:
NAME ID
---------- ----------
shahtaj 13
sultana 14
manhar 15
parveen 16
ghosu 17
Query:
SQL> insert into pen values('reshu',18);
Output:
1 row created.
Query:
SQL> select * from pen;
Output:
NAME ID
---------- ----------
shahtaj 13
sultana 14
manhar 15
parveen 16
ghosu 17
reshu 18
6 rows selected.
Query:
SQL>savepoint s3;
Output:
Savepoint created.
Query:
SQL> select * from pen;
Output:
NAME ID
---------- ----------
shahtaj 13
sultana 14
manhar 15
parveen 16
ghosu 17
reshu 18
6 rows selected.
Query:
SQL> rollback to s2;
Output:
Rollback complete.
Query:
SQL> select * from pen;

Output:
NAME ID
---------- ----------

shahtaj 13

sultana 14

manhar 15

parveen 16

Query:

SQL> rollback to s1;

Output:
Rollback complete.

Query:

SQL> select * from pen;

Output:
NAME ID
---------- ----------

shahtaj 13

sultana 14

Query:

SQL> create table beauty(name char(13),id number(14));

Output:
Table created.
Query:

SQL>savepoint s1;

Output:

Savepoint created.

Query:

SQL> insert into beauty values('shetu',10);

Output:

1 row created.

Query:
SQL> insert into beauty values('mahe',20);

Output:

1 row created.

Query:

SQL>savepoint s2;

Output:

Savepoint created.

Query:

SQL> delete from beauty where id=10;

Output:

1 row deleted.

Query:

SQL> select * from beauty;

Output:

NAME ID

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

mahe 20

Query:

SQL> delete from beauty where id=20;

Output:
1 row deleted.

Query:

SQL> select * from beauty;

Output:

no rows selected

Query:

SQL> rollback to s2;

Output:

Rollback complete.

Query:

SQL> commit;

Output:

Commit complete.

Query:

SQL> rollback to s1;

Output:

rollback to s1
*
ERROR at line 1:

ORA-01086: savepoint 'S1' never established


ASSIGNING COMMENTS FOR TABLE
----------------------------------------------------
SQL> comment on table employee1 is 'EMPLOYEE DETAILS';
Comment created.
SQL> select comments from user_tab_comments;
COMMENTS
-------------------------------------------------------
EMPLOYEE DETAILS
ASSIGNING COMMENTS FOR COLUMN
---------------------------------------------------------
SQL> comment on column employee1.EMPLOYEE_NO is 'EMPLOYEE REGISTRATION
NUMBER';
Comment created.
SQL> select comments from USER_COL_COMMENTS;
COMMENTS
---------------------------------------------------------
EMPLOYEE REGISTRATION NUMBER
3 rows selected.

Result:

Thus the Transaction control language and Data Control language Quries was executed
and implemented successfully
Ex.No:4 OPERATORS IN SQL

Aim:
To execute and verify the operators in SQL.
OPERATORS:
Operators are used to perform an operation on the operands.
TYPES OF OPERATORS:
1. Arithmetic operators
2. Logical operators
3. Comparison operators
4. Null operators
5. In and Not in operators
6. Like operator
7. Range operator
8. Set operator
9. Join operator
Arithmetic operators
Operator Symbol: +,-,*, /
Description:
It is used to perform the arithmetic operations like addition,subtraction,multiplication and
division.
Syntax:
select columnname1,columnname2,……,columnnamen operator symbol numeric
value from tablename;
‘+’ Operator:
It is used to perform the addition operation.
Example:
select accountbal+250 from accountsdetails;
‘-’ Operator:
It is used to perform the subtraction operation.
Example:
select accountbal-1000 from accountsdetails;
‘*’ Operator:
Description:
It is used to perform the multiplication operation.
Example:
select accountbal*250 from accountsdetails;
‘/’ Operator:
It is used to perform the division operation.
Example:
select accountbal/3 from accountsdetails;
Logical operators
Operator Symbol: AND, OR, NOT
It is used to perform the logical operations like AND, OR, NOT.
Syntax:
select * from tablename where condition1 logical operator symbol condition2;
AND Operator:
Description:
It is used to display the records that satisfy all the condition specified.
Example:
select * from accountdetails where customerid=101 and customername= ‘Anish’;
OR Operator:
Description:
It is used to display the records that satisfy any one of the condition specified.
Example:
select * from accountdetails where customerid=101 or customername= ‘Anish’;
NOT Operator:
Description:
It is used to display the records that are not in the condition specified.
Example:
select * from accountdetails where not customername= ‘Anish’;
..
Comparison operators
Operator Symbol: =, !=, <, > ,<=, >=
Description:
It is used to compare the values which are equal, not equal, lesser than, greater than,
lesser than or equal to, greater than or equal to.
Syntax:
select * from tablename where columnname operator symbol value;
Equal to Operator (=):
It is used to check whether the given condition is equal or not.
Example:
select * from accountdetails where accountbal=25000;
Not Equal to Operator (! =):
It is used to check whether the condition specified is not equal.
Example:
select * from accountdetails where accountbal !=25000;
Greater than Operator (>):
It is used to check whether the given condition specified is greater or not.
Example:
select * from accountdetails where accountbal>25000;
Lesser than Operator(<):
It is used to check whether the given condition specified is lesser or not.
Example:
select * from accountdetails where accountbal<25000;
Greater than or equal to Operator(>=):
It is used to check whether the condition specified is greater than or equal to or not.
Example:
select * from accountdetails where accountbal>=25000;
Lesser than or equal to Operator(<=):
It is used to check whether the condition specified is lesser than or equal to or not.
Example:
select * from accountdetails where accountbal<=25000;
Null operators
Operator Symbol: isnull / isnotnull
Description:
It is used to display the records in which any one of the column is not null or null.
Syntax:
select columnname1,columnname2,……,columnnamen from tablename where
columnname NULL operator symbol;
ISNULL Operator:
It is used to display the records which have null column values in the table.
Example:
select * from accountdetails where phoneno is null;

ISNOTNULL Operator:
It is used to display the records which are not having null value in any of its column.
Example:
select * from accountdetails where phoneno is not null;
In and Not in operators
Operator Symbol: IN, NOTIN
Description:
It is used to display the records that are in the values specified or not.
Syntax:
select columnname1,columnname2,……columnnamen from tablename where
columnname operator symbol(value1,value2,………..valuen);
‘IN’ Operator:
It is used to display the records that are in the values specified.
Example:
select * from accountdetails where customerid in(101,103);
‘NOT IN’ Operator:
It is used to display the records that are not in the values specified.
Example:
select * from accountdetails where customerid notin(101,103);
Like operator
Operator Symbol:%, _(underscore)
Description:
It is used to search for a specified pattern in a column.
Syntax:
select * columnname1,columnname2 from tablename where columnname like
operator symbol;
The percent sign represents zero, one, or multiple characters. The underscore represents a
single number or character. The symbols can be used in combinations.
Example:

Statement Description

WHERE SALARY LIKE


Finds any values that start with 200
'200%'

WHERE SALARY LIKE


Finds any values that have 200 in any position
'%200%'

WHERE SALARY LIKE Finds any values that have 00 in the second and third
'_00%' positions

WHERE SALARY LIKE Finds any values that start with 2 and are at least 3
'2_%_%' characters in length

WHERE SALARY LIKE


Finds any values that end with 2
'%2'

WHERE SALARY LIKE Finds any values that have a 2 in the second position
'_2%3' and end with a 3

WHERE SALARY LIKE Finds any values in a five-digit number that start with
'2 3' 2 and end with 3

Range operator:
Operator Symbol: between…….and………
Description:
It is used to display the records that are in the given range.
Syntax:
select colunname1,columnname2 from tablename where columnname between
value1 and value2;
Example:
select * from accountdetails where customerid between 101 and 103;
Set Operator:
Operator Symbol: Union,Union all,intersection,set difference
Description:
It is used to display the records that are in the given set operator.
Syntax:
select columnname from tablename1 set operator symbol select columnname from
tablename2;
Union Operator:
It is used to combine the results of two or more Select statements. However it will eliminate
duplicate rows from its result set. In case of union, number of columns and datatype must be same
in both the tables.
Example:
select accountbal from accountdetails union select loanamount from loan;
Union All Operator:
It is used to display all the records of the column and also the duplicate records
Example:
select accountbal from accountdetails unionall select loanamount from loan;
Intersection Operator:
It is used to display the records that are common in both the tables.
Example:
select customerid from accountdetails intersect select customerid from loan;
Set Difference Operator:
It is used to return all rows in the first SELECT statement that are not returned in the
second SELECT statement.
Example:
select accountbal from accountdetails minus select balance from bankaccount;
CREATE:
Query:
SQL> create table account2(customerid number(13),customername char(18),customerage
number(20),balance number(12),loanamount number(16),phoneno number(16));
Output:
Table created.
INSERT:
Query:
SQL> insert into account2 values(2,'shatu',20,2000,500,676);
Output:
1 row created.
Query:
SQL> insert into account2 values(3,'sheza',15,3000,600,898);
Output:
1 row created.
Query:
SQL> insert into account2 values(4,'sameeha',16,4000,700,567);
Output:
1 row created.
Query:
SQL> insert into account2 values(5,'fathima',17,5000,800,543);
Output:
1 row created.
DISPLAY WHOLE DATABASE:
Query:
SQL> select * from account2;
Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT
PHONENO
---------- ------------------ ----------- ---------- ---------- ----------
2 shatu 20 2000 500 676
3 sheza 15 3000 600 898
4 sameeha16 4000 700 567
5 fathima17 5000 800 543
ARITHMETIC OPERATOR:
‘+’ operator:
Query:
SQL> select balance+250 from account2;
Output:
BALANCE+250
-----------
2250
3250
4250
5250
‘-‘ operator:
Query:
SQL> select balance-250 from account2;
Output:
BALANCE-250
-----------
1750
2750
3750
4750
‘*’ operator:
Query:
SQL> select balance*250 from account2;
Output:
BALANCE*250
-----------
500000
750000
1000000
1250000
‘/’ operator:
QUERY:
SQL> select balance/2 from account2;
OUTPUT:
BALANCE/2
-------------------------
1000
1500
2000
2500
LOGICAL OPERATOR:

AND Operator:

Query:

SQL> select * from account2 where customerid=3 and customername='sheza';

Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT PHONENO
---------- ------------------ ----------- ---------- ---------- ----------
3 sheza 15 3000 600 898
OR Operator:

Query:

SQL> select * from account2 where customerid=3 or customername='sheza';


Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT PHONENO
---------- ------------------ ----------- ---------- ---------- ----------
3 sheza 15 3000 600 898

Not Operator:

Query:

SQL> select * from account2 where not customername='sheza';

Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT PHONENO
---------- ------------------ ----------- ---------- ---------- ----------
2 shatu 20 2000 500 676

4 sameeha 16 4000 700 567

5 fathima 17 5000 800 543

COMPARISON OPERATOR:

Equal Operator(=):

Query:

SQL> select * from account2 where balance=2000;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu 20 2000 500 676

Not equal to operator(!=):

Query:

SQL> select * from account2 where balance!=2000;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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


3 sheza 15 3000 600 898

4 sameeha16 4000 700 567

5 fathima17 5000 800 543

Greator than operator(>):

Query:

SQL> select * from account2 where balance>3000;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

4 sameeha 16 4000 700 567

5 fathima17 5000 800 543

Lesser than operator(<):

Query:

SQL> select * from account2 where balance<5000;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu20 2000 500 676

3 sheza 15 3000 600 898

4 sameeha 16 4000 700 567

Greator than or equal to operator(>=):

Query:

SQL> select * from account2 where balance>=4000;

Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT
PHONENO

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

4 sameeha 16 4000 700 567

5 fathima17 5000 800 543

Lesser than or equal to operator(<=):

Query:

SQL> select * from account2 where balance<=4000;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu 20 2000 500 676

3 sheza 15 3000 600 898

4 sameeha16 4000 700 567

INSERT:

Query:

SQL> insert into account2 values(6,'shatu',18,6000,900,NULL);

Output:

1 row created.

NULL OPERATOR:

Is Null Operator:

Query:

SQL> select * from account2 where phoneno is null;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO
---------- ------------------ ----------- ---------- ---------- ----------

6 shatu 18 6000 900

Is Not Null Operator:

Query:

SQL> select * from account2 where phoneno is not null;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu 20 2000 500 676

3 sheza 15 3000 600 898

4 sameeha16 4000 700 567

5 fathima17 5000 800 543

DISPLAY WHOLE DATABASE:

Query:

SQL> select * from account2;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu20 2000 500 676

3 sheza15 3000 600 898

4 sameeha16 4000 700 567

5 fathima 17 5000 800 543

6 shatu18 6000 900

IN AND NOT OPERATOR:

In Operator:
Query:

SQL> select * from account2 where customerid in (2,4);

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu 20 2000 500 676

4 sameeha16 4000 700 567

Not In Operator:

Query:

SQL> select * from account2 where customerid not in (3,5);

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu 20 2000 500 676

4 sameeha16 4000 700 567

6 shatu 18 6000 900

DISPLAY WHOLE DATA BASE:

Query:

SQL> select * from account2;

Output:

CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT


PHONENO

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

2 shatu 20 2000 500 676

3 sheza 15 3000 600 898


4 sameeha16 4000 700 567

5 fathima17 5000 800 543

6 shatu 18 6000 900

LIKE OPERATOR:

Query:

SQL> select balance from account2 where balance like '2000%';

Output:

BALANCE

----------

2000

Query:

SQL> select loanamount from account2 where loanamount like '%800%';

Output:

LOANAMOUNT

----------

800

Query:

SQL> select balance from account2 where balance like ‘3_%_’;

Output:

BALANCE

---------

3000

Query:

SQL> select loanamount from account2 where loanamount like ‘%900’;

Output:

LOANAMOUNT
-------------------------

900

Query:

SQL>select balance from account2 where balance like ‘_0%0’;

Output:

BALANCE

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

2000

3000

4000

5000

6000

Query:

SQL>select loanamount from loanamount like ‘9_0’;

Output:

LOANAMOUNT

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

900

Query:

SQL>select balance from account where balance like ‘_00%’;

Output:

BALANCE

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

2000

3000

4000
5000

6000

RANGE OPERATOR:

Query:

SQL>select customerid from account2 where customerid between 2 and 6;

Output:

CUSTOMERID

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

CREATE:

Query:

SQL>create table from account3(customername char(12),customerid number(15),customerage


number(20));

Output:

Table created.

INSERT:

Query:

SQL>insert into account3 values(‘aaliyah’,6,20);

Output:

1 row inserted.

CREATE:

Query:
SQL>create table from account4(customername char(12),customerid number(15),customerage
number(20));

Output:

Table created.

INSERT:

Query:

SQL>insert into account4 values(‘aaliyah’,6,20);

Output:

1 row inserted.

SET OPERATORS:

Union operator:

Query:

SQL>select customer from account3 union select customername from account4;

Output:

CUSTOMERNAME

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

Aaliyah

Union all operator:

Query:

SQL>select customerid from account3 union all select customerid from account4;

Output:

CUSTOMERID

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

Intersection Operator:
Query:

SQL>select customerage from account3 intersect select customer from account4;

Output:

CUSTOMERAGE

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

20

Result:

Thus the operators in SQL was performed and implemented successfully.


Ex.No:5 VIEWS IN SQL

Aim:
To create a virtual table based on the result set of SQL commands.
VIEWS:
A view is an object that gives the user a logical view of data from the table.
VIEW COMMANDS:
• Create
• Insert
• Select
• Update
• Delete
• Drop
CREATE:
Creating view with one table:
It is used to create the view from only one table.
Syntax:
create view viewname as select columnname1,columnname2 from tablename;
Example:
create view v1 as select eid,ename,street from emp;
Creating view with more than one table:
It is used to create the view from more than one table.
Syntax:
create view viewname as select columnname1,columnname2 from tablename1,table
name2;
Example:
create view v2 as select eid,ename,street from emp,person;
INSERT:
It is used to insert a record into the view table and that should be updated in original
table.
Syntax:
insert into viewname values(value1,value2);
Example:
insert into v2 values(2,’Sam’,15000);
SELECT:
It is used to display the view table.
Syntax:
select * from viewname;
select columnname1,columnname2 from viewname;
Example:
select * from v1;
select eid,ename from v2;
UPDATE:
It is used to update the records in the view table.
Syntax:
update viewname set columnname=value where condition;
Example:
update v2 set salary=9000 where eid=1;
DELETE:
It is used to delete a record in view table.
Syntax:
delete from viewname where columnname=value;
Example:
delete from v2 where eid=5;
DROP:
It is used to drop a view.
Syntax:
drop view viewname;
Example:
drop view v2;
Creation of table
------------------------------
SQL> create table employee ( Employee_name varchar2(10),employee_nonumber(8),
dept_name varchar2(10),dept_no number (5),date_of_join date);

Table created.

Table description
-------------------------------

SQL> desc employee;


Name Null? Type
------------------------------- -------- ------------------------
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)
DATE_OF_JOIN DATE

Creation of view
------------------------------

SQL> create view empview as select


employee_name,employee_no,dept_name,dept_no,date_of_join from employee;

View created.

Description of view
------------------------------

SQL> desc empview;

Name Null? Type


----------------------------------------- -------- ----------------------------
EMPLOYEE_NAME VARCHAR2(10)
EMPLOYEE_NO NUMBER(8)
DEPT_NAME VARCHAR2(10)
DEPT_NO NUMBER(5)

SQL> select * from empview;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO


---------- ----------- ---------- ----------
Ravi 124 ECE 89
Vijay 345 CSE 21
Raj 98 IT 22
Giri 100 CSE 67
Modification
----------------------
SQL> insert into empview values ('Sri',120,'CSE',67,'16-nov-1981');

1 row created.

SQL> select * from empview;


EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO
---------- ----------- ---------- ----------
Ravi 124 ECE 89
Vijay 345 CSE 21
Raj 98 IT 22
Giri 100 CSE 67
Sri 120 CSE 67

SQL> select * from employee;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO DATE_OF_J


---------- ----------- ---------- ---------- ---------
Ravi 124 ECE 89 15-JUN-05
Vijay 345 CSE 21 21-JUN-06
Raj 98 IT 22 30-SEP-06
Giri 100 CSE 67 14-NOV-81
Sri 120 CSE 67 16-NOV-81

SQL> delete from empview where employee_name='Sri';

1 row deleted.

SQL> select * from empview;

EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO


---------- ----------- ---------- ----------
Ravi 124 ECE 89
Vijay 345 CSE 21
Raj 98 IT 22
Giri 100 CSE 67

SQL> update empkaviview set employee_name='kavi' where employee_name='ravi';

0 rows updated.

SQL> update empkaviview set employee_name='kavi' where employee_name='Ravi';

1 row updated.

SQL> select * from empkaviview;


EMPLOYEE_N EMPLOYEE_NO DEPT_NAME DEPT_NO
---------- ----------- ---------- ----------
kavi 124 ECE 89
Vijay 345 CSE 21
Raj 98 IT 22
Giri 100 CSE 67

SQL>drop view empview;

View droped

Result:

Thus the views in SQL was performed and implemented successfully.


Ex.No:6 INDEX IN SQL

Aim:

To create a lookup table to increase the data retrieval process.

Index:

Indexes are special lookup tables that the database search engine can use to speed up data
retrieval.It speed up SELECT queries and WHERE clauses, but it slows down data input, with
UPDATE and INSERT statements. Indexes can be created or dropped with no effect on the data.
Create index:
Creating an index involves the CREATE INDEX statement, which allows you to name
the index, to specify the table and which column or columns to index, and to indicate whether the
index is in ascending or descending order.Indexes can also be unique, similar to the UNIQUE
constraint, in that the index prevents duplicate entries in the column or combination of columns
on which there's an index.
Syntax:
create index indexname on tablename;
Single-Column Indexes:
A single-column index is one that is created based on only one table column.
Syntax:
create index indexname
on tablename (columnname);
Unique Indexes:
Unique indexes are used not only for performance, but also for data integrity. A unique
index does not allow any duplicate values to be inserted into the table.
Syntax:
create index indexname
on tablename (columnname);
Composite Indexes:
A composite index is an index on two or more columns of a table.
Syntax:
create index indexname
on tablename (column1, column2);
Implicit Indexes:
Implicit indexes are indexes that are automatically created by the database server when an object
is created.Indexes are automatically created for primary key constraints and unique constraints.
Drop index:
An index can be dropped using SQL DROP command..
Syntax:
drop index indexname;

Result:

Thus the index in SQL was performed and implemented successfully.


Ex.No:7 CONSTRAINTS IN SQL

Aim

To create a table and execute the different types of constraints.

CONSTRAINTS

Constraints in a property that we can assign to column in a table by assigning an


constraint.

Types of constraint

▪ Primary key
▪ Foreign key/references
▪ Check
▪ Unique
▪ Not null
▪ Default

Constraint Description and Syntax:


Primary key:
This constraint defines a column or combination of columns which uniquely identifies
each row in the table. It must not contain null value.
Syntax to define a Primary key at column level:
Create table <tablename>(col1 data type constraint <constraint_name> primary key,col2 data
type,…)
Eg:create table employee1(empid number(7),empname varchar(9),primary
key(empid,empname));
Syntax to define a Primary key at table level:
Create table <tablename>(col1 datatype ,col2 datatype,…constraint <constraint_name>
primary key (col1))
Eg: create table employee (empname varchar2(15),empid number(8) constraint emp_pkey
primary key,age number(7));
Foreign key or Referential Integrity:
It establishes a relationship between two columns in the same table or between different
tables. For a column to be defined as a Foreign Key, it should be a defined as a Primary Key in
the table which it is referring.
Syntax:
Create table <tablename>(col1 datatype ,col2 datatype,..coln datatype,
Foreign key(column_name) references <referenced_table_name>(column_name));
EG: create table cseemployee(empid number(7),name varchar(9),foreign key(empid)
references employee (empid));
Check Constraint:
This constraint defines a rule on a column. All the rows must satisfy this rule.
The constraint can be applied for a single column or a group of columns.
Syntax
Create table <tablename>(col1 datatype ,col2 datatype check(col2 in(predefined values),..coln
datatype);
Eg: create table employee(empid number(7),empname varchar2(15),gender varchar2(1)
check(gender in ('m','f')),mobile number(10));
Unique Key:
Description:
This constraint ensures that a column or a group of columns in each row have a distinct value. A
column(s) can have a null value but the values cannot be duplicated.
Syntax
Create table <tablename>(col1 datatype ,col2 datatype unique,..coln datatype);
Eg: create table employee3(empid number(7),empname varchar2(12) unique,address
varchar2(15));
Not Null Constraint:
This constraint ensures all rows in the table contain a definite value for the column which is
specified as not null. Which means a null value is not allowed.
Syntax :
Create table <tablename>(col1 datatype ,col2 datatype not null,..coln datatype);
Eg: create table employee4(empid number(5),empname varchar2(20) not null);
Default Constraint:
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
Syntax:
Create table <tablename>(col1 datatype ,col2 datatype default value,..coln datatype value);
Eg:create table employee5(empid number(7),sname varchar2(15),bonus number default 7);
Adding a constraint to already created table
Syntax:
ALTER TABLE tablename ADD Constraint_Type (Col_name)
Eg:alter table employee4 add primary key(empid);
Removing a constraint:
Syntax:
ALTER TABLE tablename DROP CONSTRAINT constraint_name
Eg: alter table emloyee drop constraint emp_pkey;
Constraint Disable \ Enable
Enable Constraint:
Syntax:
ALTER TABLE <TABLE-NAME> DISABLE CONSTRAINT <CONSTRAINT-NAME>
Eg: alter table emloyee enable constraint emp_pkey;
Disable Constraint:
Syntax:
ALTER TABLE <TABLE-NAME> DISABLE CONSTRAINT <CONSTRAINT-NAME>
Eg alter table emloyee disable constraint emp_pkey;

Result:

Thus constraints in SQL was performed and implemented successfully.


Ex.No:8 RELATIONSHIP BETWEEN THE DATABASE

Aim:
To create a relationship between the database.

Set Operation in SQL


SQL supports few Set operations to be performed on table data. These are used to get meaningful
results from data, under different special conditions.

Union
UNION is used to combine the results of two or more Select statements. However it will eliminate
duplicate rows from its result set. In case of union, number of columns and datatype must be same in
both the tables.

Example of UNION

The First table,


ID Name
1 abhi
2 adam
The Second table,
ID Name
2 adam
3 Chester
Union SQL query will be,
select * from First
UNION
select * from second
The result table will look like,
ID NAME
1 abhi
2 adam
3 Chester
Union All
This operation is similar to Union. But it also shows the duplicate rows.
Example of Union All
The First table,
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
Union All query will be like,
select * from First
UNION ALL
select * from second
The result table will look like,
ID NAME
1 abhi
2 adam
2 adam
3 Chester
Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the records which
are common from both SELECT statements. In case of Intersect the number of columns and datatype
must be same. MySQL does not support INTERSECT operator.

Example of Intersect
The First table,
ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
Intersect query will be,
select * from First
INTERSECT
select * from second
The result table will look like
ID NAME
2 adam
Set Difference (Minus)
Minus operation combines result of two Select statements and return only those result which
belongs to first set of result. MySQL does not support INTERSECT operator.

Example of Minus

The First table,


ID NAME
1 abhi
2 adam
The Second table,
ID NAME
2 adam
3 Chester
Minus query will be,
select * from First
MINUS
select * from second
The result table will look like,
ID NAME
1 abhi

JOIN
The JOIN keyword is used in an SQL statement to query data from two or more tables,
based on a relationship between certain columns in these tables.
Tables in a database are often related to each other with keys.
A primary key is a column (or a combination of columns) with a unique value for each
row. Each primary key value must be unique within the table. The purpose is to bind data together,
across tables, without repeating all of the data in every table.
"Persons" table:
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


Note that the "P_Id" column is the primary key in the "Persons" table. This means that no two
rows can have the same P_Id. The P_Id distinguishes two persons even if they have the same
name.
Next, we have the "Orders" table:
O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15
Different SQL JOINS:
JOIN: Return rows when there is at least one match in both tables
LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table
RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table
FULL JOIN: Return rows when there is a match in one of the tables

SQL INNER JOIN:


The INNER JOIN keyword return rows when there is at least one match in both tables.
Syntax:
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Example:
The "Persons" table:
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


The "Orders" table:
O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15
Now we want to list all the persons with any orders.
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678


The INNER JOIN keyword return rows when there is at least one match in both tables. If there
are rows in "Persons" that do not have matches in "Orders", those rows will NOT be listed.
SQL LEFT JOIN:
The LEFT JOIN keyword returns all rows from the left table (table_name1), even if there are no
matches in the right table (table_name2).
SQL LEFT JOIN Syntax
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Example:
The "Persons" table:
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn Sandnes


10

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


The "Orders" table:
O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15
List all the persons and their orders:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678


Svendson Tove
The LEFT JOIN keyword returns all the rows from the left table (Persons), even if there are no
matches in the right table (Orders).
SQL RIGHT JOIN:
The RIGHT JOIN keyword returns all the rows from the right table (table_name2), even
if there are no matches in the left table (table_name1).
Syntax:
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Example:
The "Persons" table:
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


The "Orders" table:
O_Id OrderNo P_Id
1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15
List all the orders with containing persons.
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo
Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

34764
The RIGHT JOIN keyword returns all the rows from the right table (Orders), even if
there are no matches in the left table (Persons).

SQL FULL JOIN:


The FULL JOIN keyword return rows when there is a match in one of the tables.
Syntax:
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
Example:
The "Persons" table:
P_Id LastName FirstName Address City

1 Hansen Ola Timoteivn 10 Sandnes

2 Svendson Tove Borgvn 23 Sandnes

3 Pettersen Kari Storgt 20 Stavanger


The "Orders" table:
O_Id OrderNo P_Id

1 77895 3

2 44678 3

3 22456 1

4 24562 1

5 34764 15
List all the persons and their orders, and all the orders with their persons.
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
The result-set will look like this:
LastName FirstName OrderNo

Hansen Ola 22456

Hansen Ola 24562

Pettersen Kari 77895

Pettersen Kari 44678

Svendson Tove

34764

Result:

Thus the relationship between the database was performed and implemented
successfully.
Ex.No:9 SEQUENCE AND SYNONYM IN SQL

Aim:

To create a sequence and synonym in SQL.

SEQUENCE:

Sequence is a feature supported by some database systems to produce unique values on


demand. Some DBMS like supports AUTO_INCREMENT in place of Sequence.
AUTO_INCREMENT is applied on columns, it automatically increments the column value by 1
each time a new record is entered into the table. Sequence is also some what similar to
AUTO_INCREMENT but its has some extra features.
Syntax:

create sequence

sequence-number

increment by increment-value

maxvalue maximum-value

cycle|no cycle

• initial-value specifies the starting value of the Sequence


• increment-value is the value by which sequence will be incremented
• maxvalue specifies the maximum value until which sequence will increment itself.
• cycle specifies that if the maximum value exceeds the set limit, sequence will restart its
cycle from the begining.
• No cycle specifies that if sequence exceeds maxvalue an error will be thrown.
SYNONYM:
Synonyms provide both data independence and location transparency. Synonyms permit
applications to function without modification regardless of which user owns the table or view
and regardless of which database holds the table or view. However, synonyms are not a
substitute for privileges on database objects. Appropriate privileges must be granted to a user
before the user can use the synonym.
Prerequisites:
• To create a private synonym in your own schema, you must have
the CREATE SYNONYM system privilege.
• To create a private synonym in another user's schema, you must have
the CREATE ANY SYNONYM system privilege.
• To create a PUBLIC synonym, you must have
the CREATE PUBLIC SYNONYM system privilege.
Syntax
create_synonym::=

OR REPLACE
Specify OR REPLACE to re-create the synonym if it already exists. Use this clause to change
the definition of an existing synonym without first dropping it.
Restriction on Replacing a Synonym You cannot use the OR REPLACE clause for a type
synonym that has any dependent tables or dependent valid user-defined object types.
PUBLIC
Specify PUBLIC to create a public synonym. Public synonyms are accessible to all users.
However each user must have appropriate privileges on the underlying object in order to use the
synonym.
When resolving references to an object, Oracle Database uses a public synonym only if the
object is not prefaced by a schema and is not followed by a database link.
If you omit this clause, then the synonym is private and is accessible only within its schema. A
private synonym name must be unique in its schema.
schema
Specify the schema to contain the synonym. If you omit schema, then Oracle Database creates
the synonym in your own schema. You cannot specify a schema for the synonym if you have
specified PUBLIC.
synonym
Specify the name of the synonym to be created.
Synonyms longer than 30 bytes can be created and dropped. However, unless they represent a
Java name they will not work in any other SQL command. Names longer than 30 bytes are
transformed into an obscure shorter string for storage in the data dictionary.
FOR Clause
Specify the object for which the synonym is created. The schema object for which you are creating
the synonym can be of the following types:
• Table or object table
• View or object view
• Sequence
• Stored procedure, function, or package
• Materialized view
• Java class schema object
• User-defined object type
• Synonym
The schema object need not currently exist and you need not have privileges to access the object.
Restriction on the FOR Clause The schema object cannot be contained in a package.
schema Specify the schema in which the object resides. If you do not qualify object
with schema, then the database assumes that the schema object is in your own schema.
If you are creating a synonym for a procedure or function on a remote database, then you must
specify schema in this CREATE statement. Alternatively, you can create a local public synonym
on the database where the object resides. However, the database link must then be included in all
subsequent calls to the procedure or function.
dblink - specify a complete or partial database link to create a synonym for a schema object on a
remote database where the object is located. If you specify dblink and omit schema, then the
synonym refers to an object in the schema specified by the database link. Oracle recommends
that you specify the schema containing the object in the remote database.
If you omit dblink, then Oracle Database assumes the object is located on the local database.
CREATE SYNONYM:
To define the synonym offices for the table locations in the schema hr, issue the
following statement:
CREATE SYNONYM offices
FOR hr.locations;
To create a PUBLIC synonym for the employees table in the schema hr on the remote database,
you could issue the following statement:
CREATE PUBLIC SYNONYM emp_table
FOR [email protected];
A synonym may have the same name as the underlying object, provided the underlying object is
contained in another schema.
Resolution of Synonyms:
User SYSTEM creates a PUBLICsynonym named customers for oe.customers:
CREATE PUBLIC SYNONYM customers FOR oe.customers;
If the user sh then issues the following statement, then the database returns the count of rows
from sh.customers:
SELECT COUNT(*) FROM customers;
To retrieve the count of rows from oe.customers, the user sh must preface customers with the
schema name. (The user sh must have select permission onoe.customers as well.)
SELECT COUNT(*) FROM oe.customers;
If the user hr's schema does not contain an object named customers, and if hr has select
permission on oe.customers, then hr can access the customerstable in oe's schema by using the
public synonym customers:
SELECT COUNT(*) FROM customers;

Result:

Thus Sequence and Synonym was performed and implemented successfully.


Ex.No:10 STUDY OF PL/SQL BLOCK

PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and
written in logical blocks of code.
Advantages of PL/SQL
Block Structures: PL SQL consists of blocks of code, which can be nested within each other. Each
block forms a unit of a task or a logical module. PL/SQL Blocks can be stored in the database and
reused.
Procedural Language Capability: PL SQL consists of procedural language constructs such as
conditional statements (if else statements) and loops like (FOR loops).
Better Performance: PL SQL engine processes multiple SQL statements simultaneously as a single
block, thereby reducing network traffic.
Error Handling: PL/SQL handles errors or exceptions effectively during the execution of a
PL/SQL program. Once an exception is caught, specific actions can be taken depending upon the
type of the exception or it can be displayed to the user with a message.

Each block consists of three sub-parts:

S.N. Sections & Description

Declarations
This section starts with the keyword DECLARE. It is an optional section and
1
defines all variables, cursors, subprograms, and other elements to be used in the
program.

ExecutableCommands
This section is enclosed between the keywords BEGIN and END and it is a
2 mandatory section. It consists of the executable PL/SQL statements of the
program. It should have at least one executable line of code, which may be just
a NULL command to indicate that nothing should be executed.

Exception Handling
3
This section starts with the keyword EXCEPTION. This section is again
optional and contains exception(s) that handle errors in the program.

Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within
other PL/SQL blocks using BEGIN and END.
Basic structure of a PL/SQL block:
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
Example:
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
OUTPUT:
Hello World
PL/SQL procedure successfully completed.
PL/SQL Identifiers:
PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved
words. The identifiers consist of a letter optionally followed by more letters, numerals, dollar
signs, underscores, and number signs and should not exceed 30 characters.
PL/SQL Delimiters:
A delimiter is a symbol with a special meaning.

Delimiter Description

+, -, *, / Addition, subtraction/negation, multiplication, division

% Attribute indicator
' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator

; Statement terminator

:= Assignment operator

=> Association operator

|| Concatenation operator

** Exponentiation operator

<<, >> Label delimiter (begin and end)

/*, */ Multi-line comment delimiter (begin and end)

-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, ^= Different versions of NOT EQUAL

PL/SQL Comments:
The PL/SQL supports single-line and multi-line comments. All characters available
inside any comment are ignored by PL/SQL compiler. The PL/SQL single-line comments start
with the delimiter --(double hyphen) and multi-line comments are enclosed by /* and */.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END
PL/SQL Program Units
A PL/SQL unit is any one of the following:
• PL/SQL block
• Function
• Package
• Package body
• Procedure
• Trigger
• Type
• Type body
Variable Declaration in PL/SQL:
PL/SQL variables must be declared in the declaration section or in a package as a global
variable. When you declare a variable, PL/SQL allocates memory for the variable's value and the
storage location is identified by the variable name.
Syntax for declaring a variable:
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
variable_name- valid identifier in PL/SQL
datatype-valid PL/SQL data type or any user defined data type
Example:
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
Initializing Variables in PL/SQL:
Whenever declaring a variable, PL/SQL assigns it a default value of NULL. If you want
to initialize a variable with a value other than the NULL value, you can do so during the
declaration, using either of the following:
o DEFAULT keyword
o Assignment operator
Example:
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
Example:
DECLARE
a integer := 10;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
Output:
Value of c: 30
Value of f: 23.333333333333333333
PL/SQL procedure successfully completed.
Variable Scope in PL/SQL:
PL/SQL allows the nesting of Blocks, i.e., each program block may contain another inner
block. If a variable is declared within an inner block, it is not accessible to the outer block.
However, if a variable is declared and accessible to an outer Block, it is also accessible to all
nested inner Blocks. There are two types of variable scope:
Local variables - variables declared in an inner block and not accessible to outer blocks.
Global variables - variables declared in the outermost block or a package.
Example:
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num1 number := 195;
num2 number := 185;
BEGIN
dbms_output.put_line('Inner Variable num1: ' || num1);
dbms_output.put_line('Inner Variable num2: ' || num2);
END;
END;
Output:
Outer Variable num1: 95
Outer Variable num2: 85
Inner Variable num1: 195
Inner Variable num2: 185
PL/SQL procedure successfully completed.
CONTROL STRUCTURES:
IF-THEN STATEMENT:
IF condition THEN
sequence_of_statements
END IF;
Example:
IF sales > quota THEN
compute_bonus(empid);
UPDATE payroll SET pay = pay + bonus WHERE empno = emp_id;
END IF;
IF-THEN-ELSE STATEMENT:
IF condition THEN
sequence_of_statements1
ELSE
sequence_of_statements2
END IF;
Example:
IF trans_type = 'CR' THEN
UPDATE accounts SET balance = balance + credit WHERE ...
ELSE
UPDATE accounts SET balance = balance - debit WHERE ...
END IF;
IF-THEN-ELSIF STATEMENT:
IF condition1 THEN
sequence_of_statements1
ELSIF condition2 THEN
sequence_of_statements2
ELSE
sequence_of_statements3
END IF;
Example:
BEGIN
IF sales > 50000 THEN
bonus := 1500;
ELSIF sales > 35000 THEN
bonus := 500;
ELSE
bonus := 100;
END IF;

INSERT INTO payroll VALUES (emp_id, bonus, ...);


END;
CASE STATEMENT:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
Example:
SELECT table_name,
CASE owner
WHEN 'SYS' THEN 'The owner is SYS'
WHEN 'SYSTEM' THEN 'The owner is SYSTEM'
ELSE 'The owner is another value'
END
FROM all_tables;
LOOP STATEMENT:
LOOP
{………..statements……….}
END LOOP;
Example:
LOOP
monthly_value := daily_value * 31;
EXIT WHEN monthly_value > 4000;
END LOOP;
SYNTAX
FOR LOOP:
FOR loop_counter IN [REVERSE] lowest_number..highest_number
LOOP
{...statements...}
END LOOP;
PARAMETERS OR ARGUMENTS:
• loop_counter is the loop counter variable in the FOR LOOP.
• REVERSE is optional. If REVERSE is specified, the LOOP counter will count in
reverse.
• lowest_number -starting value for loop_counter.
• highest_number -ending value for loop_counter.
• statements are the statements of code to execute each pass through the FOR LOOP.
Example:
For lcntr in 1..20
Loop
lcalc := lcntr * 31;
End loop;
WHILE Loop:
WHILE condition
LOOP
{...statements...}
END LOOP;
PARAMETERS OR ARGUMENTS:
• condition is the condition is test each pass through the loop. If condition evaluates to
TRUE, the loop body is executed. If condition evaluates to FALSE, the loop is
terminated.
• statements are the statements of code to execute each pass through the loop.
Example:
WHILE monthly_value <= 4000
LOOP
monthly_value := daily_value * 31;
END LOOP;
EXIT STATEMENT:
EXIT [WHEN boolean_condition];
PARAMETERS OR ARGUMENTS:
WHEN boolean_condition is optional. It is the condition to terminate the LOOP.
Example:
LOOP
monthly_value := daily_value * 31;
EXIT WHEN monthly_value > 4000;
END LOOP;

Result:

Thus structure of PL/SQL was studied.


Ex. No. 11 CONTROL STRUCTURES IN PL/SQL

AIM
To write a PL/SQL block using different control (if else, for loop, while loop,…)
statements.

PROCEDURE
Step 1: Start
Step 2: Initialize the necessary parameters.
Step 3: Develop the set of statements with the essential operational parameters.
Step 4: Specify the Individual operation to be carried out.
Step 5: Execute the statements.
Step 6: Stop.
********************ADDITION OF TWO NUMBERS***********************
SQL> declare
a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('sum of'||a||'and'||b||'is'||c);
end;
/
INPUT:
Enter value for a: 23
old 6: a:=&a;
new 6: a:=23;
Enter value for b: 12
old 7: b:=&b;
new 7: b:=12;
OUTPUT:
sum of23and12is35
*********** GREATEST OF THREE NUMBERS USING IF ELSE*************
SQL> declare
a number;
b number;
c number;
d number;
begin
a:=&a;
b:=&b;
c:=&b;
if(a>b)and(a>c) then
dbms_output.put_line('A is maximum');
elsif(b>a)and(b>c)then
dbms_output.put_line('B is maximum');
else
dbms_output.put_line('C is maximum');
end if;
end;
/
INPUT:
Enter value for a: 21
old 7: a:=&a;
new 7: a:=21;
Enter value for b: 12
old 8: b:=&b;
new 8: b:=12;
Enter value for b: 45
old 9: c:=&b;
new 9: c:=45;
OUTPUT:
C is maximum
PL/SQL procedure successfully completed.
***********SUMMATION OF ODD NUMBERS USING FOR LOOP***********
SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1..endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum ='||sum1);
end;
/
INPUT:
Enter value for endvalue: 4
old 6: endvalue:=&endvalue;
new 6: endvalue:=4;
OUTPUT:
sum =4
PL/SQL procedure successfully completed.
***********SUMMATION OF ODD NUMBERS USING WHILE LOOP***********
SQL> declare
n number;
sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
while(n<endvalue)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd no. bt 1 and' ||endvalue||'is'||sum1);
end;
/
INPUT:
Enter value for endvalue: 4
old 6: endvalue:=&endvalue;
new 6: endvalue:=4;
OUTPUT:
sum of odd no. bt 1 and4is4
PL/SQL procedure successfully completed.

RESULT:

Thus the PL/SQL block for different controls are verified and executed.
Ex.No:12 PL/SQL Exceptions

Aim:

To execute PL/SQL exceptions.

An error condition during a program execution is called an exception in PL/SQL.


PL/SQL supports programmers to catch such conditions using EXCEPTION block in the
program and an appropriate action is taken against the error condition. There are two types of
exceptions:
• System-defined exceptions
• User-defined exceptions
Syntax for Exception Handling
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Example
DECLARE
c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
OUTPUT
No such customer!
PL/SQL procedure successfully completed.
The above program displays the name and address of a customer whose ID is given.
Since there is no customer with ID value 8 in our database, the program raises the run-time
exceptionNO_DATA_FOUND, which is captured in EXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
command RAISE.
SYNTAX
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
You can use above syntax in raising Oracle standard exception or any user-defined exception.
Next section will give you an example on raising user-defined exception, similar way you can raise
Oracle standard exceptions as well.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
SYNTAX
DECLARE
my-exception EXCEPTION;
Example:
This program asks for a customer ID, when the user enters an invalid ID, the exception
invalid_id is raised.
DECLARE
c_id customers.id%type := &cc_id;
c_name customers.name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
OUTPUT
When the above code is executed at SQL prompt, it produces the following result:
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
PL/SQL procedure successfully completed.
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is
violated by a program. For example, the predefined exception NO_DATA_FOUND is raised
when a SELECT INTO statement returns no rows. The following table lists few of the important
pre-defined exceptions:

Oracle
Exception SQLCODE Description
Error

It is raised when a null object is


ACCESS_INTO_NULL 06530 -6530
automatically assigned a value.

It is raised when none of the choices in


the WHEN clauses of a CASE statement
CASE_NOT_FOUND 06592 -6592
is selected, and there is no ELSE clause.

It is raised when a program attempts to


apply collection methods other than
EXISTS to an uninitialized nested
COLLECTION_IS_NULL 06531 -6531
table or varray, or the program
attempts to assign values to the elements
of an uninitialized nested
table or varray.

It is raised when duplicate values are


DUP_VAL_ON_INDEX 00001 -1 attempted to be stored in a column
with unique index.

It is raised when attempts are made to


make a cursor operation that is not
INVALID_CURSOR 01001 -1001
allowed, such as closing an unopened
cursor.

It is raised when the conversion of a


character string into a number fails
INVALID_NUMBER 01722 -1722
because the string does not represent a
valid number.

It is raised when s program attempts to


LOGIN_DENIED 01017 -1017 log on to the database with an invalid
username or password.

It is raised when a SELECT INTO


NO_DATA_FOUND 01403 +100
statement returns no rows.

It is raised when a database call is issued


NOT_LOGGED_ON 01012 -1012 without being connected to the database.

It is raised when PL/SQL has an


PROGRAM_ERROR 06501 -6501
internal problem.

It is raised when a cursor fetches value


ROWTYPE_MISMATCH 06504 -6504 in a variable having incompatible data
type.

It is raised when a member method is


SELF_IS_NULL 30625 -30625 invoked, but the instance of the object
type was not initialized.
It is raised when PL/SQL ran out of
STORAGE_ERROR 06500 -6500
memory or memory was corrupted.

It is raised when s SELECT INTO


TOO_MANY_ROWS 01422 -1422
statement returns more than one row.

It is raised when an arithmetic,


VALUE_ERROR 06502 -6502 conversion, truncation, or size-
constraint error occurs.

It is raised when an attempt is made to


ZERO_DIVIDE 01476 1476
divide a number by zero.

Result:

Thus exception handling in PL/SQL was performed and implemented successfully.


Ex.No:13 PROCEDURES

Aim:
To execute procedures using Pl/SQL.
Procedures:
A stored procedure or in simple a proc is a named PL/SQL block which performs one
or more specific task. This is similar to a procedure in other programming languages. A
procedure has a header and a body. The header consists of the name of the procedure and the
parameters or variables passed to the procedure. The body consists or declaration section,
execution section and exception section similar to a general PL/SQL Block. A procedure is
similar to an anonymous PL/SQL Block but it is named for repeated usage.We can pass
parameters to procedures in three ways.
1) IN-parameters
2) OUT-parameters
3) IN OUT-parameters

A procedure may or may not return any value.


SYNTAX:
CREATE [OR REPLACE] PROCEDURE proc_name [list of parameters]
IS
Declaration section
BEGIN
Execution section
EXCEPTION
Exception section
END;

Two ways to execute a procedure.


1) From the SQL prompt.
EXECUTE [or EXEC] procedure_name;

2) Within another procedure – simply use the procedure name.


procedure_name;
Procedure Creation:

create or replace procedure mm1(a in number,b in number,c in out number)is


begin

c:=a+b;

end;

Procedure created.

Query:

set serveroutput on

declare

a number(3);

b number(3);

c number(3);

begin

a:=&a;

b:=&b;

mm1(a,b,c);

dbms_output.put_line(c);

end;

Output:

old 6: a:=&a;
new 6: a:=21;
old 7: b:=&b;
new 7: b:=15;
36

PL/SQL procedure successfully completed.

Result:

Thus procedures in PL/SQL was performed and implemented successfully.


Ex.No:14 TRIGGERS

Aim:

To write a sql program to perform and create the trigger using sql queries.

PROCEDURE:

A trigger is a PL/SQL block or a PL/SQL procedure that executes implicitly whenever a


particular event takes place. It can either be:
1. Application trigger: Fires whenever an event occurs with a particular application.
2. Database Trigger: Fires whenever a data event (such as DML) occurs on a schema or
database.
GUIDELINES TO DESIGNING TRIGGERS:
• Use the following guidelines when designing triggers.
• Use triggers to guarantee that when a specific operation is performed, related
actions are performed.
• Only use database triggers for centralized, global operations that should be fired for the
triggering statement, regardless of which user or application issues the statement.
• Do not define triggers to duplicate or replace the functionality already built into the
oracle database. For example do not define trigger to implement integrity rules that can
be done by using declarative constraints.
• The excessive use to triggers can result in complex interdependencies, which may be
difficult to maintain in large applications. Only use triggers when necessary, and
beware of recursive and cascading effects.
Elements in a Trigger:

o Trigger timing
o For table: BEFORE, AFTER
o For view: INSTEAD OF
o Trigger event: INSERT, UPDATE, OR DELETE
o Table name: On table, view
o Trigger Type: Row or statement
o When clause: Restricting condition
o Trigger body: PL/SQL block
“Before triggers” execute the trigger body before the triggering DML event on a table. These
are frequently used to determine whether that triggering statement should be allowed to
complete. This situation enables you to eliminate unnecessary processing of the triggering
statement and it eventual rollback in cases where an exception is raised in the triggering action.

“After triggers” are used when the triggering statement is to be completed before the triggering
action and to perform a different action on the same triggering statement if a BEFORE trigger is
already present.

“Instead of Triggers” are used to provide a transparent way of modifying views that cannot be
modified directly through SQL DML statements because the view is not inherently
modifiable. You can write INSERT, UPDATE, and DELETE statements against the view. The
INSTEAD OF trigger works invisibly in the background performing the action coded in the trigger
body directly on the underlying tables.

Triggering user events:

➢ UPDATE
➢ INSERT
➢ DELETE

Trigger Components:
o Statement: The trigger body executes once for the triggering event. This is the default. A
statement trigger fires once, even if no rows are affected at all.
o Row: The trigger body executes once for each row affected by the triggering event.
A row trigger is not executed if the triggering event affects no rows.
Trigger Body: The trigger body is a PL/SQL block or a call to a procedure.

SYNTAX:
CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
BEGIN
--- sql statements
END;
CREATE [OR REPLACE ] TRIGGER trigger_name :
This clause creates a trigger with the given name or overwrites an existing trigger with the same
name.
{BEFORE | AFTER | INSTEAD OF }:
This clause indicates at what time should the trigger get fired. i.e for example: before or after
updating a table. INSTEAD OF is used to create a trigger on a view. before and after cannot be
used to create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}:
This clause determines the triggering event. More than one triggering events can be used
together separated by OR keyword. The trigger gets fired at all the specified triggering event.
FOR EACH ROW:
This clause is used to determine whether a trigger must fire when each row gets affected ( i.e. a
Row Level Trigger) or just once when the entire sql statement is executed(i.e.statement level
Trigger).
WHEN (condition):
This clause is valid only for row level triggers. The trigger is fired only for rows that satisfy the
condition specified.
CREATE TRIGGER FOR INSERTING RECORDS

create table snt52(stuname char(10),rollno number(5));


Table created
insert into snt52 values('sarath',45);
insert into snt52 values('sarava',15);
insert into snt52 values('satheesh',25);
select * from snt52;
STUNAME ROLLNO
kavi 45
hema 15
maha 25

PROGRAM:
set serveroutput on
create or replace trigger tri52 after insert on snt52 for each row
begin
dbms_output.put_line('record inserted');
end;
Trigger created.
insert into snt52 values('sidhanth',25);
OUTPUT:
record inserted
1 row created..
select * from snt52;
STUNAME ROLLNO
kavi 45
hema 15
maha 25
sidhanth 25
CREATE TRIGGER FOR INSERT,UPDATE AND DELETE

Create table dept52(loc varchar2(10),deptno number(10));


Table created
insert into dept52(loc,deptno)values('Chennai',10);
insert into dept52(loc,deptno)values('salem',15);
select *from dept52;
LOC DEPTNO
Chennai 10
salem 15

PROGRAM
set serveroutput on
create or replace trigger trg50
after insert or update or delete on dept52
begin
dbms_output.put_line('Thank You');
end;
Trigger created
Query:Update52 dept set loc='DELHI' where deptno =10;
OUTPUT:
Thank you
1 row updated
LOC DEPTNO
DELHI 10
salem 15

Query:delete from dept52 where deptno=15;


OUTPUT:
Thank you
1 Row deleted.
LOC DEPTNO
DELHI 10
CREATE TRIGGER FOR DELETE RECORDS

create table emp52(empno number(5),ename char(10),job char(10),salary number(10),deptno


number(10));
insert into emp52 values(1,'sarala','manager',30000,3);
insert into emp52 values(1,'saro','clerk',10000,2);
insert into emp52 values(1,'roshan','g m',100000,1);
selct *from emp52
EMPNO ENAME JOB SALARY DEPTNO
1 sarala manager 30000 3
1 saro clerk 10000 2
1 roshan gm 100000 1

create table emp49(empno number(5),ename char(10),job char(10),salary number(10),deptno


number(10));
set serveroutput on
create or replace trigger del52_tri
before delete on emp52
for each row
begin
insert into emp49 values(:old.empno,:old.ename,:old.job,:old.salary,:old.deptno);
end;
Trigger created
Query:delete from emp52 where empno=1;
3 rows deleted.
OUTPUT:
select *from emp49;
EMPNO ENAME JOB SALARY DEPTNO
1 sarala manager 30000 3
1 saro clerk 10000 2
1 roshan gm 100000 1
CREATE A EMPLOYEE DATABASE TO INCREMENT EMPLOYEE SALARY BY
1000.

create table emp50(ename varchar2(30),eno number(5),salary number(30));


Table created.
insert into emp50(ename,eno,salary)values('anitha',2,2000);
insert into emp50(ename,eno,salary)values('sheela',3,3500);
create table updemp050(salary number(5),systemdate date);
Table created.
PROGRAM:
set serveroutput on
create or replace trigger etrig12 after update on emp12 for each row
begin
if(:new.salary<:old.salary)then
raise_application_error(-20030,'increase the salary');
end if;
insert into updemp050 values(:new.salary,sysdate);
end; /

OUTPUT:

update emp12 set salary=salary+1000 where eno=2;

select *from emp12;


ENAME ENO SALARY
anitha 2 3000
sheela 3 3500

STUDENT DETAILS USING TRIGGER


Program specification :
TABLE : I
SQL>create table student1(rno number(10),name varchar2(20),mark1 number(3),
mark2 number(3),mark3 number(3));
Table created
TABLE : II
SQL>create table student2(rno number(10),name varchar2(20),tot number(3),avg
number(8,2),result varchar2(5));
Table created
INSERTING VALUES :
SQL>insert into student1 values(&rno,’&name’,&mark1,&mark2,&mark3);
CODING :
set serveroutput on
create or replace trigger tri after insert or update on student1 for each row
declare
n number(10);
sname varchar2(20);
stot number(3);
savg number(8,2);
sres varchar2(5);
begin n:=:new.rno;
sname:=:new.name;
stot:=:new.mark1+:new.mark2+:new.mark3;
savg:=stot/3;
if(:new.mark1>=35 and :new.mark2>=35 and :new.mark3>=35)then
sres:='pass';
else
sres:='fail';
end if;
insert into student2 values(n,sname,stot,savg,sres);
end;
OUTPUT :
TABLE : I
select *from student1;
RNO NAME Mark1 Mark2 Mark3
01 Vidhya 100 98 78
02 Surya 50 88 30
03 Anitha 66 50 65
04 Sathya 55 30 60
05 Ramesh 98 90 89

TABLE : II
select*from student2;
RNO NAME TOT AVG RESULT
01 Vidhya 276 92 pass
02 Surya 168 56 fail
03 Anitha 181 60.33 pass
04 Sathya 145 48.33 fail
05 Ramesh 277 92.33 pass

Result:

Thus trigger was performed and implemented successfully.

You might also like