DBMS Lab Manual
DBMS Lab Manual
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:
CREATE:
SYNTAX:
Example:
DESC:
SYNTAX:
desc tablename;
EXAMPLE:
desc student;
ALTER:
1. Add
2. Modify
3. Drop
ADD:
It is used to add a column in a table.
SYNTAX:
MODIFY:
SYNTAX:
EXAMPLE:
DROP:
SYNTAX:
EXAMPLE:
RENAME:
SYNTAX:
EXAMPLE:
TRUNCATE:
EXAMPLE:
DROP:
SYNTAX:
EXAMPLE:
TABLE CREATION:
OUTPUT:
Table created.
ALTER(ADD):
OUTPUT: Table
altered.
ALTER(MODIFY):
OUTPUT: Table
altered.
DESCRIPTION:
NAME CHAR(30)
REGISTERNUMBER NUMBER(12)
CGPA FLOAT(126)
AGE NUMBER(2)
ALTER(DROP):
OUTPUT: Table
altered.
DESCRIPTION:
OUTPUT:
NAME CHAR(30)
REGISTERNUMBER NUMBER(12)
CGPA FLOAT(126)
RENAME:
OUTPUT:
Table renamed.
DROP:
OUTPUT:
Table truncated.
DROP:
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:
DML enable users to access or manipulate data as organized by the appropriate data
model. The types of access are:
SYNTAX:
Example:
DELETE:
SYNTAX:
Example:
UPDATE:
Example:
SELECT:
SYNTAX:
Example:
TABLE CREATION:
OUTPUT: Table
created.
DESCRIPTION:
OUTPUT:
CUSTOMERID NUMBER
CUSTOMERNAME CHAR(20)
AGE NUMBER(2)
BALANCE NUMBER
LOANAMOUNT NUMBER
INSERTION:
OUTPUT:
1 row created.
INSERTION:
OUTPUT:
1 row created.
INSERTION:
OUTPUT:
1 row created.
INSERTION:
OUTPUT:
1 row created.
DISPLAY:
OUTPUT:
DELETION:
OUTPUT:
2 rows deleted.
QUERY:
OUTPUT:
UPDATION:
OUTPUT:
1 row updated.
DISPLAY:
OUTPUT:
OUTPUT:
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.
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
A B C
a1 b1 c1 Savepoint B;
a2 b2 c2
a3 b3 c3
a4 b4 c4
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:
Output:
NAME ID
---------- ----------
shahtaj 13
sultana 14
manhar 15
parveen 16
Query:
Output:
Rollback complete.
Query:
Output:
NAME ID
---------- ----------
shahtaj 13
sultana 14
Query:
Output:
Table created.
Query:
SQL>savepoint s1;
Output:
Savepoint created.
Query:
Output:
1 row created.
Query:
SQL> insert into beauty values('mahe',20);
Output:
1 row created.
Query:
SQL>savepoint s2;
Output:
Savepoint created.
Query:
Output:
1 row deleted.
Query:
Output:
NAME ID
------------- ----------
mahe 20
Query:
Output:
1 row deleted.
Query:
Output:
no rows selected
Query:
Output:
Rollback complete.
Query:
SQL> commit;
Output:
Commit complete.
Query:
Output:
rollback to s1
*
ERROR at line 1:
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 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 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:
Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT PHONENO
---------- ------------------ ----------- ---------- ---------- ----------
3 sheza 15 3000 600 898
OR Operator:
Query:
Not Operator:
Query:
Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT PHONENO
---------- ------------------ ----------- ---------- ---------- ----------
2 shatu 20 2000 500 676
COMPARISON OPERATOR:
Equal Operator(=):
Query:
Output:
Query:
Output:
Query:
Output:
Query:
Output:
Query:
Output:
CUSTOMERID CUSTOMERNAME CUSTOMERAGE BALANCE LOANAMOUNT
PHONENO
Query:
Output:
INSERT:
Query:
Output:
1 row created.
NULL OPERATOR:
Is Null Operator:
Query:
Output:
Query:
Output:
Query:
Output:
In Operator:
Query:
Output:
Not In Operator:
Query:
Output:
Query:
Output:
LIKE OPERATOR:
Query:
Output:
BALANCE
----------
2000
Query:
Output:
LOANAMOUNT
----------
800
Query:
Output:
BALANCE
---------
3000
Query:
Output:
LOANAMOUNT
-------------------------
900
Query:
Output:
BALANCE
-------------------------
2000
3000
4000
5000
6000
Query:
Output:
LOANAMOUNT
-------------------------
900
Query:
Output:
BALANCE
-------------------------
2000
3000
4000
5000
6000
RANGE OPERATOR:
Query:
Output:
CUSTOMERID
-------------------------
CREATE:
Query:
Output:
Table created.
INSERT:
Query:
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:
Output:
1 row inserted.
SET OPERATORS:
Union operator:
Query:
Output:
CUSTOMERNAME
-------------------------
Aaliyah
Query:
SQL>select customerid from account3 union all select customerid from account4;
Output:
CUSTOMERID
-------------------------
Intersection Operator:
Query:
Output:
CUSTOMERAGE
-------------------------
20
Result:
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
-------------------------------
Creation of view
------------------------------
View created.
Description of view
------------------------------
1 row created.
1 row deleted.
0 rows updated.
1 row updated.
View droped
Result:
Aim:
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:
Aim
CONSTRAINTS
Types of constraint
▪ Primary key
▪ Foreign key/references
▪ Check
▪ Unique
▪ Not null
▪ Default
Result:
Aim:
To create a relationship between the database.
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
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
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 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
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
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
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
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).
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
Svendson Tove
34764
Result:
Thus the relationship between the database was performed and implemented
successfully.
Ex.No:9 SEQUENCE AND SYNONYM IN SQL
Aim:
SEQUENCE:
create sequence
sequence-number
increment by increment-value
maxvalue maximum-value
cycle|no cycle
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:
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.
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
% Attribute indicator
' Character string delimiter
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
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;
Result:
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:
Oracle
Exception SQLCODE Description
Error
Result:
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
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
Result:
Aim:
To write a sql program to perform and create the trigger using sql queries.
PROCEDURE:
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.
➢ 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
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
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
OUTPUT:
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: