Vous êtes sur la page 1sur 39

Experiment No.

: - 1
Aim: - Introduction to DBMS.

Introduction:

Database management system (DBMS) is computer software designed for the purpose of
managing databases based on a variety of data models.
A DBMS is a complex set of software programs that controls the organization, storage,
management, and retrieval of data in a database. DBMS are categorized according to their
data structures or types. It is a set of prewritten programs that are used to store, update
and retrieve a Database.

Approaches to Data Management


• File-

Based Systems
Conventionally, before the Database systems evolved, data in software systems
was stored in and represented using flat files.
• Database Systems
Database Systems evolved in the late 1960s to address common issues in
applications handling large volumes of data which are also data intensive. Some of
these issues could be traced back to the following disadvantages of File-based
systems.

Drawbacks of File-Based Systems


As shown in the figure, in a file-based system, different programs in the same
application may be interacting with different private data files.
There is no system enforcing any Standardized control on the organization and structure of
these data files.
• Data Redundancy and Inconsistency
Since data resides in different private data files, there are chances of redundancy
and resulting inconsistency. For example, in the above example shown, the same
customer can have a savings account as well as a mortgage loan. Here the
customer details may be duplicated since the programs for the two functions store
their corresponding data in two different data files. This gives rise to redundancy in
the customer's data. Since the same data is stored in two files, inconsistency arises
if a change made in the data in one file is not reflected in the other.
• Unanticipated Queries
In a file-based system, handling sudden/ad-hoc queries can be difficult, since it
requires changes in the existing programs.
• Data Isolation
Though data used by different programs in the application may be related, they
reside in isolated data files.
• Concurrent Access Anomalies
In large multi-user systems the same file or record may need to be accessed by
multiple users simultaneously. Handling this in a file-based system is difficult.
• Security Problems
In data-intensive applications, security of data is a major concern. Users should be
given access only to required data and not the whole database. In a file-based
system, this can be handled only by additional programming in each application.
• Integrity Problems
In any application, there will be certain data integrity rules which need to be
maintained. These could be in the form of certain conditions/constraints on the
elements of the data records. In the savings bank application, one such integrity
rule could be “Customer ID, which is the unique identifier for a customer record,
should be non-empty”. There can be several such integrity rules. In a file-based
system, all these rules need to be explicitly programmed in the application
program.

 Functions of a DBMS
The functions performed by a typical DBMS are the following:
• Data Definition
The DBMS provides functions to define the structure of the data in the application.
These include defining and modifying the record structure, the type and size of
fields and the various constraints/conditions to be satisfied by the data in each
field.
• Data Manipulation
Once the data structure is defined, data needs to be inserted, modified or deleted.
The functions which perform these operations are also part of the DBMS. These
function can handle planned and unplanned data manipulation needs. Planned
queries are those which form part of the application. Unplanned queries are ad-hoc
queries which are performed on a need basis.
• Data Security & Integrity
The DBMS contains functions which handle the security and integrity of data in the
application. These can be easily invoked by the application and hence the
application programmer need not code these functions in his/her programs.
• Data Recovery & Concurrency
Recovery of data after a system failure and concurrent access of records by
multiple users are also handled by the DBMS.
• Data Dictionary Maintenance
Maintaining the Data Dictionary which contains the data definition of the
application is also one of the functions of a DBMS.
• Performance
Optimizing the performance of the queries is one of the important functions of a
DBMS. Hence the DBMS has a set of programs forming the Query Optimizer which
evaluates the different implementations of a query and chooses the best among
them.
Thus the DBMS provides an environment that is both convenient and efficient to
use when there is a large volume of data and many transactions to be processed.

• The Relational Model

Difference between DBMS and file management:

When a computer user wants to store data electronically they must do so by placing data
in files. Files are stored in specific locations on the hard disk (directories). The user can
create new files to place data in, delete a file that contains data, rename the file, etc -- all
known as file management; a function provided by the Operating System (OS).
If the user wishes to perform some operation on the data he has placed in the file, such as
viewing a list of his friends that celebrate their birthday in June, he has to scroll through all
the data by himself in order to see the data he is interested in. Moreover, he has to know
where he put the files that contain the data, and if there are multiple files he has to
remember to go through each one of them.

A Database Management System is intended to remove this burden of manually locating


data, and having to scroll through it by allowing the user to create a logical structure for
the data beforehand, and then allowing the user to place the data in the database that the
DBMS is managing. In this way the DBMS abstracts away the physical concerns of
organising files, and provides the user with a logical view of the data.
Experiment No. : - 2
Aim: Describe the data base management system

Characteristics of Data Base:


i) Data base represents aspects of real word.
ii) A data base is designed fo specific purpose.
iii) Data base is a coherent collection of data with some coherent meaning.

Advantages of Database Systems


As shown in the figure, the DBMS is a central system which provides a common
interface between the data and the various front-end programs in the application. It also
provides a central location for the whole data in the application to reside.
Due to its centralized nature, the database
system can overcome the disadvantages of the
file-based system as discussed below.

• Minimal Data Redundancy


Since the whole data resides in one central database, the various programs in the
application can access data in different data files. Hence data present in one file
need not be duplicated in another. This reduces data redundancy. However, this
does not mean all redundancy can be eliminated. There could be business or
technical reasons for having some amount of redundancy. Any such redundancy
should be carefully controlled and the DBMS should be aware of it.
• Data Consistency
Reduced data redundancy leads to better data consistency.
• Data Integration
Since related data is stored in one single database, enforcing data integrity is much
easier. Moreover, the functions in the DBMS can be used to enforce the integrity
rules with minimum programming in the application programs.
• Data Sharing
Related data can be shared across programs since the data is stored in a
centralized manner. Even new applications can be developed to operate against
the same data.
• Enforcement of Standards
Enforcing standards in the organization and structure of data files is required and
also easy in a Database System, since it is one single set of programs which is
always interacting with the data files.
• Application Development Ease
The application programmer need not build the functions for handling issues like
concurrent access, security, data integrity, etc. The programmer only needs to
implement the application business rules. This brings in application development
ease. Adding additional functional modules is also easier than in file-based systems.
• Better Controls
Better controls can be achieved due to the centralized nature of the system.
• Data Independence
The architecture of the DBMS can be viewed as a 3-level system comprising the
following:
- The internal or the physical level where the data resides.
- The conceptual level which is the level of the DBMS functions
- The external level which is the level of the application programs or the end user.
Data Independence is isolating an upper level from the changes in the organization
or structure of a lower level. For example, if changes in the file organization of a
data file do not demand for changes in the functions in the DBMS or in the
application programs, data independence is achieved. Thus Data Independence can
be defined as immunity of applications to change in physical representation and
access technique. The provision of data independence is a major objective for
database systems.
• Reduced Maintenance
Maintenance is less and easy, again, due to the centralized nature of the system

Disadvantages of DBMS :
i) High cost of DBMS
ii) High hardware cost
iii) Complex
iv) Backup and Recovery are more difficult
v) Does not support client server architecture
vi) Does not support distributed data base.

Difference between DBMS and RDBMS:


i) In DBMS relation between two tables or files is maintained programmatically while
in RDBMS relationship between two tables can be specified at the time of table
creation.
ii) RDBMS supports client server architecture while DBMS does not .
iii) DBMS does not support distributed data base whil;e RDBMS support distributed
data base.
iv) There is no security of data in DBMS while RDBMS provides multiple level of
security.
Experiment No: - 3
Aim: Describe three level architecture of DBMS
Procedure:

The three level architecture of DBMS is as follows:

The external level:

External level is the view that the individual user of the database has. This view is often a
restricted view of the database and the same database may provide a number of different
views for different classes of users. In general, the end users and even the applications
programmers are only interested in a subset of the database. For example, a department
head may only be interested in the departmental finances and student enrolments but not
the library information. The librarian would not be expected to have any interest in the
information about academic staff. The payroll office would have no interest in student
enrolments.

The conceptual view:

The conceptual view is the information model of the enterprise and contains the view of
the whole enterprise without any concern for the physical implementation. This view is
normally more stable than the other two views. In a database, it may be desirable to
change the internal view to improve performance while there has been no change in the
conceptual view of the database. The conceptual view is the overall community view of the
database and it includes all the information that is going to be represented in the
database. The conceptual view is defined by the conceptual schema which includes
definitions of search of the various types of data.

The internal view:

The internal view is the view about the actual physical storage of data. It tells us what data
is stored in the database and how. At least the following aspects are considered at this
level:

1. Storage allocation e.g. B-trees, hashing etc.


2. Access paths e.g. specification of primary and secondary keys, indexes and
pointers and sequencing.
3. Miscellaneous e.g. data compression and encryption techniques, optimisation of the
internal structures.

Efficiency considerations are the most important at this level and the data structures are
chosen to provide an efficient database. The internal view does not deal with the physical
devices directly. Instead it views a physical device as a collection of physical pages and
allocates space in terms of logical pages.
Experiment No. : - 4
Aim: Describe the SQL fundamentals
Introduction:

SQL, Structured Query Language, is the standard language used to communicate with a
relational database. The prototype was originally developed by IBM using Dr. E.F. Codd's
paper ("A Relational Model of Data for Large Shared Data Banks") as a model. In 1979, not
long after IBM's prototype, the first SQL product, ORACLE, was released by Relational
Software, Incorporated (it was later renamed Oracle Corporation). It is, today, one of the
distinguished leaders in relational database technologies.

DML

DML is abbreviation of Data Manipulation Language. It is used to retrieve, store,


modify, delete, insert and update data in database.

Examples: SELECT, UPDATE, INSERT statements

DDL

DDL is abbreviation of Data Definition Language. It is used to create and modify the
structure of database objects in database.

Examples: CREATE, ALTER, DROP statements

DCL

DCL is abbreviation of Data Control Language. It is used to create roles, permissions,


and referential integrity as well it is used to control access to database by securing it.

Examples: GRANT, REVOKE statements

TCL
TCL is abbreviation of Transactional Control Language. It is used to manage different
transactions occurring within a database.

Examples: COMMIT, ROLLBACK statements

Embedded SQL

Embedded SQL is a method of combining the computing power of a programming


language and the database manipulation capabilities of SQL. Embedded SQL statements
are SQL statements written inline with the program source code of the host language. The
embedded SQL statements are parsed by an embedded SQL preprocessor and replaced by
host-language calls to a code library. The output from the preprocessor is then compiled
by the host compiler. This allows programmers to embed SQL statements in programs
written in any number of languages such as: C/C++, COBOL and Fortran.

The ANSI SQL standards committee defined the embedded SQL standard in two steps: a
formalism called Module Language was defined, then the embedded SQL standard was
derived from Module Language. The SQL standard defines embedding of SQL as embedded
SQL and the language in which SQL queries are embedded is referred to as the host
language. A popular host language is C. The mixed C and embedded SQL is called Pro*C in
Oracle and Sybase database management systems. In the PostgreSQL database
management system this precompiler is called ECPG. Other embedded SQL precompilers
are Pro*Ada, Pro*COBOL, Pro*FORTRAN, Pro*Pascal, and Pro*PL/I.
Experiment No. : - 5
Aim: Introduction to Oracle data base.
Each column value and constant in a SQL statement has a datatype, which is associated
with a specific storage format, constraints, and a valid range of values. When you create a
table, you must specify a datatype for each of its columns.

Oracle provides the following categories of built-in datatypes:

• Character Datatypes
• Numeric Datatypes
• DATE Datatype
• LOB Datatypes
• RAW and LONG RAW Datatypes
• ROWID and UROWID Datatypes

Character Datatypes

The character datatypes store character (alphanumeric) data in strings, with byte values
corresponding to the character encoding scheme, generally called a character set or code
page.

The database's character set is established when you create the database. Examples of
character sets are 7-bit ASCII (American Standard Code for Information Interchange),
EBCDIC (Extended Binary Coded Decimal Interchange Code), Code Page 500, Japan
Extended UNIX, and Unicode UTF-8. Oracle supports both single-byte and multibyte
encoding schemes.

Numeric Datatypes

The numeric datatypes store positive and negative fixed and floating-point numbers, zero,
infinity, and values that are the undefined result of an operation (that is, is "not a number"
or NAN).

DATE Datatype

The DATE datatype stores point-in-time values (dates and times) in a table. The DATE
datatype stores the year (including the century), the month, the day, the hours, the
minutes, and the seconds (after midnight).

Oracle Database can store dates in the Julian era, ranging from January 1, 4712 BCE
through December 31, 9999 CE (Common Era, or 'AD'). Unless BCE ('BC' in the format
mask) is specifically used, CE date entries are the default.
Oracle Database uses its own internal format to store dates. Date data is stored in fixed-
length fields of seven bytes each, corresponding to century, year, month, day, hour,
minute, and second.

For input and output of dates, the standard Oracle date format is DD-MON-YY, as follows:

'13-NOV-92'

You can change this default date format for an instance with the parameter
NLS_DATE_FORMAT. You can also change it during a user session with the ALTER SESSION
statement. To enter dates that are not in standard Oracle date format, use the TO_DATE
function with a format mask:

TO_DATE ('November 13, 1992', 'MONTH DD, YYYY')

Oracle Database stores time in 24-hour format—HH:MI:SS. By default, the time in a date
field is 00:00:00 A.M. (midnight) if no time portion is entered. In a time-only entry, the date
portion defaults to the first day of the current month. To enter the time portion of a date,
use the TO_DATE function with a format mask indicating the time portion, as in:

INSERT INTO birthdays (bname, bday) VALUES


('ANDY',TO_DATE('13-AUG-66 12:56 A.M.','DD-MON-YY HH:MI A.M.'));

LOB Datatypes

The LOB datatypes BLOB, CLOB, NCLOB, and BFILE enable you to store and manipulate
large blocks of unstructured data (such as text, graphic images, video clips, and sound
waveforms) in binary or character format. They provide efficient, random, piece-wise
access to the data. Oracle recommends that you always use LOB datatypes over LONG
datatypes. You can perform parallel queries (but not parallel DML or DDL) on LOB columns.

LOB datatypes differ from LONG and LONG RAW datatypes in several ways. For example:

• A table can contain multiple LOB columns but only one LONG column.
• A table containing one or more LOB columns can be partitioned, but a table
containing a LONG column cannot be partitioned.
• The maximum size of a LOB is 128 terabytes depending on database block size,
and the maximum size of a LONG is only 2 gigabytes.
• LOBs support random access to data, but LONGs support only sequential access.
• LOB datatypes (except NCLOB) can be attributes of a user-defined object type but
LONG datatypes cannot.
• Temporary LOBs that act like local variables can be used to perform
transformations on LOB data. Temporary internal LOBs (BLOBs, CLOBs, and
NCLOBs) are created in a temporary tablespace and are independent of tables. For
LONG datatypes, however, no temporary structures are available.
• Tables with LOB columns can be replicated, but tables with LONG columns cannot.

SQL statements define LOB columns in a table and LOB attributes in a user-defined object
type. When defining LOBs in a table, you can explicitly specify the tablespace and storage
characteristics for each LOB.
LOB datatypes can be stored inline (within a table), out-of-line (within a tablespace, using
a LOB locator), or in an external file (BFILE datatypes). With compatibility set to Oracle9i or
higher, you can use LOBs with SQL VARCHAR operators and functions.

RAW and LONG RAW Datatypes

• The LONG RAW datatype is provided for backward compatibility with existing
applications. For new applications, use the BLOB and BFILE datatypes for large
amounts of binary data.
• Oracle also recommends that you convert existing LONG RAW columns to LOB
columns. LOB columns are subject to far fewer restrictions than LONG columns.
Further, LOB functionality is enhanced in every release, whereas LONG RAW
functionality has been static for several releases.
• The RAW and LONG RAW datatypes are used for data that is not to be interpreted
(not converted when moving data between different systems) by Oracle Database.
These datatypes are intended for binary data or byte strings. For example, LONG
RAW can be used to store graphics, sound, documents, or arrays of binary data.
The interpretation depends on the use.
• RAW is a variable-length datatype like the VARCHAR2 character datatype, except
Oracle Net Services (which connects user sessions to the instance) and the Import
and Export utilities do not perform character conversion when transmitting RAW or
LONG RAW data. In contrast, Oracle Net Services and Import/Export automatically
convert CHAR, VARCHAR2, and LONG data between the database character set and
the user session character set, if the two character sets are different.
• When Oracle Database automatically converts RAW or LONG RAW data to and from
CHAR data, the binary data is represented in hexadecimal form with one
hexadecimal character representing every four bits of RAW data. For example, one
byte of RAW data with bits 11001011 is displayed and entered as 'CB'.
• LONG RAW data cannot be indexed, but RAW data can be indexed.

ROWID and UROWID Datatypes

Oracle Database uses a ROWID datatype to store the address (rowid) of every row in the
database.

• Physical rowids store the addresses of rows in ordinary tables (excluding index-
organized tables), clustered tables, table partitions and subpartitions, indexes, and
index partitions and subpartitions.
• Logical rowids store the addresses of rows in index-organized tables.

A single datatype called the universal rowid, or UROWID, supports both logical and
physical rowids, as well as rowids of foreign tables such as non-Oracle tables accessed
through a gateway.

A column of the UROWID datatype can store all kinds of rowids. The value of the
COMPATIBLE initialization parameter (for file format compatibility) must be set to 8.1 or
higher to use UROWID columns.
Experiment No. : - 6
Aim: Describe the data models

Data Model:

A data model in software engineering is an abstract model


that describes how data is represented and accessed. Data
models formally define data objects and relationships among
data objects for a domain of interest. Some typical applications
of database models include supporting the development of
databases and enabling the exchange of data for a particular
area of interest. Data models are specified in a data modeling
language.

Uses of Data Model:

i) Managing large quantities of structured and unstructured data is a primary function


of information systems.
ii) Data models describe structured data for storage in data management systems
such as relational databases.
iii) It allows the conceptualization of the association between various entities and their
attributes.

Components of Data Model:

i) Structural Part: Most data are presentation models provide mechanism to


structure the data for the entities being modeled.
ii) Manipulative Part: This allows a set of operations to be defined on the
data model.
iii) Integrative Part: The model can also enforce a set of constraints to maintain
the integrity of data.

Types of data models

• Flat model: This may not strictly qualify as a data model. The flat (or table) model
consists of a single, two-dimensional array of data elements, where all members of
a given column are assumed to be similar values, and all members of a row are
assumed to be related to one another.
• Hierarchical model: In this model data is organized into a tree-like structure,
implying a single upward link in each record to describe the
nesting, and a sort field to keep the records in a particular
order in each same-level list.

• Network model: This model organizes data using two fundamental constructs,
called records and sets. Records contain fields, and sets define one-to-many
relationships between records: one owner, many members.

• Relational model: is a database model based on first-order predicate logic. Its


core idea is to describe a database as a collection of
predicates over a finite set of predicate variables, describing
constraints on the possible values and combinations of
values.

• Entity-relationship model: is an abstract conceptual


representation of structured data, which produce a
conceptual data model a system, and its requirements in a
top-down fashion.
• Object-relational model: Similar to a relational database model, but objects,
classes and inheritance are directly supported in database schemas and in the
query language.

• Star schema: It is the simplest style of data warehouse schema. The star schema
consists of a few "fact tables" (possibly only one, justifying the name) referencing
any number of "dimension tables". The star schema is considered an important
special case of the snowflake schema.
Experiment No. : - 7
Aim: Describe the data models.
Entity-relationship model:

An entity- relationship model


(ERM) is an abstract conceptual representation of structured data. Entity-relationship
modeling is a relational schema database modeling method, used in software engineering
to produce a type of conceptual data model (or semantic data model) of a system, often a
relational database, and its requirements in a top-down fashion.

Entity:

An entity may be defined as a thing which is recognized as being capable of an


independent existence and which can be uniquely identified. An entity is an abstraction
from the complexities of some domain. When we speak of an entity we normally speak of
some aspect of the real world which can be
distinguished from other aspects of the real world .

An entity may be a physical object such as a house or a car, an event such as a house sale
or a car service, or a concept such as a customer transaction or order. Although the term
entity is the one most commonly used, following Chen we should really distinguish
between an entity and an entity-type. An entity-type is a category. An entity, strictly
speaking, is an instance of a given entity-type. There are usually many instances of an
entity-type. Because the term entity-type is somewhat cumbersome, most people tend to
use the term entity as a synonym for this term.
Entities can be thought of as nouns. Examples: a computer, an employee, a song, a
mathematical theorem. Entities are represented as rectangles.

Relationship:

A relationship captures how two or more entities are related to one another.
Relationships can be thought of as verbs, linking two or more nouns.
Examples: an owns relationship between a company and a computer, a
supervises relationship between an employee and a department, a
performs relationship between an artist and a song, a proved relationship between a
mathematician and a theorem. Relationships are represented as diamonds, connected by
lines to each of the entities in the relationship.

Entities and relationships can both have attributes. Examples: an employee entity might
have a Social Security Number (SSN) attribute; the proved relationship may have a date
attribute. Attributes are represented as ellipses connected to their owning entity sets by a
line.

Primary key:

Every entity (unless it is a weak entity) must have a minimal set of uniquely identifying
attributes, which is called the entity's primary key.

Entity-relationship diagrams don't show single entities or single instances of relations.


Rather, they show entity sets and relationship sets. Example: a particular song is an entity.
The collection of all songs in a database is an entity set. The eaten relationship between a
child and her lunch is a single relationship. The set of all such child-lunch relationships in a
database is a relationship set.

Lines are drawn between entity sets and the


relationship sets they are involved in. If all entities in an
entity set must participate in the relationship set, a thick
or double line is drawn. This is called a participation constraint. If each entity of the entity
set can participate in at most one relationship in the relationship set, an arrow is drawn
from the entity set to the relationship set. This is called a key constraint. To indicate that
each entity in the entity set is involved in exactly one relationship, a thick arrow is drawn.

A sample ER diagram
Experiment No. : - 8
Aim: Describe about Select statement.
The SQL SELECT statement queries data from tables in the database. The statement
begins with the SELECT keyword. The basic SELECT statement has 3 clauses:

• SELECT
• FROM
• WHERE

The SELECT clause


specifies the table
columns that are
retrieved.
The FROM clause
specifies the tables
accessed.
The WHERE clause
specifies which table
rows are used. The
WHERE clause is optional; if missing, all table rows are used.

For example

SELECT name FROM s WHERE city='Rome'


This query accesses rows from the table - s. A detailed description of the query actions:

• The FROM clause accesses the s table. Contents:


S.No name city
S1 Pierre Paris
S2 John London
S3 Mario Rome
• The WHERE clause filters the rows of the FROM table to use those whose city
column contains Rome. This chooses a single row from s:
S.No name city
S3 Mario Rome
• The SELECT clause retrieves the name column from the rows filtered by the WHERE
clause:

name
Mario
• FROM Clause -- specifies the tables to be accessed.
• WHERE Clause -- specifies which rows in the FROM tables to use.

The SQL SELECT Statement Use:

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

SQL SELECT Syntax :


SELECT column_name(s)

FROM table_name

And

SELECT * FROM table_name

Note: SQL is not case sensitive. SELECT is the same as select.

An SQL SELECT Example

The "Persons" table:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger

Now we want to select the content of the columns named "LastName" and "FirstName"
from the table above.

We use the following SELECT statement:

SELECT LastName,FirstName FROM Persons


The result-set will look like this:

LastName FirstName
Hansen Ola
Svendson Tove
Pettersen Kari

SELECT * Example

Now we want to select all the columns from the "Persons" table.

We use the following SELECT statement:

SELECT * FROM Persons

Note: The asterisk (*) is a quick way of selecting all columns!

The result-set will look like this:

P_Id LastName FirstName Address City


1 Hansen Ola Timoteivn 10 Sandnes
2 Svendson Tove Borgvn 23 Sandnes
3 Pettersen Kari Storgt 20 Stavanger
Experiment No. : - 9
Aim: Describe functions in SQL*Plus.
Introduction:

SQL*Plus is a client terminal software allowing users to interact with Oracle server to
manipulate data and data structures. Users type in SQL statements in SQL*Plus that send
statements to Oracle server. Oracle server then validates and executes the statements on
its databases. The query results are returned to SQL*Plus and displayed to the user.
Besides sending SQL statements to the server, SQL*Plus also saves them into a local
buffer and allow users to view and change the statements. The following figure illustrates
the process.

Functions in SQL *Plus:

AVG([DISTINCT]n) Averge value of ‘n’ ignoring NULLs


BETWEEN value AND value Where ‘x’ between 25 AND 100
BFILENAME (’directory‘,’filename‘) Get the BFILE locator associated with a
physical LOB binary file.

ABS (n) Absolute value of number


ACOS (n) arc cosine of n
ADD_MONTHS (date,num_months) Returns date + num_months
ASCII (char) Converts char into a decimal ascii code
ASIN (n) arc sine of n.
ATAN (n) arc tangent of n.
ATAN2 (n.m) arc tangent of n and m.

CASE Group the data into sub-sets.


CEIL (n) Round n up to next whole number.
CHARTOROWID(char) Converts a Char into a rowid value.
CHR (n) Character with value n
CONCAT (s1,s2) Concatenate string1 and string2 Concat (’abc’, ‘defg’) =>
‘abcdefg’
CONVERT (char_to_convert, new_char_set, old_char_set) Convert character sets
COS (n) Cosine of number
COSH (n) Hyperbolic Cosine of number

COUNT(*) Count the no of rows returned


COUNT ([DISTINCT] expr) Count the no of rows returned by expr
DECODE IF x THEN return y ELSE return z
DENSE_RANK Calculate the rank of a value in a group
DEREF (e) Return the object reference of argument e.
DUMP (expr,fmt[,start,length])
Convert to dec/hex/oct and display char set

EMPTY_BLOB Return an empty LOB locator (use to empty a column or variable)


EMPTY_CLOB Return an empty LOB locator (use to empty a column or variable)
EXISTS Return TRUE if a subquery returns at least one row
EXP (n) Exponential (e to ‘n’th power)
FLOOR (n) Round n down to the next whole number.
GREATEST (expression, expression…) Returns the largest in a list of expressions.
GROUPING Grouping for superaggregate rows=NULL
HEXTORAW (char) Convert char containing hex digits to a raw value.

Experiment No. : - 10
Aim: Introduction to Group functions in SQL.
SQL GROUP Functions

Group functions are built-in SQL functions that operate on groups of rows and return one
value for the entire group. These functions are: COUNT, MAX, MIN, AVG, SUM,
DISTINCT

SQL COUNT (): This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified, then
the query returns the total number of rows in the table.

For Example: If you want the number of employees in a particular department, the query
would be:

SELECT COUNT (*) FROM employee


WHERE dept = ‘Electronics’;

The output would be '2' rows.

If you want the total number of employees in all the department, the query would take the
form:

SELECT COUNT (*) FROM employee;

The output would be '5' rows.

SQL DISTINCT(): This function is used to select the distinct rows.

For Example: If you want to select all distinct department names from employee table,
the query would be:

SELECT DISTINCT dept FROM employee;

To get the count of employees with unique name, the query would be:

SELECT COUNT (DISTINCT name) FROM employee;

SQL MAX(): This function is used to get the maximum value from a column.

To get the maximum salary drawn by an employee, the query would be:
SELECT MAX (salary) FROM employee;

SQL MIN(): This function is used to get the minimum value from a column.

To get the minimum salary drawn by an employee, he query would be:

SELECT MIN (salary) FROM employee;

SQL AVG(): This function is used to get the average value of a numeric column.

To get the average salary, the query would be

SELECT AVG (salary) FROM employee;

SQL SUM(): This function is used to get the sum of a numeric column

To get the total salary given out to the employees,

SELECT SUM (salary) FROM employee;


Experiment No. : - 11
Aim: Introduction to Grouping of data by Group By clause.
Introduction:
GROUP BY clause is used to group or categorized data. In other words it divides the rows
in a table in smaller groups. We can then use group functions to return summary
information for each group.
If no GROUP BY clause is specified, then the default grouping is the entire result set .
When the query executes and data is fetched, it is grouped based on the GROUP BY clause
and the group functions are applied.

Syntax:
SELECT column, group_function (column) FROM table
[WHERE condition]
[GROUP BY group_by_experssion]
[ORDER BY column];
Here, group_by_experssion specifies columns whose value determines the basis for
grouping rows.
For example, if we have to find total salary of each department manually, first we group
the records on the basis of department no and then we apply the sum function on salary of
each group to obtain the required result.
Similarly in SQL, we apply the GROUP BY clause on department no and then calculate the
total salary for each group by sum (sal) function as shown below:

The OUTPUT is:


DEPTNO SUM(SAL)
10 2916.6667
20 2175
30 1566.6667

The following figure shows the grouping and the execution of the query:

DEPTN SUM(SA
O L)
10 8750
20 10875
30 9400
Experiment No. : - 12
Aim: Joining of tables for multiple queries.
Types of Joins:
While different implementations have many ways of joining tables, you concentrate on the
most common joins in this lesson. The types of joins that you learn are
i) EQUIJOINS
ii) NATURAL JOINS
iii) NON-EQUIJOINS
iv) OUTER JOINS
v) SELF JOINS

Component Locations of a Join Condition:


The SELECT and FROM clauses are both required SQL statement elements; the WHERE
clause is a required element of a SQL statement when joining tables. The tables being
joined are listed in the FROM clause. The join is performed in the WHERE clause. Several
operators can be used to join tables, such as =, <, >, <>, <=, >=, !=, BETWEEN, LIKE,
and NOT; they can all be used to join tables. However, the most common operator is the
equal symbol.

Joins of Equality:
Perhaps the most used and important of the joins is the EQUIJOIN, also referred to as an
INNER JOIN. The EQUIJOIN joins two tables with a common column in which each is usually
the primary key.

The syntax for an EQUIJOIN :


SELECT TABLE1.COLUMN1, TABLE2.COLUMN2...
FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME
[ AND TABLE1.COLUMN_NAME = TABLE3.COLUMN_NAME ]

Example:
SELECT EMPLOYEE_TBL.EMP_ID,
EMPLOYEE_PAY_TBL.DATE_HIRE
FROM EMPLOYEE_TBL,
EMPLOYEE_PAY_TBL
WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID;

Natural Joins:
A NATURAL JOIN is nearly the same as the EQUIJOIN; however, the NATURAL JOIN differs
from the EQUIJOIN by eliminating duplicate columns in the joining columns. The JOIN
condition is the same, but the columns selected differ.

The syntax:
SELECT TABLE1.*, TABLE2.COLUMN_NAME
[ TABLE3.COLUMN_NAME]
FROM TABLE1, TABLE2 [ TABLE3 ]
WHERE TABLE1.COLUMN_NAME = TABLE2.COLUMN_NAME
[ AND TABLE1.COLUMN_NAME = TABLE3.COLUMN ]
Example:
SELECT EMPLOYEE_TBL.*, EMPLOYEE_PAY_TBL.SALARY
FROM EMPLOYEE_TBL,
EMPLOYEE_PAY_TBL
WHERE EMPLOYEE_TBL.EMP_ID = EMPLOYEE_PAY_TBL.EMP_ID;
Joins of Non-Equality:
NON-EQUIJOIN joins two or more tables based on a specified column value not equaling a
specified column value in another table.
The syntax for the NON-EQUIJOIN:
FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1.COLUMN_NAME != TABLE2.COLUMN_NAME
[ AND TABLE1.COLUMN_NAME != TABLE2.COLUMN_NAME ]
Example:
SELECT EMPLOYEE_TBL.EMP_ID, EMPLOYEE_PAY_TBL.DATE_HIRE
FROM EMPLOYEE_TBL,
EMPLOYEE_PAY_TBL
WHERE EMPLOYEE_TBL.EMP_ID != EMPLOYEE_PAY_TBL.EMP_ID;
Outer Joins:
An OUTER JOIN is used to return all rows that exist in one table, even though
corresponding rows do not exist in the joined table. The (+) symbol is used to denote an
OUTER JOIN in a query. The (+) is placed at the end of the table name in the WHERE
clause. The table with the (+) should be the table that does not have matching rows. In
many implementations, the OUTER JOIN is broken down into joins called LEFT OUTER JOIN,
RIGHT OUTER JOIN, and FULL OUTER JOIN. The OUTER JOIN in these implementations is
normally optional.
The general syntax:
FROM TABLE1
{RIGHT | LEFT | FULL} [OUTER] JOIN
ON TABLE2
The Oracle syntax:
FROM TABLE1, TABLE2 [, TABLE3 ]
WHERE TABLE1.COLUMN_NAME[(+)] = TABLE2.COLUMN_NAME[(+)]
[ AND TABLE1.COLUMN_NAME[(+)] = TABLE3.COLUMN_NAME[(+)]]
Self Joins:
The SELF JOIN is used to join a table to itself, as if the table were two tables, temporarily
renaming at least one table
The syntax is:
In the SQL statement.
SELECT A.COLUMN_NAME, B.COLUMN_NAME, [ C.COLUMN_NAME ]
FROM TABLE1 A, TABLE2 B [, TABLE3 C ]
WHERE A.COLUMN_NAME = B.COLUMN_NAME
[ AND A.COLUMN_NAME = C.COLUMN_NAME ]
Example:
SELECT A.LAST_NAME, B.LAST_NAME, A.FIRST_NAME
FROM EMPLOYEE_TBL A,
EMPLOYEE_TBL B
WHERE A.LAST_NAME = B.LAST_NAME;
Experiment No. : - 13
Aim: SQL commands using set operators.
Introduction:
Set operators can be used to select data from multiple data base. Set operators are
basically combine the result of two queries in to one. These queries are known as
compound queries. All set operators have equal precedence; when multiple set of
operators are present in a single query, they are evaluated from left to right unless
specified otherwise with parentheses. The data types of the resulting columns should
match in both the queries. Oracle has 4 set operators which are shown below:

Operator Description
UNION Returns all unique rows selected by either query
UNION ALL Return all rows, including duplicates selected by
either query
INTERSECT Returns rows selected from both queries
MINUS Returns unique rows selected by the first query
but not the rows selected by the second query.

• Union operator: The union operator merges the output of two or more queries in
a single set of rows or columns. It eliminates the duplicate values between two or
more queries.

Syntax:
SELECT <statements1>
UNION
SELECT < statements2>
[ORDER BY clause];
e.g.
SQL> Select job from emp where deptno=20
UNION
Select job from emp where deptno=30;

The Output is:


JOB
ANALYST
CLERK
MANAGER
SALESMAN

• UNION ALL
The union all operator merges the output of two or more queries in a single set of rows and
columns. It does not eliminate the duplicate values between two or more queries.

Syntax:
SELECT<statements1>
UNION ALL
SELECT <statements2>
[ORDER BY clause];

e.g.
SQL> select job from emp where deptno=20
UNION ALL
Select job from emp where deptno=30
The output is :
JOB
CLERK
MANAGER
ANALYST
CLERK
ANALYST
SALESMAN

• INTERSECT OPERATOR : It gives only those rows in the output which have
common records among them.
Syntax:
SELECT <statements1>
INTERSECT
SELECT<statements2>
[ORDER BY clause];
e.g. SQL> select jobs from emp where deptno =20
INTERSECT
Select jobs from emp where deptno=30

The Output is :
JOB
CLERK
MANAGER

• Minus Operator : The minus operator returns the rows which are unique to the
first query. It must be remembered that in case of minus A-B is different from B-A.
Syntax:
SELECT <statements1>
MINUS
SELECT<statements2>
[ORDER BY clause];
e.g. SQL> select jobs from emp where deptno =20
INTERSECT
Select jobs from emp where deptno=30

The output is :
JOB
ANALYST
Experiment No. : - 14
Aim: SQL commands using sub queries to solve a problem.
Sub queries:
A sub query is a query that appears within another SQL command. SQL DML commands
(SELECT, DELETE, and UPDATE) support sub queries, though the rules and reasons for
using them vary. Some sub queries stand alone; you can run the sub query independent of
the command that contains it. Other sub queries rely on fields from the containing
command—these sub queries are said to be correlated.
A sub query is a complete query, but cannot contain the TO or INTO clause. Sub queries
are enclosed in parentheses in the containing query. Sub queries can appear in the WHERE
clause of SELECT, UPDATE, and DELETE.subqueries can also be used in the field list of
SELECT, in the SET clause of UPDATE, and in the FROM clause of SELECT, UPDATE, and
DELETE. a sub query cannot contain another sub query.

Types of sub queries:

TYPE DESCRIPTION
Single row sub queries Queries that return only one row from inner SELECT
statement.
Multiple row sub Queries that returns more than one rows from inner SELECT
queries statements.
Multiple column sub Queries that return more than one column from the inner
queries SELECT statement.

1. Single sub queries : Queries that return only one row from inner SELECT
statement.
e.g.
SQL> SELECT ename,job from emp
Where job=(SELECT job from emp WHERE empno=7369);

The output is :
ENAM JOB
E
JAMES CLERK
SMITH CLERK
ADAMS CLERK
MILLER CLERK

2. Multiple row sub query : Queries that returns more than one rows from inner
SELECT statements.

There are following multiple row operators :

OPERATO MEANING
R
IN Equal to any number in the list.
ANY Compare value to each value returned by
subquery
ALL Compare value to every value returned by
subquery.

e.g. SQL > SELECT empno, ename, job


FROM emp
WHERE sal<ANY(SELECT sal from emp WHERE job=’clerk’> AND
Job< >’clerk’;

The output is:


EMPN ENAME JOB
O
7654 MANTIN SALESMAN
7521 WARD SALESMAN

3. Multiple Column Sub queries : Queries that return more than one column from
the inner SELECT statement.

Syntax :
SELECT column, column…
FROM table
WHERE (column, column…..)
(SELECT column, column…
FROM table
WHERE cond);
e.g. SELECT ordid, prodid, qty FROM item
WHERE (prodid,qty) IN
(SELECT prodid,qty FROM item
WHERE ordid=605) AND ordid< >605;

The output is :

ORDI PRODID QTY


D
617 100861 100
617 100870 500
616 102130 10

Vous aimerez peut-être aussi