0% found this document useful (0 votes)
32 views47 pages

LAB FILE DBMS GLBM 2022-23new

The document discusses different data types used in databases including character, number, date, raw and other data types. It also discusses SQL and data definition language statements like CREATE, DROP, ALTER which are used to define and manage database structure and objects.

Uploaded by

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

LAB FILE DBMS GLBM 2022-23new

The document discusses different data types used in databases including character, number, date, raw and other data types. It also discusses SQL and data definition language statements like CREATE, DROP, ALTER which are used to define and manage database structure and objects.

Uploaded by

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

Experiment-1

Objective: Study of DBMS, RDBMS.

DATABASE AND DATABASE MANAGEMENT SYSTEM (DBMS)


Database is a collection of interrelated data and a Database Management System is a software system that
enables users to define, create and maintain the database and which provides controlled access to the database.
Any Programming environment used to create containers, to manage human data, can be conceptualized as a
DBMS. Traditionally, the block of human data being managed is called Database.
All DBMSs (Oracle being one of them) allow users to create containers for data storage and management.
These containers are called ‘Cells’. The minimum information that has to be given to Oracle for suitable
container to be constructed which can hold free form human data is
• The cell Name
• The Cell length
• The type of Data that can be placed into the Cell

Cell Name- When we wish to view the contents of a cell later, all we need to do is tell the programming
environment the cell name. The programming environment is intelligent enough to fetch for us Contents of
Cell rather than the cell itself.

Cell Length- This is the manner we ‘Rigidize’ free form human data. We create a container of
predetermined length into which we will store ‘free form’ human data for management. For example – this
automatically puts a limit on the length of a person’s ‘Name’ that we can hold in the container.

Cell Data type- The human data is mainly of two types, Characters or Numbers. We would then have to
inform the programming environment, which is creating the cell for us, what kind of data we will store in the
cell when it is being used.

Another name that programming environment use for a ‘Cell’ is ‘Field. These names can be used
interchangeably and generally mean the same thing.

RDBMS
A relational database management system (RDBMS) is a database management system (DBMS) that is based
on the relational model as invented by E. F. Codd, of IBM's San Jose Research Laboratory. In 2016, many of
the databases in widespread use are based on the relational database model.
RDBMSs are a common choice for the storage of information in new databases used for financial records,
manufacturing and logistical information, personnel data, and other applications since the 1980s. Relational
databases have often replaced legacy hierarchical databases and network databases because they are easier to
understand and use.

1
Figure: The general structure of Relational Database

According to research company Gartner, the five leading commercial relational database vendors by revenue
in 2011 were Oracle (48.8%), IBM (20.2%), Microsoft (17.0%), SAP including Sybase (4.6%), and Teradata
(3.7%).

The four leading open source implementations are Firebird, MySQL, PostgreSQL, and SQLite. MariaDB is a
prominent fork of MySQL prompted by Oracle's acquisition of MySQL AB. According to Gartner, in 2008,
the percentage of database sites using any given technology were (a given site may deploy multiple
technologies):

• Oracle Database - 70%


• Microsoft SQL Server - 68%
• MySQL (Oracle Corporation) - 50%
• IBM DB2 - 39%
• IBM Informix - 18%
• SAP Sybase Adaptive Server Enterprise - 15%
• SAP Sybase IQ - 14%
• Teradata - 11%

According to DB-Engines, the most widely used systems are Oracle, MySQL, Microsoft SQL Server,
PostgreSQL and IBM DB2.

E. F. CODD'S 12 RULES
Dr Edgar F. Codd, after his extensive research on the Relational Model of database systems, came up with
twelve rules of his own, which according to him, a database must obey in order to be regarded as a true
relational database.

2
These rules can be applied on any database system that manages stored data using only its relational
capabilities. This is a foundation rule, which acts as a base for all the other rules.

Rule 1: Information Rule- The data stored in a database, may it be user data or metadata, must be a value of
some table cell. Everything in a database must be stored in a table format.

Rule 2: Guaranteed Access Rule- Every single data element (value) is guaranteed to be accessible logically
with a combination of table-name, primary-key (row value), and attribute-name (column value). No other
means, such as pointers, can be used to access data.

Rule 3: Systematic Treatment of NULL Values- The NULL values in a database must be given a systematic
and uniform treatment. This is a very important rule because a NULL can be interpreted
as one the following − data is missing, data is not known, or data is not applicable.

Rule 4: Active Online Catalog- The structure description of the entire database must be stored in an online
catalog, known as data dictionary, which can be accessed by authorized users. Users can use the same query
language to access the catalog which they use to access the database itself.

Rule 5: Comprehensive Data Sub-Language Rule- A database can only be accessed using a language
having linear syntax that supports data definition, data manipulation, and transaction management operations.
This language can be used directly or by means of some application. If the database allows access to data
without any help of this language, then it is considered as a violation.

Rule 6: View Updating Rule- All the views of a database, which can theoretically be updated, must also be
updatable by the system.

Rule 7: High-Level Insert, Update, and Delete Rule- A database must support high-level insertion,
updation, and deletion. This must not be limited to a single row, that is, it must also support union, intersection
and minus operations to yield sets of data records.

Rule 8: Physical Data Independence- The data stored in a database must be independent of the applications
that access the database. Any change in the physical structure of a database must not have any impact on how
the data is being accessed by external applications.

Rule 9: Logical Data Independence- The logical data in a database must be independent of its user’s view
(application). Any change in logical data must not affect the applications using it. For example, if two tables
are merged or one is split into two different tables, there should be no impact or change on the user application.
This is one of the most difficult rule to apply.

Rule 10: Integrity Independence- A database must be independent of the application that uses it. All its
integrity constraints can be independently modified without the need of any change in the application. This
rule makes a database independent of the front-end application and its interface.

3
Rule 11: Distribution Independence- The end-user must not be able to see that the data is distributed over
various locations. Users should always get the impression that the data is located at one site only. This rule
has been regarded as the foundation of distributed database systems.
Rule 12: Non-Subversion Rule- If a system has an interface that provides access to low-level records, then
the interface must not be able to subvert the system and bypass security and integrity constraints.

4
Experiment-2

Objective: To study the Data Types and Data Definition language Statements.

VARIOUS DATA TYPES

1. CHARACTER DATA TYPES


Char – fixed length character string that can varies between 1-2000 bytes
Varchar/Varchar2 – variable length character string, size ranges from 1-4000 bytes. it saves the disk
space(only length of the entered value will be assigned as the size of column) Long - variable length character
string, maximum size is 2 GB

2. NUMBER DATA TYPES


Can store +ve, -ve, zero, fixed point, floating point with 38 precision.
Number – {p=38,s=0}
Number(p) - fixed point
Number(p, s) –floating point (p=1 to 38,s= -84 to 127)

3. DATE DATA TYPE


Used to store date and time in the table.
DB uses its own format of storing in fixed length of 7 bytes for century, date, month, year, hour, minutes, and
seconds.
Default data type is “dd-mon-yy”

4. RAW DATA TYPE


Used to store byte oriented data like binary data and byte string.

5. OTHER
CLOB – stores character object with single byte character.
BLOB – stores large binary objects such as graphics, video, sounds. BFILE – stores
file pointers to the LOB’s.

SQL (STRUCTURED QUERY LANGUAGE)


It is structured query language, basically used to pass the query to retrieve and manipulate the information
from database. Depending upon the nature of query, SQL is divided into different components:
• DDL(Data Definition Language )
• DML(Data Manipulation Language )
• DCL(Data Control Language )

DDL (Data Definition Language) The Data Definition Language (DDL) is used to create the database (i.e.
tables, keys, relationships etc), maintain the structure of the database and destroy databases an d database
objects. Eg. Create, Drop, Alter, Describe, Truncate
1. CREATE statements -
5
It is used to create the table.

Syntax
CREATE TABLE table-name ( column-name1 datatype
(size), column-name2 datatype (size),………
);

Example
CREATE TABLE student (Rollno number(10), Name varchar2(20),
Branch varchar2(2), Semester number(1));

2. DROP statements -
To destroy an existing database, table, index, or view. If a table is dropped all records held within it are lost
and cannot be recovered.

Syntax
DROP TABLE table-name;

Example
DROP TABLE student;

3. ALTER statements -
To modify an existing database object.

Adding new columns

Syntax
ALTER TABLE table-name ADD (new-column-name1 datatype (size), new_column-name2
datatype (size),………);

Example
ALTER TABLE student Add (Age number (2));

Dropping a columns from a table

Syntax
ALTER TABLE table-name DROP column column-name;

Example
ALTER TABLE student DROP column age;

6
Modifying Existing columns
Syntax
ALTER TABLE table-name MODIFY (column-name1 Newdatatype(Newsize));

Example
ALTER TABLE student MODIFY (Rollno varchar2(10));

4. Describe statements -
To describe the structure (column and data types) of an existing
database, table, index, or view.
Syntax
DESC table-name;

Example
DESC student;

5. Truncate statements –
To destroy the data in an existing database, table, index, or view. If a
table is truncated all records held within it are lost and cannot be recovered but the table structure is
maintained.

Syntax
TRUNCATE TABLE table-name;

Example
TRUNCATE TABLE student;

7
Experiment-3

Objective: To study Data Manipulation Statements.

DML (DATA MANIPULATION LANGUAGE)


A Data Manipulation Language enables programmers and users of the database to retrieve insert, delete and
update data in a database. e.g. INSERT, UPDATE, DELETE, SELECT.

1. INSERT
INSERT statement adds one or more records to any single table in a relational database.

Syntax
INSERT INTO table-name VALUES (expr1, expr2……..);

Example
INSERT INTO student VALUES (0123456789, ‘Sameer’, ‘CS’, 3);

2. UPDATE
UPDATE statement that changes the data of one or more records in a table. Either all the rows can be updated,
or a subset may be chosen using a condition.

Syntax
UPDATE table-name SET column-name = value, column-name = value ….WHERE condition;

Example
UPDATE student SET branch = ‘ME’ WHERE name = ‘Sameer’;

3. DELETE
DELETE statement removes one or more records from a table. A subset may be defined for deletion using a
condition, otherwise all records are removed.

Syntax
DELETE FROM table-name WHERE condition;

Example
DELETE FROM student WHERE name = ‘Sameer’;

4. SELECT
SELECT statement returns a result set of records from one or more tables.

Syntax

8
SELECT<attribute list>
FROM<table list>
WHERE<condition>;
Example:
SELECT branch, semester FROM student WHERE name = ‘Sameer’;
• Attribute list is a list of attribute name whose values to be retrieved by the query.
• Table list is a list of table name required to process query.
• Condition is a Boolean expression that identifies the tuples to be retrieved by query.

9
Experiment-4
Objective: To Study of SELECT command with different clauses.

VIEWING DATA IN THE TABLES


Since data has been inserted into a table, the next most logical operation would be to view what has been
entered. The ‘SELECT’ SQL verb is used to achieve this.
To understand all type of SELECT statement, consider the example table given below:

Rollno Name Branch Semester Age


1234567801 Lokesh CS 1 18
1234567802 Kushagra CS 1 19
1234567803 Rohit ME 3 20
1234567804 Mohit ME 1 17
1234567805 Soham EC 3 19
1234567806 Rohan EC 1 18
1234567807 Versha CS 1 17
1234567808 Pooja EE 3 18
1234567890 Neeraj EE 1 20
1234567810 Sooraj CE 3 21
table-name: student

1. ALL ROWS AND ALL COLUMNS


In order to view global table data, the syntax is:

Syntax
SELECT (column-name1, column-name2, …………., column-name N) FROM table-name;
OR
SELECT * FROM table-name;

Example
SELECT * FROM student;

Result
The whole student table will be displayed as output of query.

2. FILTERING TABLE DATA


While viewing data from a table it is rare that all the data from the table will be required each time. Hence,
SQL must give us a method of filtering out data that is not required. The way of filtering table data will be:

Selected Columns and All Rows-

10
The retrieval of specific columns from a table:

Syntax
SELECT column-name1, column-name2,………, column-name M FROM table-name;

Here M (<N) are the required number of columns.

Example
SELECT Name, Age FROM student;

Result
Only values of columns Name and Age will be displayed from the whole table.

Selected Rows and All Columns-


If information of a particular a particular record must be retrieved from the table, its retrieval must be based
on a specific condition.

Syntax
SELECT * FROM table-name WHERE condition;

Example
SELECT * FROM student WHERE Branch = ‘CS’;

Result
Records of all CS Branch students will be displayed.

Selected Rows and Selected Columns-


To view a specific data set from the table and also a select number of columns. The syntax
and Example is already discussed in previous experiment.

11
Experiment – 5

Objective: To Study of SINGLE ROW functions (character, numeric, Data functions).

SINGLE-ROW FUNCTIONS
Single-row functions return a single result row for every row of a queried table or view. These functions can
appear in select lists, WHERE clauses, start with and CONNECT BY clauses, and HAVING clauses.

1. NUMERIC FUNCTIONS
Numeric functions accept numeric input and return numeric values. Most numeric functions return NUMBER
values that are accurate to 38 decimal digits. The transcendental functions COS, COSH, EXP, LN, LOG, SIN,
SINH, SQRT, TAN, and TANH are accurate to 36 decimal digits. The transcendental functions ACOS, ASIN,
ATAN, and ATAN2 are accurate to 30 decimal digits. The Examples of some numeric functions are:

1. ABS
ABS returns the absolute value of n.

Syntax
SELECT ABS (n) "Absolute" FROM DUAL;

Example
SELECT ABS (-15) "Absolute" FROM DUAL;

Result
Absolute
---------- 15

ACOS
ACOS returns the arc cosine of n. The argument n must be in the range of -1 to 1, and the function returns a
value in the range of 0 to pi, expressed in radians.
This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly
converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns
BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument.

Note- All other trigonometric functions like ASIN, ATAN, COS, COSH, SIN, SINH, TAN, TANH etc
works same as this function.

Syntax
SELECT ACOS (n) "Arc_Cosine" FROM DUAL; here n is real number.

Example

12
The following example returns the arc cosine of .3:
SELECT ACOS (.3) "Arc_Cosine" FROM DUAL;

Result
Arc_Cosine
----------
1.26610367

EXP
EXP returns e raised to the nth power, where e = 2.71828183... . The function returns a value of the same type
as the argument.
This function takes as an argument any numeric data type or any nonnumeric data type that can be implicitly
converted to a numeric data type. If the argument is BINARY_FLOAT, then the function returns
BINARY_DOUBLE. Otherwise the function returns the same numeric data type as the argument.

Note- All other mathematical functions like FLOOR, LN, LOG, MOD, SQRT etc works same as this
function.

Syntax
SELECT EXP (n) "e to the 4th power" FROM DUAL; here n is a real
number.

Example
SELECT EXP (4) "e to the 4th power" FROM DUAL;

Result e to the 4th power


------------------
54.59815

ROUND (number)
ROUND returns n rounded to integer places to the right of the decimal point. If you omit integer, then n is
rounded to zero places. If integer is negative, then n is rounded off to the left of the decimal point.
n can be any numeric data type or any nonnumeric data type that can be implicitly converted to a numeric
data type. If you omit integer, then the function returns the value ROUND (n, 0) in the same data type as the
numeric data type of n. If you include integer, then the function returns NUMBER.
ROUND is implemented using the following rules:
• If n is 0, then ROUND always returns 0 regardless of integer.
• If n is negative, then ROUND (n, integer) returns –ROUND (-n, integer).
• If n is positive, then
ROUND (n, integer) = FLOOR (n * POWER (10, integer) + 0.5) * POWER (10, -integer) ROUND
applied to a NUMBER value may give a slightly different result from ROUND applied to the same value
expressed in floating-point. The different results arise from differences in internal representations of
NUMBER and floating point values. The difference will be 1 in the rounded digit if a difference occurs.

13
Note- The TRUNC function works same as this function.

Syntax
SELECT ROUND (n, m) "Round" FROM DUAL;
here n is a real number and m is an integer (round limit).

Example
SELECT ROUND (15.193, 1) "Round" FROM DUAL;

Result
Round
---------- 15.2

2. CHARACTER FUNCTIONS RETURNING CHARACTER VALUES


Character functions that return character values return values of the following data types unless otherwise
documented:
• If the input argument is CHAR or VARCHAR2, then the value returned is VARCHAR2.
• If the input argument is NCHAR or NVARCHAR2, then the value returned is NVARCHAR2.
• The length of the value returned by the function is limited by the maximum length of the data type
returned.
• For functions that return CHAR or VARCHAR2, if the length of the return value exceeds the limit,
then Oracle Database truncates it and returns the result without an error message.
• For functions that return CLOB values, if the length of the return values exceeds the limit, then Oracle
raises an error and returns no data.

The character functions that return character values are:

CHR
CHR returns the character having the binary equivalent to n as a VARCHAR2 value in either the database
character set or, if you specify USING NCHAR_CS, the national character set.
For single-byte character sets, if n > 256, then Oracle Database returns the binary equivalent of n mod 256.
For multi byte character sets, n must resolve to one entire code point. Invalid code points are not validated,
and the result of specifying invalid code points is indeterminate.
This function takes as an argument a NUMBER value, or any value that can be implicitly converted to
NUMBER, and returns a character.

Syntax
SELECT CHR (n1) || CHR (n2) || …….. || CHR (nk) "text" FROM DUAL; Here n1,
n2…….. , nk are the decimal equivalents of ASCII Code.

14
Example
SELECT CHR (67) || CHR (65) || CHR (84) "text" FROM DUAL;

Result text -----


CAT

INITCAP
INITCAP returns char, with the first letter of each word in uppercase, all other letters in lowercase. Words
are delimited by white space or characters that are not alphanumeric.
char can be of any of the data types CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The return value is
the same data type as char. The database sets the case of the initial characters based on the binary mapping
defined for the underlying character set. For linguistic-sensitive uppercase and lowercase, refer to
NLS_INITCAP.
This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through
implicit data conversion.

Syntax
SELECT INITCAP ('text value') "init cap" FROM DUAL;

Example
SELECT INITCAP ('the soap') "init cap" FROM DUAL;

Result init cap


---------
The Soap

REPLACE
REPLACE returns char with every occurrence of search_string replaced with replacement_string. If
replacement_string is omitted or null, then all occurrences of search_string are removed. If search_string is
null, then char is returned.
Both search_string and replacement_string, as well as char, can be any of the data types CHAR, VARCHAR2,
NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is in the same character set as char. The
function returns VARCHAR2 if the first argument is not a LOB and returns CLOB if the first argument is a
LOB.
REPLACE provides functionality related to that provided by the TRANSLATE function. TRANSLATE
provides single-character, one-to-one substitution. REPLACE lets you substitute one string for another as
well as to remove character strings.

Syntax
SELECT REPLACE ('text1 and text2','char1','char2') "Changes" FROM DUAL;

Example
The following example replaces occurrences of J with BL:
SELECT REPLACE ('JACK and JUE','J','BL') "Changes" FROM DUAL; Result

15
Changes
--------------
BLACK and BLUE

LOWER
LOWER returns char, with all letters lowercase. char can be any of the data types CHAR, VARCHAR2,
NCHAR, NVARCHAR2, CLOB, or NCLOB. The return value is the same data type as char. The database
sets the case of the characters based on the binary mapping defined for the underlying character set. For
linguistic-sensitive lowercase, refer to NLS_LOWER. The UPPER function works just reversely.

Syntax
SELECT LOWER ('TEXT VALUE IN UPPER CASE') "lowercase" FROM DUAL;

Example
SELECT LOWER ('MR. SCOTT MCMILLAN') "lowercase" FROM DUAL;

Result
lowercase
----------------- mr. scott
mcmillan

3. CHARACTER FUNCTIONS RETURNING NUMBER VALUES


Character functions that return number values can take as their argument any character data type.

The character functions that return number values are:

ASCII
ASCII returns the decimal representation in the database character set of the first character of char. char can
be of data type CHAR, VARCHAR2, NCHAR, or NVARCHAR2. The value returned is of data type
NUMBER. If your database character set is 7-bit ASCII, then this function returns an ASCII value. If your
database character set is EBCDIC Code, then this function returns an EBCDIC value. There is no
corresponding EBCDIC character function.
This function does not support CLOB data directly. However, CLOBs can be passed in as arguments through
implicit data conversion.

Example
The following example returns students whose last names begin with the letter L, whose ASCII equivalent is
76:
SELECT Name FROM student
WHERE ASCII (SUBSTR (Name, 1, 1)) = 76

16
ORDER BY name;

Result
Name
-------
Lokesh

LENGTH
The LENGTH functions return the length of char. LENGTH calculates length using characters as defined by
the input character set. LENGTHB uses bytes instead of characters. LENGTHC uses Unicode complete
characters. LENGTH2 uses UCS2 code points. LENGTH4 uses UCS4 code points.
char can be any of the data types CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The
exceptions are LENGTHC, LENGTH2, and LENGTH4, which do not allow char to be a CLOB or NCLOB.
The return value is of data type NUMBER. If char has data type CHAR, then the length includes all trailing
blanks. If char is null, then this function returns null.

Restriction on LENGTHB
The LENGTHB function is supported for single-byte LOBs only. It cannot be used with CLOB and NCLOB
data in a multi byte character set.

Syntax
SELECT LENGTH ('text') "Length in characters" FROM DUAL;

Example
SELECT LENGTH ('CANDIDE') "Length in characters" FROM DUAL;

Result
Length in characters
-------------------- 7

4. DATE TIME FUNCTIONS


Datetime functions operate on date (DATE), timestamp (TIMESTAMP, TIMESTAMP WITH TIME ZONE,
and TIMESTAMP WITH LOCAL TIME ZONE), and interval (INTERVAL DAY TO SECOND,
INTERVAL YEAR TO MONTH) values.
Some of the datetime functions were designed for the Oracle DATE data type (ADD_MONTHS,
CURRENT_DATE, LAST_DAY, NEW_TIME, and NEXT_DAY). If you provide a timestamp value as their
argument, then Oracle Database internally converts the input type to a DATE value and returns a DATE value.
The exceptions are the MONTHS_BETWEEN function, which returns a number, and the ROUND and
TRUNC functions, which do not accept timestamp or interval values at all.
The remaining datetime functions were designed to accept any of the three types of data (date, timestamp, and
interval) and to return a value of one of these types.
All of the datetime functions that return current system datetime information, such as SYSDATE,
SYSTIMESTAMP, CURRENT_TIMESTAMP, and so forth, are evaluated once for each SQL statement,
regardless how many times they are referenced in that statement. The date time functions are:

17
CURRENT_DATE
CURRENT_DATE returns the current date in the session time zone, in a value in the Gregorian calendar of
data type DATE. Example
The following example illustrates that CURRENT_DATE is sensitive to the session time zone:
ALTER SESSION SET TIME_ZONE = '-5:0';
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;

Result
SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-05:00 29-MAY-2000 13:14:03

ALTER SESSION SET TIME_ZONE = '-8:0';


SELECT SESSIONTIMEZONE, CURRENT_DATE FROM DUAL;

SESSIONTIMEZONE CURRENT_DATE
--------------- --------------------
-08:00 29-MAY-2000 10:14:33

SYSDATE
SYSDATE returns the current date and time set for the operating system on which the database server resides.
The data type of the returned value is DATE, and the format returned depends on the value of the
NLS_DATE_FORMAT initialization parameter. The function requires no arguments. In distributed SQL
statements, this function returns the date and time set for the operating system of your local database. You
cannot use this function in the condition of a CHECK constraint.

Example
The following example returns the current operating system date and time:
SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "NOW" FROM DUAL;

Result
NOW
-------------------
04-13-2001 09:45:51

NEW_TIME
NEW_TIME returns the date and time in time zone timezone2 when date and time in time zone timezone1
are date. Before using this function, you must set the NLS_DATE_FORMAT parameter to display 24-hour
time. The return type is always DATE, regardless of the data type of date.
The arguments timezone1 and timezone2 can be any of these text strings:

18
• AST, ADT: Atlantic Standard or Daylight Time
• BST, BDT: Bering Standard or Daylight Time
• CST, CDT: Central Standard or Daylight Time
• EST, EDT: Eastern Standard or Daylight Time
• GMT: Greenwich Mean Time
• HST, HDT: Alaska-Hawaii Standard Time or Daylight Time.
• MST, MDT: Mountain Standard or Daylight Time
• NST: Newfoundland Standard Time
• PST, PDT: Pacific Standard or Daylight Time
• YST, YDT: Yukon Standard or Daylight Time

Example
The following example returns an Atlantic Standard Time, given the Pacific Standard Time equivalent:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY HH24: MI: SS';

SELECT NEW_TIME (TO_DATE ('11-10-09 01:23:45', 'MM-DD-YY HH24: MI: SS'), 'AST',
'PST')
"New Date and Time"
FROM DUAL;

Result
New Date and Time
--------------------
09-NOV-2009 21:23:45

SESSIONTIMEZONE
SESSIONTIMEZONE returns the time zone of the current session. The return type is a time zone offset (a
character type in the format '[+|-]TZH:TZM') or a time zone region name, depending on how the user specified
the session time zone value in the most recent ALTER SESSION statement.

Example
The following example returns the time zone of the current session:
SELECT SESSIONTIMEZONE FROM DUAL;

Result
SESSION
------- -08:00

19
EXPERIMENT—6

Objective: To Study of AGGREGATE functions (avg, count, max, min, Sum).

AGGREGATE FUNCTIONS
Aggregate functions return a single result row based on groups of rows, rather than on single rows … .
Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are … select
list can be aggregate functions, GROUP BY expressions, constants, or expressions. These functions are:

1. COUNT
COUNT returns the number of rows returned by the query. You can use it as an aggregate or analytic
function.
If you specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. The
order_by_clause and windowing_clause are not allowed.
If you specify expr, then COUNT returns the number of rows where expr is not null. You can count either all
rows, or only distinct values of expr.
If you specify the asterisk (*), then this function returns all rows, including duplicates and nulls. COUNT
never returns null.

Syntax
SELECT COUNT (*) FROM table-name;

Example
SELECT COUNT (*) "Total" FROM student;

Result
Total
-------- 10

2. MIN
MIN returns minimum value of expr. You can use it as an aggregate or analytic function.

Syntax
SELECT MIN (column-name) FROM table-name;

Example
SELECT MIN (age) "Youngest" FROM student;

Result
Youngest

20
--------- 17

3. SUM
SUM returns the sum of values of expr. You can use it as an aggregate or analytic function. This function
takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to
a numeric data type. The function returns the same data type as the numeric data type of the argument. If you
specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause.

Syntax
SELECT SUM (column-name) FROM table-name;

Example:
SELECT SUM (age) "Total Age" FROM student;

Result
Total Age
---------
187

4. MAX
MAX returns maximum value of expr. You can use it as an aggregate or analytic function.

Syntax
SELECT MAX (column-name) FROM table-name;

Example
SELECT MIN (age) "Oldest" FROM student;

Result
Oldest
--------- 21

5. AVG
AVG returns the average of values of expr. You can use it as an aggregate or analytic function. This function
takes as an argument any numeric data type or any nonnumeric data type that can be implicitly converted to
a numeric data type. The function returns the same data type as the numeric data type of the argument. If you
specify DISTINCT, then you can specify only the query_partition_clause of the analytic_clause. (The
order_by_clause and windowing_clause are not allowed. This is also applicable to SUM function).

Syntax
SELECT AVG (column-name) FROM table-name;

Example
21
SELECT AVG (age) "Average Age" FROM student;

Result
Average Age
---------
18.7

22
Experiment -7

Objective: To Study of various type of SET OPERATORS (Union, Intersect, Minus).

SET OPERATORS
Set operators combine the results of two component queries into a single result. Queries containing set
operators are called compound queries. They are fully described, including examples and restrictions on these
operators, in "The UNION [ALL], INTERSECT, MINUS Operators".
To understand these operations, consider the following database design:
BORROWER_SCHEMA = (customer_name, loan_number)
DEPOSITOR_SCHEMA = (cumstomer_name, account_number)
Now we will construct queries involving the union, intersect, and except (minus) operations of two sets:
The set of all customers who have an account at the bank, which can be derived by-
SELECT customer_name FROM depositor;
And the set of customers who have a loan at the bank, which can be derived by- SELECT
customer_name FROM borrower;

1. UNION
The UNION operation automatically eliminates duplicates, unlike the SELECT clause.

Example
To find all customers having a loan, an account, or both at the bank.
SELECT customer_name FROM depositor
UNION
SELECT customer_name FROM borrower;

2. INTERSECT
The INTERSECT automatically eliminates the duplicates.

Example
To find all customers who have both a loan and an account at the bank.
SELECT customer_name FROM depositor
INTERSECT
SELECT customer_name FROM borrower;

3. EXCEPT (MINUS)
The EXCEPT operation automatically eliminates duplicates.

Example
To find all customers who have an account but no loan at the bank.
SELECT customer_name FROM depositor
EXCEPT
SELECT customer_name FROM borrower;

23
Experiment-8

Objective: To Study of various type of Integrity Constraints.

CONSTRAINTS
Constraints are the businesses Rules which are enforced on the data being stored in a table are called
Constraints.

There are so many type of constraints. These are:

1. I/O CONSTRAINT
This type of constraint determines the speed at which data can be inserted or extracted from an Oracle table.
I/O Constraints is divided into two different types
• The Primary Key Constraint
• The Foreign Key Constraint

2. BUSINESS RULE CONSTRAINT


This type of constraint is applied to data prior the data being inserted into table columns.
Oracle allows programmer to define constraints at
• Column level
• Table level

3. THE PRIMARY KEY DEFINED AT COLUMN LEVEL

Syntax
CREATE TABLE table-name
(column-name1 DATATYPE CONSTRAINT <constraintname1> PRIMARY KEY, column-name2
DATATYPE, column-name3 DATATYPE,.....);

4. THE PRIMARY KEY DEFINED AT TABLE LEVEL

Syntax
CREATE TABLE table-name1
(column-name1 DATATYPE, column-name2 DATATYPE, column-name3
DATATYPE, PRIMARY KEY (column-name1, column-name2));

5. THE FOREIGN KEY DEFINED AT COLUMN LEVEL

Syntax
CREATE TABLE table-name2
(column-name1 DATATYPE REFERENCES table-name1 [(column-name)] [ON DELETE

24
CASCADE], column-name2 DATATYPE, column-name3 DATATYPE,.....);

The table in which FOREIGN KEY is defined is called FOREIGN TABLE or DETAIL TABLE.

The table in which PRIMARY KEY is defined and referenced by FOREIGN KEY is called PRIMARY
TABLE or MASTER TABLE.

ON DELETE CASCADE is set then DELETE operation in master table will trigger the DELETE operation
for corresponding records in the detail table.

6. THE FOREIGN KEY DEFINED AT TABLE LEVEL

Syntax
CREATE TABLE table-name
(column-name1 DATATYPE, column-name2 DATATYPE, column-name3 DATATYPE, PRIMARY KEY
(column-name1, column-name2), FOREIGN KEY (column-name2)
REFERENCES table-name2;
A CONSTRAINT can be given User Defined Name, the syntax is:
CONSTRAINT < constraint name><constraint definition>

7. THE CHECK CONSTRAINT DEFINED AT COLUMN LEVEL

Syntax
CREATE TABLE table-name
(column-name1 DATATYPE CHECK (logical expression), column-name2 DATATYPE, columnname3
DATATYPE, ...);

8. THE CHECK CONSTRAINT DEFINED AT TABLE LEVEL

Syntax
CREATE TABLE table-name
(column-name1 DATATYPE, column-name2 DATATYPE, column-name3 DATATYPE, CHECK
(logical expression1), CHECK (logical expression2));

9. THE UNIQUE CONSTRAINT DEFINED AT THE COLUMN LEVEL

Syntax
CREATE TABLE table-name
(column-name1 DATATYPE UNIQUE, column-name2 DATATYPE UNIQUE, column-name3
DATATYPE ...);

10. THE UNIQUE CONSTRAINT DEFINED AT THE THE TABLE LEVEL

25
Syntax
CREATE TABLE table-name
(column-name1 DATATYPE, column-name2 DATATYPE, column-name3 DATATYPE,
UNIQUE (column-name1));

11. NOT NULL CONSTRAINT DEFINED AT COLUMN LEVEL

Syntax
CREATE TABLE table-name
(column-name1 DATATYPE NOT NULL, column-name2 DATATYPE NOT NULL, column-name3
DATATYPE,...);
Note- The NOT NULL constraint can only be applied at column level.

26
Experiment – 9

Objective: To Study of Various type of JOINS.

JOINS
A join is a query that combines rows from two or more tables, views, or materialized views. Oracle Database
performs a join whenever multiple tables appear in the FROM clause of the query. The select list of the query
can select any columns from any of these tables. If any two of these tables have a column name in common,
then you must qualify all references to these columns throughout the query with table names to avoid
ambiguity.

1. JOIN CONDITIONS
Most join queries contain at least one join condition, either in the FROM clause or in the WHERE clause. The
join condition compares two columns, each from a different table. To execute a join, Oracle Database
combines pairs of rows, each containing one row from each table, for which the join condition evaluates to
TRUE. The columns in the join conditions need not also appear in the select list.
To execute a join of three or more tables, Oracle first joins two of the tables based on the join conditions
comparing their columns and then joins the result to another table based on join conditions containing columns
of the joined tables and the new table. Oracle continues this process until all tables are joined into the result.
The optimizer determines the order in which Oracle joins tables based on the join conditions, indexes on the
tables, and, any available statistics for the tables. A WHERE clause that contains a join condition can also
contain other conditions that refer to columns of only one table. These conditions can further restrict the rows
returned by the join query.

2. EQUIJOINS
An equijoin is a join with a join condition containing an equality operator. An equijoin combines rows that
have equivalent values for the specified columns. Depending on the internal algorithm the optimizer chooses
to execute the join, the total size of the columns in the equijoin condition in a single table may be limited to
the size of a data block minus some overhead. The size of a data block is specified by the initialization
parameter DB_BLOCK_SIZE.

Example
The following examples show various ways of joining tables in a query. In the first example, an equijoin
returns the name and job of each employee and the number and name of the department in which the employee
works:

SELECT last_name, job_id, departments.department_id, department_name FROM employees, departments


WHERE employees.department_id = departments.department_id
ORDER BY last_name, job_id;

3. SELF JOINS
A self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table
aliases that qualify column names in the join condition. To perform a self join, Oracle Database combines and
returns rows of the table that satisfy the join condition.

27
Example
The following query uses a self join to return the name of each employee along with the name of the
employee's manager. A WHERE clause is added to shorten the output.

SELECT e1.last_name||' works for '||e2.last_name


"Employees and Their Managers"
FROM employees e1, employees e2
WHERE e1.manager_id = e2.employee_id
AND e1.last_name LIKE 'R%'
ORDER BY e1.last_name;

4. CARTESIAN PRODUCT
If two tables in a join query have no join condition, then Oracle Database returns their Cartesian product.
Oracle combines each row of one table with each row of the other. A Cartesian product always generates
many rows and is rarely useful. For example, the Cartesian product of two tables, each with 100 rows, has
10,000 rows. Always include a join condition unless you specifically need a Cartesian product. If a query
joins three or more tables and you do not specify a join condition for a specific pair, then the optimizer may
choose a join order that avoids producing an intermediate Cartesian product.

5. INNER JOINS
An inner join (sometimes called a simple join) is a join of two or more tables that returns only those rows that
satisfy the join condition.

6. OUTER JOIN
An outer join extends the result of a simple join. An outer join returns all rows that satisfy the join condition
and also returns some or all of those rows from one table for which no rows from the other satisfy the join
condition.
• To write a query that performs an outer join of tables A and B and returns all rows from A (a left outer
join), use the LEFT [OUTER] JOIN syntax in the FROM clause, or apply the outer join operator (+)
to all columns of B in the join condition in the WHERE clause. For all rows in A that have no matching
rows in B, Oracle Database returns null for any select list expressions containing columns of B.
• To write a query that performs an outer join of tables A and B and returns all rows from B (a right
outer join), use the RIGHT [OUTER] JOIN syntax in the FROM clause, or apply the outer join
operator (+) to all columns of A in the join condition in the WHERE clause. For all rows in B that
have no matching rows in A, Oracle returns null for any select list expressions containing columns of
A.
• To write a query that performs an outer join and returns all rows from A and B, extended with nulls if
they do not satisfy the join condition (a full outer join), use the FULL [OUTER] JOIN syntax in the
FROM clause.
• You cannot compare a column with a sub query in the WHERE clause of any outer join, regardless
which form you specify.

28
• You can use outer joins to fill gaps in sparse data. Such a join is called a partitioned outer join and is
formed using the query_partition_clause of the join_clause syntax. Sparse data is data that does not
have rows for all possible values of a dimension such as time or department. For example, tables of
sales data typically do not have rows for products that had no sales on a given date. Filling data gaps
is useful in situations where data sparsity complicates analytic computation or where some data might
be missed if the sparse data is queried directly.

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator.
Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions,
which do not apply to the FROM clause OUTER JOIN syntax:
• You cannot specify the (+) operator in a query block that also contains FROM clause join syntax.
• The (+) operator can appear only in the WHERE clause or, in the context of left-correlation (when
specifying the TABLE clause) in the FROM clause, and can be applied only to a column of a table or
view.
• If A and B are joined by multiple join conditions, then you must use the (+) operator in all of these
conditions. If you do not, then Oracle Database will return only the rows resulting from a simple join,
but without a warning or error to advise you that you do not have the results of an outer join.
• The (+) operator does not produce an outer join if you specify one table in the outer query and the
other table in an inner query.
• You cannot use the (+) operator to outer-join a table to itself, although self joins are valid. For example,
the following statement is not valid:

SELECT employee_id, manager_id FROM employees


WHERE employees.manager_id(+) = employees.employee_id;

However, the following self join is valid:


SELECT e1.employee_id, e1.manager_id, e2.employee_id
FROM employees e1, employees e2
WHERE e1.manager_id(+) = e2.employee_id
ORDER BY e1.employee_id, e1.manager_id, e2.employee_id;

• The (+) operator can be applied only to a column, not to an arbitrary expression. However, an arbitrary
expression can contain one or more columns marked with the (+) operator.
• A WHERE condition containing the (+) operator cannot be combined with another condition using
the OR logical operator.
• A WHERE condition cannot use the IN comparison condition to compare a column marked with the
(+) operator with an expression.

If the WHERE clause contains a condition that compares a column from table B with a constant, then the (+)
operator must be applied to the column so that Oracle returns the rows from table A for which it has generated
nulls for this column. Otherwise Oracle returns only the results of a simple join.
In previous releases of Oracle Database, in a query that performed outer joins of more than two pairs of tables,
a single table could be the null-generated table for only one other table. Beginning with Oracle Database 12c,
a single table can be the null-generated table for multiple tables. For example, the following statement is
allowed in Oracle Database 12c:
29
SELECT * FROM A, B, D
WHERE A.c1 = B.c2(+) and D.c3 = B.c4(+);
In this example, B, the null-generated table, is outer-joined to two tables, A and D. Refer to SELECT for the
syntax for an outer join.

Example
The following example shows how a partitioned outer join fills data gaps in rows to facilitate analytic function
specification and reliable report formatting. The example first creates a small data table to be used in the join:

SELECT d.department_id, e.last_name


FROM departments d LEFT OUTER JOIN employees e
ON d.department_id = e.department_id
ORDER BY d.department_id, e.last_name;

Users familiar with the traditional Oracle Database outer joins syntax will recognize the same query in this
form:

SELECT d.department_id, e.last_name FROM departments d, employees e


WHERE d.department_id = e.department_id(+)
ORDER BY d.department_id, e.last_name;

7. ANTIJOINS
An antijoin returns rows from the left side of the predicate for which there are no corresponding rows on the
right side of the predicate. It returns rows that fail to match (NOT IN) the subquery on the right side.

Example
The following example selects a list of employees who are not in a particular set of departments:

SELECT * FROM employees


WHERE department_id NOT IN

(SELECT department_id FROM departments


WHERE location_id = 1700)
ORDER BY last_name;

8. SEMIJOINS
A semijoin returns rows that match an EXISTS subquery without duplicating rows from the left side of the
predicate when multiple rows on the right side satisfy the criteria of the subquery.
Semijoin and antijoin transformation cannot be done if the subquery is on an OR branch of the WHERE
clause.

30
Example
In the following example, only one row needs to be returned from the departments table, even though many
rows in the employees table might match the subquery. If no index has been defined on the salary column in
employees, then a semijoin can be used to improve query performance.

SELECT * FROM departments


WHERE EXISTS
(SELECT * FROM employees
WHERE departments.department_id = employees.department_id
AND employees.salary > 2500)
ORDER BY department_name;

31
Experiment -10

Objective: To study Views and Indices.

VIEWS
A view is nothing more than a SQL statement that is stored in the database with an associated name. A view
is actually a composition of a table in the form of a predefined SQL query.
A view can contain all rows of a table or select rows from a table. A view can be created from one or many
tables which depends on the written SQL query to create a view.

Views, which are kind of virtual tables, allow users to do the following:
• Structure data in a way that users or classes of users find natural or intuitive.
• Restrict access to the data such that a user can see and (sometimes) modify exactly what they need
and no more.
• Summarize data from various tables which can be used to generate reports.

1. CREATING VIEWS
Database views are created using the CREATE VIEW statement. Views can be created from a single table,
multiple tables, or another view.
To create a view, a user must have the appropriate system privilege according to the specific implementation.

Syntax
CREATE VIEW view_name AS SELECT column1,
column2.....
FROM tablename
WHERE [condition];

You can include multiple tables in your SELECT statement in very similar way as you use them in normal
SQL SELECT query.

Example
CREATE VIEW student_view AS
SELECT Name, Age
FROM student;

Now, you can query CUSTOMERS_VIEW in similar way as you query an actual table. Following is the
example:
SELECT * FROM student_view;

This display names of all the students with their ages.

2. UPDATING A VIEW

32
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.

So if a view satisfies all the above-mentioned rules then you can update a view. Following is an example to
update the age of Lokesh:
UPDATE student_view SET AGE = 25 WHERE name='Lokesh';

This would ultimately update the base table CUSTOMERS and same would reflect in the view itself.

3. INSERTING ROWS INTO A VIEW


Rows of data can be inserted into a view. The same rules that apply to the UPDATE command also apply to
the INSERT command.
Here we cannot insert rows in student_view because we have not included all the NOT NULL columns in this
view, otherwise you can insert rows in a view in similar way as you insert them in a table.

4. DELETING ROWS INTO A VIEW


Rows of data can be deleted from a view. The same rules that apply to the UPDATE and INSERT commands
apply to the DELETE command.

Example
Following is an example to delete a record having AGE= 22.
DELETE FROM student_view WHERE age = 22;

This would ultimately delete a row from the base table student and same would reflect in the view itself.

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

Syntax
DROP VIEW view_name;

Example
DROP VIEW student_view;

33
INDICES (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.
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.

1. CREATING INDEX

Syntax
CREATE INDEX index_name ON tablename;

2. SINGLE-COLUMN INDEXES
A single-column index is one that is created based on only one table column.

Syntax
CREATE INDEX index_name ON tablename (column_name);

3. 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 UNIQUE INDEX index_name ON tablename (column_name);

4. COMPOSITE INDEXES
A composite index is an index on two or more columns of a table.

Syntax
CREATE INDEX index_name ON tablename (column1, column2);

5. IMPLICIT INDEXES

34
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.

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

Syntax
DROP INDEX index_name;

35
Experiment – 11

Objective: To implement the concept of Nested/Sub-queries.

SUBQUERIES
A subquery is best defined as a query within a query. Subqueries enable you to write queries that select data
rows for criteria that are actually developed while the query is executing at run time. More formally, it is the
use of a SELECT statement inside one of the clauses of another SELECT statement. n fact, a subquery can
be contained inside another subquery, which is inside another subquery, and so forth. A subquery can also be
nested inside INSERT, UPDATE, and DELETE statements. Subqueries must be enclosed within parentheses.

A subquery can be used any place where an expression is allowed providing it returns a single value. This
means that a subquery that returns a single value can also be listed as an object in a FROM clause listing. This
is termed an inline view because when a subquery is used as part of a FROM clause, it is treated like a virtual
table or view. Subquery can be placed either in FROM clause, WHERE clause or HAVING clause of the
main query.

Oracle allows a maximum nesting of 255 subquery levels in a WHERE clause. There is no limit for nesting
subqueries expressed in a FROM clause.In practice, the limit of 255 levels is not really a limit at all because
it is rare to encounter subqueries nested beyond three or four levels.

Syntax
A subquery SELECT statement is very similar to the SELECT statement used to begin a regular or outer
query.The complete syntax of a subquery is:

( SELECT [DISTINCT] subquery_select_parameter FROM


{table_name | view_name} {table_name | view_name} ...
[WHERE search_conditions]
[GROUP BY column_name [,column_name ] ...]
[HAVING search_conditions] )

TYPES OF SUBQUERIES
There are three types of subqueries:

1. SINGLE ROW SUB QUERY


Sub query which returns single row output. They mark the usage of single row comparison operators, when
used in WHERE conditions.

Example
SELECT first_name, salary, department_id
FROM employees
WHERE salary = (SELECT MIN (salary)

36
FROM employees);

Result
In the below SELECT query, inner SQL returns only one row i.e. the minimum salary for the company. It in
turn uses this value to compare salary of all the employees and displays only those, whose salary is equal to
minimum salary.

Note- A HAVING clause is used when the group results of a query need to be restricted based on some
condition. If a subquery's result must be compared with a group function, you must nest the inner query in the
outer query's HAVING clause.

SELECT department_id, MIN (salary)


FROM employees
GROUP BY department_id
HAVING MIN (salary) < (SELECT AVG (salary)
FROM employees);

2. MULTIPLE ROW SUB QUERY


Sub query returning multiple row output. They make use of multiple row comparison operators like IN,
ANY, ALL. There can be sub queries returning multiple columns also. Since it returns multiple rows,it must
be handled by set comparison operators (IN, ALL, ANY).

Below query shows the error when single row sub query returns multiple rows.

SELECT first_name, department_id


FROM employees
WHERE department_id = (SELECT department_id
FROM employees
WHERE LOCATION_ID = 100)
department_id = (select
*
ERROR at line 4:
ORA-01427: single-row subquery returns more than one row.

Usage of Multiple Row operators


• [> ALL] More than the highest value returned by the subquery
• [< ALL] Less than the lowest value returned by the subquery
• [< ANY] Less than the highest value returned by the subquery
• [> ANY] More than the lowest value returned by the subquery
• [= ANY] Equal to any value returned by the subquery (same as IN)

Above SQL can be rewritten using IN operator like below:

SELECT first_name, department_id

37
FROM employees
WHERE department_id IN (SELECT department_id
FROM departments
WHERE LOCATION_ID = 100);

Result
Note in the above query, IN matches department ids returned from the sub query,compares it with that in the
main query and returns employee's name who satisfy the condition.

3. CORRELATED SUB QUERY


Correlated subqueries depend on data provided by the outer query.This type of subquery also includes
subqueries that use the EXISTS operator to test the existence of data rows satisfying specified criteria.

Example
SELECT EMPLOYEE_ID, salary, department_id
FROM employees E
WHERE salary > (SELECT AVG(salary)
FROM EMP T
WHERE E.department_id = T.department_id);

4. MULTIPLE COLOUMN SUB QUERY


A multiple-column subquery returns more than one column to the outer query and can be listed in the outer
query's FROM, WHERE, or HAVING clause.

Example
SELECT first_name, job_id, salary
FROM emp_history
WHERE (salary, department_id) in (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000
AND department_id BETWEEN 10 and 20)
ORDER BY first_name;

Result
The below query shows the employee's historical details for the ones whose current salary is in range of 1000
and 2000 and working in department 10 or 20.

Note- When a multiple-column subquery is used in the outer query's FROM clause, it creates a temporary
table that can be referenced by other clauses of the outer query. This temporary table is more formally called

38
an inline view. The subquery's results are treated like any other table in the FROM clause. If the temporary
table contains grouped data, the grouped subsets are treated as separate rows of data in a table. Consider the
FROM clause in the below query. The inline view formed by the subquery is the data source for the main
query.

SELECT *
FROM (SELECT salary, department_id
FROM employees
WHERE salary BETWEEN 1000 and 2000);

39
EXPERIMENT--12

Objective
: To implement the concept of PL/SQL with Cursors.

PL/SQL BLOCK
PLSQL stands for "Procedural Language extensions to SQL", and can be used in Oracle databases.
PLSQL is closely integrated into the SQL language, yet it adds programming constructs that are not
native to SQL.

The different sections of PL/SQL block are as follows:

Declare section
Declarations of memory variables, constants, cursors etc in PL/SQL

Begin
SQL executable statements
PL/SQL executable statements

Exception
SQL or PL/SQL code to handle errors that may arise during the execution of the code block.

Advantages of PL/SQL
1. PL/SQL supports not only SQL data manipulation but also provides facilities of conditional
checking, branching and looping.
2. PL/SQL sends an entire block of statements to the Oracle engine at one time.
3. PL/SQL permits dealing with errors and displaying user friendly messages when the error
occurs.
4. Via PL/SQL all sorts of calculations can be done quickly without the use of Oracle Engine.
5. Applications written in PL/SQL are portable to any computer hardware and operating system
where Oracle is operational.

CURSORS
The oracle engine uses a work area for its internal processing in order to execute an SQL statement.
This work area is private to SQL’s operations and is called a cursor. A cursor is a mechanism by
which you can assign a name to a "select statement" and manipulate the information within that SQL
statement.

There are two types of Cursors.


• Implicit Cursors
• Explicit Cursors

40
Both the types of Cursors have following General attributes.

Attribute Name Description

%ISOPEN returns true if cursor is open, false otherwise


%FOUND returns true if record was fetched successfully, false otherwise.
%NOTFOUND returns true if record was not fetched successfully, false otherwise.
%ROWCOUNT returns number of records processed from the cursor.

Implicit cursor attributes can be used to access information about status of last insert, update, delete
or single - row select statement. This can be done by preceding the implicit cursor attribute with
cursor name (i.e. sql).
Explicit cursor is defined in the declarative part of a pl/sql block. This is done by naming the cursor
and mapping it to a query.
The commands used to control the cursor are DECLARE, OPEN, FETCH and CLOSE.

1. ORACLE/PLSQL: DECLARE A CURSOR


A cursor is a SELECT statement that is defined within the declaration section of your PLSQL code.
We'll take a look at three different syntaxes for cursors.

a. Cursor without parameters (simplest)


Syntax
CURSOR cursor_name
IS
SELECT_statement;

b. Cursor with parameters


Syntax
CURSOR cursor_name (parameter_list)
IS
SELECT_statement;

c. Cursor with return clause


Syntax
CURSOR cursor_name
RETURN field%ROWTYPE
IS
SELECT_statement;

2. ORACLE/PLSQL: OPEN STATEMENT


Once you've declared your cursor, the next step is to open the cursor.

Syntax
OPEN cursor_name;
41
3. ORACLE/PLSQL: FETCH STATEMENT
The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some
type of operation can be performed on the data. After declaring and opening your cursor, the next
step is to FETCH the rows from your cursor.

Syntax
FETCH cursor_name INTO <list of variables>;

4. ORACLE/PLSQL: CLOSE STATEMENT


The final step of working with cursors is to close the cursor once you have finished using it.

Syntax
CLOSE cursor_name;

42
Experiment – 13
Objective: To implement the concept of Procedures.

PROCEDURE
Procedure is a subprogram used to perform a specific action. A subprogram is a named block of
PL/SQL. There are two types of subprograms in PL/SQL namely Procedures and Functions. Every
subprogram will have a declarative part, an executable part or body, and an exception handling part,
which is optional. Declarative part contains variable declarations. Body of a subprogram contains
executable statements of SQL and PL/SQL. Statements to handle exceptions are written in exception
part.
Procedure specification begins with CREATE and ends with procedure name or parameters list.
Procedures that do not take parameters are written without a parenthesis. The body of the procedure
starts after the keyword IS or AS and ends with keyword END.

Syntax
Procedure is created using CREATE PROCEDURE statement.

CREATE [OR REPLACE] PROCEDURE procedure_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{ IS | AS}
BEGIN procedure_body
EXCEPTION
Exception handling END procedure_name;

REPLACE specifies the procedure is to replace an existing procedure if present. One can use this
option to modify an existing procedure.

Parameter Passing
A procedure may be passed multiple parameters. IN | OUT | IN OUT specifies the mode of the
parameter. Type specifies the datatype of the parameter.
• IN - The parameter can be referenced by the procedure or function. The value of the
parameter cannot be overwritten by the procedure or function.
• OUT - The parameter cannot be referenced by the procedure or function, but the value of the
parameter can be overwritten by the procedure or function.
• IN OUT - The parameter can be referenced by the procedure or function and the value of the
parameter can be overwritten by the procedure or function.

Procedure body contains the SQL and PL/SQL statements to perform the procedure's task.

Exception Section
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION. This
section is optional. Any errors in the program can be handled in this section, so that the PL/SQL
Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be handled, the
Block terminates abruptly with errors.
Advantages
43
• When client executes a procedure or a function, the processing is done in the server. Server
is likely to me more powerful than the clients which in turn mean that stored procedures
should run faster. This reduces network traffic.
• As the procedures/functions are stored in the Oracle database there is no need to transfer the
code from the clients to the database server or to transfer intermediate results from the server
to the clients. This results in much less network traffic and again improves scalability.
• The subprograms are compiled and stored in the Oracle database as stored programs and can
be invoked whenever required. As they are stored in compiled form when called, they only
need to be executed. Hence they save time needed for compilation. They allow breaking the
program into manageable modules. They provide reusability and maintainability for the
code.

Disadvantages
• There is an overhead involved in embedding or calling PL/SQL procedures from SQL in
Oracle due to the context switching that the Oracle database has to perform. This may be
significant in terms of performance but usually this overhead is outweighed by performance
advantages of using PL/SQL.
• More memory may be required on the Oracle database server when using Oracle PL/SQL
packages as the whole package is loaded into memory as soon as any object in the package
is accessed.

Conclusion
Stored procedures should be used to improve the performance and scalability of applications. The
disadvantages are easily outweighed by the advantages and the use of packages to combine related
objects (procedures, functions and variables) into one physical unit enhances these advantages.

44
Experiment – 14
Objective: To implement the concept of Functions.

FUNCTIONS
A function is a named PL/SQL Block which is similar to a procedure. The major difference between
a procedure and a function is, a function must always return a value, but a procedure may or may
not return a value.

Syntax
CREATE [OR REPLACE] FUNCTION function_name [parameters] RETURN
return_datatype;
IS Declaration_section
BEGIN
Execution_section
Return
return_variable;
EXCEPTION
exception section Return
return_variable; END;

Return Type
The header section defines the return type of the function. The return datatype can be any of the
oracle datatype like varchar, number etc.
The execution and exception section both should return a value which is of the datatype defined in
the header section.

Conclusion
Functions are PL/SQL stored programming units, providing a way to hide implementation details in
a programming unit. Functions can be used as right operands in PL/SQL and be called from SQL
statements, while procedures cannot.

45
Experiment – 15

Objective: To implement the concept of Triggers.

TRIGGERS
A database triggers is stored PL/SQL program unit associated with a specific database table or view.
The code in the trigger defines the action the database needs to perform whenever some database
manipulation (INSERT, UPDATE, and DELETE) takes place.
Unlike the stored procedure and functions, which have to be called explicitly, the database triggers
are fired (executed) or called implicitly whenever the table is affected by any of the above said DML
operations. Till oracle 7.0 only 12 triggers could be associated with a given table, but in higher
versions of Oracle there is no such limitation. A database trigger fires with the privileges of owner
not that of user.

Parts of Triggers
A database trigger has three parts:

1. A triggering event
A triggering event can be an insert, update, or delete statement or a instance shutdown or startup etc.
The trigger fires automatically when any of these events occur on the specified table or a view.

2. A trigger constraint (optional)


A trigger constraint specifies a Boolean expression that must be true for the trigger to fire. This
condition is specified using the WHEN clause.

3. Trigger action
The trigger action is a procedure that contains the code to be executed when the trigger fires.

Syntax
CREATE or REPLACE TRIGGER trigger_name BEFORE/AFTER
INSERT/UPDATE/DELETE ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations BEGIN
-- trigger code
EXCEPTION WHEN
...
exception handling END;

A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation
is executed.

46
trigger_name is the name of the trigger to create.

Restrictions
• One can not create a BEFORE trigger on a view.
• One can update the :NEW values.
• One can not update the :OLD values.

47

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy