You are on page 1of 33

INDEX

Sr.
Program Name Remarks
No.

1 Introduction to DBMS & RDBMS.

2 Introduction about SQL commands.

3 To create table using constraints.

4 Write a program to modify a record in table.

5 Write a program to sort data of a table using order by clause.

6 Write a program to analyses DDL and DML commands.

7 Write a SQL program to add two numbers.

8 Illustrate SQL data types.

9 State SQL variables.

10 Apply SQL loops.

11 To create queries using Procedures.


PRACTICAL NO. 1

AIM :Introduction to DBMS and RDBMS.

REQUIREMENTS: PC with windows, internet connection and MySQL software.

THEORY: A Database is a collection of related information stored to provide the


availability to many users for different purposes. The content of database is obtained
by combining data from various sources in an organization. So that data are available to all
users and redundant data can be minimized or eliminated. Database systems are designed
to manage large bodies of information. The management of data involves both
definition of structure for storage of information.

Database Management System

A database can be of any size and of varying complexity. For example a data consists of only a
few hundred records, each with a simple structure. On the other hand, the card catalog of a large
library may contain half a million cards stored under different categories— by primary author's
last name, by subject, by book title-with each category organized in alphabetic order.

A database of even greater size and complexity is maintained by the Internal Revenue Service to
keep track of the tax forms filed by U.S. taxpayers. If we assume that there are 100 million taxpayers
and if each taxpayer files an average of five form with approximately 200 characters of
information per form, we would get a database of 10*(106)*200*5 characters (bytes) of
information.

If the IRS keeps the past three returns for each taxpayer in addition to the current return, we would
get a database of 4*(10U) bytes (400 gigabytes). This huge amount of information must be organized
and managed so that users can search for, retrieve, and update the data as needed.

Creation of files,Addition of data,deletion of data,modification of data; Creation, addition and


deletion of entire files.

 The data can be retrieved collectively and selectively.

 Stored data can be sorted or indexed according to Users direction and desecration.
 System can generate various reports. Thus report may be either standardized or
generated according to user definition.

 Mathematical function can be performed and stored data can be manipulated with
these functions to perform desired calculations. To maintain data integrity and
Database use.

The DBMS process and interprets users request to retrieve information from database. These
requests may be keyed directly from a terminal or coded as high level language programs to
be submitted for either processing or interactive.

A database represents some aspect of the real world, sometimes called the mini-world
or the Universe of Discourse (UOD).Changes to the mini-world is reflected in the database.

A database is a logically coherent collection of data with some inherent meaning. A random
assortment of data cannot correctly be referred to as a Database.

A database is designed, built, and populated with data for a Specific purpose. It has an intended
group of users and some preconceived applications in which these users are interested.

Schemas, Instances, and Database State

In any data model it is important to distinguish between the description of the database and the
database itself. The description of the database is called the database schema, which is specified
during database design and is not expected to change frequently Most data models have
certain conventions for displaying the schemas as diagrams A displayed schema is called
a schema diagram for the database shown in the diagram displays the structure of each record type but
not the actual instances of records. The data in the database at a particular moment in time is called
a database state or snapshot. It is also called the current set of occurrences or instance.

Relational Database Management System

A relationship is a logical linkage between two entities that describes how the entities are
associated with each other. Creating a relationship explicitly defines an association between entities
in the data model. RDBMS is an acronym for Relational Database Management System.
The data in RDBMS is stored in database objects called tables. The database tables are the
primary data storage for every RDBMS and essentially they are collections of related data
entries. For example a table called Users might store information about many persons, and each
entry in this table will represent one unique user.

Even though all user entries in the Users table are unique, they are related in the sense that they
describe similar objects. Each database table consists of columns and rows. Each table column
defines the type of data stored in it, and this data type is valid for all rows in this table. A table row
is a collection of data having 1 entry for each column in this particular table. RDBMS store the data
into group of tables, which might or might not be related by common fields (database table
columns).
Degree of Relationship

 One to One (1:1)


 One to Many (1:N)
 Many to Many (M:N)

Attributes and Entities

This is second important data-modeling concept, which is to be understood. Attributes are additional
characteristics or information defined for an entity. An entity's attributes do not define an entity, but
they provide additional information about an entity' that may be useful elsewhere.

Entities and Attributes enable to explicitly define what information is being stored in the
database.

The following should be kept in mind while implementing Entities and Attributes,

 Entities are modeled as tables.

 In a table, each instance of an entity is called a row.

 Attributes are modeled as columns in a table.

 Programmers often refer to rows and columns as records and fields.

Tables and columns are usually singular, modeling convention.


thisI is relational named after the
Tables are almost always entity they represent.
Primary key and Foreign Key

The primary key is special column in the table that can be used to identify any one row. The
important thing is that the value in the primary key column must be unique in the table, in which
it resides.

The primary key may be chosen out of the existing fields in a table, or a new field can be
created expressly for this purpose. The easiest way to create a primary key is to create a
special column called as identity column,

Column Constraints

One may specify additional constraints on the column when designing your database. These
constraints enable you to include basic business requirements into your data model. These are
three fundamental types of column constraints used in a database design,

Not Null (NN)

This allows the database designer to force the user to enter a value in a particular column. The
not null concept is used for columns involved in a primary key.

No Duplicate (ND)

This specifies that the values in a column must be unique. This concept is used in primary keys and
alternate keys.

No Change (NC)

This concept allows the database designer to prohibit change,' in the values in a column. This
concept is used mainly for columns participating in primary keys.

Normalization

In 1970, E.F. Codd formalized three rules for relational database design known as
normal forms. In later years, additional normal forms have been defined, but the first three
are the most widely used.

Normalizing a database ensures the following things,

 Dependence between data are identified


 Redundant data is minimized
 The data model is flexible and easier to maintain.

Codd's normal forms were derived from set-based calculus. Before normalizing an entity, it
is helpful to first identify or create a primary key. In addition, columns should be decomposed
before normalization.
PRACTICAL NO.-2

AIM: Introduction about SQL Commands.

REQUIREMENTS: PC with window operating system AND mysql.

THEORY: SQL commands are instructions used to communicate with the database to perform
specific task that work with data. SQL commands can be used not only for searching the database
but also to perform various other functions like, for example, you can create tables, add data to
tables, or modify data, drop the table, set permissions for users.

CREATE TABLE COMMAND

The CREATE TABLE Statement is used to create tables to store data. Integrity Constraints like
primary key, unique key, foreign key can be defined for the columns while creating the table. The
integrity constraints can be defined at column level or table level

Syntax :
CREATE TABLE table_name
(column_name1 datatype,
column_name2 datatype,
... column_nameN datatype
);

INSERT COMMAND

The INSERT Statement is used to add new rows of data to a table.

Syntax :
INSERT INTO TABLE_NAME
[ (col1, col2, col3,...colN)]
VALUES (value1, value2, value3,...valueN);

UPDATE COMMAND

The UPDATE Statement is used to modify the existing rows in a table.

Syntax :
UPDATE table_name
SET column_name1 = value1,
column_name2 = value2, ...
[WHERE condition]

Delete COMMAND
The DELETE Statement is used to delete rows from a table.

Syntax:
DELETE FROM table name [WHERE condition];

DROP command

DROP command is used to remove an object from the database. If you drop a table, all the rows
in the table is deleted and the table structure is removed from the database. Once a table is dropped
we cannot get it back, so be careful while using RENAME command. When a table is dropped all
the references to the table will not be valid.

Syntax:

DROP TABLE table_name;

ALTER TABLE Statement

The SQL ALTER TABLE command is used to modify the definition (structure) of a table by
modifying the definition of its columns. The ALTER command is used to perform the following
functions.

1) Add, drop, modify table columns


2) Add and drop constraints
3) Enable and Disable constraints

Syntax to add a column:


ALTER TABLE table_name ADD column_name datatype;

RENAME command

RENAME command is used to change the name of the table or a database object.

Syntax to rename a table:


RENAME old_table_name To new_table_name;

ORDER BY

The ORDER BY clause is used in a SELECT statement to sort results either in ascending or
descending order. Oracle sorts query results in ascending order by default.
Syntax for using SQL ORDER BY clause to sort data is:

SELECT column-list
FROM table_name [WHERE condition]
[ORDER BY column1 [, column2, .. columnN] [DESC]];
PRACTICAL NO.3

AIM: TO CREATE A TABLE USING CONSTRAINTS

REQUIREMENTS: PC with window operating system and MYSQL.

THEORY:

Tables are defined with the create table commend. It is a DDL command. When a table is
created, its columns are named, datatypes and sizes are supplied for each column. Each table
must have atleast one column. There are two ways in which tables can be defined.

Creating a new table(with no column from any other table):

When we create a table, we can apply CONSTRAINTS on the values that can be entered into
its fields. The two basic types of constraints are column constraints and table constraints. A
column constraint can be applied to individual columns, whereas a table constraint is applied
to a group of one or more columns.

CODE:

Thus the syntax of CREATE TABLE command is:

CREATE TABLE<table name>

( <column name> <datatype> [ (size) ] [ <column constraint> ],

<column name> <datatype> [ (size) ] [ <column constraint> ]…

<table constraint> ( <column name> [ <column name>…] )

);

Constraints

The following constraints ensure database integrity, thus are sometimes called database
integrity constraints. A few of them are:
1.NOT NULL constraint

This constraint specifies that the column cannot have empty or null values. Otherwise SQL
assumes that nulls are permitted. Two NULLS cannot be added, subtracted or compared.
Consider the following SQL command.

CREATE TABLE employee

( ecode integer NOT NULL,

Ename char(30) NOT NULL,

Sex char(1) NOT NULL,

Grade char(1),

Gross number(7,2)

);

2. UNIQUE Constraint

This constraint ensures that no two rows have the same value in the specified column(s).

For example, UNIQUE constraint can be applied on ecode of employee table ensures that

No two rows have the same ecode value-

CREATE TABLE employee

( ecode integer UNIQUE,

Ename char(30), NOT NULL,

Sex char(1), NOT NULL,

Grade char(1),
Gross number(7,2)

);

This constraint can be applied only to columns that have also been declared not null,

However this condition is implementation dependent.

3. PRIMARY KEY constraint

This constraint declares a column as the primary key of a table. This constraint is similar

To UNIQUE constraint except that only one column (or one group of columns) can be

applied in this constraint. Primary keys cannot allow null values, thus, this constraint

must be applied to columns declared as NOT NULL. Consider the following SQL

statement.

CREATE TABLE employee

( ecode integer PRIMARY KEY,

Ename char(30) NOT NULL,

Sex char(1) NOT NULL,

Grade char(1),

Gross number(7,2),

);

4. DEFAULT constraint

A default value can be specified for a column using the default clause. When a user does

not enter a value for a column (having default value), automatically the defined default

value is inserted in the field. Consider the following SQL statement.


CREATE TABLE employee

( ecode integer PRIMARI KEY,

Ename char(30) NOT NULL,

Sex char(1) NOT NULL,

Grade char(1) DEFAULT ‘E’,

Gross number(7,2) );

According to above command, if no value is provided for grade, the default value ‘E’ will

be entered. The data type of default has to be compatible with the data type of the column

to which it is assigned. Insertion of null is possible only if the column definition permits.

A column can have only one default value.

5. CHECK constraint

This constraint limits the values that can be inserted into a column of a table. For

Instance, consider the following SQL statement.

CREATE TABLE employee

( ecode integer PRIMARY KEY,

Ename char(30) NOT NULL,

Sex char(1) NOT NULL,

Grade char(1) DEFAULT=’E’,

Gross number(7,2) CHECK (gross>2000)


);

This statement ensures thet the value inserted for gross must be greater than 2000.

Applying table constraints

When a constraintis to be applied on a group of columns of the table, it is called table

constraint. These appear at the end of table definition. For example, if you want the

combination of icode and descp to be unique, you may write it as follows:

CREATE TABLE items

( icode char(5) PRIMARY KEY,

Descp char(20) NOT NULL,

Rol integer,

Qoh integer,

CHECK (rol<qoh) );
PRACTICAL NO.4

AIM: To modify a record in a table.


REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: Sometimes you need to change some or all the values in an existing row. This can be
done using the UPDATE command specifies the rows to be changed using the WHERE clause,
and the new data using the SET keyword. The new data can be specified constant, an expression
or data from other tables.

CODE:
The SYNTAX is of UPDATE command is as:-
UPDATE <table name>
SET <column name>=<new value>
[WHERE<statement>];
For an example to change the roll of all items to 250, you would write UPDATE items
SET roll=400
WHERE roll=300;

Updating multiple columns


To update multiple columns, multiple column assignments can be specified follows:-

UPDATE<table name>
SET<column1>=<new value> [<column2>=<new value>…]
[WHERE<statement>];

Using expressions in update


Scalar expressions can also be used in the SET clause of an update command. Suppose if you want
to increase the gross pay of all the employees by Rs900/-,you could use the following expression.
UPDATE employee
SET gross =gross+900;

Updating to NULL values


The null values can also be entered just as other values. For example, a new grade is to be
introduced and all the employees with grade ’E’ have to be promoted to it. But for the time being,
this grade is not known. Thus null values are to be inserted for grades ‘E’. This can be done as
follows:-
UPDATE employee
SET grade= null
WHERE grade=’E’;

OUTPUT:
VIEWING INITIAL TABLE CONTENTS:
SQL>select*from student;
NAME ROLLNO BRANCH PHONE
--------- ------------ ------------- --------------
Gunjan 7577 cse 9911220000
Komal 6513 cse 9876543210
Nidhi 8421 cse 9878584857
Poonam 8432 cse 9416832272
4 rows selected.
UPDATING A SINGLE COLUMN:
SQL>update student
Set phone=9876543219
Where rollno=6513;
1 row updated.

SQL>select *from student;


NAME ROLLNO BRANCH PHONE
--------- ------------ ------------- --------------
Gunjan 7577 cse 9911220000
Komal 6513 cse 9876543219
Nidhi 8421 cse 9878584857
Poonam 8432 cse 9416832272
4 rows selected.

UPDATING MULTIPLE COLUMNS:


SQL>update student
Set phone=9911229999,rollno=7515
WHERE name=’gunjan’;
1 row updated.

NAME ROLLNO BRANCH PHONE


--------- ------------ ------------- --------------
Gunjan 7515 cse 9911229999
Komal 6513 cse 9876543210
Nidhi 8421 cse 9878584857
Poonam 8432 cse 9416832272
4 rows selected.
PRACTICAL NO.5

AIM: To sort the data of a table using the ORDER BY clause.


REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: Whenever a SELECT query is executed, the resulting rows emerge in a predecided
order. We can sort the result in a specific order using ORDER BY clause. The ORDER BY clause
allows sorting of query results by one or more columns. The sorting can be done either in ascending
or descending order, the default order is the ascending. The data in the table is not sorted; only the
results that appear on the screen are sorted.

SYNTAX:
The ORDER BY clause is used as:
SELECT<column name>[<column name>,….]
FROM<table name>
[WHERE<predicate>]
[ORDER BY<column name>];
For example, to display the list of employees in the alphabetical order of their names, we use the
command:
SELECT*FROM employee
ORDER BY ename;
To display the list of employees having salary more than 2500 in the alphabetical order of their
names, we may give the command:
SELECT empno, empname,job, FROM emp
WHERE sal>2500
ORDER BY ename;

SORTING IN DESCENDING ORDER:


To display the list of employee in the descending order of employee code, we use the command:
SELECT *FROM employee
ORDER BY ecode DESC;

SORTING THE RESULTS BASED ON THE CONDITION:


SQL>select *from student where branch=’i.t’ order by name;
NAME ROLLNO BRANCH PHONE
---------------------- --------------- ---------------
Annu 7547 i.t 7612345890
Nidhi 7531 i.t 9087654321
Sam 7532 i.t 8907654321
4 rows selected.

SORTING IN DESCENDING ORDER:


SQL>select *from student order by name DESC;
NAME ROLLNO BRANCH PHONE
---------------------- --------------- ---------------
Sam 7532 i.t 8907654321
Nidhi 7531 i.t 9087654321
Annu 7547 i.t 7612345890
3 rows selected.

SORTING BY COLUMN ALIAS:


SQL>select name, phone_number from student order by mobile_number;
NAME MOBILE_NUMBER
----------- -----------------------------
Annu 7612345890
Sam 8907654321
Nidhi 9087654321
3 rows selected.
SQL>commit;
Commit complete.
PRACTICAL NO.6

AIM: Consider the following employee relational database


REQUIREMENTS: PC with window operating system and MYSQL.

THEORY : Make use of ddl and dml command to perform various operations on rdbms
Emp (eno,ename,age , basicpay)
Workin (eno,deptno.)
Department (deptno.,deptname)

SYNTAX:
Create table command:- It is used to create a new table in data base.
Create table <table name>
(<column1 type>, <column2 type>…..<column n type>);

INSERT COMMAND:-
Values are placed in attributes of a relation with the INSERT command. This is a DML command.
The rows (tuples) are added to relations using INSERT command of SQL.

THE SELECT STATEMENT:-


The SELECT statement retrieves data from a database and returns it to you in the form of query
result.
QUERIES
Employee table
SQL> select * from emp1;
ENO ENAME AGE BASIC PAY
---------- ------------- ----------- -------------------
100 Anil 24 20000
105 Amit 20 18000
108 Ajay 26 15000
110 Deepak 22 18000
111 Nitin 30 10000
115 Sumit 40 9000

6 rows selected.

WORKING TABLE
SQL>select * from workin;

ENO DNO
------------ -----------
100 3
105 5
108 8
110 9
111 10
115 10

6 rows selected.

DEPARTMENT TABLE:
DNO DEPT_NAME
------------ -----------
3 A
5 B
8 C
9 D
10 E

Q1 To find eno and ename of employees whose basicpay is greater than 10,000.

SQL>select eno,ename from emp1


where basicpay>10000;

ENO ENAME
---------- -------------
100 Anil
105 Amit
108 Ajay
109 Deepak

Q2 To find eno and basicpay in descending order by basicpay

SQL>select ename,basicpay from emp1


order by basicpay desc;

ENAME BASICPAY
--------------- -------------------
Anil 20000
Amit 18000
Deepak 18000
Ajay 15000
Nitin 10000
Sumit 9000

6 rows selected.
Q3. To find the eno whose name begin with A letter.

SQL>select eno from emp1


where ename like ‘a%’;

ENO
------------
100
105
108

Q4. To find ENO whose basicpay is 9000,10000,15000.

SQL>select eno from emp1


where basicpay in (9000,10000,15000);

ENO
------------
108
111

Q5. To find the names of employee working in dept 10.

SQL>select ename from emp1,workin


2 where emp1.eno=workin.eno and workin.dno=10;
ENAME
--------------
Nitin
Sumit
PRACTICAL NO.7

AIM: Write a SQL program to add two number.

REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: PL SQL Program For to add two numbers. declare a number(2); b number(2);
c number(2); begin a:=&a; b:=&b; c:=a+b; dbms_output.put_line(a|| ' + '||b||' = '||c); end;
CODE: Declare
Var1 integer;
Var2 integer;
Var3 integer;
Begin
Var1:=&var1;
Var2:=&var2;
Var3:=var1+var2;
Dbms_output.put_line(var3);
End

OUTPUT:
PRACTICAL NO.8

AIM: Discuss about various data types used in SQL

REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: Every programming language has built-in data types which are used for
declaring variables and many other related tasks. Variable is nothing but the name of the
memory space. Every variable has a data type which specifies the storage format, set of
specified values, range of the variable and many other such factors.

Variables have to be defined in the declaration section of a PL/SQL program. However,


its not mandatory to include a declaration section and variable declaration in a PL/SQL
program if its not required.

The Data Types used in PL/SQL are as follows:

1. Scalar: These data types don’t include any internal components. It includes data types
such as NUMBER, DATE, BOOLEAN, etc.
2. Large Objects (LOB): This type of data type stores objects that are relatively large
in size and stored separately from other data types such as text, graphic images, video
clips, sound, etc.
3. Composite: These type of data types have internal components that can be accessed
individually. It includes records and collections.
4. Reference: As the name sounds, it includes pointers that refer to the location of the
other data items.
Now, I have listed down some of the sub data types frequently used in PL/SQL

1. Numeric: Numeric values on which arithmetic operations are performed. It includes


sub types such as number, decimal, real, float, etc.
2. Character: Character values on which character operations such as strings are
performed. It includes sub types such as char, varchar, varchar2, nvarchar2, etc.
3. Data and Time: This data type is used to store fixed data type which displays and
saves time and date values. The default data format saved into the database might be
‘DD-MM-YY’. However, you can change and alter the position of the terms accordingly.
4. Boolean: These include logical values on which logical operations are performed. The
logical values are the Boolean values TRUE and FALSE and the value NULL. But, SQL has
no data type equivalent to BOOLEAN. It cannot be used in SQL Statements, built in SQL
functions such as To_char, PL/SQL function invoked from DQL commands.
5. Number: Syntax: Number(Precision, Scale). Fixed-point or floating-point number with
absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can
also represent 0.
6. Float: ANSI and IBM specific floating-point type with maximum precision of 126 binary
digits (approximately 38 decimal digits).
7. Integer: ANSI and IBM specific integer type with maximum precision of 38 decimal
digits
8. Real: Floating-point type with maximum precision of 63 binary digits (approximately
18 decimal digits).
9. Varchar2: Variable-length character string with maximum size of 32,767 bytes.
10. Rowid: Physical row identifier, the address of a row in an ordinary table.
11. Bfile: Used to store large binary objects in operating system files outside the
database System-dependent. Cannot exceed 4GB.
12. Blob: Used to store large binary objects in the database. Memory Capacity: 8 to 128
TB.
13. Clob: Used to store large blocks of character data in the database. Memory Capacity:
8 to 128 TB.
14. Nclob: Used to store large blocks of NCHAR data in the database. Memory Capacity:
8 to 128 TB.
Note: A variable in PL/SQL program code can be assigned a NULL value i.e. ‘’. However,
it cannot be equated with any other variable or even itself.

Variable Declaration

Syntax
Variable-Name DataType(Precision/Dimension)
Example
Emp_name varchar2(30)
Here, Emp_name is the variable name and varchar2 is the data type with the 30 as the
precision or the dimension. It is allowed to assign values during declaration of a variable
in the declaration block. Setting the precision as 30 allows us to assign a string value of
not more than 30 characters for that particular variable.

There are many more PL/SQL data types used in PL/SQL programming language. Since,
this tutorial is especially for beginners, we just want you to first grasp the basic
understanding and then jump into deeper details. These mentioned are sufficient for you
to get started into PL/SQL programming. However, we shall mention new data types at
regular intervals later.
PRACTICAL NO.9

AIM: Discuss about SQL variables.

REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: Constraints are associated with the variables defined in the code block. A constraint
is a condition that is placed on the variable.

Two frequently used constraints in PL/SQL are:

Constant – This constraint will cause Oracle Engine to ensure the value is not changed after a
value is initially assigned to a variable. If a statement tries to change the variable value, an error
will be displayed.

Not Null – This constraint will cause Oracle Engine to ensure that the variable always contains a
value. If the statement attempts to assign an empty or a null value to that particular variable, the
program will be error prone and will get abnormal termination of the program or the exception
section will execute, if included in the program code.

How to Assign Values to Variables

A PL/SQL procedure is of no use if there isn’t any method to associate values with the variables.
But, PL/SQL provides us with the following ways to achieve this.

:=

This sign includes a ‘colon’ with a succeeding ‘equal to’ sign. This particular sign assigns the
parameter on the right hand side of the sign to the parameter or the variable on the left hand side
of the sign.

Into

The ‘Into’ keyword is used in a ‘Fetch’ or a ‘Select’ statement. For a Select statement, it assigns
the value in the Select section to the variables following the ‘Into’ keyword. When used with the
Fetch statement, it assigns the cursor values to the variables that follow the ‘Into’ keyword.

DECLARE

Var1 integer := 35;

Var2 integer := 55;

Var3 integer;
Var4 real;

BEGIN

Var3 := Var1 + Var2;

dbms_output.put_line('Value of Var3: ' || Var3);

Var4 := 70.0/3.0;

dbms_output.put_line('Value of Var4: ' || Var4);

END;

OUTPUT:

Value of Var3: 90

Value of Var4: 23.333333333333333333

SCOPE OF VARIABLES

Scope defines the visibility of a particular variable in a program code. PL/SQL gives us the
option to develop nesting of blocks which means that every block can contain another block
within itself. However, the outer block won’t be accessible.

There are two types of variable scope.

1. Local Variables

2. Global Variables

DECLARE

-- Global variables

num1 number := 100;

num2 number := 200;

BEGIN

dbms_output.put_line('Outer Block Variable num1: ' || num1);

dbms_output.put_line('Outer Block Variable num2: ' || num2);

DECLARE

-- Local variables
num1 number := 300;

num2 number := 400;

BEGIN

dbms_output.put_line('Inner Block Variable num1: ' || num1);

dbms_output.put_line('Inner Block Variable num2: ' || num2);

END;

END;

OUTPUT:

Outer Block Variable num1: 100

Outer Block Variable num2: 200

Inner Block Variable num1: 300

Inner Block Variable num2: 400

PL/SQL procedure successfully completed.


PRACTICAL NO.10

AIM: Discuss and Write a Program on SQL loops.

REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: A General Loop in PL/SQL is used to execute a set of statements at least once before
the termination of the loop. An EXIT condition has to be specified in the loop; otherwise the
looping process will get into a never ending loop, also known as an Infinite Loop. When the EXIT
condition in the loop is satisfied, the control exits from the loop.

SYNTAX:

LOOP

Statement1;

Statement2;

EXIT;

END LOOP;

EXAMPLE:

declare

var1 integer;

begin

var1:=&var1;

loop

dbms_output.put_line(var1);

var1:=var1+1;

exit when var1>5;

end loop;

end;
SQL FOR LOOP

FOR LOOP is used to execute a series of statements for a specific number of times. Iteration
occurs between the starting and ending integer values in a given range. The counter variable
(which is mandatory) is always incremented by 1. The loop exits when the counter attains the
value of the end integer.

Syntax

FOR counter IN var1....var2

LOOP statement1;

statement2;

END LOOP;

EXAMPLE

declare

var1 integer;

begin
var1:=&var1;

for var1 in 1..5

loop

dbms_output.put_line(var1);

end loop;

end;

OUTPUT:
PRACTICAL NO.11

AIM: To create queries using Procedures.

REQUIREMENTS: PC with window operating system and MYSQL.

THEORY: A Stored Procedure is a collection of Structured Query Language (SQL) statements


with a name assigned to them. These stored procedures are stored in a relational database
management system (RDBMS). So it is possible for multiple calling of the procedures to reduce
multiple executions and resulting in reduced execution time. Data can be modified using
procedures, and the major advantage is that it is not tied to a particular application.

Stored procedures can accept parameters as input and can return multiple values as an output
parameter. In SQL Server, stored procedures perform operations in the database and can return a
status value to an application or a batch calling procedure. User-defined procedures are created
using the user-defined database, with the exception when we have a read-only database. For that,
we need to develop it in Transact SQL (T-SQL). Tempdb is where all the temporary procedures
are stored.

There are two types of stored procedures.

 Local procedures
 Global procedures

Local procedures are the one which is only visible for the user using it in the connection, whereas
Global procedures are visible to any of the users in the same connection.

CREATE PROCEDURE <owner>.<procedure name>

<param> <datatype>

AS

<Body>

Execute a Stored Procedure

Exec is the command for the execution of the procedure.

EXEC Procedure_name

The following SQL statement creates a stored procedure that selects the company.
Code:

CREATE PROCEDURE SelectAllExample

AS

SELECT * FROM company GO;

Execute the stored procedure above as follows:

Executing the above-stored procedure, we can use the following command:

Code:

EXEC SelectAllExample;

Stored Procedure Example With One Parameter

The following SQL statement creates a stored procedure with a single parameter to be passed
that selects a company with an item as a parameter.

Code:

CREATE PROCEDURE SelectAllExample @item nvarchar(30)

AS

SELECT * FROM company WHERE item = @item GO;

Execute the stored procedure above as follows:

To execute the above-stored procedure with one parameter, we can use the following command:

Code:

EXEC SelectAllExample item = "cookies";

Stored Procedure Example with Multiple Parameters

The following SQL statement creates a stored procedure with multiple parameters that select
company with item and category as a parameter

Code:

CREATE PROCEDURE SelectAllExample @item nvarchar(30), @ category nvarchar(10)

AS SELECT * FROM company WHERE item = @ item AND category = @ category GO;
Execute the stored procedure above as follows:

To execute the above-stored procedure with multiple parameters, we can use the following
command we need to pass the multiple parameters with comma-separated: EXEC
SelectAllExample item =”cookies”, category =”edibles”;

Advantages and Disadvantages of Procedure in SQL

Below are the advantages and disadvantages mentioned:

Advantages:

Application improvement can be achieved by procedures. If a procedure is called multiple times


in a single application, then the compiled version of the procedure is utilized.

Traffic between the database and the application can be reduced as the big statements are already
fed into the database, and we don’t have to send it again and again.

Using procedures, code reusability can be achieved, similar to the functions and methods that
work in the java and other programming languages.

Disadvantages:

Stored Procedures consume a lot of memory. It is the duty of a database administrator has to
decide an upper bound to how many stored procedures are feasible for a particular application.

Stored procedures cannot be debugged using MySQL.

You might also like