Top Banner
PRACTICAL FILE OF RDBMS INTRODUCTION TO RDBMS A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. Most popular commercial and open source databases currently in use are based on the relational model. A short definition of an RDBMS may be a DBMS in which data is stored in the form of tables and the relationship among the data is also stored in the form of tables. Relational databases are powerful because they require few assumptions about how data is related or how it will be extracted from the database. As a result, the same database can be viewed in many different ways. An important feature of relational systems is that a single database can be spread across several tables. This differs from flat-file databases, in which each database is self-contained in a single table. Almost all full-scale database systems are RDBMS's. Small database systems, however, use other designs that provide less flexibility in posing queries. RDBMS data is structured in database tables, fields and records. Each RDBMS table consists of database table rows. Each database table row consists of one or more database table fields. RDBMS store the data into collection of tables, which might be related by common fields (database table columns). MONIKA/CSE 6 th SEM/7026030250 Page 1
98
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: rdbms

PRACTICAL FILE OF RDBMS

INTRODUCTION TO RDBMS

A Relational database management system (RDBMS) is a database management system (DBMS) that is based on the relational model as introduced by E. F. Codd. Most popular commercial and open source databases currently in use are based on the relational model.

A short definition of an RDBMS may be a DBMS in which data is stored in the form of tables and the relationship among the data is also stored in the form of tables.

Relational databases are powerful because they require few assumptions about how data is related or how it will be extracted from the database. As a result, the same database can be viewed in many different ways.

An important feature of relational systems is that a single database can be spread across several tables. This differs from flat-file databases, in which each database is self-contained in a single table.

Almost all full-scale database systems are RDBMS's. Small database systems, however, use other designs that provide less flexibility in posing queries. RDBMS data is structured in database tables, fields and records. Each RDBMS table consists of database table rows.

Each database table row consists of one or more database table fields. RDBMS store the data into collection of tables, which might be related by common fields (database table columns).

RDBMS also provide relational operators to manipulate the data stored into the database tables. Most RDBMS use SQL as database query language.Edgar Codd introduced the relational database model.

Many modern DBMS do not conform to the Codd’s definition of a RDBMS, but nonetheless they are still considered to be RDBMS. The most popular RDBMS are MS SQL Server, DB2, Oracle and MySQL.

INTRODUCTION TO ORACLE

MONIKA/CSE 6th SEM/7026030250 Page 1

Page 2: rdbms

PRACTICAL FILE OF RDBMS

The Oracle Database (commonly referred to as Oracle RDBMS or simply Oracle) consists of a relational database management system (RDBMS) produced and marketed by Oracle Corporation. As of 2008, Oracle had become a major presence in database computing.

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

Oracle Database is the first database designed for enterprise grid computing, the most flexible and cost effective way to manage information and applications. Enterprise grid computing creates large pools of industry-standard, modular storage and servers. With this architecture, each new system can be rapidly provisioned from the pool of components. There is no need for peak workloads, because capacity can be easily added or reallocated from the resource pools as needed.

Physical and logical structuring in Oracle

An Oracle database system — identified by an alphanumeric system identifier or SID comprises at least one instance of the application, along with data storage. An instance — identified persistently by an instantiation number comprises a set of operating-system processes and memory-structures that interact with the storage. Typical processes include PMON (the process monitor) and SMON (the system monitor).

Users of Oracle databases refer to the server-side memory-structure as the SGA (System Global Area). The SGA typically holds cache information such as data-buffers, SQL commands and user information. In addition to storage, the database consists of online redo logs (which hold transactional history). Processes can in turn archive the online redo logs into archive logs (offline redo logs), which provide the basis (if necessary) for data recovery and for some forms of data replication.

The Oracle RDBMS stores data logically in the form of tablespaces and physically in the form of data files. Tablespaces can contain various types of memory segments; for example, Data Segments, Index Segments etc. Segments in turn

MONIKA/CSE 6th SEM/7026030250 Page 2

Page 3: rdbms

PRACTICAL FILE OF RDBMS

comprise one or more extents. Extents comprise groups of contiguous data blocks. Data blocks form the basic units of data storage. At the physical level, data-files comprise one or more data blocks, where the block size can vary between data-files.

Oracle database management tracks its computer data storage with the help of information stored in the SYSTEM table space. The SYSTEM tablespace contains the data dictionary — and often (by default) indexes and clusters. (A data dictionary consists of a special collection of tables that contains information about all user-objects in the database). Since version 8i, the Oracle RDBMS also supports "locally managed" tablespaces which can store space management information in bitmaps in their own headers rather than in the SYSTEM tablespace (as happens with the default "dictionary-managed" tablespaces).

If the Oracle database administrator has instituted Oracle RAC (Real Application Clusters), then multiple instances, usually on different servers, attach to a central storage array. This scenario offers numerous advantages, most importantly performance, scalability and redundancy. However, support becomes more complex, and many sites do not use RAC. In version 10g, grid computing has introduced shared resources where an instance can use (for example) CPU resources from another node (computer) in the grid.

The Oracle DBMS can store and execute stored procedures and functions within itself. PL/SQL (Oracle Corporation's proprietary procedural extension to SQL), or the object-oriented language Java can invoke such code objects and/or provide the programming structures for writing them.

Difference between RDBMS and DBMS

MONIKA/CSE 6th SEM/7026030250 Page 3

Page 4: rdbms

PRACTICAL FILE OF RDBMS

S.no DBMS RDBMS1 There is no relationship concept. It is use to establish relationship

concept between two database objects i.e. tables.

2 It support single user. It support multiuser.3 It reads data as files internally. It reads tables internally.4 It requires low software and

hardware requirements.It requires high software and hardware requirements.

5 It is less secure. It is more secure.6 It is possible to store and retrieve

fewer amounts of data in it.It is possible to store and retrieve large amount of data in it.

7 No keys are used. Keys are used.8 Normalization concept is not

present.Normalization is present.

9 Used for smaller organizations where security is not major concern.

Large organizations where large amount data is maintain and security is also important.

10 No data integrity. Data integrity concept is present.11 It does not support null values. Support null values.12 Examples: FoxPro

MS-AccessExamples: SQL Server Oracle

Similarities between RDBMS and DBMS

1. Both store data in the form of tables.2. Both are used for storage.3. It is possible to edit record in both DBMS and RDBMS.4. It is easy to retrieve data in both.

Data Type

A data type is a set of data with values having predefined characteristics. Each language has its own data types. Usually, a limited number of such data types

MONIKA/CSE 6th SEM/7026030250 Page 4

Page 5: rdbms

PRACTICAL FILE OF RDBMS

come built into a language. The language usually specifies the range of values for a given data type, how the values are processed by the computer, and how they are stored. Some data types in SQL are: char, number, date etc.The various Data Types along with their description are shown below:

Data Type Description

char(size) Holds fixed-length character string. Size is specified in parenthesis. Max 255 bytes.

varchar(size) Holds variable-length character string. Max size is specified in parenthesis.

number(size) Holds Number value with a max number digits specified in parenthesis.

Date Holds a Date value.

number(size,d)

Holds a Number value with a maximum number of digits of "size" total, with a maximum number of "d" digits to the right of the decimal.

Create Table

With CREATE TABLE, a new table can be created. A table can be considered as a basic structure within which data is stored. It consists of rows and columns. A row represents a single record while a column represents attributes/fields which

MONIKA/CSE 6th SEM/7026030250 Page 5

Page 6: rdbms

PRACTICAL FILE OF RDBMS

can be thought of as one of the components contributing to make a record. While creating a table, data types have to be mentioned for each field.

Syntax: CREATE TABLE table_name (column_name1 data_type, column_name2 data_type, ...)

Query: create table emp1(e_no number,b_no number,name varchar2(10),dept varchar2(10),desg varchar2(10));The above statement creates an empty table (containing no records) named Details having fields-e_no,b_no,name,dept,desg.

SQL SelectThis statement is used to view data from the table.

Syntax: SELECT column_name(s) FROM table_name

Query:To select all the column from the table:select * from studentcse;

The Where Clause

We might want to retrieve records which satisfy a particular condition. For example, we want to retrieve Employee names from database table Employee with

MONIKA/CSE 6th SEM/7026030250 Page 6

Page 7: rdbms

PRACTICAL FILE OF RDBMS

salaries above 14000. To do this, we make use of the clause Where. Thus Where clause is used to specify a selection criterion.

Syntax: SELECT column_name(s) FROM table_nameWHERE condition

Query: select * from studentcse where marks>300;

The Distinct Keyword

Distinct keyword is used to retrieve values that are distinct or non-repetitive. The SQL Select retrieves values from database table which may be repetitive. Adding the word Distinct to Select, we can get rid of this problem.

Syntax: SELECT DISTINCT column_name(s) FROM table_name

Query: select distinct * from studentcse;

Sorting

Sorting is an important feature of any database. We can arrange data according to the sequence we need to put them into.

MONIKA/CSE 6th SEM/7026030250 Page 7

Page 8: rdbms

PRACTICAL FILE OF RDBMS

Order by Clause

ORDER BY is used to get the result in the sorted manner. Unless Explicitly stated, the order by clause sorts the result in ascending order.

Syntax: SELECT column_name(s) FROM table_name ORDER BY column_name

Query: select * from studentcse order by rollno;

Query: select * from studentcse order by rollno desc;

SQL Delete

The SQL delete is used to delete rows from a database table.

Syntax: DELETE FROM table_name WHERE column_name = some_value

Query: delete from studentcse where rollno=106;

MONIKA/CSE 6th SEM/7026030250 Page 8

Page 9: rdbms

PRACTICAL FILE OF RDBMS

Query: delete from studentcse where name like '__n%';

Query: delete from studentcse where name='Radhika' and marks>300;

DROP TABLE

If the user want to delete a table (the table structure, attributes, and indexes will

also be deleted) Permanently then drop command can be used for the purpose.

Syntax: DROP TABLE <table_name>;

Query: drop table studentdet;

MONIKA/CSE 6th SEM/7026030250 Page 9

Page 10: rdbms

PRACTICAL FILE OF RDBMS

TRUNCATE

Truncate command is used to simply get rid of the data but not the table itself.

Syntax: TRUNCATE TABLE <table_name>;

Query: truncate table student1;

SQL Update

Update statement is used to edit or update data in the table. Once there's data in the

table, we might find that there is a need to modify the data. To do so, we can use

the UPDATE command.

Syntax: UPDATE table_name SET column_name = new_value WHERE column_name = old_value

MONIKA/CSE 6th SEM/7026030250 Page 10

Page 11: rdbms

PRACTICAL FILE OF RDBMS

Query: update studentcse set marks=721 where rollno>205;

Query: update studentcse set marks=marks+10 where rollno>205 and name like 'Anish';

MONIKA/CSE 6th SEM/7026030250 Page 11

Page 12: rdbms

PRACTICAL FILE OF RDBMS

Modify Table:

alter table:

Once a table is created in the database, there are many occasions where one may

wish to change the structure of the table. ALTER TABLE is basically used to

- Add a column

- Drop a column

- Change a column name

- Change the data type for a column

Syntax: ALTER TABLE table_name ADD column_name datatype

Query: alter table studentdet1 add(s_address varchar2(10));

Syntax: ALTER TABLE table_name DROP COLUMN column_name

Query: alter table studentdet1 drop column s_address;

Syntax: ALTER TABLE table_name MODIFY column_name datatype

Query: alter table studentdet1 modify(s_name varchar2(20));

MONIKA/CSE 6th SEM/7026030250 Page 12

Page 13: rdbms

PRACTICAL FILE OF RDBMS

Rename

Column Alias are used to rename a table’s columns for the purpose of a particular

query.

Syntax: select column_name alias_name from table_name;

Query: rename emp to emp2;

Tab:

This command is used to view all the tables.

Syntax: select * from tab;

MONIKA/CSE 6th SEM/7026030250 Page 13

Page 14: rdbms

PRACTICAL FILE OF RDBMS

Describe:

This command is used to describe the structure of the the structure of the table.

Syntax: describe tablename;

Query: describe emp2;

MONIKA/CSE 6th SEM/7026030250 Page 14

Page 15: rdbms

PRACTICAL FILE OF RDBMS

Arithmetic Functions:

Various functions like as addition, multiplication, division, subtraction are used on

the database.

Syntax: select <arithmetic operation>fieldname from <tablename>;

Query: select sal+10 from emp2;

Query: select sal/10 from emp2;

Logical Operators:

MONIKA/CSE 6th SEM/7026030250 Page 15

Page 16: rdbms

PRACTICAL FILE OF RDBMS

Oracle provides a set of built-in operators-Arithmetic Operators (+, -, *, ), Comparison Operators ( =, >, <), Logical operators (NOT, AND, OR). These operators take as input oneor more arguments (operands) and return a result.

The various Operators along with their description are shown below in tabular form:

Operator Description

= Equal

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

<> Not equal to

LIKE String comparison test

AND Logical And returns TRUE when both the specified conditions are true

OR Logical Or returns TRUE when atleast one of the specified conditions is true

NOT Logical Not returns TRUE when none one of the specified conditions is true

Query: select * from studentcse where marks>300;

Range Searching:

MONIKA/CSE 6th SEM/7026030250 Page 16

Page 17: rdbms

PRACTICAL FILE OF RDBMS

SQL In & Between

The IN keyword is used to test whether a value(s) is present in the list of values specified after the keyword IN.

Syntax: SELECT column_name FROM table_name WHERE column_name IN ( value1, value2,...')

Query: select * from student where sid in(101,333,336,226,387);

select ename from employee where ecity like 'APS' AND ecode IN(select ecode from company where desg like 'Manager');

The BETWEEN keyword is used to test whether or not a value is present between the two values mentioned in the query followed by the keyword BETWEEN.

Syntax: SELECT column_name(s) FROM table_name WHERE column_name BETWEEN value1 AND value2

Query: select * from students where rollno between 111 and 113;

Not between

MONIKA/CSE 6th SEM/7026030250 Page 17

Page 18: rdbms

PRACTICAL FILE OF RDBMS

The NOTBETWEEN ... AND operator selects a range of data between two values. These values can be numbers, text, or dates.

Syntax: select * from <table_name> where <column_name> Not between <Range1> and <Range2>;

Pattern Matching:

The Like Clause:

MONIKA/CSE 6th SEM/7026030250 Page 18

Page 19: rdbms

PRACTICAL FILE OF RDBMS

The Like condition can be used to search for a particular pattern in a column in a database table.

Syntax: SELECT column_name FROM table_name WHERE column_name LIKE pattern

Query: select * from studentcse where name like 'R%' and marks>300;

select * from studentcse where name like 'A%';

select * from studentcse where name like '__m%';

ORACLE Table dual

Dual is a dummy table. Its predefined in ORACLE database.

MONIKA/CSE 6th SEM/7026030250 Page 19

Page 20: rdbms

PRACTICAL FILE OF RDBMS

Syntax: select * from dual;

Syntax: Select sysdate from dual;

-- AGGREGATE FUNCTIONS:

MONIKA/CSE 6th SEM/7026030250 Page 20

Page 21: rdbms

PRACTICAL FILE OF RDBMS

Aggregate functions operate against a collection of values, but return a single

value.

(i) AVG (Average):

It returns the average value of a column.

Syntax: SELECT avg(column) FROM <table_name>;

(ii) MIN (Minimum):

It returns the lowest value of a column in a table.

Syntax: SELECT min(column) FROM <table_name>

(iii) MAX(Maximum):

MONIKA/CSE 6th SEM/7026030250 Page 21

Page 22: rdbms

PRACTICAL FILE OF RDBMS

It returns the highest value of a column in a table.

Syntax: SELECT max(column) FROM <table_name>;

-- NUMERIC FUNCTIONS:

Numeric functions are applied on any table having numeric data.

(i) ABS (Absolute):

It returns the absolute value of any numeric data. It can also be applied on dual

table.

MONIKA/CSE 6th SEM/7026030250 Page 22

Page 23: rdbms

PRACTICAL FILE OF RDBMS

Syntax: Select abs(value) from <table_name>

(ii)SQRT (Square root)

It is used to find square root of any numeric value.

Syntax: Select sqrt(value) from <table_name>;

(iii) POWER:

This numeric function calculates the power of any numeric value.

Syntax: Select power(value,power of value) from <table_name>

MONIKA/CSE 6th SEM/7026030250 Page 23

Page 24: rdbms

PRACTICAL FILE OF RDBMS

(iv) ROUND:

This function is used to get a rounded figure of a decimal value.

Syntax: Select round(value,no. of digits desired after decimal ) from

<table_name>;

(v) Trunc:

It shows the specified number of digits after truncating the other digits after

decimal.

Syntax: Select trunc(value,no. of digits desired after decimal) from <table_name>;

MONIKA/CSE 6th SEM/7026030250 Page 24

Page 25: rdbms

PRACTICAL FILE OF RDBMS

(vi) EXTRACT function:

It returns a value extracted from a date or an internal value.

Syntax: Select extract (<value_name> from ‘value’) from <table_name>;

(vii) MOD:

This function returns the remainder provided two numbers dividend and divisor.

Syntax: Select MOD(dividend,divisor) from <table_name>;

MONIKA/CSE 6th SEM/7026030250 Page 25

Page 26: rdbms

PRACTICAL FILE OF RDBMS

(viii) FLOOR Function:

It returns the immediate smaller integer of given decimal value.

Syntax: Select FLOOR(value) from <table_name>

(ix) CEIL Function:

It returns the immediate greater integer value of the given decimal value.

Syntax: Select CEIL(value) from <table_name>

MONIKA/CSE 6th SEM/7026030250 Page 26

Page 27: rdbms

PRACTICAL FILE OF RDBMS

-- STRING FUNCTIONS:

There are various functions in SQL that can be applied on the string type data.

(i) ASCII:

It returns the decimal representation in the database character set of the first

character of string.

Syntax: Select ascii(char) from <table_name>;

MONIKA/CSE 6th SEM/7026030250 Page 27

Page 28: rdbms

PRACTICAL FILE OF RDBMS

(ii) UPPER:

It returns char, with all letters uppercase.

Syntax: Select upper(string/column_name) from <table_name>;

(ii) LOWER:

It returns char, with all letters lowercase.

Syntax: Select lower(string/column_name) from <table_name>;

(iii) INITCAP:

It returns char, with first letter of each word capitalized.

Syntax: Select initcap(string/column_name) from <table_name>;

MONIKA/CSE 6th SEM/7026030250 Page 28

Page 29: rdbms

PRACTICAL FILE OF RDBMS

(iv) LPAD & RPAD:

What this function does is that it fills up the extra space in the field with the

padding either from the left or from the right.

Syntax: select lpad(fieldnames) from tablename;

MONIKA/CSE 6th SEM/7026030250 Page 29

Page 30: rdbms

PRACTICAL FILE OF RDBMS

--CONVERSION FUNCTIONS:

(i) To_Char:

TO_CHAR (number) converts n to a value of VARCHAR2 datatype, using the

optional number format fmt. The value n can be of type NUMBER,

BINARY_FLOAT, or BINARY_DOUBLE, DATE. If you omit fmt, then n is

converted to a VARCHAR2 value exactly long enough to hold its significant

digits.

Syntax: Select to_char(value, format) from <table_name>;

(ii) To_Number:

It is used to convert character to number datatype.

Syntax: Select to_number(‘value’) from <table_name>;

MONIKA/CSE 6th SEM/7026030250 Page 30

Page 31: rdbms

PRACTICAL FILE OF RDBMS

(iii) To_Date:

It converts a character field to a date field.

Syntax: Select to_date(‘date’, ‘format’) from <table_name>;

MONIKA/CSE 6th SEM/7026030250 Page 31

Page 32: rdbms

PRACTICAL FILE OF RDBMS

GROUP BY CLAUSE:

GROUP BY... was added to SQL because aggregate functions (like SUM) return

the aggregate of all column values every time they are called, and without the

GROUP BY function it was impossible to find the sum for each individual group

of column values.

Syntax: SELECT column1,<aggregate function>(column2) FROM <table_name>

GROUP BY <column1>;

MONIKA/CSE 6th SEM/7026030250 Page 32

Page 33: rdbms

PRACTICAL FILE OF RDBMS

HAVING CLAUSE:

HAVING... was added to SQL because the WHERE keyword could not be used

against aggregate functions (like SUM), and without HAVING... it would be

impossible to test for result conditions.

Syntax: SELECT column1,<aggregate function>(column) FROM table GROUP

BY column1 HAVING <aggregate function> condition;

MONIKA/CSE 6th SEM/7026030250 Page 33

Page 34: rdbms

PRACTICAL FILE OF RDBMS

JOINS:

Sometimes we have to select data from two or more tables to make our result

complete. We have to perform a join.

-- INNER JOIN:

The INNER JOIN returns all rows from both tables where there is a match. If there

are rows in Employees that do not have matches in Orders, those rows will not be

listed.

Syntax: SELECT <column1>, <column2>, <column3> FROM <first_table>

INNER JOIN second_table ON <first_table.keyfield> = <second_table.keyfield>;

--Outer Join:

Outer join uses two tables to extract the data .It displays all the rows of first table

or second table or both depending on left outer join ,right outer join or full outer

join.

LEFT OUTER JOIN

MONIKA/CSE 6th SEM/7026030250 Page 34

Page 35: rdbms

PRACTICAL FILE OF RDBMS

It displays all the rows of the first table of the join.

Syntax: SELECT <cloumn1>, <column2>, <column3> FROM <first_table>

LEFT JOIN second_table ON <first_table.keyfield> =

<second_table.keyfield>;

RIGHT OUTER JOIN:

It displays all the rows of the second table of the join.

Syntax: SELECT <cloumn1>, <column2>, <column3> FROM

<first_table>RIGHT JOIN second_table ON <first_table.keyfield> =

<second_table.keyfield>;

MONIKA/CSE 6th SEM/7026030250 Page 35

Page 36: rdbms

PRACTICAL FILE OF RDBMS

FULL OUTER JOIN

It displays all the rows of the first table and second table of the join.

Syntax: SELECT <cloumn1>, <column2>, <column3>FROM

<first_table>FULL JOIN second_table ON <first_table.keyfield> =

<second_table.keyfield>;

MONIKA/CSE 6th SEM/7026030250 Page 36

Page 37: rdbms

PRACTICAL FILE OF RDBMS

UNION and INTERSECT operations

----Union: It is used to combine the tuples of two different tables.

----INTERSECT: It select the common tuples in both the tables.

Constraints in SQL

MONIKA/CSE 6th SEM/7026030250 Page 37

Page 38: rdbms

PRACTICAL FILE OF RDBMS

A constraint is a condition or check applicable on field or set of fields.Consider the following SQL commandCreate table employee

(ecode integer NOT NULL,ename varchar2(9) NOT NULl,gross decimal);

If you write the keyword NOT NULL after the data type of a column, this means the column can never be empty.

Different Constraintsa. Unique constraintb. Primary key constraintc. Default constraintd. Check constraint

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

b. Primary key constraint: This declares a column as the primary key of the table. It is similar to default constraint except that only one column can be specified as primary key. Example

MONIKA/CSE 6th SEM/7026030250 Page 38

Page 39: rdbms

PRACTICAL FILE OF RDBMS

c. Default constraint: A default value can be specified for a column using the DEFAULT clause. When a user does not enter value for the column (having default value), automatically the defined default value inserted in the field.

d. Check constraint: This constraint limits values that can be inserted into a column of a table. Examples

MONIKA/CSE 6th SEM/7026030250 Page 39

Page 40: rdbms

PRACTICAL FILE OF RDBMS

INDEXES

Indices are created in an existing table to locate rows more quickly and efficiently.

It is possible to create an index on one or more columns of a table, and each index

is given a name. The users cannot see the indexes, they are just used to speed up

queries.

-- Create Index:

It creates a simple index on a table. Duplicate values are allowed in simple index.

Syntax: CREATE INDEX <index_name> ON <table_name> (column_name);

Query: create index id on studentcse(rollno);

-- Drop index:

It is used to vanish the existing index.

Syntax: DROP INDEX index_name ON table_name;

Query: drop index id;

MONIKA/CSE 6th SEM/7026030250 Page 40

Page 41: rdbms

PRACTICAL FILE OF RDBMS

VIEWS:

MONIKA/CSE 6th SEM/7026030250 Page 41

Page 42: rdbms

PRACTICAL FILE OF RDBMS

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

contains rows and columns, just like a real table. The fields in a view are fields

from one or more real tables in the database. You can add SQL functions,

WHERE, and JOIN statements to a view and present the data as if the data were

coming from a single table. The database design and structure will NOT be

affected by the functions, where, or join statements in a view.

--CREATE VIEW:

This command creates the view of a table.

Syntax: Create view <viewname> as select <columnname1,columname2,

………,columname n>From <table_name>;

Query: create view vw as select rollno,name from studentcse where rollno>300;

insert into vw values(&rollno,'&name');

Using Views

A view could be used from inside a query, a stored procedure, or from inside

another view. By adding functions, joins, etc., to a view, it allows you to present

exactly the data you want to the user.

INTRODUCTION TO PL/SQL

MONIKA/CSE 6th SEM/7026030250 Page 42

Page 43: rdbms

PRACTICAL FILE OF RDBMS

PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporation's proprietary procedural extension to the SQL database language, used in the Oracle database. Some other SQL database management systems offer similar extensions to the SQL language. PL/SQL's syntax strongly resembles that of Ada, and just like Ada compilers of the 1980s the PL/SQL runtime system uses Diana as intermediate representation. The key strength of PL/SQL is its tight integration with the Oracle database. PL/SQL is one of three languages embedded in the Oracle Database, the other two being SQL and Java.

History

PL/SQL made its first appearance in Oracle Forms v3. A few years later, it was included in the Oracle Database server v7 (as database procedures, functions, packages, triggers and anonymous blocks) followed by Oracle Reports v2.

Basic code structure

PL/SQL programs consist of procedures, functions, and anonymous blocks. Each of these is made up of the basic PL/SQL unit which is the block. Blocks take the general form:

DECLARE -- Declaration block (optional) BEGIN -- Program proper EXCEPTION -- Exception-handling (optional) END /* Sample comment spanning multiple lines... */Numeric variables

variable_name number(P[,S]) := value;

To define a numeric variable, the programmer appends the variable type NUMBER to the name definition. To specify the (optional) precision(P) and the (optional) scale (S), one can further append these in round brackets, separated by a comma. ("Precision" in this context refers to the number of digits which the variable can hold, "scale" refers to the number of digits which can follow the decimal point.)

A selection of other datatypes for numeric variables would include:

MONIKA/CSE 6th SEM/7026030250 Page 43

Page 44: rdbms

PRACTICAL FILE OF RDBMS

binary_float, binary_double, dec, decimal, double precision, float, integer, int, numeric, real, smallint, binary_integer

Character variables

variable_name varchar2(L) := 'Text';

To define a character variable, the programmer normally appends the variable type VARCHAR2 to the name definition. There follows in brackets the maximum number of characters which the variable can store.

Other datatypes for character variables include:

varchar, char, long, raw, long raw, nchar, nchar2, clob, blob, bfile

Date variables

variable_name date := '01-Jan-2005';

Oracle provides a number of data types that can store dates (DATE, DATETIME, TIMESTAMP etc), however DATE is most commonly used.

Programmers define date variables by appending the datatype code "DATE" to a variable name. The TO_DATE function can be used to convert strings to date values. The function converts the first quoted string into a date, using as a definition the second quoted string, for example:

TO_DATE('31-12-2004','dd-mm-yyyy')

"or"

TO_DATE ('31-Dec-2004','dd-mon-yyyy', 'NLS_DATE_LANGUAGE = American')

To convert the dates to strings one uses the function TO_CHAR (date_string, format_string).

Difference between SQL and PL/SQL

MONIKA/CSE 6th SEM/7026030250 Page 44

Page 45: rdbms

PRACTICAL FILE OF RDBMS

1. SQL is Structured Query Language used for DDL,DML.PL/SQL is used for Cursors and Triggers .

Embeded SQL is used to embed SQL statements in C,Cobol,Pascal,Foxpro like languages.Embedded SQL - SQL statements are invoked from a host environment like C/C++, Java or any other programming languages.

2. SQL is a structured query language used for various operations such as retrieval,manipulation of data using DML,DDL statements.

PL/SQL is programming language used to write various sql statements together.Advantage of pl/sql over sql is,you can write many sql statements within a pl/sql block.One more advantage is subprogramming like procedures and functions. We can write cursors for fetching number of records at a time. And also packages and triggers.

3. Both sql and pl/sql are languages used to acess data with in oracle data base....sql writtens querys by using ddl,dml,dcl etc...where plsql uses cursors,triggers,procedures etc.. In sql querys process at a time where as in plsql it done step by step or recoed by record ...

MONIKA/CSE 6th SEM/7026030250 Page 45

Page 46: rdbms

PRACTICAL FILE OF RDBMS

PL/SQL Execution Environment

The PL/SQL engine, which processes PL/SQL program units, is a special component of many Oracle products, including the Oracle server.

The procedure (or package) is stored in a database. When an application calls a procedure stored in the database, Oracle loads the compiled procedure (or package) into the shared pool in the system global area (SGA), and the PL/SQL and SQL statement executors work together to process the statements within the procedure.

The following Oracle products contain a PL/SQL engine:

Oracle server Oracle Forms (Version 3 and later) SQL*Menu (Version 5 and later) Oracle Reports (Version 2 and later) Oracle Graphics (Version 2 and later)

MONIKA/CSE 6th SEM/7026030250 Page 46

Page 47: rdbms

PRACTICAL FILE OF RDBMS

You can call a stored procedure from another PL/SQL block, which can be either an anonymous block or another stored procedure. For example, you can call a stored procedure from Oracle Forms (Version 3 or later).

Also, you can pass anonymous blocks to Oracle from applications developed with these tools:

Oracle precompilers (including user exits) Oracle Call Interfaces (OCIs) SQL*Plus Server Manager Oracle Enterprise Manager

MONIKA/CSE 6th SEM/7026030250 Page 47

Page 48: rdbms

PRACTICAL FILE OF RDBMS

Displaying user message on the screen

Set server output on

Set server output off

MONIKA/CSE 6th SEM/7026030250 Page 48

Page 49: rdbms

PRACTICAL FILE OF RDBMS

Conditional Statements

The following code segment shows the IF-THEN-ELSIF construct. The ELSIF and ELSE parts are optional so it is possible to create simpler IF-THEN or, IF-THEN-ELSE constructs.

IF x = 1 THEN sequence_of_statements_1;ELSIF x = 2 THEN sequence_of_statements_2;ELSE sequence_of_statements_N;END IF;

The CASE statement simplifies some large IF-THEN-ELSE structures.

CASE WHEN x = 1 THEN sequence_of_statements_1; WHEN x = 2 THEN sequence_of_statements_2; ELSE sequence_of_statements_N;END CASE;

MONIKA/CSE 6th SEM/7026030250 Page 49

Page 50: rdbms

PRACTICAL FILE OF RDBMS

Write a PL/SQL block to find greatest number among three numbers.

MONIKA/CSE 6th SEM/7026030250 Page 50

Page 51: rdbms

PRACTICAL FILE OF RDBMS

CASE statement can be used with predefined selector:

CASE x WHEN 1 THEN sequence_of_statements_1; WHEN 2 THEN sequence_of_statements_2; ELSE sequence_of_statements_N;END CASE;

LoopingAs a procedural language by definition, PL/SQL provides several iteration constructs, including basic LOOP statements, WHILE loops, FOR loops, and Cursor FOR loops.

LOOP statements

Syntax:LOOP statement1; statement2;END LOOP;Loops can be terminated by using the EXIT keyword, or by raising an exception.

MONIKA/CSE 6th SEM/7026030250 Page 51

Page 52: rdbms

PRACTICAL FILE OF RDBMS

Write a PL/SQL block that display table for entered no using for loop.

MONIKA/CSE 6th SEM/7026030250 Page 52

Page 53: rdbms

PRACTICAL FILE OF RDBMS

WHILE loops

Syntax:

WHILE LOOP ...do something...END LOOP;

FOR loops

Cursor FOR loopsFOR RecordIndex IN (SELECT person_code FROM people_table)LOOP DBMS_OUTPUT.PUT_LINE(RecordIndex.person_code);END LOOP;

Sequential Statements

Syntax:

GOTO record

Where record is place in the PL/SQL to which goto label shift the control of program.

MONIKA/CSE 6th SEM/7026030250 Page 53

Page 54: rdbms

PRACTICAL FILE OF RDBMS

TRANSACT-SQL (T-SQL)

It is a part of PL/SQL. Oracle treats a series of operators as a single entity. The changes made to the table is a two step process, First the changes requested are done, secondly to make change permanent a commit statement has to be given at SQL prompt. A roolback statemet given at the SQL prompt can be used to undo a part of entire transaction.

1. COMMIT- saves work done.2. SAVEPOINT- identifies a point in transaction to which you can later roll

back.3. ROLLBACK- restore database to original since the last COMMIT.4. SET TRANSACTION- Change transaction options like isolation level and

what rollback segment to use.

Syntax: Commit;

Rollback [to[savepoint]savepointname];

Savepoint savepoint_name;

MONIKA/CSE 6th SEM/7026030250 Page 54

Page 55: rdbms

PRACTICAL FILE OF RDBMS

Query: If price of product 10 is less than 4000 then change the price to 4000. The price change is to be than recorded to the table oldprice along with productnumber (pno), date of change of price and oldprice.

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 55

Page 56: rdbms

PRACTICAL FILE OF RDBMS

Query: Write a PL/SQL block of code as following:1. Insert a record in employ2 table.2. Update salary of Raman & Teena by 2000 & 1500, then check.3. To see that the total salary does not exceed 20,000. If

total_salary>20,000 then undo the update, made to the salary of the person.

MONIKA/CSE 6th SEM/7026030250 Page 56

Page 57: rdbms

PRACTICAL FILE OF RDBMS

Cursors

PL/SQL uses two types of cursors: implicit and explicit. PL/SQL declares a cursor implicitly for all SQL data manipulation statements, including queries that return only one row.

Explicit Cursors

The set of rows returned by a query can consist of zero, one, or multiple rows, depending on how many rows meet your search criteria. When a query returns multiple rows, one can explicitly declare a cursor to process the rows. Moreover, one can declare a cursor in the declarative part of any PL/SQL block, subprogram, or package.

We use three commands to control a cursor: OPEN, FETCH, and CLOSE. First, we initialize the cursor with the OPEN statement, which identifies the result set. Then, you can execute FETCH repeatedly until all rows have been retrieved. When the last row has been processed, we release the cursor with the CLOSE statement.

Cursor Attribute Values%FOUND

%ISOPEN

%NOTFOUND

%ROWCOUNT

OPEN before exception FALSE exception exception

after NULL TRUE NULL 0

First FETCH before NULL TRUE NULL 0

after TRUE TRUE FALSE 1

Next FETCH(es)

before TRUE TRUE FALSE 1

after TRUE TRUE FALSE data dependent

Last FETCH before TRUE TRUE FALSE data dependent

after FALSE TRUE TRUE data dependent

MONIKA/CSE 6th SEM/7026030250 Page 57

Page 58: rdbms

PRACTICAL FILE OF RDBMS

CLOSE before FALSE TRUE TRUE data dependent

after exception FALSE exception exception

Declaring a Cursor

When we declare a cursor, we name it and associate it with a specific query using the syntax:

CURSOR cursor_name [(parameter[, parameter]...)]

[RETURN return_type] IS select_statement;

where return_type must represent a record or a row in a database table, and parameter stands for the following syntax:

cursor_parameter_name [IN] datatype [{:= | DEFAULT} expression]

Opening a Cursor

Opening the cursor executes the query and identifies the result set, which consists of all rows that meet the query search criteria. For cursors declared using the FOR UPDATE clause, the OPEN statement also locks those rows.

Passing Cursor Parameters

We use the OPEN statement to pass parameters to a cursor. Unless we want to accept default values, each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement.

Fetching with a CursorThe FETCH statement retrieves the rows in the result set one at a time. Each fetch retrieves the current row and then advances the cursor to the next row in the result set.

Closing a CursorThe CLOSE statement disables the cursor, and the result set becomes undefined. Once a cursor is closed, we can reopen it.

MONIKA/CSE 6th SEM/7026030250 Page 58

Page 59: rdbms

PRACTICAL FILE OF RDBMS

Implicit Cursors

Oracle implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. We can refer to the most recent implicit cursor as the SQL cursor. Although we cannot use the OPEN, FETCH, and CLOSE statements to control the SQL cursor, we can use cursor attributes to get information about the most recently executed SQL statement.

Oracle implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. PL/SQL lets you refer to the most recent implicit cursor as the SQL cursor. You cannot use the OPEN, FETCH, and CLOSE statements to control the SQL cursor. But, you can use cursor attributes to get information about the most recently executed SQL statement

Using Cursor Attributes

Each cursor or cursor variable has four attributes:

1) %FOUND 2) %ISOPEN 3) %NOTFOUND4) %ROWCOUNT.

When appended to the cursor or cursor variable, these attributes return useful information about the execution of a data manipulation statement. You can use cursor attributes in procedural statements but not in SQL statements

IMPLICIT CURSOR HANDLING

implicit cursor attributes return information about the execution of an insert, update, delete, or select into statement. the values of the cursor attributes always refer to the most recently executed sql statement. before oracle opens the sql cursor, the implicit cursor attributes yield null

the implicit cursor attributes are referred by preceding the implicit cursor attribute with cursor name.(i.e sql).

SQL%FOUND

Until a SQL data manipulation statement is executed, %FOUND yields NULL. Thereafter, %FOUND yields TRUE if an INSERT, UPDATE, or DELETE

MONIKA/CSE 6th SEM/7026030250 Page 59

Page 60: rdbms

PRACTICAL FILE OF RDBMS

statement affected one or more rows, or a SELECT INTO statement returned one or more rows. Otherwise, %FOUND yields FALSE.

In the following example, you use %FOUND to insert a row if a delete succeeds:

DELETE FROM emp WHERE empno = my_empno;IF SQL%FOUND THEN -- delete succeeded INSERT INTO new_emp VALUES (my_empno, my_ename, ...);

SQL%ISOPEN

Oracle closes the SQL cursor automatically after executing its associated SQL statement. As a result, %ISOPEN always yields FALSE.

SQL%NOTFOUND

%NOTFOUND is the logical opposite of %FOUND. %NOTFOUND yields TRUE if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows. Otherwise, %NOTFOUND yields FALSE.

SQL%ROWCOUNT

%ROWCOUNT yields the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by a SELECT INTO statement. %ROWCOUNT yields 0 if an INSERT, UPDATE, or DELETE statement affected no rows, or a SELECT INTO statement returned no rows.

In the following example, you use %ROWCOUNT to take action if more than ten rows have been deleted:

DELETE FROM emp WHERE ...IF SQL%ROWCOUNT > 10 THEN -- more than 10 rows were deleted ...END IF;

MONIKA/CSE 6th SEM/7026030250 Page 60

Page 61: rdbms

PRACTICAL FILE OF RDBMS

Query: Write a PL/SQL block of code to display a message to check whether the record is deleted or not using sql%notfound.

Output:Records of employee table before execution:

MONIKA/CSE 6th SEM/7026030250 Page 61

Page 62: rdbms

PRACTICAL FILE OF RDBMS

Program:

Records of employee table after execution:

MONIKA/CSE 6th SEM/7026030250 Page 62

Page 63: rdbms

PRACTICAL FILE OF RDBMS

MONIKA/CSE 6th SEM/7026030250 Page 63

Page 64: rdbms

PRACTICAL FILE OF RDBMS

Query: Write a PL/SQL block of code to display a message to check whether the record is deleted or not using sql%found.

Output:Records of employee table before execution:

Program:

Records of employee table after execution:

MONIKA/CSE 6th SEM/7026030250 Page 64

Page 65: rdbms

PRACTICAL FILE OF RDBMS

MONIKA/CSE 6th SEM/7026030250 Page 65

Page 66: rdbms

PRACTICAL FILE OF RDBMS

Query: Write a PL/SQL block of code to display a message to give the no of records deleted by a delete statement in PL/SQL block.

Output:Records of employee table before execution:

Program:

MONIKA/CSE 6th SEM/7026030250 Page 66

Page 67: rdbms

PRACTICAL FILE OF RDBMS

Records of employee table after execution:

MONIKA/CSE 6th SEM/7026030250 Page 67

Page 68: rdbms

PRACTICAL FILE OF RDBMS

Implicit cursor handling

Kinds of variables: The types of attribute are

a. %Typeb. %Rowtype

a. %Type: This attribute is used when declaring variables that refer to data base column by using type variable; we need the name of columns and table to which the variable correspond.Syntax: variable_name <table_name>.<column_name>%type.

b. %Rowtype: This attribute is used to declare the single variable for various columns in a table.

MONIKA/CSE 6th SEM/7026030250 Page 68

Page 69: rdbms

PRACTICAL FILE OF RDBMS

Query1: Write PL/SQL code to calculate total salary of employee having Employee number 100, the table employee has the following column, employee(ENO,BP,ENAME,DA,HRA,TOTAL).

Using %type:

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 69

Page 70: rdbms

PRACTICAL FILE OF RDBMS

Query: Write PL/SQL code to calculate total salary of employee having Employee number 100, the table employee has the following column, employee(EMPNO,ENAME,BP,DA,HRA,TOTAL).

Using %ROWTYPE:

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 70

Page 71: rdbms

PRACTICAL FILE OF RDBMS

Methods or steps to perform explicit cursor management

a. Declare a cursor: A cursor is declared in the declare section of a PL/SQL block.Syntax: cursor <cursor_name> is select <statement>;

b. Open a cursor: It is use to open cursor explicitly that is by the user.Syntax: open <cursor_name>;

c. Fetch data from cursor into memory variable:Syntax: fetch <cursor_name> into variable_name;

d. Exit from loop.

e. Close a cursor:Syntax: close <cursor_name>;

MONIKA/CSE 6th SEM/7026030250 Page 71

Page 72: rdbms

PRACTICAL FILE OF RDBMS

Query: Write a PL/SQL block to display eno, ename, job of employees of department number 10.

Using %rowtype:

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 72

Page 73: rdbms

PRACTICAL FILE OF RDBMS

Query: Write a PL/SQL block to display eno, ename, job of employees of department number 10.

Using %type:

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 73

Page 74: rdbms

PRACTICAL FILE OF RDBMS

Query: To display ename and eno, sal of top 3 highest paid employees, Emp(eno,ename,salary).

Using %type:

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 74

Page 75: rdbms

PRACTICAL FILE OF RDBMS

Query: To display ename and eno, sal of top 3 highest paid employees, Emp(eno,ename,salary).

Using %rowtype:

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 75

Page 76: rdbms

PRACTICAL FILE OF RDBMS

Cursor for loop

Syntax:

For <variable_name> in <cursor_name>

Loop

<SQL statement>;

Query: To display eno, ename, job of employee of department number 10 with the help of cursor for loop.

Before execution

MONIKA/CSE 6th SEM/7026030250 Page 76

Page 77: rdbms

PRACTICAL FILE OF RDBMS

After execution

MONIKA/CSE 6th SEM/7026030250 Page 77

Page 78: rdbms

PRACTICAL FILE OF RDBMS

Query: To display eno, ename, salary of top 3 highest paid employees with the help of cursor for loop.

Before execution

After execution

MONIKA/CSE 6th SEM/7026030250 Page 78