DBMS - Lab - Manual Satyam

You might also like

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

Roll No.

:2028216 SUBJECT CODE:- BTCS501-18

Table of Content:

SNo. Name of the Practical Page No.

1 Introduction to SQL and installation of SQL Server /


Oracle 11G.

2 Representation of various Data Types, and SQL


Commands.

3 SQL/ORACLE Aggregate Functions and Matching a


pattern from a Table using Grouping the Result of a
query and Working with Null Values.

4 SQL/ORACLE Joins, Nested queries using Set


operators

5 (A) SQL/ORACLE Views, Indexes, Database security


and Privileges.
(B) SQL/ORACLE Grant, Revoke commands and
Commit, Rollback commands

6 PL/SQL Architecture, Assignments and Expressions, Writing


PL/SQL
Code, Referencing Non-SQL parameters.

7 PL/SQL Program to Print Message.

8 PL/SQL Program to Accept Number and Find the Sum


of Number.

9 PL/SQL Program to Calculate the Area of a Circle


Using Radius

10 PL/SQL Program to Print the no. is Even or odd.

11 Find the salary of the employee.


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

12 Write a Program to Find the Grade of the Students

13 PL/SQL Program for the Multiplication Table.

14 PL/SQL Program that Accepts a Number and Find the


Factorial

15 PL/SQL Program that Accepts a Number print its


Fibonacci series

16 PL/SQL Program that Accepts Three Values and


Display the Greater Value

17 PL/SQL Program to Find Simple Interest

18
PL/SQL Program to Accept a Number and Check it is
Prime Number or Not

19 PL/SQL Program to display the information of a given


department number using cursor.

20 PL/SQL Program to insert the values in a table using


cursor.

21 PL/SQL Program to update the salary of employee


Using Cusors.

22 PL/SQL Program to insert or update the Ename and Job


column of Employee table using trigger..

23 PL/SQL Program to delete the information of the


employee using dept_no from the employee table using
triggers

24 PL/SQL Program to Create a trigger that generate a


primary key automatically for a table emp3.Here Empno
should be of number datatype.

25 PL/SQL Program of a local procedure that accept two


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

number using parameters.

26 A stored procedure of PL\SQL that accepts two number 116


and display the product of two numbers.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Introduction to SQL & Oracle Database

SQL (Structured Query Language) is a special-purpose programming language designed


for managing data held in a relational database management system (RDBMS).

Originally based upon relational algebra and tuple relational calculus, SQL consists of a data
definition language and a data manipulation language. The scope of SQL includes data insert,
query, update and delete, schema creation and modification, and data access control.
Although SQL is often described as, and to a great extent is, a declarative language (4GL), it
also includes procedural elements.

The Oracle Database (commonly referred to as Oracle RDBMS or simply as Oracle) is an


object-relational database management system produced and marketed by Oracle
Corporation.

An Oracle database is a collection of data treated as a unit. The purpose of a database is to


store and retrieve related information. A database server is the key to solving the problems of
information management. In general, a server reliably manages a large amount of data in a
multiuser environment so that many users can concurrently access the same data. All this is
accomplished while delivering high performance. A database server also prevents
unauthorized access and provides efficient solutions for failure recovery.

Figure No.1 (SQL/ ORACLE DATABASE)


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 1

1). Introduction to SQL and installation of SQL Server / Oracle.

Step-by-step installing Oracle:-

As with most Windows installation programs, inserting the CD-ROM (ordered or purchased
from Oracle) into the CD-ROM drive automatically executes the setup program. (If this does
not happen, use the Windows Explorer to view the contents of your CD-ROM drive and
double click on the “setup” program there).

If you downloaded the Oracle9i from Oracle Technet, then you need to unzip the files into a
three temporary directories and double click on the setup.exe program in the Disk1 directory)
to get the installation process started.

The following Welcome window will appear:

Figure No.2

It is assumed that this is a fresh install so no other Oracle products should be installed at this
time.

Click on the Next button to move to the File Locations screen as shown below:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No. 3

In this screen, the Source and Destination locations must be selected.

The Source path should reflect either your CD-ROM or the directory in which you unzipped
the source files. Leave this as the default. In the example above, the source files were
unzipped into c:\source\Oralce\9i\NT20009011\Disk1 directory.

For the Destination, leave the Oracle Home named OraHome90 as the default. Choose a hard
disk drive that has at least 10 gigabytes of free space. In the example here, we are using the
C: drive.

Leave the \Oracle\Ora90 path as it is (the default). If you must change this to a different
drive, only change the drive letter and not the directories.

Click on the Next button to load the Product information. This may take up to 2 minutes
(depending on the speed of your machine). Once the product information has been read, the
following 3 “Available Products” options are presented:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.4

Make sure the Oracle9i Database 9.0.1.1.1 is selected and click on the Next button.

The “Installation Types” screen will appear next. For this installation, we chose the
Enterprise Edition.

Figure No.5

The “Database Configuration” screen will appear next:


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.6

For this install, we chose the “General Purpose” Database option. Click on the Next button to
continue.

The next step is to identify the database using the Global database name:

Figure No.7

If some default Global database name and SID are given, keep them. Otherwise, use the
following (make a note of these for later on):

Global Database Name is orcl


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Oracle SID is orcl

Click on the Next button to continue to the “Data File Location ” screen

Figure No.8

In this step, you need to select where the Oracle data files will be located. In large operations,
we typically keep the data files on a separate disk (or disks), however, for this install, we are
storing the data files in the same C:\oracle directory tree. Keep the default as shown and click
on the Next button to continue.

In the next screen, choose the default character set for the database:

Figure No.9

Click on the Next button to move to the “Summary” screen:


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.10

In this screen (shown above), the products and files that will be installed are summarized.
Note that in this example, it will take 1.5 GB MB of disk space for the installation of the
software. Additional space will be required for the default database.

If everything looks OK at this point, click on the Install button to begin the installation.

Figure No.11

During the install, you will notice various Oracle products being copied over to the hard disk.
For example, in the above figure, a portion of the Oracle Enterprise Manager is being
installed.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Once the installation is completed, the next step will be to configure the various additional
services and the database. This is shown below:

Figure No.12

Each of the configuration programs will be executed in turn. The HTTP Server
(Oracle/Apache) should launch automatically and open up TCP/IP port 80. You should notice
a new Command window as follows:

Oracle HTTP Server Powered by Apache/1.3.12 (Win32) ApacheJServ/1.1


mod_ssl/2.6.4 OpenSSL/0.9.5a mod_perl/1.24 running...

The Net Configuration Assistant and Oracle Intelligent Agent should run automatically and
not prsent any sustained screens.

The Oracle Database Configuration Assistant will appear for some time while the default
database is created and opened. As below:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.13

Once the default database has been installed, the following screen will appear:

Figure No.14

Clicking on the Password Management button and change the default passwords for the SYS,
SYSTEM, SCOTT and DBSNMP accounts as shown below:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.15

Click the OK button when done.

This should conclude the configuration of the database and the “End of Installation” screen
should appear as below. Click on the Exit button and click on the following Yes button to
confirm exiting the Installation program.

Figure No.16
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

At this point, be sure to reboot your computer so any final changes can take affect. In
particular, the path c:\oracle\ora90\bin will be added to the PATH environment variable.

New Program Groups:-

After Oracle9i is installed, you will notice several new program groups in the Start menu.

Figure No.17

These include:

• Oracle Installation ProductsTools to help manage the installation and removal of


Oracle products on the machine.
• Oracle – OraHome90The set of tools used to work with Oracle90. These include:
o Application Development – Tools to develop Oracle applications including
SQL*Plus
o Configuration and Migration Tools – Tools to migrate older Oracle
databases to version 9i
o Enterprise Management Packs
o Enterprise Manager Quick Tours
o Integrated Management Tools
o Oracle HTTP Server

Starting and Stopping the Database:-


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Under Windows NT and Windows 7 or Windows 2000, the Oracle 9i database runs
automatically as a service. Below is a view of the Windows 2000 Services mangement
console showing the services installed by default:

Figure No.18

Note the last one OracleServerORCL is the actual database process itself.
OracleOraHome90TNSListener is the listener process for remote connections to the database.
OracleOraHome90Agent is the Oracle Agent used to communicate with management
services. Finally, the OracleOraHome90HTTPServer is the Oracle/Apache web server.

Since the OracleServerORCL service is set to start automatically, the database wll start and
mount each time the computer is started up. To manage the database processes directly, one
can use the Enterprise Manager Console in Stand-alone mode. From the Start menu, choose
Programs -> Oracle - OraHome90 -> Enterprise Manager Console and select Launch
Standalone. The following screen should appear:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.19

Click on the plus sign to expand the Databases branch and then once again to expand the
ORCL branch. When prompted for username and password, use the SYSTEM account and
choose to log in as SYSDBA. In SYSDBA mode, the SYSTEM user can perform most any
manipulation of the database.

Once logged in, clicking on the Instance tree and then the Configuration tree should display
the current state of the database:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.20

Testing the Installation:-

Once the database is running, the SQL*Plus tool can be used to connect to the database.

Go to the Start -> Programs -> Oracle - OraHome90 -> Application Development program
group and run the SQL Plus application. Once SQL Plus is running, you will be prompted for
3 things: Username, password and Host String.

The default Database Administrator’s account has a username of SYSTEM and a default
password of MANAGER. You may have changed the SYSTEM account password in a
previous step so use the new password.

Fill in the Username and password fields with the SYSTEM account and leave the Host
String field blank. Since we are connecting to a local Oracle database, no Host String is
required. Click on the OK button as shown below:

Figure No.21

If the database is running and the username and password are typed correctly, SQL*Plus
should log the SYSTEM user in and present the SQL> prompt as shown below:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.22

By default, you can also log in with the SCOTT/TIGER account. That is, there is a demo
account already set up in the database with username SCOTT and password TIGER. Many of
the examples in the Oracle documentation use the tables included in the SCOTT user’s
account.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 2

2). Representation of various Data Types, and SQL Commands.

Oracle Database Data Types:-

Oracle Data Types


This chapter discusses the Oracle built-in data types, their properties, and how they map to
non-Oracle data types.

This chapter includes the following topics:

• Overview of Character Data types.


• Overview of Numeric Data types.
• Overview of DATE Data type.
• Overview of LOB Data types.
• Overview of Numeric Data types.

1). CHAR Data type:-

The CHAR data type stores fixed-length character strings. When you create a table with a
CHAR column, you must specify a string length (in bytes or characters) between 1 and 2000
bytes for the CHAR column width. The default is 1 byte. Oracle then guarantees that:

• When you insert or update a row in the table, the value for the CHAR column has the
fixed length.
• If you give a shorter value, then the value is blank-padded to the fixed length.
• If a value is too large, Oracle Database returns an error.

Oracle Database compares CHAR values using blank-padded comparison semantics.

2).VARCHAR2 and VARCHAR Data types:-

The VARCHAR2 data type stores variable-length character strings. When you create a table
with a VARCHAR2 column, you specify a maximum string length (in bytes or characters)
between 1 and 4000 bytes for the VARCHAR2 column. For each row, Oracle Database stores
each value in the column as a variable-length field unless a value exceeds the column's
maximum length, in which case Oracle Database returns an error. Using VARCHAR2 and
VARCHAR saves on space used by the table.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

For example, assume you declare a column VARCHAR2 with a maximum size of 50
characters. In a single-byte character set, if only 10 characters are given for the VARCHAR2
column value in a particular row, the column in the row's row piece stores only the 10
characters (10 bytes), not 50.

Oracle Database compares VARCHAR2 values using nonpadded comparison semantics.

3).Length Semantics for Character Data types:-

Globalization support allows the use of various character sets for the character data types.
Globalization support lets you process single-byte and multisystem character data and
convert between character sets. Client sessions can use client character sets that are different
from the database character set.

Consider the size of characters when you specify the column length for character data types.
You must consider this issue when estimating space for tables with columns that contain
character data.

The length semantics of character data types can be measured in bytes or characters.

• Byte semantics treat strings as a sequence of bytes. This is the default for character
data types.
• Character semantics treat strings as a sequence of characters. A character is
technically a code point of the database character set.

For single byte character sets, columns defined in character semantics are basically the same
as those defined in byte semantics. Character semantics are useful for defining varying-width
multi byte strings; it reduces the complexity when defining the actual length requirements for
data storage. For example, in a Unicode database (UTF8), you must define a VARCHAR2
column that can store up to five Chinese characters together with five English characters. In
byte semantics, this would require (5*3 bytes) + (1*5 bytes) = 20 bytes; in character
semantics, the column would require 10 characters.

VARCHAR2 (20 BYTE) and SUBSTRB (<string>, 1, 20) use byte semantics. VARCHAR2 (10 CHAR)
and SUBSTR (<string>, 1, 10) use character semantics.

4).NCHAR and NVARCHAR2 Data types:-

NCHAR and NVARCHAR2 are Unicode data types that store Unicode character data. The
character set of NCHAR and NVARCHAR2 data types can only be either AL16UTF16 or UTF8 and
is specified at database creation time as the national character set. AL16UTF16 and UTF8 are
both Unicode encoding.

• The NCHAR data type stores fixed-length character strings that correspond to the
national character set.
• The NVARCHAR2 data type stores variable length character strings.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

When you create a table with an NCHAR or NVARCHAR2 column, the maximum size specified
is always in character length semantics. Character length semantics is the default and only
length semantics for NCHAR or NVARCHAR2.

For example, if national character set is UTF8, then the following statement defines the
maximum byte length of 90 bytes:

CREATE TABLE tab1 (col1 NCHAR(30));

This statement creates a column with maximum character length of 30. The maximum byte
length is the multiple of the maximum character length and the maximum number of bytes in
each character.

This section includes the following topics:

• NCHAR
• NVARCHAR2

NCHAR:-

The maximum length of an NCHAR column is 2000 bytes. It can hold up to 2000 characters.
The actual data is subject to the maximum byte limit of 2000. The two size constraints must
be satisfied simultaneously at run time.

NVARCHAR2:-

The maximum length of an NVARCHAR2 column is 4000 bytes. It can hold up to 4000
characters. The actual data is subject to the maximum byte limit of 4000. The two size
constraints must be satisfied simultaneously at run time.

5). LOB Character Data types:-

The LOB data types for character data are CLOB and NCLOB. They can store up to 8 terabytes
of character data (CLOB) or national character set data (NCLOB).

LONG Data type:-

Columns defined as LONG can store variable-length character data containing up to 2


gigabytes of information. LONG data is text data that is to be appropriately converted when
moving among different systems.

LONG data type columns are used in the data dictionary to store the text of view definitions.
You can use LONG columns in SELECT lists, SET clauses of UPDATE statements, and VALUES
clauses of INSERT statements.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

6). NUMBER Data type:-

The NUMBER datatype stores fixed and floating-point numbers. Numbers of virtually any
magnitude can be stored and are guaranteed portable among different systems operating
Oracle Database, up to 38 digits of precision.

The following numbers can be stored in a NUMBER column:

• Positive numbers in the range 1 x 10-130 to 9.99...9 x 10125 with up to 38 significant


digits
• Negative numbers from -1 x 10-130 to 9.99...99 x 10125 with up to 38 significant digits
• Zero
• Positive and negative infinity (generated only by importing from an Oracle Database,
Version 5)

For numeric columns, you can specify the column as:

column_name NUMBER

Various Database Languages:-

1). Data manipulation Language.


2)/ Data Definition Language.

3). Data Control Language.

1) Data Manipulation Language:-

The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete
data:

• INSERT adds rows (formally tuples) to an existing table, e.g.:

INSERT INTO My_table


(field1, field2, field3)
VALUES

• UPDATE modifies a set of existing table rows, e.g.:

UPDATE My_table
SET field1 = 'updated value'
WHERE field2 = 'N';

• DELETE removes existing rows from a table, e.g.:

DELETE FROM My_table


WHERE field2 = 'N';
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

• MERGE is used to combine the data of multiple tables. It combines the INSERT and
UPDATE elements. It is defined in the SQL:2003 standard; prior to that, some databases
provided similar functionality via different syntax, sometimes called "upsert".

MERGE INTO TABLE_NAME USING table_reference ON (condition)


WHEN MATCHED THEN
UPDATE SET column1 = value1 [, column2 = value2 ...]
WHEN NOT MATCHED THEN
INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...

2) Data Definition Language:-

The Data Definition Language (DDL) manages table and index structure. The most basic
items of DDL are the CREATE, ALTER, RENAME, DROP and TRUNCATE statements:

• CREATE creates an object (a table, for example) in the database, e.g.:

CREATE TABLE My_table(


my_field1 INT,
my_field2 VARCHAR(50),
my_field3 DATE NOT NULL,
PRIMARY KEY (my_field1, my_field2)
);

• ALTER modifies the structure of an existing object in various ways, for example, adding a
column to an existing table or a constraint, e.g.:

ALTER TABLE My_table ADD my_field4 NUMBER(3) NOT NULL;

• TRUNCATE deletes all data from a table in a very fast way, deleting the data inside the table
and not the table itself. It usually implies a subsequent COMMIT operation, i.e., it cannot be
rolled back (data is not written to the logs for rollback later, unlike DELETE).

TRUNCATE TABLE My_table;

• DROP deletes an object in the database, usually irretrievably, i.e., it cannot be rolled back,
e.g.:

DROP TABLE My_table;

3) Data Control Language:-

The Data Control Language (DCL) authorizes users to access and manipulate data. Its two
main statements are:

• GRANT authorizes one or more users to perform an operation or a set of operations on an


object.
• REVOKE eliminates a grant, which may be the default grant.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Example:

GRANT SELECT, UPDATE


ON My_table
TO some_user, another_user;

REVOKE SELECT, UPDATE


ON My_table
FROM some_user, another_user;

1).CREATES DATABASE :-
The following SQL statement creates a database called "my_db":

CREATE DATABASE my_db;

Database tables can be added with the CREATE TABLE statement.

2).Creating Tables:-
The CREATE TABLE statement is used to create a table in a database.

Tables are organized into rows and columns; and each table must have a name.

CREATE TABLE Syntax:-

CREATE TABLE table_name


(
column_name1 data_type(size),
column_name2 data_type(size),
column_name3 data_type(size),
....
);

CREATE TABLE Example:-

Now we want to create a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City.

We use the following CREATE TABLE statement:

CREATE TABLE Persons


(
PersonID int,
LastName varchar(255),
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

The PersonID column is of type int and will hold an integer.

The LastName, FirstName, Address, and City columns are of type varchar and will hold
characters, and the maximum length for these fields is 255 characters.

The empty "Persons" table will now look like this:

OUTPUT:-

Figure No.1

3). INSERT INTO Statement:-

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

INSERT INTO Syntax:-

It is possible to write the INSERT INTO statement in many forms.

INSERT INTO table_name


VALUES (value1,value2,value3,...);

INSERT INTO Example:-

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal','Tom B. Erichsen','Skagen 21','Stavanger','4006','Norway');

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2

4). SELECT Statement:-

The SELECT statement is used to select data from a database. The result is stored in a result
table, called the result-set.

SELECT Syntax:-

SELECT column_name,column_name
FROM table_name;

SELECT * FROM table_name;

SELECT DISTINCT column_name,column_name


FROM table_name;

SELECT * Example:-

SELECT * FROM Customers;

SELECT DISTINCT City FROM Customers;


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

OUTPUT:-

Figure No.3

Figure No.4

Conditional Statement:-

5).WHERE Clause :-

The WHERE clause is used to extract only those records that fulfill a specified criterion.

WHERE Syntax:-

SELECT column_name,column_name
FROM table_name
WHERE column_name operator value;
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

WHERE Clause Example:-

The following SQL statement selects all the customers from the country "Mexico", in the
"Customers" table:

SELECT * FROM Customers


WHERE Country='Mexico';

OUTPUT:-

Figure No.5

6). AND & OR Operators:-

The AND operator displays a record if both the first condition AND the second condition are
true.

The OR operator displays a record if either the first condition OR the second condition is
true.

AND Operator Example:-

SELECT * FROM Customers


WHERE Country='Germany'
AND City='Berlin';
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

OR Operator Example:-

SELECT * FROM Customers


WHERE City='Berlin'
OR City='München';

Combining AND & OR:-

SELECT * FROM Customers


WHERE Country='Germany'
AND (City='Berlin' OR City='Mexico D.F.');

OUTPUT:-

Figure No.6

7).ORDER BY Keyword:-

The ORDER BY keyword is used to sort the result-set by one or more columns.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records
in a descending order, you can use the DESC keyword.

ORDER BY Syntax:-

SELECT column_name,column_name
FROM table_name
ORDER BY column_name,column_name ASC|DESC;
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

ORDER BY Example:-

SELECT * FROM Customers


ORDER BY Country;

SELECT * FROM Customers


ORDER BY Country DESC;

OUTPUT:-

Figure No.7

8). ALTER TABLE Statement:-

The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

ALTER TABLE Syntax

To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype

SQL Server / MS Access:


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

ALTER TABLE table_name


ALTER COLUMN column_name datatype

My SQL / Oracle:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype

ALTER TABLE Example:-

OUTPUT:-

Figure No.8

ALTER TABLE Persons


ADD DateOfBirth date

OUTPUT:-

Figure No.9

ALTER DROP COLUMN:-

we want to delete the column named "DateOfBirth" in the "Persons" table.


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

ALTER TABLE Persons


DROP COLUMN DateOfBirth

OUTPUT:-

Figure No.10

9). UPDATE Statement:-

The UPDATE statement is used to update existing records in a table.

UPDATE Syntax:-

UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

UPDATE Example:-

Assume we wish to update the customer "Alfreds Futterkiste" with a new contact person and
city.

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.11

UPDATE Customers
SET ContactName='Alfred Schmidt', City='Hamburg'
WHERE CustomerName='Alfreds Futterkiste';

OUTPUT:-

Figure No.12

10). DELETE Statement:-

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

DELETE Syntax:-

DELETE FROM table_name


WHERE some_column=some_value;
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

DELETE Example:-

Assume we wish to delete the customer "Alfreds Futterkiste" from the "Customers" table.

OUTPUT:-

Figure No.13

DELETE FROM Customers


WHERE CustomerName='Alfreds Futterkiste' AND ContactName='Maria Anders';

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.14

Delete All Data:- DELETE * FROM table_name;

11). DROP Statement:-

Indexes, tables, and databases can easily be deleted/removed with the DROP statement.

DROP INDEX Statement:-

The DROP INDEX statement is used to delete an index in a table.

DROP INDEX Syntax for DB2/Oracle:-

DROP INDEX index_name

The DROP DATABASE Statement:-

The DROP DATABASE statement is used to delete a database.

DROP DATABASE database_name;

The DROP TABLE Statement:-

The DROP TABLE statement is used to delete a table.

DROP TABLE table_name;


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

OUTPUT:-

Figure No.15

TRUNCATE TABLE Statement:-

What if we only want to delete the data inside the table, and not the table itself?

Then, use the TRUNCATE TABLE statement:

TRUNCATE TABLE table_name;

OUTPUT:-

Figure No.16

12). Rename Statement:-

RENAME TABLE Syntax:-


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

RENAME TABLE tbl_name TO new_tbl_name


[, tbl_name2 TO new_tbl_name2] ...

This statement renames one or more tables.

The rename operation is done atomically, which means that no other session can access any
of the tables while the rename is running. For example, if you have an existing table old_table,
you can create another table new_table that has the same structure but is empty, and then
replace the existing table with the empty one as follows (assuming that backup_table does not
already exist):

CREATE TABLE new_table (...);

RENAME TABLE TableName1 TO TableName2

13) DESCRIBE:-

The describe SQL command is used to list all of the fields in a table and the data format of each field.
It is phrased as: describe ;

Examples:
This would list all of the fields and their formats for the table called 'Colors':

Describe Colors;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.17
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 3

3). SQL/ORACLE Aggregate Functions and Matching a pattern from a


Table using Grouping the Result of a query and Working with Null Values.

SQL/Oracle aggregate functions return a single value, calculated from values in a column.

Useful aggregate functions:

• AVG() - Returns the average value


• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum

1). AVG () Function:-

The AVG () function returns the average value of a numeric column.

AVG () Syntax:-

SELECT AVG(column_name) FROM table_name;

AVG () Example:-

SELECT AVG(Price) AS PriceAverage FROM Products;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.1

Figure No.2

2). MAX () Function:-

The MAX () function returns the largest value of the selected column.

SQL MAX() Syntax:-

SELECT MAX(column_name) FROM table_name;

MAX() Example:-

SELECT MAX (Price) AS Highest Price FROM Products;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.3

Figure No.4

3). MIN() Function:-

The MIN() function returns the smallest value of the selected column.

MIN() Syntax:-

SELECT MIN(column_name) FROM table_name;

MIN() Example:-

SELECT MIN(Price) AS SmallestOrderPrice FROM Products;

OUTPUT:-

Figure No.5
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Fig
ure No.6

4). SUM() Function:-

The SUM() function returns the total sum of a numeric column.

SQL SUM() Syntax:-

SELECT SUM(column_name) FROM table_name;

SUM() Example:-

SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;

OUTPUT:-

Figure No.7

Figure No.8

**********Grouping the Result of a query**********

GROUP BY () Function:-

The GROUP BY statement is used in conjunction with the aggregate functions to group the
result-set by one or more columns.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

GROUP BY Syntax:-

SELECT column_name, aggregate_function(column_name)


FROM table_name
WHERE column_name operator value
GROUP BY column_name;

GROUP BY() Example:-

The following SQL statement counts as orders grouped by shippers:

SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders


LEFT JOIN Shippers
ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;

OUTPUT:-

Figure No.9
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.10

**********Matching a pattern from a Table**********

LIKE Operator for pattern matching:-

The LIKE operator is used to search for a specified pattern in a column.

LIKE Syntax:-

SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;

LIKE Operator Examples:-

SELECT * FROM Customers

WHERE Country LIKE 'M%';

OUTPUT:-

Figure No.11

Figure No.12
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

**********Working with Null Values**********

NULL Values:-

If a column in a table is optional, we can insert a new record or update an existing record
without adding a value to this column. This means that the field will be saved with a NULL
value.

NULL values are treated differently from other values.

NULL is used as a placeholder for unknown or inapplicable values.

Example:-

CREATE TABLE Persons


(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255)
)

OUTPUT:-

Figure No.13

SELECT LastName,FirstName,Address FROM Persons


WHERE Address IS NULL;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.14
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 4

4). SQL/ORACLE Joins, Nested queries using Set operators.

JOIN:-

An SQL JOIN clause is used to combine rows from two or more tables, based on a common
field between them.

The most common type of join is: SQL INNER JOIN (simple join). An SQL INNER JOIN
return all rows from multiple tables where the join condition is met.

OUTPUT:-

Figure No.1

Figure No.2

Example:-

SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate


FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

OUPTUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.3

INNER JOIN Keyword:-

The INNER JOIN keyword selects all rows from both tables as long as there is a match
between the columns in both tables.

INNER JOIN Syntax:-

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name;

INNER JOIN is the same as JOIN.

Figure No.4

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.5

Figure No.6

Example:-

SELECT Customers.CustomerName, Orders.OrderID

FROM Customers

INNER JOIN Orders

ON Customers.CustomerID=Orders.CustomerID

ORDER BY Customers.CustomerName;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.7

LEFT JOIN Keyword:-

The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows
in the right table (table2). The result is NULL in the right side when there is no match.

LEFT JOIN Syntax:-

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name=table2.column_name;

In some databases LEFT JOIN is called LEFT OUTER JOIN.

Figure No.8

Figure No.9
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.10

LEFT JOIN Example:-

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

OUTPUT:-

Figure No.11

RIGHT JOIN Keyword:-

The RIGHT JOIN keyword returns all rows from the right table (table2), with the matching
rows in the left table (table1). The result is NULL in the left side when there is no match.

RIGHT JOIN Syntax:-

SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name=table2.column_name;
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

Figure No.12

Database:-

Figure No.13

Figure No.14

Example:-

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
RIGHT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.15

FULL OUTER JOIN Keyword:-

The FULL OUTER JOIN keyword returns all rows from the left table (table1) and from the
right table (table2).

The FULL OUTER JOIN keyword combines the result of both LEFT and RIGHT joins.

FULL OUTER JOIN Syntax:-

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name=table2.column_name;

Figure No.16

Database:-

Figure No.17
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.18

Example:-

SELECT Customers.CustomerName, Orders.OrderID


FROM Customers
FULL OUTER JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

OUTPUT:-

Figure No.19

SET operators:-

INTERSECT, EXCEPT, and UNION are set operators that perform operations between two or more
input sets. UNION has been available in t-sql for some time, while INTERSECT and EXCEPT were
introduced in SQL 2005. All three operators have similar requirements:

1. Require a minimum of 2 input sets


2. Each input set must have the same number of columns returned
3. Each relative column must have compatible data types
4. The ORDER BY clause can only be used on the final set.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

UNION Operator:-

The UNION operator is used to combine the result-set of two or more SELECT statements.

UNION Syntax:-

SELECT column_name(s) FROM table1


UNION
SELECT column_name(s) FROM table2;

Database:-

Figure No.20

Figure No.21

OUTPUT:-

Figure No.22
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

INTERSECT operator:-

The SQL INTERSECT operator takes the results of two queries and returns only rows that appear in
both result sets. For purposes of duplicate removal the INTERSECT operator does not distinguish
between NULLs. The INTERSECT operator removes duplicate rows from the final result set. The
INTERSECT ALL operator does not remove duplicate rows from the final result set.
Syntax:-

SELECT column1 [, column2 ]


FROM table1 [, table2 ]
[WHERE condition]
INTERSECT
SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

DATABASE:-

Figure No.23

Figure No.24

EXAMPLE:-

SELECT ID, NAME, AMOUNT, DATE


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

FROM CUSTOMERS

LEFT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

INTERSECT

SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

RIGHT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

OUTPUT:-

Figure No.25

EXCEPT operator:-

The EXCEPT clause/operator is used to combine two SELECT statements and returns rows from the
first SELECT statement that are not returned by the second SELECT statement. This means EXCEPT
returns only rows, which are not available in second SELECT statement.

Syntax:-

SELECT column1 [, column2 ]


FROM table1 [, table2 ]
[WHERE condition]

EXCEPT

SELECT column1 [, column2 ]


FROM table1 [, table2 ]
[WHERE condition]

DATABASE:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.26

Figure No.27

Example:-

SQL> SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

LEFT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

EXCEPT

SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS

RIGHT JOIN ORDERS

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.28

***************Nested queries***************

A Sub query or Inner query or Nested query is a query within another SQL query and
embedded within the WHERE clause.

A sub query is used to return data that will be used in the main query as a condition to further
restrict the data to be retrieved.

Sub queries can be used with the SELECT, INSERT, UPDATE, and DELETE statements
along with the operators like =, <, >, >=, <=, IN, BETWEEN etc.

There are a few rules that sub queries must follow:

• Sub queries must be enclosed within parentheses.


• A sub query can have only one column in the SELECT clause, unless multiple
columns are in the main query for the sub query to compare its selected columns.
• An ORDER BY cannot be used in a sub query, although the main query can use an
ORDER BY. The GROUP BY can be used to perform the same function as the
ORDER BY in a sub query.
• Sub queries that return more than one row can only be used with multiple value
operators, such as the IN operator.
• The SELECT list cannot include any references to values that evaluate to a BLOB,
ARRAY, CLOB, or NCLOB.
• A sub query cannot be immediately enclosed in a set function.
• The BETWEEN operator cannot be used with a sub query; however, the BETWEEN
operator can be used within the sub query.

Syntax:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

SELECT column_name [, column_name ]

FROM table1 [, table2 ]

WHERE column_name OPERATOR

(SELECT column_name [, column_name ]

FROM table1 [, table2 ]

[WHERE])condition

DATABASE:-

Figure No.29

EXAMPLE:-

SQL> SELECT *

FROM CUSTOMERS

WHERE ID IN (SELECT ID

FROM CUSTOMERS

WHERE SALARY > 4500) ;.

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.30
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 5

5). (A) SQL/ORACLE Views, Indexes, Database security and Privileges.


(B) SQL/ORACLE Grant, Revoke commands and Commit, Rollback
commands.

Views:-

A view is a virtual table. A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.

CREATE VIEW Statement:-

A view is a virtual table based on the result-set of an SQL statement.

A view contains rows and columns, just like a real table. The fields in a view are fields from
one or more real tables in the database. You can add SQL functions, WHERE, and JOIN
statements to a view and present the data as if the data were coming from one single table.

Syntax:-

CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition;

DATABASE:-

Figure No.1

EXAMPLE:-

CREATE VIEW CUSTOMERS_VIEW AS


SELECT name, age
FROM CUSTOMERS;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2
Updating a View:-

A view can be updated under certain conditions:

• The SELECT clause may not contain the keyword DISTINCT.


• The SELECT clause may not contain summary functions.
• The SELECT clause may not contain set functions.
• The SELECT clause may not contain set operators.
• The SELECT clause may not contain an ORDER BY clause.
• The FROM clause may not contain multiple tables.
• The WHERE clause may not contain sub queries.
• The query may not contain GROUP BY or HAVING.
• Calculated columns may not be updated.
• All NOT NULL columns from the base table must be included in the view in order for
the INSERT query to function.

EXAMPLE:-

UPDATE CUSTOMERS_VIEW

SET AGE = 35

WHERE name='Ramesh';

OUTPUT:-

Figure No.3
Deleting Rows into a View:-

DELETE FROM CUSTOMERS_VIEW


WHERE age = 22;
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

OUTPUT:-

Figure No.4
Dropping Views:-

Obviously, where you have a view, you need a way to drop the view if it is no longer needed.

DROP VIEW CUSTOMERS_VIEW;

Indexes:-

Indexes are special lookup tables that the database search engine can use to speed up data
retrieval. Simply put, an index is a pointer to data in a table. An index in a database is very
similar to an index in the back of a book.

For example, if you want to reference all pages in a book that discuss a certain topic, you first
refer to the index, which lists all topics alphabetically and are then referred to one or more
specific page numbers.

An index helps 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 Command:-

CREATE INDEX index_name ON table_name;

Single-Column Indexes:-

A single-column index is one that is created based on only one table column. The basic
syntax is as follows:

CREATE INDEX index_name


ON table_name (column_name);
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. The basic syntax is as
follows:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

CREATE INDEX index_name


on table_name (column_name);

Composite Indexes:

A composite index is an index on two or more columns of a table. The basic syntax is as
follows:

CREATE INDEX index_name


on table_name (column1, column2,…….. columnn);

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 Command:-

An index can be dropped using SQL DROP command. Care should be taken when dropping
an index because performance may be slowed or improved.

DROP INDEX index_name;


*************** Database security and Privileges***************
Introduction to Database Security:-

Database security entails allowing or disallowing user actions on the database and the objects
within it. Oracle uses schemas and security domains to control access to data and to restrict
the use of various database resources.

Oracle provides comprehensive discretionary access control. Discretionary access control


regulates all user access to named objects through privileges. A privilege is permission to
access a named object in a prescribed manner; for example, permission to query a table.
Privileges are granted to users at the discretion of other users.

Database Users and Schemas:-

Each Oracle database has a list of user names. To access a database, a user must use a
database application and attempt a connection with a valid user name of the database. Each
user name has an associated password to prevent unauthorized use.

Security Domain:-

Each user has a security domain—a set of properties that determine such things as:

• The actions (privileges and roles) available to the user


• The table space quotas (available disk space) for the user
• The system resource limits (for example, CPU processing time) for the user
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Privileges:-

A privilege is a right to run a particular type of SQL statement. Some examples of privileges
include the right to:

• Connect to the database (create a session)


• Create a table in your schema
• Select rows from someone else's table
• Run someone else's stored procedure

(B) SQL/ORACLE Grant, Revoke commands and Commit, Rollback commands.

COMMIT Command:-

The COMMIT command is the transactional command used to save changes invoked by a
transaction to the database.

DATABASE:-

Figure No.5
Example:-

DELETE FROM CUSTOMERS

WHERE AGE = 25;

COMMIT;

OUTPUT:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.6
ROLLBACK Command:-

The ROLLBACK command is the transactional command used to undo transactions that have
not already been saved to the database.

DATABASE:-

Figure No.7

EXAMPLE:-

DELETE FROM CUSTOMERS

WHERE AGE = 25;

ROLLBACK;

OUTPUT:-

Figure No.8
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 6

6). PL/SQL Architecture, Assignments and Expressions, Writing PL/SQL


Code, Referencing Non-SQL parameters.

SQL (Structured Query Language) is a special-purpose programming language designed


for managing data held in a relational database management system (RDBMS).

Originally based upon relational algebra and tuple relational calculus, SQL consists of a data
definition language and a data manipulation language. The scope of SQL includes data insert,
query, update and delete, schema creation and modification, and data access control.
Although SQL is often described as, and to a great extent is, a declarative language (4GL), it
also includes procedural elements.

Procedural Language/Structured Query Language (PL/SQL) is Oracle Corporation's


procedural extension language for SQL and the Oracle relational database. PL/SQL's general
syntax resembles that of Ada or Pascal. It is also one of three key programming languages
embedded in the Oracle Database, along with SQL itself and Java.

PL/SQL is available in Oracle Database (since version 7), Times Ten in-memory database
(since version 11.2.1), and IBM DB2 (since version 9.7).[1]

PL/SQL supports variables, conditions, loops and exceptions. Arrays are also supported,
though in a somewhat unusual way, involving the use of PL/SQL collections.

Implementations from version 8 of Oracle Database onwards have included features


associated with object-orientation.

Once the program units have been stored into the database, they become available for
execution at a later time.

While programmers can readily embed Data Manipulation Language (DML) statements
directly into their PL/SQL code using straightforward SQL statements, Data Definition
Language (DDL) requires more complex "Dynamic SQL" statements to be written in the
PL/SQL code. However, DML statements underpin the majority of PL/SQL code in typical
software applications.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.1 PL/SQL ORACLE DATABASE

********************Differences between SQL and PL-SQL ********************

SQL is a query language that allows you to issue a single query or execute a single
insert/update/delete.

PL-SQL is Oracle's "Programming Language" SQL, which allows you to write a full program (loops,
variables, etc.) to accomplish multiple selects/inserts/updates/deletes. You should learn SQL first,
then move on to PL-SQL. You will probably need both to be an Oracle DBA.

SQL is the only language through which you create or modify data and structures in Oracle.
Although other tools will connect with the database, they all use SQL to read and modify
data.

Oracle's PL/SQL is a programming language that extends SQL to include procedural


elements, such as loops and whatnot. With PL/SQL alone there is little you can do -- learn
SQL first, then learn PL/SQL to learn how to write effective scripts and programs.

SQL is used to perform operations on data. There is an ANSI standard for it. Most databases
support it, although each may have differences in the interpretation, and each typically has
some proprietary extensions to it.

PL SQL is exactly as Shane described. It allows programmatic manipulation of SQL and


result sets, and if you look at the Oracle PL-SQL APIs, lots of other stuff too.

PL/SQL Architecture:-

The PL/SQL compilation and run-time system is an engine that compiles and executes
PL/SQL blocks and subprograms. The engine can be installed in an Oracle server or in an
application development tool such as Oracle Forms.

In either environment, the PL/SQL engine accepts as input any valid PL/SQL block or
subprogram. Figure shows the PL/SQL engine processing an anonymous block. The PL/SQL
engine executes procedural statements but sends SQL statements to the SQL engine in the
Oracle database.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2

Where PL/SQL stands?

Figure No.3

The client can interact with the system through front end application program.When there is a
data oriented operation it invokes the PL/SQL program in single step.In PL/SQL end it
approaches PL/SQL Engine which splits PL and SQL part separately and send the SQL
request to the SQL. Now SQL sends the data request through query to database.Data if
available will be send back to SQL in turn to PL/SQL.Now PL/SQL will send the return
values back to the client application

Assignment Statement:-

An assignment statement sets the current value of a variable, field, parameter, or element. The
statement consists of an assignment target followed by the assignment operator and an expression.
When the statement is executed, the expression is evaluated and the resulting value is stored in the
target. For more information, see "Assigning Values to Variables".

Syntax:-
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Assignment statement:-

Figure No.4

PL/SQL Expressions:-

Regular expressions enable you to search for patterns in string data by using standardized syntax
conventions. You specify a regular expression by means of the following types of characters:

• Meta characters, which are operators that specify search algorithms

• Literals, which are the characters for which you are searching

How Are Oracle Database Regular Expressions Useful?

Regular expressions are a powerful text processing component of programming languages such as
Perl and Java. For example, a Perl script can process each HTML file in a directory, read its contents
into a scalar variable as a single string, and then use regular expressions to search for URLs in the
string.

Oracle's support of regular expressions enables developers to implement complex match logic in the
database. This technique is useful for the following reasons:

• By centralizing match logic in Oracle Database, you avoid intensive string processing of SQL
results sets by middle-tier applications.

• Prior to Oracle Database 10g, developers often coded data validation logic on the client,
requiring the same validation logic to be duplicated for multiple clients. Using server-side
regular expressions to enforce constraints solves this problem.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

• The built-in SQL and PL/SQL regular expression functions and conditions make string
manipulations more powerful and less cumbersome than in previous releases of Oracle
Database.

Writing PL/SQL code:-

PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and
written in logical blocks of code. Each block consists of three sub-parts:

S.N. Sections & Description

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

Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists
2
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. Here is the basic structure of a PL/SQL block:

Syntax:-

DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;

The 'Hello World' Example:

DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

The end; line signals the end of the PL/SQL block. To run the code from SQL command line,
you may need to type / at the beginning of the first blank line after the last line of the code.
When the above code is executed at SQL prompt, it produces the following result:

OUTPUT:-

Hello World

PL/SQL procedure successfully completed.


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 7

7). PL/SQL Program to Print Message.

SET SERVER OUTPUT ON;

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 8

8). PL/SQL Program to Accept Number and Find the Sum of Number.

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 9

9) PL/SQL Program to Calculate the Area of a Circle Using Radius

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 10

10). PL/SQL Program to Print the no. is Even or odd.

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 11

11) Find the salary of the employee.

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 12

12) Write a Program to Find the Grade of the Student

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 13

13). PL/SQL Program for the Multiplication Table.

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 14

14). PL/SQL Program that Accepts a Number and Find the Factorial

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 15

15). PL/SQL Program that Accepts a Number print its Fibonacci series

Figure No.1

OUTPUT:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 16

16). PL/SQL Program that Accepts Three Values and Display the Greater
Value

Figure No.1

OUTPUT:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 17

17). PL/SQL Program to Find Simple Interest

Figure No.1

OUTPUT:

Figure No.2
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 18

18). PL/SQL Program to Accept a Number and Check it is Prime Number


or Not

Figure No.1

OUTPUT:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 19

19). PL/SQL Program to display the information of a given department


number using cursor.

Figure No.1

OUTPUT:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 20

20). PL/SQL Program to insert the values in a table using cursor.

Figure No.1
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

Figure No.2
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 21

21). PL/SQL Program to update the salary of employee Using cursors.


Roll No.:-2028216 SUBJECT CODE:- BTCS501-18
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 22

22). PL/SQL Program to insert or update the Ename and Job column of
Employee table using trigger.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 23

23). PL/SQL Program to delete the information of the employee using


dept_no from the employee table using triggers.
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 24

24). PL/SQL Program to Create a trigger that generates a primary key


automatically for a table emp3.Here Empno should be of number data
type.

Output:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 25

25). PL/SQL Program of a local procedure that accept two number using
parameters.

Output:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

PRACTICAL # 26

26) A stored procedure of PL\SQL that accepts two number and display
the product of two numbers.

OUTPUT:
Roll No.:-2028216 SUBJECT CODE:- BTCS501-18

You might also like