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.

MONIKA/CSE 6th SEM/7026030250

Page 1

PRACTICAL FILE OF RDBMS
INTRODUCTION TO ORACLE 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 databuffers, 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.

MONIKA/CSE 6th SEM/7026030250

Page 2

PRACTICAL FILE OF RDBMS
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 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 datafiles. 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.

MONIKA/CSE 6th SEM/7026030250

Page 3

PRACTICAL FILE OF RDBMS Difference between RDBMS and DBMS S. No data integrity. It is easy to retrieve data in both. 4. It reads tables internally. Keys are used. No keys are used. MONIKA/CSE 6th SEM/7026030250 Page 4 . It is possible to edit record in both DBMS and RDBMS. It is less secure. Support null values. also important.no DBMS 1 There is no relationship concept. Both store data in the form of tables. It is more secure. It support single user. Used for smaller organizations Large organizations where large where security is not major amount data is maintain and security is concern. It is possible to store and retrieve It is possible to store and retrieve large fewer amounts of data in it. 2. present. It reads data as files internally. It support multiuser. amount of data in it. requirements.e. It does not support null values. 3. 2 3 4 5 6 7 8 9 10 11 12 RDBMS It is use to establish relationship concept between two database objects i. Examples: FoxPro Examples: SQL Server MS-Access Oracle Similarities between RDBMS and DBMS 1. Both are used for storage. Data integrity concept is present. It requires low software and It requires high software and hardware hardware requirements. Normalization concept is not Normalization is present. tables.

d) Holds a Number value with a maximum number of digits of "size" total. Holds variable-length character string.PRACTICAL FILE OF RDBMS Data Type A data type is a set of data with values having predefined characteristics. how the values are processed by the computer. Some data types in SQL are: char. The various Data Types along with their description are shown below: Data Type char(size) varchar(size) number(size) Date Description Holds fixed-length character string. with a maximum number of "d" digits to the right of the decimal. Max 255 bytes. number(size. Size is specified in parenthesis. date etc. MONIKA/CSE 6th SEM/7026030250 Page 5 . Max size is specified in parenthesis. The language usually specifies the range of values for a given data type. a limited number of such data types come built into a language. Holds Number value with a max number digits specified in parenthesis. Usually. number. Holds a Date value. Each language has its own data types. and how they are stored.

name varchar2(10).dept.PRACTICAL FILE OF RDBMS Create Table With CREATE TABLE. While creating a table. SQL Select This statement is used to view data from the table.) Query: create table emp1(e_no number. A row represents a single record while a column represents attributes/fields which can be thought of as one of the components contributing to make a record. data types have to be mentioned for each field. A table can be considered as a basic structure within which data is stored.name. Syntax: SELECT column_name(s) FROM table_name Query:To select all the column from the table:select * from studentcse.dept varchar2(10).desg varchar2(10)). . column_name2 data_type. a new table can be created. MONIKA/CSE 6th SEM/7026030250 Page 6 . The above statement creates an empty table (containing no records) named Details having fields-e_no. Syntax: CREATE TABLE table_name (column_name1 data_type..b_no number. It consists of rows and columns.b_no..desg.

To do this. Syntax: SELECT DISTINCT column_name(s) FROM table_name Query: select distinct * from studentcse. For example. Adding the word Distinct to Select. we make use of the clause Where. Syntax: SELECT column_name(s) FROM table_name WHERE condition Query: select * from studentcse where marks>300. we want to retrieve Employee names from database table Employee with salaries above 14000.PRACTICAL FILE OF RDBMS The Where Clause We might want to retrieve records which satisfy a particular condition. The Distinct Keyword Distinct keyword is used to retrieve values that are distinct or non-repetitive. we can get rid of this problem. MONIKA/CSE 6th SEM/7026030250 Page 7 . The SQL Select retrieves values from database table which may be repetitive. Thus Where clause is used to specify a selection criterion.

SQL Delete The SQL delete is used to delete rows from a database table. Order by Clause ORDER BY is used to get the result in the sorted manner. Query: select * from studentcse order by rollno desc. Unless Explicitly stated.PRACTICAL FILE OF RDBMS Sorting Sorting is an important feature of any database. the order by clause sorts the result in ascending order. Syntax: DELETE FROM table_name WHERE column_name = some_value MONIKA/CSE 6th SEM/7026030250 Page 8 . Syntax: SELECT column_name(s) FROM table_name ORDER BY column_name Query: select * from studentcse order by rollno. We can arrange data according to the sequence we need to put them into.

Query: drop table studentdet. attributes. DROP TABLE If the user want to delete a table (the table structure.PRACTICAL FILE OF RDBMS Query: delete from studentcse where rollno=106. Query: delete from studentcse where name like '__n%'. and indexes will also be deleted) Permanently then drop command can be used for the purpose. Syntax: DROP TABLE <table_name>. MONIKA/CSE 6th SEM/7026030250 Page 9 . Query: delete from studentcse where name='Radhika' and marks>300.

To do so. Syntax: UPDATE table_name SET column_name = new_value WHERE column_name = old_value MONIKA/CSE 6th SEM/7026030250 Page 10 . we can use the UPDATE command. we might find that there is a need to modify the data. Once there's data in the table. Query: truncate table student1. Syntax: TRUNCATE TABLE <table_name>. SQL Update Update statement is used to edit or update data in the table.PRACTICAL FILE OF RDBMS TRUNCATE Truncate command is used to simply get rid of the data but not the table itself.

MONIKA/CSE 6th SEM/7026030250 Page 11 .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'.

PRACTICAL FILE OF RDBMS Modify Table: alter table: Once a table is created in the database. ALTER TABLE is basically used to Change Add Drop a a a column column 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)). there are many occasions where one may wish to change the structure of the table. MONIKA/CSE 6th SEM/7026030250 Page 12 . 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)).

Query: rename emp to emp2. Syntax: select * from tab. Syntax: select column_name alias_name from table_name.PRACTICAL FILE OF RDBMS Rename Column Alias are used to rename a table¶s columns for the purpose of a particular query. MONIKA/CSE 6th SEM/7026030250 Page 13 . Tab: This command is used to view all the tables.

PRACTICAL FILE OF RDBMS Describe: This command is used to describe the structure of the the structure of the table. Query: describe emp2. Syntax: describe tablename. MONIKA/CSE 6th SEM/7026030250 Page 14 .

PRACTICAL FILE OF RDBMS Arithmetic Functions: Various functions like as addition. MONIKA/CSE 6th SEM/7026030250 Page 15 . Query: select sal+10 from emp2. multiplication. division. subtraction are used on the database. Syntax: select <arithmetic operation>fieldname from <tablename>. Query: select sal/10 from emp2.

Logical operators (NOT. These operators take as input one or more arguments (operands) and return a result. -. Comparison Operators ( =. The various Operators along with their description are shown below in tabular form: Operator Description = > < >= <= <> LIKE AND OR NOT Equal Greater than Less than Greater than or equal to Less than or equal to Not equal to String comparison test Logical And returns TRUE when both the specified conditions are true Logical Or returns TRUE when atleast one of the specified conditions is true Logical Not returns TRUE when none one of the specified conditions is true Query: select * from studentcse where marks>300. OR). >. <). *. MONIKA/CSE 6th SEM/7026030250 Page 16 . ).PRACTICAL FILE OF RDBMS Logical Operators: Oracle provides a set of built-in operators-Arithmetic Operators (+. AND.

PRACTICAL FILE OF RDBMS Range Searching: 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.336... 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. MONIKA/CSE 6th SEM/7026030250 Page 17 .') Query: select * from student where sid in(101..333. value2. 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.387). select ename from employee where ecity like 'APS' AND ecode IN(select ecode from company where desg like 'Manager').226.

. Syntax: select * from <table_name> where <column_name> Not between <Range1> and <Range2>. AND operator selects a range of data between two values. text. These values can be numbers. or dates.PRACTICAL FILE OF RDBMS Not between The NOTBETWEEN . MONIKA/CSE 6th SEM/7026030250 Page 18 ..

select * from studentcse where name like '__m%'. MONIKA/CSE 6th SEM/7026030250 Page 19 . Syntax: SELECT column_name FROM table_name WHERE column_name LIKE pattern Query: select * from studentcse where name like 'R%' and marks>300.PRACTICAL FILE OF RDBMS Pattern Matching: The Like Clause: The Like condition can be used to search for a particular pattern in a column in a database table. select * from studentcse where name like 'A%'.

Syntax: select * from dual. Its predefined in ORACLE database.PRACTICAL FILE OF RDBMS ORACLE Table dual Dual is a dummy table. MONIKA/CSE 6th SEM/7026030250 Page 20 . Syntax: Select sysdate from dual.

(ii) MIN (Minimum): It returns the lowest value of a column in a table. Syntax: SELECT min(column) FROM <table_name> MONIKA/CSE 6th SEM/7026030250 Page 21 . (i) AVG (Average): It returns the average value of a column.PRACTICAL FILE OF RDBMS -. Syntax: SELECT avg(column) FROM <table_name>. but return a single value.AGGREGATE FUNCTIONS: Aggregate functions operate against a collection of values.

PRACTICAL FILE OF RDBMS (iii) MAX(Maximum): It returns the highest value of a column in a table. Syntax: SELECT max(column) FROM <table_name>. MONIKA/CSE 6th SEM/7026030250 Page 22 .

MONIKA/CSE 6th SEM/7026030250 Page 23 . (i) ABS (Absolute): It returns the absolute value of any numeric data. Syntax: Select sqrt(value) from <table_name>.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.NUMERIC FUNCTIONS: Numeric functions are applied on any table having numeric data. It can also be applied on dual table.

PRACTICAL FILE OF RDBMS (iii) POWER: This numeric function calculates the power of any numeric value. of digits desired after decimal ) from MONIKA/CSE 6th SEM/7026030250 Page 24 . Syntax: Select <table_name>. round(value.power of value) from <table_name> (iv) ROUND: This function is used to get a rounded figure of a decimal value. Syntax: Select power(value.no.

Syntax: Select trunc(value. MONIKA/CSE 6th SEM/7026030250 Page 25 .PRACTICAL FILE OF RDBMS (v) Trunc: It shows the specified number of digits after truncating the other digits after decimal.no. of digits desired after decimal) from <table_name>. (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>.

(viii) FLOOR Function: It returns the immediate smaller integer of given decimal value.divisor) from <table_name>. Syntax: Select MOD(dividend. Syntax: Select FLOOR(value) from <table_name> MONIKA/CSE 6th SEM/7026030250 Page 26 .PRACTICAL FILE OF RDBMS (vii) MOD: This function returns the remainder provided two numbers dividend and divisor.

Syntax: Select CEIL(value) from <table_name> MONIKA/CSE 6th SEM/7026030250 Page 27 .PRACTICAL FILE OF RDBMS (ix) CEIL Function: It returns the immediate greater integer value of the given decimal value.

with all letters uppercase. Syntax: Select ascii(char) from <table_name>.STRING FUNCTIONS: There are various functions in SQL that can be applied on the string type data.PRACTICAL FILE OF RDBMS -. (i) ASCII: It returns the decimal representation in the database character set of the first character of string. Syntax: Select upper(string/column_name) from <table_name>. (ii) UPPER: It returns char. MONIKA/CSE 6th SEM/7026030250 Page 28 .

PRACTICAL FILE OF RDBMS (ii) LOWER: It returns char. with first letter of each word capitalized. MONIKA/CSE 6th SEM/7026030250 Page 29 . Syntax: Select initcap(string/column_name) from <table_name>. Syntax: Select lower(string/column_name) from <table_name>. (iii) INITCAP: It returns char. with all letters lowercase.

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

The value n can be of type NUMBER. (ii) To_Number: It is used to convert character to number datatype. BINARY_FLOAT. If you omit fmt. MONIKA/CSE 6th SEM/7026030250 Page 31 . or BINARY_DOUBLE. Syntax: Select to_char(value.PRACTICAL FILE OF RDBMS --CONVERSION FUNCTIONS: (i) To_Char: TO_CHAR (number) converts n to a value of VARCHAR2 datatype. DATE. Syntax: Select to_number(µvalue¶) from <table_name>. format) from <table_name>. then n is converted to a VARCHAR2 value exactly long enough to hold its significant digits. using the optional number format fmt.

Syntax: Select to_date(µdate¶. MONIKA/CSE 6th SEM/7026030250 Page 32 .PRACTICAL FILE OF RDBMS (iii) To_Date: It converts a character field to a date field. µformat¶) from <table_name>.

Syntax: SELECT column1.PRACTICAL FILE OF RDBMS GROUP BY CLAUSE: GROUP BY... and without the GROUP BY function it was impossible to find the sum for each individual group of column values. MONIKA/CSE 6th SEM/7026030250 Page 33 .<aggregate function>(column2) FROM <table_name> GROUP BY <column1>. was added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called.

MONIKA/CSE 6th SEM/7026030250 Page 34 .<aggregate function>(column) FROM table GROUP BY column1 HAVING <aggregate function> condition.PRACTICAL FILE OF RDBMS HAVING CLAUSE: HAVING. Syntax: SELECT column1... 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..

We have to perform a join. <column3> FROM <first_table> INNER JOIN second_table ON <first_table.keyfield> = <second_table. those rows will not be listed. Syntax: SELECT <column1>. y LEFT OUTER JOIN MONIKA/CSE 6th SEM/7026030250 Page 35 .INNER JOIN: The INNER JOIN returns all rows from both tables where there is a match. --Outer Join: Outer join uses two tables to extract the data .keyfield>. <column2>.PRACTICAL FILE OF RDBMS JOINS: Sometimes we have to select data from two or more tables to make our result complete.It displays all the rows of first table or second table or both depending on left outer join . -. If there are rows in Employees that do not have matches in Orders.right outer join or full outer join.

<column2>.keyfield>.keyfield> <second_table.keyfield>. y RIGHT OUTER JOIN: It displays all the rows of the second table of the join.PRACTICAL FILE OF RDBMS It displays all the rows of the first table of the join. MONIKA/CSE 6th SEM/7026030250 Page 36 .keyfield> = <second_table. Syntax: SELECT <cloumn1>. <column3> FROM <first_table> LEFT JOIN second_table ON <first_table. ON <column3> FROM = <first_table>RIGHT second_table <first_table. JOIN <column2>. Syntax: SELECT <cloumn1>.

keyfield>. ON <column3>FROM = <first_table>FULL <first_table.keyfield> <second_table. Syntax: SELECT <cloumn1>. JOIN second_table <column2>. MONIKA/CSE 6th SEM/7026030250 Page 37 .PRACTICAL FILE OF RDBMS y FULL OUTER JOIN It displays all the rows of the first table and second table of the join.

MONIKA/CSE 6th SEM/7026030250 Page 38 .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.

Unique constraint b. this means the column can never be empty. If you write the keyword NOT NULL after the data type of a column. Unique constraint: This constraint ensures that no two rows have same value in the specified column(s). Different Constraints a. Default constraint d. Example MONIKA/CSE 6th SEM/7026030250 Page 39 . Check constraint a. Primary key constraint c. Consider the following SQL command Create table employee (ecode integer NOT NULL. ename varchar2(9) NOT NULl. gross decimal). Example b.PRACTICAL FILE OF RDBMS Constraints in SQL A constraint is a condition or check applicable on field or set of fields. It is similar to default constraint except that only one column can be specified as primary key. Primary key constraint: This declares a column as the primary key of the table.

Default constraint: A default value can be specified for a column using the DEFAULT clause. Examples MONIKA/CSE 6th SEM/7026030250 Page 40 . d.PRACTICAL FILE OF RDBMS c. Check constraint: This constraint limits values that can be inserted into a column of a table. automatically the defined default value inserted in the field. When a user does not enter value for the column (having default value).

Drop index: It is used to vanish the existing index. The users cannot see the indexes. and each index is given a name. -. they are just used to speed up queries.Create Index: It creates a simple index on a table. MONIKA/CSE 6th SEM/7026030250 Page 41 . Query: create index id on studentcse(rollno).PRACTICAL FILE OF RDBMS INDEXES Indices are created in an existing table to locate rows more quickly and efficiently. Syntax: DROP INDEX index_name ON table_name. It is possible to create an index on one or more columns of a table. -. Duplicate values are allowed in simple index. Syntax: CREATE INDEX <index_name> ON <table_name> (column_name).

PRACTICAL FILE OF RDBMS Query: drop index id. MONIKA/CSE 6th SEM/7026030250 Page 42 .

a stored procedure. or join statements in a view. By adding functions. it allows you to present exactly the data you want to the user.name from studentcse where rollno>300. Using Views A view could be used from inside a query. --CREATE VIEW: This command creates the view of a table. just like a real table.columname n>From <table_name>. joins. etc. MONIKA/CSE 6th SEM/7026030250 Page 43 . You can add SQL functions.«««.'&name'). or from inside another view. Query: create view vw as select rollno.. insert into vw values(&rollno. A view contains rows and columns. Syntax: Create view <viewname> as select <columnname1. The database design and structure will NOT be affected by the functions. and JOIN statements to a view and present the data as if the data were coming from a single table. The fields in a view are fields from one or more real tables in the database. WHERE.PRACTICAL FILE OF RDBMS VIEWS: A view is a virtual table based on the result-set of a SELECT statement. where.columname2. to a view.

the programmer appends the variable type NUMBER to the name definition. PL/SQL's syntax strongly resembles that of Ada.) MONIKA/CSE 6th SEM/7026030250 Page 44 .Program proper EXCEPTION -. separated by a comma.S]) := value.. */ Numeric variables variable_name number(P[.Declaration block (optional) BEGIN -. Each of these is made up of the basic PL/SQL unit which is the block.PRACTICAL FILE OF RDBMS INTRODUCTION TO PL/SQL 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. "scale" refers to the number of digits which can follow the decimal point. triggers and anonymous blocks) followed by Oracle Reports v2. Basic code structure PL/SQL programs consist of procedures. and just like Ada compilers of the 1980s the PL/SQL runtime system uses Diana as intermediate representation. A few years later. functions. History PL/SQL made its first appearance in Oracle Forms v3. the other two being SQL and Java. ("Precision" in this context refers to the number of digits which the variable can hold. it was included in the Oracle Database server v7 (as database procedures. packages. Blocks take the general form: DECLARE -.Exception-handling (optional) END /* Sample comment spanning multiple lines. functions. To define a numeric variable. 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.. and anonymous blocks. To specify the (optional) precision(P) and the (optional) scale (S). one can further append these in round brackets.

smallint. The function converts the first quoted string into a date. float. Oracle provides a number of data types that can store dates (DATE. blob. nchar. MONIKA/CSE 6th SEM/7026030250 Page 45 . char. the programmer normally appends the variable type VARCHAR2 to the name definition. raw. for example: TO_DATE('31-12-2004'. To define a character variable. dec. double precision.'dd-mm-yyyy') "or" TO_DATE American') ('31-Dec-2004'. integer. long raw. format_string). nchar2.'dd-mon-yyyy'. decimal. 'NLS_DATE_LANGUAGE = To convert the dates to strings one uses the function TO_CHAR (date_string. binary_integer Character variables variable_name varchar2(L) := 'Text'.PRACTICAL FILE OF RDBMS A selection of other datatypes for numeric variables would include: binary_float. The TO_DATE function can be used to convert strings to date values. There follows in brackets the maximum number of characters which the variable can store. binary_double. long. using as a definition the second quoted string. however DATE is most commonly used. numeric. Programmers define date variables by appending the datatype code "DATE" to a variable name. Other datatypes for character variables include: varchar. bfile Date variables variable_name date := '01-Jan-2005'. real. clob. DATETIME. TIMESTAMP etc). int.

And also packages and triggers. 3.DDL statements.DML. Java or any other programming languages...sql writtens querys by using ddl... Both sql and pl/sql are languages used to acess data with in oracle data base. Embedded SQL ..Advantage of pl/sql over sql is.dcl etc..dml.where plsql uses cursors.Foxpro like languages.triggers..you can write many sql statements within a pl/sql block.SQL statements are invoked from a host environment like C/C++. Embeded SQL is used to embed SQL statements in C. In sql querys process at a time where as in plsql it done step by step or recoed by record .PRACTICAL FILE OF RDBMS Difference between SQL and PL/SQL 1. MONIKA/CSE 6th SEM/7026030250 Page 46 .PL/SQL is used for Cursors and Triggers .One more advantage is subprogramming like procedures and functions.manipulation of data using DML. SQL is Structured Query Language used for DDL. 2. SQL is a structured query language used for various operations such as retrieval. We can write cursors for fetching number of records at a time.Pascal.Cobol..procedures etc. PL/SQL is programming language used to write various sql statements together.

PRACTICAL FILE OF RDBMS PL/SQL Execution Environment The PL/SQL engine. which processes PL/SQL program units. Oracle loads the compiled procedure (or package) into the shared pool in the system global area (SGA). The procedure (or package) is stored in a database. is a special component of many Oracle products. When an application calls a procedure stored in the database. The following Oracle products contain a PL/SQL engine: y y y y y 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) Page 47 MONIKA/CSE 6th SEM/7026030250 . and the PL/SQL and SQL statement executors work together to process the statements within the procedure. including the Oracle server.

Also. you can pass anonymous blocks to Oracle from applications developed with these tools: y y y y y Oracle precompilers (including user exits) Oracle Call Interfaces (OCIs) SQL*Plus Server Manager Oracle Enterprise Manager MONIKA/CSE 6th SEM/7026030250 Page 48 . For example. you can call a stored procedure from Oracle Forms (Version 3 or later).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.

PRACTICAL FILE OF RDBMS Displaying user message on the screen Set server output on Set server output off MONIKA/CSE 6th SEM/7026030250 Page 49 .

ELSE sequence_of_statements_N. IF x = 1 THEN sequence_of_statements_1. CASE WHEN x = 1 THEN sequence_of_statements_1. END IF. ELSIF x = 2 THEN sequence_of_statements_2. The ELSIF and ELSE parts are optional so it is possible to create simpler IF-THEN or. The CASE statement simplifies some large IF-THEN-ELSE structures.PRACTICAL FILE OF RDBMS Conditional Statements The following code segment shows the IF-THEN-ELSIF construct. IF-THENELSE constructs. END CASE. WHEN x = 2 THEN sequence_of_statements_2. ELSE sequence_of_statements_N. MONIKA/CSE 6th SEM/7026030250 Page 50 .

MONIKA/CSE 6th SEM/7026030250 Page 51 .PRACTICAL FILE OF RDBMS Write a PL/SQL block to find greatest number among three numbers.

END CASE. ELSE sequence_of_statements_N. statement2. Looping As a procedural language by definition. LOOP statements Syntax: LOOP statement1. FOR loops. PL/SQL provides several iteration constructs. END LOOP. including basic LOOP statements. or by raising an exception. MONIKA/CSE 6th SEM/7026030250 Page 52 . WHILE loops. WHEN 2 THEN sequence_of_statements_2. and Cursor FOR loops.PRACTICAL FILE OF RDBMS CASE statement can be used with predefined selector: CASE x WHEN 1 THEN sequence_of_statements_1. Loops can be terminated by using the EXIT keyword.

PRACTICAL FILE OF RDBMS Write a PL/SQL block that display table for entered no using for loop. MONIKA/CSE 6th SEM/7026030250 Page 53 .

. END LOOP.person_code). MONIKA/CSE 6th SEM/7026030250 Page 54 . FOR loops Cursor FOR loops FOR RecordIndex IN (SELECT person_code FROM people_table) LOOP DBMS_OUTPUT.. Sequential Statements Syntax: GOTO record Where record is place in the PL/SQL to which goto label shift the control of program...PUT_LINE(RecordIndex.do something.PRACTICAL FILE OF RDBMS WHILE loops Syntax: WHILE LOOP . END LOOP.

SAVEPOINT. ROLLBACK.PRACTICAL FILE OF RDBMS TRANSACT-SQL (T-SQL) It is a part of PL/SQL. MONIKA/CSE 6th SEM/7026030250 Page 55 . SET TRANSACTION. Syntax: Commit. 2. Oracle treats a series of operators as a single entity.identifies a point in transaction to which you can later roll back. COMMIT. The changes made to the table is a two step process. 1. Savepoint savepoint_name. 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. Rollback [to[savepoint]savepointname]. First the changes requested are done. 4.Change transaction options like isolation level and what rollback segment to use. 3.restore database to original since the last COMMIT.saves work done.

date of change of price and oldprice. The price change is to be than recorded to the table oldprice along with productnumber (pno). Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 56 .PRACTICAL FILE OF RDBMS Query: If price of product 10 is less than 4000 then change the price to 4000.

then check. Insert a record in employ2 table. If total_salary>20.PRACTICAL FILE OF RDBMS Query: Write a PL/SQL block of code as following: 1. Update salary of Raman & Teena by 2000 & 1500. MONIKA/CSE 6th SEM/7026030250 Page 57 .000 then undo the update. To see that the total salary does not exceed 20. 2. made to the salary of the person. 3.000.

one can declare a cursor in the declarative part of any PL/SQL block. PL/SQL declares a cursor implicitly for all SQL data manipulation statements. or package. we release the cursor with the CLOSE statement. We use three commands to control a cursor: OPEN. When a query returns multiple rows. Cursor Attribute Values %FOUN %ISOPE %NOTFOU %ROWCOU D N ND NT OPEN before exception FALSE after First FETCH NULL TRUE TRUE TRUE TRUE exception NULL NULL FALSE FALSE exception 0 0 1 1 before NULL after TRUE Next FETCH(es) before TRUE after TRUE TRUE TRUE TRUE FALSE FALSE TRUE data dependent data dependent data dependent Last FETCH before TRUE after FALSE MONIKA/CSE 6th SEM/7026030250 Page 58 . or multiple rows. subprogram. and CLOSE. we initialize the cursor with the OPEN statement. Then. When the last row has been processed. depending on how many rows meet your search criteria. including queries that return only one row. you can execute FETCH repeatedly until all rows have been retrieved. one. Explicit Cursors The set of rows returned by a query can consist of zero. FETCH. Moreover. which identifies the result set.PRACTICAL FILE OF RDBMS Cursors PL/SQL uses two types of cursors: implicit and explicit. one can explicitly declare a cursor to process the rows. First.

Closing a Cursor The CLOSE statement disables the cursor. 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.. Fetching with a Cursor The FETCH statement retrieves the rows in the result set one at a time.PRACTICAL FILE OF RDBMS CLOSE before FALSE after TRUE TRUE exception data dependent exception exception FALSE Declaring a Cursor When we declare a cursor. For cursors declared using the FOR UPDATE clause. Passing Cursor Parameters We use the OPEN statement to pass parameters to a cursor. where return_type must represent a record or a row in a database table. each formal parameter in the cursor declaration must have a corresponding actual parameter in the OPEN statement. Each fetch retrieves the current row and then advances the cursor to the next row in the result set. and the result set becomes undefined. MONIKA/CSE 6th SEM/7026030250 Page 59 . parameter]. which consists of all rows that meet the query search criteria. we can reopen it.)] [RETURN return_type] IS select_statement. the OPEN statement also locks those rows. Once a cursor is closed. we name it and associate it with a specific query using the syntax: CURSOR cursor_name [(parameter[.. Unless we want to accept default values.

PL/SQL lets you refer to the most recent implicit cursor as the SQL cursor. Oracle implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. Although we cannot use the OPEN. we can use cursor attributes to get information about the most recently executed SQL statement. 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) 2) 3) 4) %FOUND %ISOPEN %NOTFOUND %ROWCOUNT. We can refer to the most recent implicit cursor as the SQL cursor. When appended to the cursor or cursor variable. You cannot use the OPEN. and CLOSE statements to control the SQL cursor. FETCH. FETCH. and CLOSE statements to control the SQL cursor. these attributes return useful information about the execution of a data manipulation statement. But.PRACTICAL FILE OF RDBMS Implicit Cursors Oracle implicitly opens a cursor to process each SQL statement not associated with an explicitly declared cursor. You can use cursor attributes in procedural statements but not in SQL statements MONIKA/CSE 6th SEM/7026030250 Page 60 .

e sql). SQL%ISOPEN Oracle closes the SQL cursor automatically after executing its associated SQL statement.delete succeeded INSERT INTO new_emp VALUES (my_empno. In the following example. . the values of the cursor attributes always refer to the most recently executed sql statement. or a SELECT INTO statement returned one or more rows. the implicit cursor attributes yield null the implicit cursor attributes are referred by preceding the implicit cursor attribute with cursor name. %ISOPEN always yields FALSE. UPDATE. or DELETE statement affected no rows. %NOTFOUND yields FALSE. before oracle opens the sql cursor. UPDATE. or DELETE statement. %FOUND yields TRUE if an INSERT.. IF SQL%FOUND THEN -. SQL%FOUND Until a SQL data manipulation statement is executed. SQL%ROWCOUNT %ROWCOUNT yields the number of rows affected by an INSERT. you use %FOUND to insert a row if a delete succeeds: DELETE FROM emp WHERE empno = my_empno. %FOUND yields NULL. or select into statement. %ROWCOUNT MONIKA/CSE 6th SEM/7026030250 Page 61 . or a SELECT INTO statement returned no rows. %FOUND yields FALSE. my_ename.. update. %NOTFOUND yields TRUE if an INSERT. As a result.PRACTICAL FILE OF RDBMS IMPLICIT CURSOR HANDLING implicit cursor attributes return information about the execution of an insert. delete.(i. Otherwise. Thereafter. SQL%NOTFOUND %NOTFOUND is the logical opposite of %FOUND. or DELETE statement affected one or more rows. UPDATE. Otherwise. or returned by a SELECT INTO statement.).

..PRACTICAL FILE OF RDBMS yields 0 if an INSERT. you use %ROWCOUNT to take action if more than ten rows have been deleted: DELETE FROM emp WHERE . or DELETE statement affected no rows. END IF..more than 10 rows were deleted . In the following example. IF SQL%ROWCOUNT > 10 THEN -.. MONIKA/CSE 6th SEM/7026030250 Page 62 . UPDATE. or a SELECT INTO statement returned no rows.

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: Program: Records of employee table after execution: MONIKA/CSE 6th SEM/7026030250 Page 63 .

PRACTICAL FILE OF RDBMS MONIKA/CSE 6th SEM/7026030250 Page 64 .

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 65

PRACTICAL FILE OF RDBMS

MONIKA/CSE 6th SEM/7026030250

Page 66

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 67

PRACTICAL FILE OF RDBMS Records of employee table after execution: MONIKA/CSE 6th SEM/7026030250 Page 68 .

PRACTICAL FILE OF RDBMS Implicit cursor handling Kinds of variables: The types of attribute are a. MONIKA/CSE 6th SEM/7026030250 Page 69 .<column_name>%type. Syntax: variable_name <table_name>. %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. %Rowtype a. %Type b. b. %Rowtype: This attribute is used to declare the single variable for various columns in a table.

Using %type: Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 70 .BP. employee(ENO.PRACTICAL FILE OF RDBMS Query1: Write PL/SQL code to calculate total salary of employee having Employee number 100.ENAME.TOTAL).HRA. the table employee has the following column.DA.

TOTAL).BP.PRACTICAL FILE OF RDBMS Query: Write PL/SQL code to calculate total salary of employee having Employee number 100. Using %ROWTYPE: Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 71 . the table employee has the following column.DA. employee(EMPNO.ENAME.HRA.

Close a cursor: Syntax: close <cursor_name>.PRACTICAL FILE OF RDBMS Methods or steps to perform explicit cursor management a. c. b. Syntax: open <cursor_name>. Declare a cursor: A cursor is declared in the declare section of a PL/SQL block. Exit from loop. Open a cursor: It is use to open cursor explicitly that is by the user. e. MONIKA/CSE 6th SEM/7026030250 Page 72 . Fetch data from cursor into memory variable: Syntax: fetch <cursor_name> into variable_name. Syntax: cursor <cursor_name> is select <statement>. d.

job of employees of department number 10. Using %rowtype: Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 73 .PRACTICAL FILE OF RDBMS Query: Write a PL/SQL block to display eno. ename.

PRACTICAL FILE OF RDBMS Query: Write a PL/SQL block to display eno. Using %type: Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 74 . ename. job of employees of department number 10.

sal of top 3 highest paid employees. Using %type: Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 75 .PRACTICAL FILE OF RDBMS Query: To display ename and eno.salary). Emp(eno.ename.

salary). Using %rowtype: Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 76 . Emp(eno.ename.PRACTICAL FILE OF RDBMS Query: To display ename and eno. sal of top 3 highest paid employees.

Query: To display eno. Before execution MONIKA/CSE 6th SEM/7026030250 Page 77 . ename.PRACTICAL FILE OF RDBMS Cursor for loop Syntax: For <variable_name> in <cursor_name> Loop <SQL statement>. job of employee of department number 10 with the help of cursor for loop.

PRACTICAL FILE OF RDBMS After execution MONIKA/CSE 6th SEM/7026030250 Page 78 .

ename. Before execution After execution MONIKA/CSE 6th SEM/7026030250 Page 79 .PRACTICAL FILE OF RDBMS Query: To display eno. salary of top 3 highest paid employees with the help of cursor for loop.

Sign up to vote on this title
UsefulNot useful