RDBMS Using Oracle :: Wel Come To ORACLE -...

69

Transcript of RDBMS Using Oracle :: Wel Come To ORACLE -...

Page 1: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)
Page 2: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

:: Wel Come To ORACLE :: � History of DBMS

� 1960s - Apollo moon-landing project, GUAM

� mid 1960s - IMS by IBM (hierarchical DBMS)

� mid 1960s - IDS by GE (network DBMS)

� 1965 - CODASYL(Conference on Data System Language)

� 1967 -DBTG(Data Base Task Group)

� 1970 - E.F.Codd of the IBM Research Lab.

� Late 1970s - System R project at IBM

� 1980s - commercial relational DBMS(DB2, Oracle, Informix..)

� Now - OODBMS, ORDBMS

� Terminology

� Relation : a relation is a table with columns and rows

� Attribute : an attribute is a named column of a relation

� Domain : a domain is the set of allowable values for one or more attributes

� Tuple : a tuple is a row of a relation

� Degree : the degree of a relation is the number of attributes it contrains

� Cardinality : the cardinality of a relation is the number of tuples it contains

� Relational database : a collection of normalized relation

� What is SQL*Net?

- Oracle’s Client/Server middleware product

- transparent connection from client tool to DB ( from on DB to another )

- works across multiple network protocol and operation system

� What is TNS?

- Transparent Network Substrate

- Oracle’s Network applications to access the underlying network protocols transparently

- TNS-based application, Oracle Protocol Adapters, Network software like TCP/IP

� Configuration File

- TNSNAME.ORA ( Client )

- TNSNAV.ORA ( Client )

- SQLNET.ORA ( Client, Server )

- LISTENER.ORA ( Server )

Page 3: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Page 4: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Oracle Files � Datafile

� Redo Log Files

� Control Files

� Parameter File

� Archive File

� Log File (alert*.log, sqlnet.log, listener.log...)

� Trace File

Physical storage structures � Data files

� Segments

� Extents

� Blocks

Logical storage structures Tablespaces

Tables / Clusters / Indexes

Rows

Columns

Extends :

� A set of contiguous database blocks within a datafile.

� Extent are allocated when.

- The segment is created (INITIAL EXTENT)

- The segments grows (NEXT EXTENT)

- The table is altered to allocate extents.

� Extent are de-allocated when the

- The segment is dropped and truncated.

- The segment is larger than optimal and contains free extents

(for rollback segments only)

� Each segment is created with at least on extend( initial extent )

( Rollback segment : 2)

� ALTER TABLE table_name DEALLOCATE UNUSED

Segment:

� a set of one or more extents that contains all the data for a specific type of logical storage

structure within a tablespace

� Data Segment

- A collection of extents that holds all of the data for a table or a cluster

� Index Segment

- A collection of extents that holds all of the index data for search optimization on large

tables and clusters

� Rollback Segment

- A collection of extents that holds rollback data for rollback, read-consistency, or recovery

� Temporary segment

Page 5: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

- A collection of extents that holds data belonging to temporary tables created during a sort

operation

� Bootstrap segment

- An extent that contains dictionary definitions for dictionary tables to be loaded when the

database is opened.

Page 6: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Page 7: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

[ Oracle Question ‐ Answer Material ] 

ID  Question   Page No. 1  Introduction   2  Define the Terms   3  Function or DBMS.   4  What is RDBMS ?   5  What is ORDBMS ?   6  Dr. E.F.Codd’s Rules   7  What is SQL? Delimiters of SQL. Component of SQL.   8  What is Constraints ? Explain with example.   9  What is Transaction ? Explain in Brief.   10  What is Sub Query? Explain in brief.   11  Explain INDEX in brief.   12  Explain view with its type and example.   13  Advantages of PL/SQL.   14  Explain PL/SQL Block with example.   15  What is cursor ? explain with all its attributes.   16  What is Trigger? Explain DML trigger.   17  What do you mean by the exception ? Explain in brief.   18  Explain Procedure and function? Difference between them.   19  What is Package ? Explain with example.   20  Explain oracle instance in brief.   21  Explain Memory Structure of Oracle.   22  Background Processes of Oracle   23  Differences     1. DBMS v/s RDBMS     2. SQL v/s SQL*PLUS     3. CHAR  v/s VARCHAR     4. IMPLICIT CURSOR v/s EXPLICIT CURSOR     5. CONSTRAINTS v/s TRIGGER     6. GROUP BY v/s ORDER BY     7. FUNCTION v/s PROCEDURE   24.  Short Notes     1. Date Functions     2. SYNONYM     3. Sequence     4. Snapshot     5. Not null  Constraints     6. Primary Key Constraints     7. Default value concept          II    WISH U ALL THE BEST DEAR STUDENTS  II   

 

Page 8: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

 Q­1 Write the answer of following Question.      [5 marks] 1.  DEFINE THE  TERMS  

( DATA, INFORMATION, DATABASE, DBMS, RDBMS, ORDBMS , COLUMN, TUPLE)   

DATA :­   Data can be anything  like a name of a person,  roll no of  student, name of any city which is not connected with any process.   INFORMATION :­ 

Meaning  full  data  is  called  Information.  It  has  some  connection  with  process. Information is always meaningful.   DATABASE :­ 

Data base is an Organized collection of Related Information. A  database  is  a  collection  of  information  that  is  organized  so  that  it  can  easily  be 

accessed,  managed,  and  updated.  In  one  view,  databases  can  be  classified  according  to types of content: bibliographic, full‐text, numeric, and images.   DBMS :‐ (Data Base Management System)   The System which is use to manage the Database is known as Database Management System. 

A system or software designed to manage a database and run operations on the data requested by numerous clients.   RDBMS :­  ( Relational Data Base Management System) 

A  Relational  Database  Management  System(RDBMS)  is  a  database  management system(DBMS) that is based on relational model as introduced by Dr. Edgar F.Codd. Relational Database Management system (RDBMS) stores data in the form of related tables. RDBMS  are  powerful  because  they  require  few assumption  about  how data  is  related  or how is will be extracted from the database. As a result, the same database can be viewed in many different ways.   COLUMN :   A  field  is  known  as  a  column  in  RDBMS.  If we  have  table  name  student  and  that contains the Rollno, Name and per. There Rollno or name or per  is known as a column of Table  student. A Column  is also known as attribute  in RDBMS. At  the  time of Creating Relationship between two table a column is known as a Attribute.  TUPLE :­ 

Page 9: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

  A Single record of  table  is known as a  tuple  in RDBMS. Record  is Also  famous as Row and Entity In RDBMS.  RELATION OR ENTITY CLASS OR TABLE : 

A database file is known as table or Relation or as Entity Class in RDBMS.  ORDBMS : 

An  object­relational  database  (ORD),  or  object­relational  database management system  (ORDBMS),  is a database management system (DBMS) similar  to a relational  database,  but  with  an  object‐oriented  database  model:  objects,  classes  and inheritance  are  directly  supported  in  database  schemas  and  in  the  query  language.  In addition, it supports extension of the data model with custom data‐types and methods.  Table : 

Tables  are  the  basic  unit  of  data  storage  in  an Oracle  database. Data  is  stored  in rows and columns. You define a table with a table name (such as employees) and set of columns.  You  give  each  column  a  column  name  (such  as  employee_id,  last_name,  and job_id), a datatype (such as VARCHAR2, DATE, or NUMBER), and a width. The width can be predetermined by  the  datatype,  as  in DATE.  If  columns  are  of  the NUMBER datatype, define precision  and scale  instead of width. A row  is a collection of column  information corresponding to a single record. 

 Functions of a DBMS 

1. Data storage, retrieval, and update 

2. A user‐accessible catalog 

3. Transaction support 

4. Concurrency control services 

5. Recovery services 

6. Authorization services 

7. Support for data communication 

8. Integrity services 

9. Services to promote data independence 

10. Utility services 

   

Page 10: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

2. What is Relational Database Management System ? Explain in Brief. A relational database is a database structured on the relational model. A Relational 

Database Management System or RDBMS is a suite of software programs that can be used for creating, maintaining, modifying and manipulating a relational database. It can also be used to create the application that a user will require for interacting with the data stored within the database. A very important point to note here is that an RDBMS that satisfies the 12  criteria  lay  down  by  Dr.  Codd  is  called  a  true  RDBMS.  (Refer  to  Appendix  A  for  Dr. Codd's 12 Rules).  

The functionality of RDBMS is the same as DMBS except that the features offered for data  storage  and  retrieval  are  very  advanced.  These  systems  are based  on mathematical SET  theory.  The  RDBMS  ensures  that  the  data  stored  in  the  database  is  accurate  and relevant. Excellent security features are offered by these systems. RDBMS packages are used in medium to large‐scale organizations, especially, those where data has  to be made available on distributed networks. These systems have capability  to store a very large amount of data and have quick data retrieval mechanism.  

Characteristics of RDBMS  The  relational  database  also  possesses  a  set  of  characteristics  relatively  common 

across all relational database management systems including‐ 1. Write intensive operations: The RDBMS is frequently written to and its often used in transaction oriented application. 2. Data in flux or historical data: The RDBMS is designed to handle frequently changing data. Alternatively, a RDBMS can also store vast amounts of historical data, which can later be analyzed. 3. Application specific schema: The RDBMS is configured on a per application basis and a unique schema exists to support each application. 4.  Complex  data  models:  The  relational  nature  of  the  RDBMS  makes  it  suitable  for handling sophisticated, complex data models that require many tables, foreign key values, complex join operations, and so on. 5.  Data  integrity:  The  RDBMS  features  many  components  designed  to  ensure  data integrity. This  includes rollback operations, referential  integrity, and transaction oriented operations.  6. ACID (Atomic, Consistent,  Isolation, Durable)  transactions: The  transactions either commit (such that all actions are completed) or it rollback (all actions are reversed or not performed).  Atomic: Atomic transactions consist of grouping of changes to tables or rows such that 

all or none of the changes take place. A rollback operation can reverse all the actions of the atomic transaction.  Consistent: Transactions operate on a consistent view of the data. When the transaction 

is completed, the data is left in a consistent state.   Isolation:  Transactions  run  isolated  from  other  transactions.  So  if  transactions  are 

running  concurrently,  the  effects  of  transaction  are  invisible  to  transaction  B,  and  vice‐versa, until the transaction is complete.   Durable:  Upon  commitment  of  the  transaction,  its  changes  are  guaranteed.  Until  the 

transaction  commits,  none  of  its  actions  are  durable  or  persistent.  If  the  system  crashes prior to a commit, the effects of the transaction will be rolled back.    

Page 11: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

3. What is ORDBMS ? Explain in Brief.  

An  object  relational  database  is  also  called  an  object  relational  database management system (ORDBMS). This system simply puts an object oriented front end on a relational database (RDBMS). When applications  interface  to  this  type of database,  it will normally interface as though the data is stored as objects. However the system will convert the object information into data tables with rows and colums and handle the data the same as a relational database. Likewise, when the data is retrieved, it must be reassembled from simple data into complex objects.   Performance Constraints 

Because the ORDBMS converts data between an object oriented format and RDBMS format,  speed  performance  of  the  database  is  degraded  substantially.  This  is  due  to  the additional conversion work the database must do.   

To combat the limitations of RDBMS and meet the challenge of the increasing rise of the Internet and the Web, programmers developed object‐oriented databases in the 1980s. The main objective of Object‐Oriented Database Management Systems,  commonly known as OODBMS,  is  to provide consistent, data  independent,  secure,  controlled and extensible data  management  services  to  support  the  object‐oriented  model.  They  were  created to handle big and complex data that relational databases could not.  

A significant difference between object‐oriented databases and relational databases is  that  object‐oriented  databases  represent  relationships  explicitly,  supporting  both navigational and associative access to information. As the complexity of interrelationships between  information within the database  increases, so do the advantages of representing relationships explicitly. Another benefit of using explicit relationships is the improvement in data access performance over relational value‐based relationships.  

A unique characteristic of objects is that they have an identity that is independent of the  state  of  the  object.  For  example,  if  one has  a  car  object  and we  remodel  the  car  and change its appearance, the engine, the transmission, and the tires so that  it  looks entirely different,  it  would  still  be  recognized  as  the  same  object  we  had  originally.  Within  an object‐oriented database, one  can always ask  the question,  “is  this  the  same object  I had previously?”, assuming one remembers the object’s identity. Object‐identity allows objects to be related as well as shared within a distributed computing network.   ORDBMS Benefits 

The main benefit to this type of database lies in the fact that the software to convert the  object  data  between  a  RDBMS  format  and  object  database  format  is  provided. Therefore  it  is not necessary  for programmers  to write code  to  convert between the  two formats and database access is easy from an object oriented computer language.  

All  of  these  advantages  point  to  the  application  of  object‐oriented  databases  to information management problems that are characterized by the need to manage:  • a large number of different data types,  

Page 12: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

• a large number of relationships between the objects, and  • objects with complex behaviors.  

Application  areas  where  this  kind  of  complexity  exists  includes  engineering, manufacturing, simulations, office automation and large information systems  

Object‐Relational database (ORDBMS) is the third type of database common today. ORDBMS  are  systems  that  “attempt  to  extend  relational  database  systems  with  the functionality  necessary  to  support  a  broader  class  of  applications  and,  in  many  ways, provide a bridge between the relational and object‐oriented paradigms.”   

ORDBMS was created to handle new types of data such as audio, video, and image files  that  relational  databases were not  equipped  to handle.  In  addition,  its  development was  the result of  increased usage of object‐oriented programming  languages, and a  large mismatch between these and the DBMS software.   

One  advantage  of  ORDBMS  is  that  it  allows  organizations  to  continue  using  their existing  systems,  without  having  to  make  major  changes.  A  second  advantage  is  that  it allows users and programmers to start using object‐oriented systems in parallel.  

There are  challenges  in  implementing an ORDBMS. The  first  is  storage and access methods. The second is query processing, and the third is query optimization.  

Since  the  development  of  RDBMS,  OODBMS,  and  ORDBMS,  many  vendors  have extended their systems with the ability to store new data types such as images and texts, and with the ability to ask more complex queries.   

One  rising  technique  is  enterprise  resource  planning  and  management  resource planning,  which  add  another  layer  of  application‐oriented  features  on  top  of  a  DBMS. Included  applications  come  from Baan,  Oracle,  SAP,  and  Siebel.  These  programs  each identify a set of common tasks encountered by a large number of organizations and provide a general application layer to carry out these tasks.  

More importantly, DBMS have advanced into the Internet and Web Age. Stored data is  widely  being  accessed  through  a  Web  browser.  Today,  queries  are  being  generated through Web‐accessible forms and answers are being formatted using a mark‐up language such  as  HTML.  In  addition,  many  vendors  and  distributors  are  adding  features  to  their DBMS aimed at making it better equipped for Internet usage.  

In  summary,  relational  and  object‐oriented  database  systems  each  have  certain strengths  as well  as  certain weaknesses.  In  general,  the weakness  of  one  type  of  system tends to be strength of the other.    

Page 13: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

4. Explain the Dr. E. F. Codd’s Rules for RDBMS   

Dr. E. F. Codd is an IBM researcher who first developed the relational data model n 1970. In 1985, Dr. Codd published a list of 12 rules that define an ideal relational database and has provided a guideline for the design of all relational database systems.  Rule 1. The Information Rule – All data should be presented in table form. Rule 2. Guaranteed Access Rule – All data should be accessible without ambiguity. This can be accomplished  through a  combination of  the  table name, primary key, and column name. Rule  3.  Systematic Treatment  of Null Values    –  A  field  should  be  allowed  to  remain empty. This involves the support of a null value, which is distinct from an empty string or a number with a value of zero. Of course, this can’t apply to primary keys. In addition, most database implementations support the concept of a not‐null field constraint that prevents null values in a specific table column. Rule 4. Dynamic On­Line Catalog based on the Relational Model – A relational database must provide access to its structure through the same tools that are used to access the data. This  is  usually  accomplished  by  storing  the  structure  definition  within  special  system tables. Rule 5. Comprehensive Data Sublanguage Rule – The database must support at least one clearly defined language that includes functionality for data definition, data manipulation, data  integrity,  and  database  transaction  control.  All  commercial  relational  databases  use forms of standard SQL (i.e. Structured Query Language) as their supported comprehensive language. Rule 6. View Updating Rule  –  Data  can  be  presented  in  different  logical  combinations called views. Each view should support the same full range of data manipulation that has direct access to a table available. In practice, providing update and delete access to logical views is difficult and is not fully supported by any current database.  Rule 7. High­Level Insert, Update and Delete – Data can be retrieved from a relational database  in sets constructed of data from multiple rows and/or multiple tables. This rule states that insert, update, and delete operations should be supported for any retrievable set rather than just for a single row in a single table.  Rule 8. Physical Data Independence – The user is  isolated from the physical method of storing  and  retrieving  information  from  the  database.  Changes  can  be  made  to  the underlying architecture (hardware, disk storage methods) without affecting how the user accesses it.   Rule 9. Logical Data  Independence – How data  is viewed should not be changed when the  logical  structure  (table’s  structure)  of  the  database  changes.  This  rule  is  particularly difficult  ot  satisfy.  Most  databases  rely  on  strong  ties  between  the  data  viewed  and  the actual structure of the underlying tables.   

Page 14: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Rule  10.  Integrity  Independence  –  The  database  language  (like  SQL)  should  support constraints  on  user  input  that  maintain  database  integrity.  This  rule  is  not  fully implemented  by  most  major  vendors.  At  a  minimum,  all  database  do  preserve  two constraints through SQL. No component of a primary key can have a null value. If a foreign key is defined in one table, any value in it must exist as a primary key in another table.  Rule 11. Distribution  Independence – A user  should be  totally unaware of whether or not the database is distributed (whether parts of the database exist in multiple locations). A variety of reasons make this rule difficult to implement.  Rule 12. Non­Subversion Rule – There should be no way to modify the database structure other  than  through  the  multiple  row  update  language  (like  SQL).  Most  databases  today support administrative tools that allow some direct manipulation of the data structure.    

Page 15: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

5. What  is  SQL  ?  Explain  the  Delimiter  of  SQL  ?  Explaint  the  Component  of ORACLE. 

Introduction To Structured Query Language (SQL) Structured  Query  Language  (SQL)  is  a  language  that  provides  an  interface  to 

relational database systems. SQL was developed by IBM in the 1970s fro use in System R, and  is  de  facto  standard  as well  as  an  ISO  and  ANSI  standard.  SQL  is  often  pronounced SEQUEL. 

In  common  usage  SQL  also  encompasses  DML  (Data Manipulation  Language),  for INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used  for  creating and modifying tables and other database structures. 

The  development  of  SQL  is  governed  by  standards.  The  American  National Standards  Institute  (ANSI)  is  an  organization  that  approves  certain  standards  in  many different  industries.  SQL  has  been  deemed  the  standard  language  in  relational  database communication, originally approved in 1986 based on IBM’s implementation. In 1987, the International  Standards  Organization  (ISO)  accepted  the  ANSI  SQL  standard  as  the international  standard.  The  standard was  revised  again  in  1992  and was  called  SQL­92. The newest standard in now called SQL­99,  it is also referred to as SQL­3. SQL­3 support object extensions and are partially implemented in Oracle8 and 9. 

SQL  has  been  a  command  language  for  communication with  the  Oracle  9i  Server from any tool or application. Oracle SQL contains many extensions. When an SQL statement is entered, it is stored in a part of memory called SQL buffer and remains there until a new SQL statement is entered. 

SQL*PLUS  is  an  Oracle  tool  that  recognizes  and  submits  SQL  statements  to  the Oracle 9i Server for execution. It contains its own command language. Features of SQL 1. SQL can be used by a range of users, including those with little of no programming experience 2. It is non procedural language 3. It reduce the amount of time required for creating and maintaining systems 4. It is an English‐like language  Components of SQL  1. DDL (Data Definition Language)   It  is a set of SQL commands used to create, modify and delete database structures but  not  data.  These  commands  are  normally  not  used  by  a  general  user, who  should  be accessing the database via an application. They are normally used by the DBA (Data Base Administrator)  to  a  limited  extent,  a  database  designer  or  application  developer.  These statements are immediate i.e. they are not susceptible to ROLLBACK commands. It should also  be  noted  that  if  several  DML  statements  for  example  updates  are  executed,  then issuing  any  DDL  command  would  COMMIT  all  the  updates  as  every  DDL  command implicitly  issues a COMMIT command to the database. Anybody using DDL must have the CREATE object privilege. 2. DML (Data Manipulation Language)   It is the area of SQL that allows changing data within the database.  3. DCL (Data Control Language) 

Page 16: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

  It is the component of SQL statement that control access to data and to the database. Occasionally, DCL statements are grouped with DML statements.  4. DQL (Data Query Language)   It is the component of SQL statement that allows getting data from the database and imposing ordering upon it. It includes the SELECT statement. This command is the heart of SQL. It allows getting the data out of the database perform operations with it. When a select is fired against a table or tables, the result is compiled into a further temporary table, which is displayed or perhaps received by the program i.e. a front‐ end.  

Examples of DDL statements CREATE: To create objects in the database. ALTER: Alters the structure of the database. DROP: Delete objects from the database. TRUNCATE: Remove all records from a table, including all spaces allocated for the records are removed.  

Examples of DML statements INSERT: Insert data into a table UPDATE: Updates existing data within a table DELETE: Deletes all records from a table, the space for the records remain  

Examples of DQL statements SELECT: Retrieve data from a database  

Examples of DCL statements GRANT: Gives user’s access privileges to database. REVOKE: Withdraw access privileges given with the GRANT command.  

Examples of TCL statements COMMIT: Save work done SAVEPOINT: Identify a point in transaction to which you can later rollback ROLLBACK: Restore database to original since the last COMMIT  Delimiters of SQL :­ Delimiters are the symbol or compound symbols, which have a special meaning within SQL and PL/SQL.   +  ASC  “  Quote Identifier  ||  Concatation ‐  NOT  :  Host variable  <<  Label *  RAW  **  Exponent  >>  Label /  ROW  <>  != ^=  Relational  ‐  Comment =><  Relation  <= >=  Relational  /* */  Multiline 

Comment ( )  Expression or list  :=  Assignment  =>  Association ;  Terminator  %  Attribute 

Indicator ,  Item Separator 

.  Component Selector 

@  Remote  Access indicator 

‘  Character string delimiter 

Page 17: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

5. What is Constraints ? Explaint With Example .  Constraints are pre declarations of conditions about the database that must remain true. These include attributed‐based, tuple‐based, key, and referential integrity constraints. The system  checks  for  the  violation  of  the  constraints  on  actions  and  aborts  the  action accordingly  Data  integrity  allows  to  define  certain  data  quality  requirements  that  the  data  in  the database needs to meet. If a user tries to insert data that doesn't meet these requirements, Oracle will not allow so.     A constrain is a mechanism in a relation database that some rules on data inserted into a column of table. Constrain are used to ensure accuracy and consistency of data in a database. Data integrity is this assurance of accurate and consistent data in a database.  In  order  for  a  data  base  to  have  integrity  (to  ensure  that  users  perform only  operations which leave the database in a correct, consistent state) it needs to obey several rules called "Integrity Constraints".  Business  rules  that  are  applied  to  data  being  stored  in  a  table,  are  called  Constraints. Constraints super controls the data being entered into a table for permanent storage.  Domain integrity constraint:‐ (CHECK, Not null) A column MUST contain only values consistent with the defined data format. Referential integrity constraint:‐ (Foreign Key ) Only Valid Relationships. Entity integrity constraint :‐ (Primary Key, Unique) Data Integrity refers to the accuracy and consistency of the data and define the relationally correct state for a data‐base  Types of constraints : There are two types of data constraints that   can be applied to data being inserted into a Oracle  table. One  type of  Constraint  is  called  an  I/O  (input/output)  constraint.  This data constraint determines the speed at which data can be inserted or extracted from a Oracle table. The other type is called Business Rule constraint. 1. Input Output Constraint :‐ The  input/output  data  constraint  are  further  divided  into  two  distinctly  difference constraint. a. Primary Key : b. Foreign Key  2. Business Rule Constraint :‐ Business rules can be implemented in Oracle by using CHECK constraint. Check constraints can be bound to a column or a table using the  CREATE TABLE or ALTER TABLE command.  Constraint declaration :­ 

Page 18: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

  Oracle allows the programmer to define constraints at two level. 1. Column Level If  data  constraint  are  defined  as  an  attribute  of  a  column  definition  when  creating  or altering table structure, they are column level constraints. Unique, Not Null, Primary Key, Foreign Key, Check, Default all the constraints can be define at column Leve.  2. Table Level: If  data  constraint  are defined  after  defining  all  table  column  attributes when  creating  or altering  a  table  structure,  it  is  called  Table  Level  Constraints.  Primary  Key,  Foreign  key, Unique, Check, Default constraints can be define at Table level.  Oracle Provide Five Constraint:  1. Not null  2.Unique  3.Primary Key : 4. Foreign Key  5.Check:  Not null  A  column  in  a  table  can be  specified not null.  It's not possible  to  insert  a  null  in  such a column. The default is null. By default the table contain null values. The enforcement of not null  constrain  in  a  table  ensure  that  the  table  contain  values.  Oracle  doesn’t  insert  the record until this is satisfied. SYNTAX:­  CREATE TABLE <TABLENAME> (FIELDNAME DATATYPE (SIZE) NOT NULL); Ex:‐  Create table emp (emp_id number (3) not null, emp_name varchar(10)not null,  address varchar , city varchar (10));  Unique • The unique constraint doesn't allow duplicate values in a column. • If  the  unique  constraint  encompasses  two  or  more  columns,  no  two  equal combinations are allowed. • By using UNIQUE Constraint index is created automatically. • Unique key can combine upto 16 columns in a Composite Unique key. • Unique key can not be LONG or LONG ROW data type. SYNTAX:  CREATE TABLE <TABLENAME> (FIELDNAME DATATYPE (SIZE) UNIQUE); EX:    CREATE TABLE INFO (CITY VARCHAR (20) UNIQUE); A unique constraint can be extended over multiple columns: SYNTAX: CRETE TABLE <TABLENAME> (FIELDNAME1 DATATYPE (SIZE), FIELDNAME2 DATATYPE (SIZE), UNIQUE (FIELDNAME1, FIELDNAME2)); EX:  CREATE TABLE INFO (NAME VARCHAR (20), CITY VARCHAR (20), UNIQUE (NAME, CITY));  Primary key constraint: • A primary key is a one or more column in a table used to uniquely identify each row in the table. • It can be defined either in the CREATE or ALTER table statement • A table can have only one primary key. 

Page 19: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

• It  defines  the  column  as  the  mandatory  column  because  NOT  NULL  attribute  is active. • The data held across the column must be UNIQUE. • The single column primary key is called simple key. • A multicolumn primary key is called composite primary key. Syntax: 1) Primary key defined at column level: <Column name> <data type> (<size>) PRIMARY KEY Ex: Create table info (No number (3) primary key, name varchar (20), city varchar (20));       2) Primary key defined at table level: PRIMARY KEY (<column name>, <column name>)            Ex:  Create table product (pno number (3), pname varchar (20),  price number (3), primary key (pno, price));      Foreign Key Constraints:                                                                                                                     • Foreign  keys  represent  relationship  between  tables.  A  foreign  key  is  a  column(or  a group of columns) whose values are derived from the primary key or unique key of some other table. • The table in which the foreign key is called a Foreign table or Detail table. • The table that defines the primary key or unique key and is referenced by the foreign key is called the primary table or master table. • A Foreigh key can be difined in either CREATE TABLE statement or an ALTER TABLE statement. • The master  table  can  be  refreneced  in  the  foreigh  key  definition  by  using  the  clause REFRECES <table name>.<columnname> when defining the foreigh key, column attributes, in the detail table. 1) Foreign key defined at column level: <Column name> <data type> (<size>) REFRENCES <Tablename> [<columnname>)] ; Ex:Create table emp (eno number (3) PRIMARY KEY, ename varchar (20),city varchar (20), deptno number(5) REFRENCES DEPT(DEPTNO), salary number(8));       2) Foreign  key defined at table level: Ex:  Create table emp (eno number (3) PRIMARY KEY, ename varchar (20),city varchar (20), deptno number(5),salary number(8), FOREIGN KEY(dept_no) REFRENCES DEPT(DEPTNO) ); CHECK: • Business  rule  validation  can  be  applied  to  a  table  by  using  CHECK  constraints. CHECK constrints must be specified as a  logical expression that evaluates either TRUE or FALSE. • A  check  constraint  allows  to  state  a  minimum  requirement  for  the  value  in  a column. • Check constraints can be added after a table has been created. SYNTAX: CHECK at column level: <Column name> <data type> (<size>) CHECK <Condition>. It can also define at table level.   

Page 20: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Q­6 What is Transaction ? Explain Commit, Rollback and Save point with example. 

A  transaction  is  a  logical  unit  of  work  that  contains  one  or  more  SQL  statements.  A transaction is an atomic unit. The effects of all the SQL statements in a transaction can be either  all  committed  (applied  to  the  database)  or  all  rolled  back  (undone  from  the database). A transaction begins with the first executable SQL statement. A transaction ends when it is committed  or  rolled  back,  either  explicitly  with  a  COMMIT  or  ROLLBACK  statement  or implicitly when a DDL statement is issued. All  changes  of  data  in  an  Oracle  database  can  only  be  done  within  a  transaction.  A transaction must either be committed or rolled back.  Data changed within a transaction is not visible to another session until  it  is commited. A transaction is ended either by a commit or a rollback To  illustrate  the  concept  of  a  transaction,  consider  a  banking  database.  When  a  bank customer  transfers money  from a  savings  account  to  a  checking  account,  the  transaction can consist of three separate operations: • Decrement the savings account • Increment the checking account • Record the transaction in the transaction journal Oracle  must  allow  for  two  situations.  If  all  three  SQL  statements  can  be  performed  to maintain the accounts in proper balance, the effects of the transaction can be applied to the database. However,  if  a  problem  such  as  insufficient  funds,  invalid  account number,  or  a hardware failure prevents one or two of the statements in the transaction from completing, the entire transaction must be rolled back so that the balance of all accounts is correct. Commit :­ Commit command is used to end a transaction. With the help of this command transaction changes can be made permanent to the database. Committing  a  transaction means making  permanent  the  changes  performed by  the  SQL statements within the transaction Syntax:­  Commit;       or   Commit Work; Committing means that a user has explicitly or implicitly requested that the changes in the transaction be made permanent. An explicit request means that the user issued a COMMIT statement. An implicit request can be made through normal termination of an application or  in  data definition  language,  for  example. The  changes made by  the  SQL  statements  of your transaction become permanent and visible to other users only after your transaction has  been  committed.  Only  other  users'  transactions  that  started  after  yours will  see  the committed changes. Save Point :­ Save point are markers to divide a lengthy transaction in to smaller one. They are   used to identify  a  point  in  a  transaction when we  can  later  rollback  .Thus  save  point  is  used  in conjunction with rollback, to rollback portion of current transaction. Styntax:­  Savepoint <Savepoint Name > ; Ex:­    Savepoint S1; You  can  declare  intermediate  markers  called  savepoints  within  the  context  of  a transaction. Savepoints divide a long transaction into smaller parts.  

Page 21: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Using  savepoints,  you  can  arbitrarily  mark  your  work  at  any  point  within  a  long transaction.  You  then  have  the  option  later  of  rolling  back  work  performed  before  the current point in the transaction but after a declared savepoint within the transaction. For example,  you  can  use  savepoints  throughout  a  long  complex  series  of  updates,  so  if  you make an error, you do not need to resubmit every statement.  

Savepoints  are  similarly  useful  in  application  programs.  If  a  procedure  contains  several functions, then you can create a savepoint before each function begins. Then, if a function fails,  it  is  easy  to  return  the  data  to  its  state  before  the  function  began  and  re‐run  the function with revised parameters or perform a recovery action.  

After  a  rollback  to  a  savepoint,  Oracle  releases  the  data  locks  obtained  by  rolled  back statements. Other  transactions  that were waiting  for  the previously  locked resources can proceed. Other transactions that want to update previously locked rows can do so.  

When a transaction is rolled back to a savepoint, the following occurs:  

1. Oracle rolls back only the statements run after the savepoint. 2. Oracle  preserves  the  specified  savepoint,  but  all  savepoints  that were  established after the specified one are lost. 3. Oracle releases all table and row locks acquired since that savepoint but retains all data locks acquired previous to the savepoint. 4. The transaction remains active and can be continued.  

Rollback:­  

A rollback command is used to undo the work done in current transaction. We can either rollback  a  transaction  so  that  changes made  by  SQL  undo  or  rollback  a  transaction  to  a savepoint so that the SQL statements after the savepoint are rollback; Syntax:­    Rollback work;        Or  Rollback; Rolling  back  means  undoing  any  changes  to  data  that  have  been  performed  by  SQL statements within an uncommitted  transaction. Oracle uses undo  tablespaces or  rollback segments to store old values. The redo log contains a record of changes.  

Oracle lets you roll back an entire uncommitted transaction. Alternatively, you can roll back the trailing portion of an uncommitted transaction to a marker called a savepoint.  

All types of rollbacks use the same procedures: • Statement‐level rollback (due to statement or deadlock execution error) • Rollback to a savepoint • Rollback of a transaction due to user request • Rollback of a transaction due to abnormal process termination • Rollback of all outstanding transactions when an instance terminates abnormally • Rollback of incomplete transactions during recovery In  rolling back an entire  transaction, without  referencing  any  savepoints,  the  following occurs: 1. Oracle  undoes  all  changes  made  by  all  the  SQL  statements  in  the  transaction  by using the corresponding undo tablespace or rollback segment. 2. Oracle releases all the transaction's locks of data.    

Page 22: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Q­7 What is SUB­QUERY ? Explain with Suitable example.  

A sub‐query is a form of an SQL statement that appers inside another SQL statement. It is also termed as a Nested Query. The Statement containing a sub query is known as parent statement. The parent statement uses the rows (the result set) returned by the sub query.   

A sub‐query  is a query within a query.  In Oracle, you can create sub‐queries within your SQL statements. These sub‐queries can reside  In the WHERE clause  In the FROM clause, or In the SELECT clause.  

Sub query is mainly use for following Operation : 1. To insert record in a target table. 2. To create table from an existing table. 3. To update record in a target table. 4. To create view or snapshot  5. To provide value  for condition  in WHERE clause, HAVING,  IN and  so on used with SELECT, UPDATE and DELETE statement.  

Tso create table from an existing table.(using Sub Query)  

Ex.: create table employee as select * from emp; Above example  is  a  simple example of  sub query. Above  statement will  create new  table named employee having the same column as in emp table. Above statement will also copy all the records of emp table to employee table. Here select * from emp is a Sub query and Create table employee is a parent query or parent statement. If you not want to copy all the records of emp table you have to specify a condition that can not be true.  Ex.: create table employee as select * from emp where 1>2 ;  

To Insert record in a target table from an existing table.(using Sub Query)  

Ex:‐ insert into employee (select * from emp); Above example is also a simple example of Sub query which insert all the rows of emp table to employee table here the structure of employee and emp table has same. But if you have only few column you can place name of column in the place of * in sub query. Here select * from emp is a sub query. You can also use where clause in sub query to copy the specified record from table.  

To create view or snapshot (Using Sub Query) Ex:‐ Create view my_view_emp as select * from emp; Ex:‐ Create snapshot my_first_snap as select * from emp; Another Sub query examples : select * from emp where deptno in (select deptno from dept where dname='SALES'); (Above statement display the record of employee whose dname is ‘sales’) select * from emp where sal>(select avg(sal) from emp); (Above statement display the record of employee whose sal is greater than average sal of all the employee.)  

Correlated Sub Query :­ 

Page 23: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Oracle  performs  a  CORRELATED  SUB‐QUERY  when  the  sub‐query  references  a  column from a table referred to in the parent statement. A correlated sub‐query is evaluated once for each row processed by  the parent statement. The parent statement can be a SELECT, UPDATE, or DELETE statement.  

You  can  use  a  correlated  sub‐query  to  determine which  employees  earn more  than  the average  salaries  for  their  departments.  In  this  case,  the  correlated  sub‐query  specifically computes the average salary for each department.  

Scalar sub‐queries, which return a single column value from a single row, are a valid form of expression. You can use scalar sub‐query expressions in most of the places where expr is called for in syntax.  

Ex.:  considering a emp and dept  table  If we want  to  find  the  records of employee whose salary is greater than average salary of his department’s employee.  

select * from emp e where sal>(select avg(sal) from emp where deptno = e.deptno)  

Here sub query select avg(sal)  from emp where deptno=e.deptno checks the deptno with the parent query’s deptno. so it is the correlated sub query. select * from emp e where sal>=all(select max(sal) from emp where deptno=e.deptno);  Operator use with Sub query : 

Operator  Description 

ALL  Compares a value to each value in a list or returned by a subquery and yields TRUE if all of the individual comparisons yield TRUE. 

ANY, SOME 

Compares a value to each value in a list or returned by a subquery and yields TRUE if any of the individual comparisons yields TRUE. 

BETWEEN  Tests whether a value lies in a specified range. EXISTS  Returns TRUE if a sub query returns at least one row. IN  Tests for set membership. IS NULL  Tests for nulls. LIKE  Tests  whether  a  character  string  matches  a  specified  pattern,  which  can 

include wildcards.      

Page 24: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Q­ 8 . Explain INDEX in Brief ?   

• An index is a way of presenting data differently than the way it appears on the table disk. 

• Indexing a table is an access strategy, that is, a way to sort and search records in the table. Indexes are essential to improve the speed with which records can be located and retrieved from a table. 

• An index is an ordered list of the contents of column ( or  a group of columns) of a table. 

• We can create indexes explicitly to speed up SQL statements on a table. • Similar to indexes in a book that help us to locate information faster. • An oracle index provides a faster access path to table data. • The index points directly to the location of rows contain the values. • The result produced by index is not directly seen to use because is sorts the data in 

memory  but  when  SELECT  statement  is  fired  the  fetching  process  will  becomes more faster if the index is created. So we can see that to view the output of index we have to fired Select statement. 

• Oracle allows the creation of two types of indexes. These are .: 1. Unique Index 2. Duplicate Index 

  Index  can  be  created  on  one  or  more  columns.  Based  on  the  number  of column included in the index and index can be:  

1. Simple Index:    Index created on a single column of a table is called Simple Index. The syntax and example of Simple index is as follow(Simple Index allows duplicate value. Syntax : CREATE INDEX <IndexName> on <TableName>(<ColumnName>) ; Example :Create index ind_rollno on student (rollno);  

2. Composite Index:    An Index created on more than one column is called Composite Index. syntax and example of Composite Index is as follow (Composite index also allows duplicate value ) Syntax : CREATE INDEX <Index Name> on <TableName>(<Column1>,<Column2>) ; Example : Create index ind_composite on student (rollno, per);  Unique Index : ‐   Unique indexes guarantee that no two rows of table have duplicate values in the column that define the  index. Non unique  index do not  impose this restriction on the column values.    To Create simple Unique Index only UNIQUE keyword is used in the syntax of Simple Index creation. Syntax  : CREATE UNIQUE INDEX <IndexName> on <TableName>(<ColumnName>) ; Example : Create unique index  ind_rno on teacher(RNO);  An index created in more than one column, is called composite Unique index. Syntax: CREATE UNIQUE INDEX <IndexName> on <TableName>(<Column1>,<Column2>)  

Page 25: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Example : Create UNIQUE index IND_RNOPER on teacher(RNO,PER);    Reverse key Indexes : ‐   You  can  also  create  a  index  in  reverse  order.  Under  some  circumstances using a reverse key index can make application run faster.  Ex:‐  Create index ind_rnotno on teacher(PER) REVERCE;     BITMAP Indexes : ‐   Bitmap  index  is use because  it  reduce response  time  for  large  classes of ad hoc  queries.  The  advantage  of  using  Bitmap  indexes  are  greatest  for  low  cardinality columns ex. Columns in which number of distinct value  is small compared to the number of rows in the table. If the value in a column are repeated more than a humdred times, the column  is  a  candidate  for  a bitmap  index  table with one million  rows,  rows with 10,000 distinct values are candidates for a bitmap index.  Syntax :‐  Create <Bitmap index> on <table name> (<Columnname>) ;   We can also create Function Based index and Key‐compressed indeed.  To delete any index drop command(DDL Command) is used.     

Page 26: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Q­9. What is view ? Explain its type ? Explain with example. After a table is created and populate with data, it may become necessary to prevent 

all  the user  from accessing all  the column of a  table,  for data security reason. This would mean  creating  several  tables  having  the  appropriate  number  of  column  and  assigning specific users to each table, as required. This will answer data security requirements very well  but will  give  rise  to  a  great ndeal  of  redundant data being  resident  in  tables,  in  the database.  

To reduce redundant  data  to the minimum possible, Oracle allows the creation of an object called a view.   

View is known as a virtual table.  

A  view  is  a  logical  entity.  It  is  a  SQL  statement  stored  in  the  database  in  the  system tablespace. Data for a view is built  in a table created by the database engine in the TEMP tablespace.  

View is a tailored presentation of the data contained in one or more tables or other views. A view takes the output of a query and treats it as a table. Therefore, a view can be thought of as a stored query or a virtual table. You can use views in most places where a table can be used.  

Views can be created by using following syntax :  

CREATE OR REPLACE VIEW <view_name> AS  SELECT <column_name> FROM <table_name> [WHERE <column_name> = <value or condition>]; [[ Group by <column> ][Having <expression>]]  

Reason for creation of View :   Views of table are created mainly for following purpose. 

• When Data Security is required. • When  Data  redundancy  is  to  be  kept  to  the  minimum  while  maintaining  data 

security. Because  views  are  derived  from  tables,  they have many  similarities.  For  example, 

you can define views with up to 1000 columns, just like a table. You can query views, and with  some restrictions you can update,  insert  into,  and delete  from views. All operations performed on a view actually affect data in some base table of  the view and are subject to the integrity constraints and triggers of the base tables. DROP VIEW <view_name>;  

Unlike a  table,  a view  is not allocated any  storage  space, nor  does a view actually contain data. Rather,  a  view  is defined by a query  that  extracts or derives data  from  the tables that the view references. These tables are called base tables. Base tables can in turn be actual tables or can be views themselves (including materialized views). Because a view is based on other objects, a view requires no storage other than storage for the definition of the view (the stored query) in the data dictionary. There are two types view : 1. Updatable view  2. Non updatable view 

Page 27: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Updatable views are those on which any updation Is possible. Means that views on which we can  fire any DML statement are known as updatable view.Updatable views are made up of any single select statement. Updateable views can not include: • Set Operators (INTERSECT, MINUS, UNION, UNION ALL) • DISTINCT • Group Aggregate Functions (AVG, COUNT, MAX, MIN, SUM, etc.) • GROUP BY Clause • Sub query In A Select List • Join Query  

Ex.: Create view employee as select * from emp; Here employee named view is created, if we insert any record in emp table employee table will  display  that  record  as well  as  if we  insert  any  new  record  in  employee  view  that  is stored in base table emp also. View is logical table that is not exist in memory it is a runtime entity. Any DML operation  fired on  table or  in updatable view it also effect base  table on which table is created.  

Ex.: create view employee1 as select ename, sal, deptno from emp; Here  if  we  fired  above  statement  it  will  create  view  named  employee1  but  it  becomes updatable BUT when we fire insert command it will generate error  because empno column of emp table is not taken in the view and if we insert value in only particular column  then remaining columns remains blank and error will generate.  

Ex.: Create view employee2 as select ename  ”Employee Name”, sal  ”Salary”, deptno “Department no” from emp;   Here  simple  view  has  been  created  but  the  column  name  will  be  changed.  New column Name are the alias as we specify in sub query.  

Non updatable View :   Non updatable  views are  those on which  insert,  update or delete operation  is not possible  and  which  consist  of  one  or  more  Select  statement  or  may  consist  join  or  sub query. View that are created from multiple table are known as a Non updatable view.  

EX:  create  view  v1  as  select  e.ename,e.sal,d.deptno,d.dname  from  emp  e,dept  d where e.deptno=d.deptno   Here view v1 is create using the join of two table named emp and dept so it can not allow any insert, update or delete operation so it is non updatable view.  

Ex.: create view v2 as select deptno,max(sal)"Max Sal" from emp group by deptno;   Here view v2 is created by using group by clause so it  is not updatable. Here Alias for max(sal) is necessary otherwise error will be generate.  

Dropping View :   Both updatable or non updatable views can be dropped by Drop View <viewname> command. Ex : Drop view employee;  

Views that are created in memory are stored in table named user_views. If we want to see the details of view we can fire desc or select command on user_views system table. 

Page 28: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q-1 Introduction to PL/SQL. And Advantage of PL/SQL .

Using SQL statements we can retrieve or manipulate data present in a table. Using SQL statements alone it is not possible to gain the power of procedural language constructs. This aspect has been taken care of by PL/SQL, which is a procedural extension to SQL.

A PL/SQL block can have DML and TCL statements. A PL/SQL block can also contain any number of SQL statements integrated with flow of control statements. Using PL/SQL we can also trap runtime errors.

Advantages of PL/SQL SSSuuu ppppppooorrr ttt fff ooo rrr SSSQQQLLL PL/SQL allows us to use all SQL data manipulation commands, transaction control commands. SQL functions(except group functions), operators and pseudo columns , thus allowing us to manipulate data values in a table more flexibly and effectively. HHHiii ggghhheeerrr PPPrrr oooddduuuccc ttt iii vvv iii ttt yyy PL/SQL can be used to include procedural constructs in non-procedural tools like SQL*Forms and Oracle Forms 4.5 to build applications. For ex. We can use the entire PL/SQL block in an SQL*Forms trigger. Further, PL/SQL remains the same in all environments. BBBeeettt ttt eeerrr PPPeeerrr fffooo rrr mmmaaannn ccceee Without PL/SQL, Oracle must process SQL statements one at a time. With PL/SQL, an entire block of statements can be processed in a single command line statement. This reduces the time taken to communicate between the application and the Oracle Server. Thus it helps in improving performance. PPPooo rrr ttt aaabbb iii lll iii ttt yyy Applications written in PL/SQL are portable to any operating system or platform on which Oracle Ver 6.0 or 7.0 runs. IIInnn ttt eeegggrrr aaattt iii ooonnn www iii ttt hhh OOOrrraaaccc lll eee Both PL/SQL and Oracle have their foundations in SQL. PL/SQL supports all the SQL data types and it integrates PL/SQL with the Oracle data dictionary.

Page 29: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q-2 Explain PL/SQL Block with Example.

PL/SQL(Procedural Language/SQL) is a procedural extension of Oracle-

SQL that others language constructs similar to those in imperative programming languages. PL/SQL allows users and designers to develop complex database applications that require the usage of control structures and procedural elements such as procedures, functions, and modules.

The basic construct in PL/SQL is a block. Blocks allow designers to

combine logically related(SQL) statements into units. In a block, constants and variables can be declared, and variables can be used to store query results. Statements in a PL/SQL block include SQL statements, control structures(loops), condition statements(if-then-else), exception handling, and calls of other PL/SQL blocks.

PL/SQL is a block-structured language, meaning that PL/SQL programs are

divided and written in logical blocks of code. Within a PL/SQL block of code, processes such as data manipulation or queries can occur. The following parts of a PL/SQL block are discussed in this section:

• The DECLARE section contains the definitions of variables and other objects such as constants and cursors. This section is an optional part of a PL/SQL block.

• The PROCEDURE section contains conditional commands and SQL statements and is where the block is controlled. This section is the only mandatory part of a PL/SQL block.

• The EXCEPTION section tells the PL/SQL block how to handle specified errors and user-defined exceptions. This section is an optional part of a PL/SQL block.

[ NOTE: A block is a logical unit of PL/SQL code, containing at the least a PROCEDURE section and optionally the DECLARE and EXCEPTION sections.] Here is the basic structure of a PL/SQL block:

A PL/SQL block can be divided into three parts, namely, a declarative part, an executable part and an exception handling part. DECLARE -- optional, denotes beginning of block <Declarations> BEGIN -- mandatory, denotes beginning of procedure section <St. Block> EXCEPTION -- optional, denotes beginning of exception section <Error Handling> END; -- optional, denotes ending of block

Page 30: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Objects can be declared in the declarative part, which can be used in the

executable part for further manipulations. All procedural statements are included in between the BEGIN and END statements. Errors that occur during execution are default in the exception handling part.

Notice that the only mandatory parts of a PL/SQL block are the second

BEGIN and the first END, which make up the PROCEDURE section. Of course, you will have statements in between. Demonstrate PL/SQL Block : Declare A number; B number; Sum number; Begin A:=&A; A:=&B;

SUM:=A+B; Dbms_output.put_line(‘Sum of A and B is ‘ || SUM );

End;

Page 31: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q – 3 : WHAT IS CURSOR ? EXPLAIN IMPLICIT AND EXPLI CIT CURSOR WITH ALL ITS ATTRIBUTES . ANS :- � The oracle engine uses a work area for its internal processing in order to execute

an SQL statement. This work area is private to SQL’s operating and is called a cursor.

� The data is stored in the cursor is called the active data set. Conceptually, the size of

the cursor in memory in the size required to hold the number of rows in the active

data set. The actual size, however, is determined by the oracle engine’s built in

memory management capabilities and the amount of RAM available. Oracle has a

pre-defined area in main memory set aside. Within which cursors are opened. Hence

the cursor’s size will be limited by the size of this pre-defined area.

� The values retrieved from a table are held in a cursor opened in memory by the

oracle engine. This data is then transferred to the client machine via the network. In

order to hold this data, a cursor is opened at the client end. If the number of row

returned by the oracle engine is more than the available in the cursor opened on the

client, the cursor data and the retrieved data is swapped between the operating

system’s swap area and RAM.

EXAMPLE:- When a user fire a select statement as:

SELECT EMP_NO, FNAME, DEPT FROM EMP_MSTR WHERE BRANCH_NO=’B1’;

The resultant data set in the cursor opened at the server end is display on

screen.

When a cursor is loaded with multiple row via a query the oracle engine opens

and maintained a row pointer. Depending on user’s request to view data the row

pointer will be relocated within the cursor’s active data set. Additionally oracle also

maintains multiple cursor variable. The values held in these variables indicate the status

of the processing being done by the cursor.

Types of Cursor:

Cursor are classified depending on the circumstances under which they are

opened. If the oracle engine opened a cursor for its internal processing it is known as an

implicit cursor. A cursor can also be opened for processing data thought a PL/SQL block,

on demand. Such a user-defined cursor is known as an explicit cursor.

Attributes of Cursor :-

When the oracles engine creates an implicit or explicit cursor, cursor control

variables are also created to control the execution of the cursor. These are a set system

variable, which keep track of the current status of a cursor. These cursor variables can

be accessed and used in a PL/SQL code blocks.

Page 32: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

1. % is Open :- This attributes returns true if the cursor is opened successfully

otherwise it

return false value.

2. % Found :- This attributes return true if the record was found successfully

otherwise it

return false.

3. % not Found : It is the totally opposite of % found attribute. It return true if the

record was

not found successfully, otherwise it return false.

4. % Row count:This attribute return the number of rows which are effected by the

process of cursor.

Implicit cursor:- The oracle engine implicit opens a cursor on the server to process each SQL

statement. Since the implicit cursor is opened and managed by the oracle engine

internally, the function of reserving an area in memory, population this area with

appropriate data, processing the data in the memory area, releasing the memory area

when the processing is complete is taken care of by the oracle engine. The resultant

data is then passed to the client machine via the network . a cursor is then opened in

memory on the client machine to hold the row returned by the oracle engine. The

number of row held in the cursor on the client is managed by the client operating

system and it’s swap area.

Implicit cursor attributes can be used to access information about the status of

the last insert, update, delete or single –row select statement. This can be done by

preceding the implicit cursor attributes with the cursor name (i.e. SQL). The value of the

cursor attributes always refer to the most recently executed SQL statement, where the

statement appears. If an attribute value is to be saved for later use, it must be assigned

to a (Boolean) memory variable.

Explicit cursor:- The explicit cursor has all the four attributes which apply to implicit cursor.

Unlike implicit cursor the explicit cursor must be declared. The syntax for declaring

cursor is as follow :

When we want to work with a explicit cursor we must have to perform following

steps:

Cursor Control Commands

� Declaraction of Cursor

� Opening Cursor

� Fetching Data from cursor

� Closing a Cursor

Declaration of Cursor :- Cursor can be declared by using following Syntax. Cursor is declared in only

declaration section of PL/SQL :

Page 33: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Syntax :- cursor <cursor_name> is <select Statement> ;

Example :- cursor c1 is select * from student;

Opening of Cursor :- Cursor can be opened only in begin section of PL/SQL. Syntax to opening cursor

is as follow :

Syntax :- open <cursor_name>;

Example :- open c1 ;

Fetching Data from Cursor :- If a Cursor is defined successfully and opened properly the next step is to fetch

data from cursor. To store the Data fetched from cursor we need cursor type variable.

Syntax to fetch data from the cursor is as follow :

Syntax :- Fetch <cursor_name> into <variables>\<cursor type variable>;

Example :- fetch c1 into rno,nm,m1,m2,m3,tot,per;

Here rno,nm,m1,m2,m3,tot,per are local memory variable which stores the

value of first record of cursor which is open in memory. If we have declared % rowtype

variable we can fetch data to that variable by following method.

Example :- fetch c1 into rec;

If we have fetched data from cursor to a rowtype variable we can access the

value by following method:

Example :- dbms_output.put_line(‘rno is ‘ || rec.rno);

Closing of Cursor :- Cursor which is open for any purpose, is to be closed by following method.

Syntax :- close <cursor_name>;

Example :- close c1 ;

Example To demonstrate the Cursor :-

declare

cursor mycur is

select * from emp;

begin

for rec in mycur

loop

exit when mycur%notfound;

dbms_output.put_line(rec.ename || ' is working in ' || rec.deptno);

end loop;

end;

Page 34: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q – 4 : What is Trigger ? Explain DML trigger with Example. Ans :-

Database triggers are database objects created via the sql* plus toll on the client

and stored on the server in the oracle engine’s system table. This database objects

consist of the following distinct sections :

• A named database event.

• A PL/SQL block that will executed when the event occurs.

The occurrences of the database event is strongly bound to table data being changed.

The oracle engine allows the definition of procedures that are immediately

executed (i.e. executed by the oracle engine itself), when an insert, update or delete

statement is fired on any particular table. These procedures are called Database

Triggers. The major issues that make these triggers standalone are that, they are fired

implicitly (i.e. internally) by the oracle engine itself and not explicitly i.e. called by the

user.

Types of Triggers

A trigger’s type is defined by the type of triggering transactions and by the level

at which the trigger is executed. In the following sections, you will see descriptions of

these classifications, along with section.

Row-Level Triggers

Row-level triggers execute once for each row in a transaction, For the LEDGER

table auditing example described earlier, each row that is the LEDGER table may be

processed by the trigger. Row-level triggers are the most common type of trigger; they

are often used in data auditing applications. Row-level triggers are also useful for

keeping distributed data in sync, Snapshots, which use row-level triggers for this

purpose, are described in Chapter 23.

Row-level triggers are created using the for each row clause in the create trigger

command. The syntax for triggers is shown in “Trigger Syntax”, later in this chapter.

Statement-Level Triggers

Statement-level triggers execute once for each transaction, For example, if a

single transaction inserted 500 rows into the LEDGER table, then a statement-level

trigger on that table would only be executed once , Statement-level triggers therefore

are not often used for data-related activities; they are normally used to enforce

additional security measures on the types of transactions that may be performed on a

table .

Page 35: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Statement-level triggers are the default type of trigger created via the create

trigger command. The syntax for triggers is shown in “ Trigger Syntax,” later in this

chapter.

BEFORE AND AFTER Trigger

Because triggers are executed by events, they may be set to occur immediately

before of after those events. Since the events that executed immediately can be

executed immediately before or after inserts, updates, and deletes. For database-level

events, additional restrictions apply; you cannot trigger an event to occur before a logon

or startup takes place.

Within the trigger , you can reference the old and new values involved in the

transaction. The access required for the old data may determine which type of trigger

you need. “Old” refers to the data as it existed prior to the transaction; updates and

deletes usually reference old values. “New” values are data the values that transaction

creates (such as the columns in an inserted record).

If you need to set a column value in an inserted row via your trigger, then you

need to use a BEFOR INSERT trigger to access the “new” values. Using an AFTER INSERT

trigger would not allow you to set the inserted value, since the row will already have

been inserted into the table.

AFTER row-level trigger are frequently used in auditing applications, since they

do not fire until the trigger row has been modified. The row’s successful modification

implies that it has passed the referential integrity constraints defined for that table.

Trigger Syntax

The full syntax for the create trigger command is shown in the alphabetical

Reference section of this book. The following listing contains an abbreviated version of

the command syntax:

create [or replace] trigger [user .] trigger

{ before | after | instead of}

{DML event [on table ]

| DDL event on [ SCHEMA | DATABASE]

| database event on [SCHEMA |DATEBASE]

for each {row |statement } [when(condition)]]

PL/SQL block

End;

Exmample :- create or replace trigger operation_emp before insert or update or delete on emp for each row begin if inserting then insert into back_emp values (sysdate,'inserting',user); elsif updating then

Page 36: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

insert into back_emp values (sysdate,'updatation',user); else insert into back_emp values (sysdate,'deleting',user); end if; end; /

Above example will store the operation type that is perform on table emp. Operation like update or delete or insert. If user perform any operation it(Trigger) will store the date of transaction date, the operation type and current user from which you are performing operation.

Page 37: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q-5 : What do you mean by the exception in oracle ? Explain in brief.

Ans:

In PL/SQL a warning or error condition is called an exception. Exceptions can be

internally defined (by the runtime system) or user-defined.

Examples of internally defined exceptions include division by zero and out of

memory. Some common internal exceptions have predefined names, such as

ZERO_DIVIDE and STORAGE_ERROR. The other internal exceptions can be given names.

You can define exceptions of your own in the declarative part of any PL/SQL

block, subprogram, or package. For example, you might define an exception named

insufficient_funds to flag an overdrawn bank accounts. Unlike internal exceptions, user-

defined exceptions must be given names.

When an error occurs, an exception is raised. That is, normal execution stops and

control transfers to the exception handling part of your PL/SQL block or subprogram.

Internal exceptions are raised implicitly (automatically) by the

runtime system. User-defined exceptions must be raised explicitly by RAISE statements,

which can also raise predefined exceptions.

To handle raised exceptions, you write separate routines called exception

handlers. After an exception handler runs, the current block stops executing and the

enclosing block resumes with the next statement. If there is no enclosing block, control

returns to the host environment.

Advantages of Exceptions

Using exceptions for error handling has several advantages. Without exception

handling, every time you issue a command, you must check for execution errors.

Exceptions also improve reliability. You need not worry about

Checking for an error at every point it might occur. Just add an exception handler

to your PL/SQL block. If the exception is ever raised in that block (or any sub-block), you

can be sure it will be handled.

Predefined Exceptions

An internal exception is raised explicitly whenever your PL/SQL program violates

an ORACLE rule or exceeds a system-dependent limit. Every ORACLE error has a number,

but exceptions must be handled by name. So, PL/SQL predefines some common ORACLE

errors as exceptions. For example, the predefined exception NO_DATA_FOUND is raised

if a SELECT INTO statement returns no rows.

PL/SQL declares predefined exceptions globally in package STANDARD, which

defines the PL/SQL environment. So,

Page 38: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

you need not declare them yourself. You can write handlers for predefined

exceptions using the names shown below:

Exception

NameORACLE Error

SQLCODE Value Details

CURSOR_ALREADY

OPEN ORA-06511 -6511

is raised if you try to OPEN an

already open cursor.

DUP_VAL_ON_INDEX

ORA-00001 -1

is raised if you try to store duplicate

values in a database column that is

constrained by a unique index.

INVALID_CURSOR

ORA-01001 -1001

is raised if you try an illegal cursor

operation. For example, if you try

to CLOSE an unopened cursor.

INVALID_NUMBER

ORA-01722 -1722

is raised in a SQL statement if the

conversion of a character string to a

number fails.

LOGIN_DENIED

ORA-01017 -1017

is raised if you try logging on to

ORACLE with an invalid

username/password.

NO_DATA_FOUND

ORA-01403 +100

is raised if a SELECT INTO statement

returns no rows or if you reference

an uninitialized row in a PL/SQL

table.

NOT_LOGGED_ON

ORA-01012 -1012

is raised if your PL/SQL program

issues a database call without being

logged on to ORACLE.

PROGRAM_ERROR ORA-06501 -6501

is raised if PL/SQL has an internal

problem.

STORAGE_ERROR ORA-06500 -6500

is raised if PL/SQL runs out of

memory or if memory is corrupted.

TIMEOUT_ON_RESOURC

E ORA-00051 -51

is raised if a timeout occurs while

ORACLE is waiting for a resource.

TOO_MANY_ROWS ORA-01422 -1422

is raised if a SELECT INTO statement

returns more than one row.

VALUE_ERROR

ORA-06502 -6502

is raised if an arithmetic,

onversion, truncation, or constraint

error occurs.

ZERO_DIVIDE ORA-01476 -1476

ZERO_DIVIDE is raised if you try to

divide a number by zero

User-defined Exceptions

Page 39: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

PL/SQL lets you define exceptions of your own. Unlike predefined exceptions,

user-defined exceptions must be declared and must be raised explicitly by RAISE

statements. Exceptions can be declared only in the declarative part of a PL/SQL block,

subprogram, or package. You declare an exception by introducing its name, followed by

the keyword EXCEPTION.

Raise_application_error:-

Using raise_application_error. A package named DBMS_STANDARD (part of the

Procedural Database Extention) provides language facilities that help your application

interact with ORACLE. This package includes a procedure named

raise_application_error, which lets you issue user-defined error messages from a stored

subprogram or database trigger. The calling syntax is

raise_application_error(error_number, error_message);

Example :

DECLARE

fdf EXCEPTION;

number_on_hand NUMBER(4);

BEGIN

IF number_on_hand < 1 THEN

RAISE out_of_stock;

END IF;

...

EXCEPTION

WHEN out_of_stock THEN

-- handle the error

END;

Example( Oracle Exception ) :

1.Declare no emp.empno%type; rno emp.empno%type; Begin no:=&no; select empno into rno from emp where empno=no; Exception when no_data_found then dbms_output.put_line('record not found'); End; 2. declare eno s.no%type; begin select no into eno from S where no=&n; exception when too_many_rows then

Page 40: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

dbms_output.put_line('record not found-1'); when no_data_found then dbms_output.put_line('record not found-2'); end; / Example( User Define Exception ) :

declare Invalid_Mark Exception; Invalid_Rollno Exception; no number(4); m1 number(4); m2 number(4); m3 number(4); tot number(4); per number(4); begin no := &no; m1 := &m1; m2 := &m2; m3 := &m3; if no < 0 then raise Invalid_Rollno; end if; if m1 < 0 or m1> 100 then raise Invalid_Mark; end if; if m2 < 0 or m2> 100 then raise Invalid_Mark; end if; if m3 < 0 or m3> 100 then raise Invalid_Mark; end if; tot := m1 + m2 + m3; per := tot/3; dbms_output.put_line('Total ' || tot); dbms_output.put_line('Per ' || per); exception when Invalid_mark then dbms_output.put_line('Your mark is Invalid'); when Invalid_rollno then dbms_output.put_line('Your no is Invalid'); end;

Page 41: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q-6.: What is function ? What is procedure ? Explain in brief. Differentiate the procedure and function. Ans:

A procedure or Function is a logically grouped set of SQL and PL/SQL statement

that perform a specific task. A stored procedure or function is a named PL/SQL blocks

that has been complied and stored in one of the oracle engine’s system tables.

To make a procedure or function dynamic either of them can be passed

parameter before execution. A procedure or function can then change the way it works

depending upon the parameter passed prior to its execution.

Procedure and Functions are made up of :

• A declarative Part

• An executive Part

• An Optional exception handling part

Declarative Part :

The declarative part may contain the declaration of cursor, constants, variables,

exceptions and subprograms. These objects local to the procedure of function. The

objects becomes invalid once the procedure of function exist.

Executable part :

The executable part is a PL/SQL block consisting of SQL And PL/SQL statement

that assign values, control execution and manipulation data. The action that the

procedure or function is expected to perform is coded here. The data that is to be

return back to the calling environment is also returned from here. The variables

declared are put to use within this block.

Exception Handling part :

This part contains code that deals with exceptions that may be raised during the

execution of code in the declarative part. An Oracle exception handler can be redirected

to the exception handling section of the procedure or function where the procedure or

function determines the actual action that must be carried out by the oracle’s exception

handler.

The flow of code execution from the Exception Handling part cannot be

transferred to the Executable part.

Point to Remember:

1. Procedure and Functions are stored in the Oracle database.

2. They can be invoked or called by any PL/SQL block that appears within an

application.

Page 42: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

3. Before a procedure of function is stored, the oracle engine parsed and complies

the procedure of function.

Syntax to Create a Procedure :

CREATE OR REPLACE PROCEDURE <Procedurename> (<Arguments> { IN / OUT / IN OUT}

<Datatype>…) { IS , AS }

<Variable> declarations;

<Constant> declarations;

Begin

<PL/SQL sub program body>;

Exception

<Exception PL/SQL block>;

End;

Example :- Create or replace procedure proc_oddeven(n in number) is m number(5);

Begin

M:=mod(n,2);

If m=0 then

dbms_output.put_line('even number');

Else

Dbms_output.put_line('odd number');

End if;

End;

/

To Execute Above procedure :

SQL> execute proc_oddeven(n);

Syntax to Create a FUNCTION :

Create or replace function<Functionname> (<Arguments> IN <Datatype>…)RETURN

<datatype> {IS , AS }

<Variable> declarations;

<Constant> declarations;

Begin

<PL/SQL sub program body>;

Exception

<Exception PL/SQL block>;

End;

/

Example :-

Create or replace function fact (no in number) return number is

N number(5);

Ans number(5);

Begin

Page 43: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

n:=no;

if n=1 then

return 1;

else

Return n*fact(n-1);

end if;

End;

/

To execute the above function:

SQL> Select fact(5)”Factorial” from dual;

Difference between Procedure and Function :

1. Function returns value while procedure does not return any value.

2. Function can be called directly from SQL statement while procedures are called

from a PL/SQL block.

3. In the syntax of Function we must have to specify the return type of function

while procedure is not returning any value so we does not have specify any

return type.

4. Procedure has only one type of parameter ‘IN’ While function has two type two

types of parameter name ‘ IN’ AND ‘OUT’.

Page 44: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q-7 : What is package ? Explain with example.

Ans:-

A package is an oracle object which hold (Contains) other object within it. The

object which are contain in package are :

• Function

• procedure

• Constant

• Cursor and

• Exception

Sql * plus tool is used for creating a package. A package can contain a sub

program that requires in input another PLSQL block. A package has usually two

components.

Specification:-

A package specification contains types of memory variable, exception and other

sub program. The package specification contains following things.

• Name of package

• Name of data type

• The local variable are also declared which are privet.

Package Body:-

The body of a package contains the definition of public object that are declared

in the speciation part. The Body can also contains other object declaration that are

privet to the package. The object that are declared privately in the package body are not

accessible to other objects outside the package. Unlike package specification package

body can contain subprogram bodies.

Creation of Package:-

The first step to creating a package is to create its specification. The specification

declares the objects that are contained in the body of the package. A package is created

using Oracle’s SQL * PLUS iterative tool. A package can include Functions and

procedures within the package. To create a specification, create package body

command is use.

Syntax to Create Package Specification :

Create package <package name> as

<Function name>return data type is ;

<procedure name>

End <package name>

After creating a package we must have to create package body.

Syntax To create Package body :

Create package body <package name> as

Page 45: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

<function name( )><procedures name( )> IS

Begin

--------------------------------

End ;

End <package name>;

Ex:- Create package mypack is

procedure printy(str in varchar2);

function findfact( n in number);

end pack;

create package body mypack as

procedure printy(msg varchar) is

begin

dbms_output.put_line('======================');

dbms_output.put_line(msg);

dbms_output.put_line('======================');

end;

function findfact( n number) return number is

no number(20);

f number(20);

begin

no := n;

f:=1;

while no > 0

loop

f := f*no;

no:=no-1;

end loop;

return f;

end;

end mypack;

/

Once a package is created successfully a message will be display a package has

been created while package body is created it will display a message package body has

been created then we can execute (call ) the function and procedure those are define

under package by using following method.

Syntax : EXECUTER <packagename>.<function/procedurename>

([<arguments>])

Ex: EXECUTER mypack.findfact(n);

Ex: EXECUTER mypack.printy(‘hello’);

Page 46: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle 

Prepared By, Rushabh P Madhu (92287 23322) 

 

Q‐18 Explain Oracle Instance in Brief. 

An Oracle instance: 

– Is a means to access an Oracle database 

– Always opens one and only one database 

Consists of: 

– Internal memory structures 

– Processes 

Memory Structure : The Oracle RDBMS creates and uses storage on the computer hard disk and in random

access memory (RAM). The portion in the computer s RAM is called memory structure. Oracle has two memory structures in the computer s RAM. The two structures are the Program Global Area (PGA) and the System Global Area (SGA).

The PGA contains data and control information for a single user process. The SGA is the memory segment that stores data that the user has retrieved from the database or data that the user wants to place into the database.

The basic memory structures associated with an Oracle instance include the following:

• System Global Area (SGA): Shared by all server and background processes

• Program Global Area (PGA): Private to each server and background process. There is one PGA for each process.

• The SGA is a memory area that contains data and control information for the instance.

• The SGA includes the following data structures:

1. Database buffer cache: Caches blocks of data retrieved from the database

2. Redo log buffer: Caches redo information (used for instance recovery) until it can be written to the physical redo log files stored on the disk

3. Shared pool: Caches various constructs that can be shared among users

4. Large pool: Is an optional area that provides large memory allocations for certain large processes, such as Oracle backup and recovery operations, and I/O server processes

5. Java pool: Is used for all session-specific Java code and data within the Java Virtual Machine (JVM)

6. Streams pool: Is used by Oracle Streams When you start the instance by using Enterprise Manager or SQL*Plus, the amount of memory allocated for the SGA is displayed.

7. A Program Global Area (PGA) is a memory region that contains data and control information for each server process. An Oracle server process services a client’s requests. Each server process has its own private PGA that is created when the server process is started. Access to the PGA is exclusive to that server process, and the PGA is read and written only by the Oracle code acting on its behalf. With the dynamic SGA

Page 47: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle 

Prepared By, Rushabh P Madhu (92287 23322) 

 

infrastructure, the size of the database buffer cache, the shared pool, the large pool, the Java pool, and the Streams pool changes without shutting down the instance. The Oracle database uses initialization parameters to create and configure memory structures. For example, the SGA_TARGET parameter specifies the total amount of space available to the SGA. If you set SGA_TARGET to 0, Automatic Shared Memory Management is disabled. 

Processes 

The processes in an Oracle system can be categorized into two major groups: • User processes run the application or Oracle tool code. • Oracle processes run the Oracle server code. They include server processes and

background processes. To maximize performance and accommodate many users, a multiprocess Oracle system uses some additional Oracle processes called background processes. An Oracle instance can have many background processes; not all are always present. The background processes in an Oracle instance include the following: • Database Writer (DBW0 or DBWn) • Log Writer (LGWR) • Checkpoint (CKPT) • System Monitor (SMON) • Process Monitor (PMON) • Archiver (ARCn) • Recoverer (RECO) • Lock Manager Server (LMS) - Real Application Clusters only • Queue Monitor (QMNn) • Dispatcher (Dnnn) • Server (Snnn) On many operating systems, background processes are created automatically when an instance is started.

Page 48: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle 

Prepared By, Rushabh P Madhu (92287 23322) 

 

 

Page 49: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle 

Prepared By, Rushabh P Madhu (92287 23322) 

 

Q- 10. Memory Structure Of Oracle .

Ans.:

The Oracle RDBMS creates and uses storage on the computer hard disk and in random access memory (RAM). The portion in the computer s RAM is called memory structure. Oracle has two memory structures in the computer s RAM. The two structures are the Program Global Area (PGA) and the System Global Area (SGA). The PGA contains data and control information for a single user process. The SGA is the memory segment that stores data that the user has retrieved from the database or data that the user wants to place into the database.

The basic memory structures associated with an Oracle instance include the following:

• System Global Area (SGA): Shared by all server and background processes

• Program Global Area (PGA): Private to each server and background process. There is one PGA for each process.

• The SGA is a memory area that contains data and control information for the instance.

• The SGA includes the following data structures:

1. Database buffer cache: Caches blocks of data retrieved from the database

2. Redo log buffer: Caches redo information (used for instance recovery) until it can be written to the physical redo log files stored on the disk

3. Shared pool: Caches various constructs that can be shared among users

4. Large pool: Is an optional area that provides large memory allocations for certain large processes, such as Oracle backup and recovery operations, and I/O server processes

5. Java pool: Is used for all session-specific Java code and data within the Java Virtual Machine (JVM)

6. Streams pool: Is used by Oracle Streams When you start the instance by using Enterprise Manager or SQL*Plus, the amount of memory allocated for the SGA is displayed.

Page 50: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle 

Prepared By, Rushabh P Madhu (92287 23322) 

 

7. A Program Global Area (PGA) is a memory region that contains data and control information for each server process. An Oracle server process services a client’s requests. Each server process has its own private PGA that is created when the server process is started. Access to the PGA is exclusive to that server process, and the PGA is read and written only by the Oracle code acting on its behalf. With the dynamic SGA infrastructure, the size of the database buffer cache, the shared pool, the large pool, the Java pool, and the Streams pool changes without shutting down the instance. The Oracle database uses initialization parameters to create and configure memory structures. For example, the SGA_TARGET parameter specifies the total amount of space available to the SGA. If you set SGA_TARGET to 0, Automatic Shared Memory Management is disabled. 

Page 51: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

Q- 13 Explain the Background Processes of Oracle.

All connected Oracle users must run two modules of code to access an Oracle database

instance.

A process is a "thread of control" or a mechanism in an operating system that can run a

series of steps. (Some operating systems use the terms job or task.) A process normally has its own

private memory area in which it runs.

Types of Processes The processes in an Oracle system can be categorized into two major groups:

• User processes run the application or Oracle tool code.

• Oracle processes run the Oracle server code. They include server processes and background processes.

To maximize performance and accommodate many users, a multiprocess Oracle system uses some additional Oracle processes called background processes.

An Oracle instance can have many background processes; not all are always present. The background processes in an Oracle instance include the following:

• Database Writer (DBW0 or DBWn)

• Log Writer (LGWR)

• Checkpoint (CKPT)

• System Monitor (SMON)

• Process Monitor (PMON)

• Archiver (ARCn)

• Recoverer (RECO)

• Lock Manager Server (LMS) - Real Application Clusters only

• Queue Monitor (QMNn)

• Dispatcher (Dnnn)

• Server (Snnn) On many operating systems, background processes are created automatically when an instance is started.

1. DBWR (Database Writer)

� write all dirty buffers to datafiles

� Use a LRU algorithm to keep most recently used blocks in memory

� Defers write for I/O optimization

� dirty list reaches a threshold length

� A process scnas a specifed number of buffer in the LRU without finding free buffer

� A time-out occurs

� DBWR checkpoint occurs

2. LGWR (Log Writer)

� writes redo log entries to disk

� Commit occurs

� The redo log buffers pool becomes one-third full

� DBWR completes cleaning the buffer blocks at a checkpoint

� LGWR time-out

Page 52: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle

Prepared By, Rushabh P Madhu (92287 23322)

� - A commit confirmation is not issued until the tx has been recorded in the redolog file

3. PMON (Process Monitor)

� Cleans up abnormally terminated connection

� Rolls back uncommited transactions

� Releases locks held by a terminated process

� Frees SGA resources allocated to the failed processes

� Database maintenance

4. SMON (System Monitor)

� Performs automatic instance recovery

� Reclaims space used by temporary segments no longer in use

� Merges contiguous area of free space in the datafile

5. CKPT (Check Point)

� is enabled by setting the parameter CHECKPOINT_PROCESS=TRUE

� If enabled, take over LGWR’s task of updating files at a checkpoint

� Updates header of datafiles and control files at the end of checkpoint

� More frequent checkpoint reduce recovery time from instance failure

� CKPT improve the performance of database with many database files

6. ARCH (Archiver)

� Copies redo log files to tape or disk for media failure

� Operates only when a log switch occurs

� Is optional and is only needed when in ARCHIVELOG mode

� May write to a tape drive or to a disk

7. LCKn (Lock), Dnnn (Dispatcher), Snnn (Server),

RECO (Recover), Pnnn(Parallel), SNPn(Job Queue),

QMNn(Queue Monitor)

� User Processes

- A user process is used when a user runs an application program

- Runs the tool/application and is considered the client

- Passes SQL to the server process and receives the results

� Server Processes

- A server process must place the data in the database buffer cache

- Parce and execute SQL statements

- Read data blocks from disk into the shred database buffers of the SGA

- Return the results of SQL statements to the user process

• Parse : check syntax, security access, object resolution, optimization

• Execute : applies the parse tree to the data, perform a physical read and change

• Fetch : Passes data to the user (only SELECT).

Page 53: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

O­2 Write the differences              [ 5  Marks] 1. Difference Between  DBMS v/s RDBMS 

DBMS  RDBMS 1  DBMS stands for Database 

management System. 1.  RDBMS stands for Relational Database 

Management System. 2  The Concept of Relationship between 

two is missing in DBMS. 2.  RDBMS is based on the concept of 

Relationship. 3  DBMS does not support Client/Server 

Architecture. 3.  Most of the RDBMS supports the 

Client/Server Architecture. 4.  DBMS does not provide any type of 

security of Data. 4.  RDBMS provides multilevel of security 

1. Login Level. 2. Command Level. 3.Object Level 

5  DBMS use the concept of file.  5  RDBMS uses the concept of Table. 6.  DBMS may satisfy less than 7 or 8 

rules of Dr.E.F.Codd 6.  RDBMS satisfy more than 7 or 8 rules of 

Dr.E.F.Codd. 7.  DBMS does not support Distributed 

databases. 7.  Most of the RDBMS supports Distributed 

databases. 2. Difference Between  SQL v/s SQL * Plus 

SQL  SQL * PLUS 1  SQL stands for Structured Query 

Language. It is a data sub language or RDBMS. 

1.  SQL * Plus recognizes SQL statements and sends them to the server.  

2  SQL manipulate data and table definition in the database. 

2.  SQL * Plus does not allow manipulation of values in the database. 

3  SQL is entered into the SQL buffer on one or more lines. 

3.  SQL * Plus is entered one line at a time, not stored in the SQL buffer. 

4.  SQL uses a termination character to execute command immediately. 

4.  SQL * PLUS does not require termination character to executes commands immediately. 

5  SQL uses functions to perform some formatting. 

5  SQL * plus uses command to perform some formatting. 

6  

SQL does not have a continues character. 

6  SQL * plus uses dash ( ‐ ) as a continues character if the command is longer than one line. 

    

Page 54: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

3. Char v/s Varchar2 CHAR  VARCHAR 1) CHAR is a fixed length character data   type.  1) VARCHAR is a variable length 

character data type. 2) Char data type will store blank spaces it the data is less than specified length. 

2) Varchar2 will not store any blank spaces if the data is less than specified length. 

3) A char data type, when stored in a database table, always uses the maximum length and is blank padded 

3) A varchar2 data type, when stored in a database table, uses only the space allocated to it. 

4) Char data type can store up to 255 character.  4) varchar2 data type can store 4000 characters. 

4) Implicit Cursor and Explicit Cursor : Implicit Cursor  Explicit Cursor 1  Implicit cursor is that which opens 

when any DML Operation perform on table. 

1.  Explicit cursor it that which is totally handled by the programmer to perform a specific task. 

2  Implicit cursors are open automatically and it also close automatically. 

2.  Explicit cursor is handled by programmer so it is opened and closed by the programmer itself. 

3  Implicit cursors are open automatically by Oracle engine for its internal process. 

3.  Explicit cursors can be opened by for processing data through a PL/SQL Block. 

4.  Implicit cursor not  is known as user define cursor because user can not open ,close the implicit cursor or user can not see when implicit cursor is opened in memory. 

4.  Explicit cursor is known as user define cursor. Because user can see when cursor is open in memory as it is open by the user. 

5) CONSTRAINT and TRIGGER: CONSTRAINT  TRIGGER 1) Constraints are used to maintain the integrity and atomicity of database .in other words it can be said they are used to prevent invalid data entry . The main 5 constraints are   NOT NULL,PRIMARY KEY,FOREIGN KEY,UNIQUE KEY and CHECK  

1) Triggers are bascically stored procedures which automaticallly fired when any insert,update or delete is issued on table 

2) Constraint effected all row of table.  2) Trigger effected only those row after which trigger applied. 

3) Constraints is set when the application is customized so that there are restrictions to the data entered, so that the data is authentic. 

3) They start a chain reaction‐ for instance each delete, update action etc. Can trigger off another function 

6) GROUP BY and ORDER BY 

Page 55: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

GROUP BY  ORDER BY 1) GROUP BY is a way to sub‐total your results, or perform some    other "aggregate" function on them. 

1) ORDER BY is simply a way to sort your results ‐ it does not affect what shows up in your result set, only what order it is displayed. 

2) SELECT department, sum (salary) FROM tablemployee GROUP BY department    will give you salary totals by department, whereas the sum statement by itself would just give               you the grand total of all salaries in tablemployee. 

2) SELECT * FROM tablemployee ORDER BY last name will give you all tablemployee data, in order of last name.  If you want the results in descending (reversed) order, simply add DESC to the end of the clause: ORDER BY last name DESC; 

3) Group by controls the presentation of the rows. 

3) Order by controls the presentation of the columns for the results of the SELECT statement. 

4) Group By forms Groups (of course), but this means it also SORTS; but it will also retrieve a    DISTINCT RECORD SET. 

4) ORDER BY Sorts by the columns included in the Statement, and does not retrieve DISTINCT Records. 

7) FUNCTION and PROCEDURE FUNCTION  PROCEDURE 1) Function return a value  1) Procedures don’t return a value. 2) Function return type could be scalar or table. 

2) Stored procedure returns always integer value by default zero. 

3) Function is not pre compiled execution plan. 

3) Stored procedure is pre compiled execution plan. 

4) Function returns only value at a time  4) Stored procedure returns more than one value at time. 

5) Function are used for computations  5) Procedures can be used for performing business logic. 

6) A function can used in DML  6) Procedure cannot be invoked from DML. 7) We cannot use Transaction Control Language in Function. 

7) We can use TCL in Procedure.  

8) We cannot use DDL in function.  

8)  It is possible using dynamic SQL package. 

    

Page 56: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

O­3 Write the Short Notes of Following :           [ 5  Marks] 1. Date Functions :­ • Date is one of the famous Data type of oracle which is use to store date and time in oracle. • The Data Date type has special properties associated with it. It stores information about 

century, year, month, day, hour, minute and second. • The value in the column of a DATE is always stored in specific default format . This default 

format is 'DD‐MON‐YY HH:MI A.M.'. Hence, when a date has to be inserted to be in a date field. Its value has to be specified  in the same format. 

• If DATA from a date column has to be viewed in any other format other than default format oracle provides function which are known as a Date related function which are following. 

1. TO_DATE(CHAR,[,FORMAT]) 2. ADD_MONTHS(DATE,N) 3. LAST_DAY(DATE) 4. MONTHS_BETWEEN(DATE1,DATE2) 5. NEXT_DAY(DATE,CHAR) 6. ROUND(DATE, [FORMAT]) 

Sysdate : Sys date is a preserve keyword of oracle  which is use to store current date in Oracle.  

1. TO_DATE(CHAR,[,FORMAT]) To date function is use to store string date value to date type format. Here in syntax char 

is a string which a string type date and optional format clause is use to retrieve or store date in some specific format. Ex.:(To insert a new Record in Emp table or Oracle having Store Some Date Potion.)  insert into emp values (1234,'rushabh','ANALYST',1200,TO_DATE('11­DEC­90 10:10 A.M.','DD­MON­YY HH:MI A.M.'),5000,0,20);  

 

Format MM  Month Code ( 1 to 12)RM  Roman Month Code (I to XII)Mon  Name of Month in Three 

char. Such as (JAN, Feb, JUN, DEC) 

Month  Full Month Name (January)D  DAY Of Week ( 1 to 7)DY  Day Name( SUN,MON,SAT)DAY  Full day name(SUNDAY)DD  Day in Month ( 1 to 31)DDD  Day in Year (0 to 365)

FormatYYYY  Year in Four Digit (2009)YY  Year in Two Digit YEAR  Year in words 

MI  Minute (1 to 12) SS  Second of Minute AM  After Morning PM  PAST MORNING TH   SuffixSP  SpellOut 

 

 2. ADD_MONTHS(<DATE>,<N>) 

  This date Function is use to add Specified N month into specified Date. It will return Date value after add specified N month to specified date. Ex.: Select add_months(’01‐jan‐2009’,2) from dual; Output of above example will be ‘01‐MAR‐09’.  

3. LAST_DAY(<DATE>) 

Page 57: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

  This date Function is use to GET the last date of specified date’s month. It will return Date value and the return date is the last date of month.  Ex.: Select Last_day(’01‐jan‐2009’) from dual; Output of above example will be ‘31‐JAN‐09’.  

4. MONTHS_BETWEEN(<DATE 1 >,<DATE 2>)   This date Function is use to Find the difference between two date. This function will takes two arguments in the form of Date value. It find the difference from date1 to date2. It will return Integer value that that represent number of months between two date. Ex.: SELECT MONTHS_BETWEEN('02‐FEB‐09', '02‐JAN‐09') FROM DUAL Output of above example will be 1.  

5. NEXT_DAY(<DATE>,<CHAR>)   This date Function is use to Find the NEXT DATE which has specified day as specified as argument. Here CHAR argument is name of day. This function will return Date value.  Ex.: SELECT NEXT_DAY('13‐AUG‐09','SUNDAY') FROM DUAL; Output of above example will be 16‐AUG‐09 Because ’13‐aug‐09’ is Thursday and next Sunday is on 16‐AUG‐09. 

6. ROUND(<DATE>[,<FORMAT>])   This date Function is Returns a date rounded to a specified unit of measure. If the second parameter is omitted the round function will round the date to nearest day. This function will return Date value.  Ex.: SELECT ROUND(SYSDATE,'YY') FROM DUAL ; Output of above example will be 01‐JAN‐10 Means 2010 Because Round function round the year 2009 to 2010.    

Page 58: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

2. SYNONYM : • A synonym is an alternative name for objects such as tables, views, sequences, stored 

procedures, and other database objects. • Synonyms allow underlying objects to be renamed or moved, where only the synonym needs to 

be redefined and applications based on the synonym continue to function without modification. 

• There are two types of Synonym : 1. Public Synonym  2. Private Synonym • You can create both public and private synonyms. A public synonym is owned by the special 

user group named PUBLIC and is accessible to every user in a database. A private synonym is contained in the schema of a specific user and available only to the user and to grantees for the underlying object. 

• Synonyms themselves are not securable. When you grant object privileges on a synonym, you are really granting privileges on the underlying object, and the synonym is acting only as an alias for the object in the GRANT statement. 

How to Create Synonyms: • To create a private synonym in your own schema, you must have the CREATE SYNONYM 

privilege. • To create a private synonym in another user's schema, you must have the CREATE ANY 

SYNONYM privilege. • SYNTAX :  CREATE OR REPLACE [PUBLIC / PRIVATE] SYNONYM <synonym_name> FOR 

<object_name> ; • To create a public synonym, you must have the CREATE PUBLIC SYNONYM system privilege. • Synonym can be created using the CREATE SYNONYM statement. The following statement 

creates a private synonym named private_emp on the emp table contained in the schema of scott. 

• CREATE SYNONYM private_emp FOR emp; • To create private synonym you does not require any privileges but if you want to create public 

synonym you must require system privileges of  public synonym creation. Following statement creates public synonyms of emp. 

• CREATE PUBLIC SYNONYM public_emp FOR emp; Using Synonyms in DML Statements  

• You can successfully use any private synonym contained in your schema or any public synonym, assuming that you have the necessary privileges to access the underlying object, either explicitly, from an enabled role, or from PUBLIC. You can also reference any private synonym contained in another schema if you have been granted the necessary object privileges for the underlying object.  

• You can reference another user's synonym using only the object privileges that you have been granted. For example, if you have only the SELECT privilege on the jward.emp table, and the synonym jward.employee is created for jward.emp, you can query the jward.employee synonym, but you cannot insert rows using the jward.employee synonym.  

• A synonym can be referenced in a DML statement the same way that the underlying object of the synonym can be referenced. For example, if a synonym named s_emp refers to a table(emp) or view, then the following statement is valid: insert into s_emp values (1112, 'jay', 'CLERK', 1540, SYSDATE, 5400, 0, 2000); If the synonym named fire_emp refers to a standalone procedure or package procedure, then you could execute it with the command 

Page 59: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

• EXECUTE Fire_emp(7344); Dropping Synonyms 

• You can drop any private synonym in your own schema. • To drop a private synonym in another user's schema, you must have the DROP ANY SYNONYM 

system privilege. To drop a public synonym, you must have the DROP PUBLIC SYNONYM system privilege. 

• Drop a synonym that is no longer required using DROP SYNONYM statement. To drop a private synonym, omit the PUBLIC keyword. To drop a public synonym, include the PUBLIC keyword. 

• For example, the following statement drops the private synonym named s_emp: • DROP SYNONYM s_emp; • The following statement drops the public synonym named public_emp: • Syntax is DROP PUBLIC SYNONYM <synonym_name> • DROP PUBLIC SYNONYM public_emp; • When you drop a synonym, its definition is removed from the data dictionary. All objects that 

reference a dropped synonym remain. However, they become invalid (not usable). Point to Remember:  

To view how many synonyms are created in your User you can user USER_SYNONYMS inbuilt object that stores the information about the synonyms which are created. DESC USER_SYSNONYMS SELECT * FROM USER_SYNONYMS ; SELECT synonym_name, table_owner, table_name FROM user_synonyms; CREATE OR REPLACE PUBLIC SYNONYM alltab FOR all_tables; DESC ALLTAB SELECT COUNT(*) FROM alltab;       

Page 60: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

3. Sequence : • A sequence is an object in Oracle that is used to generate a number sequence. This can be 

useful when you need to create a unique number to act as a primary key. • A sequence can generate numbers maximum of 38 digits. A sequence can be define to:  Generate numbers in ascending order or descending order  Provide interval between numbers  Caching of sequence number in memory ti speed up their availability. • A sequence is an independent object and can be used with any table that require its output. • The minimum information for generating numbers using a sequence is :  The starting value of Sequence from where the sequence will start  The maximum number that can be generated by a sequence  The increment value for generating the next number. This information is provided to Oracle at the time of sequence creation. Syntax :     CREATE SEQUENCE <SEQUENCE NAME>     [ INCREMENT BY <Integer value> 

START WITH <Integer value> MAXVALUE <Integer value>/ NOMAXVALUE MINVALUE <Integer value>/ NOMIN VALUE CYCLE  / NOCYCLE CACHE  <Integer value>/ NOCACHE ORDER / NOORDER  ] 

Sequence is always given a name so that it can be referenced later when required. INCREMENY BY : It specify the interval between sequence numbers. It can be any positive or negative value but not zero. If this clause is omitted, the default value is 1. MINVALUE :Specifies the sequence minimum value. NOMINVALUE : Specifies a minimum value of 1 for an ascending sequence. MAXVALUE : Specifies the maximum value that a sequence can generate. NOMAXVALUE : Specifies a maximum of 10^27 for an ascending sequence or ‐1 for a descending sequence. This is the default case. START WITH : It specifies the first sequence number to be generated. The default for an ascending sequence minimum value 1 and for a descending sequence it’s maximum value is ‐1. CYCLE : Specifies that the sequence continues to generate repeat values after reaching its maximum value. NOCYCLE : It specifies that sequence cannot generate more values after reaching the maximum value. CACHE : Specifies how many values of a sequence Oracle pre‐allocates and keeps in memory for faster access. The minimum value for the parameter is two. NOCAHCE : Specifies that values of a sequence are not pre‐allocated. ORDER : This gurantees that sequence number are generated in the order of request. This is only necessary if using Parallel server mode option. In exclusive mode option  a sequence always generate numbers in order. NOORDER : This does not gurantee sequence numbers are generated in order of request. This is only necessary if you are using Parallel Server in Parallel Mode option. If ORDER/ NOORDER clause is omitted a sequence takes the NOORDER clause by default.   

Page 61: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Ex.: CREATE SEQUENCE S1 START WITH 1 INCREMENT BY 1 MAXVALUE 1000 CYCLE;  Above example will create sequence named S1 which will start with 1 and go up to  1000 which is max length for sequence. Interval between two Sequence value will be 1 .  Referencing a Sequence :   Once a sequence is created SQL can be used to view the value held in its cache. To simply view the sequence following syntax is use.   SELECT <SEQUENCENAME>.NEXTVAL FROM DUAL ; 

Select s1.nextval from dual; This will display the next value held in the cache on the VDU. Every time nextval 

references a sequence its output is automatically incremented from old value to the  new value ready to use. To reference the current value of a sequence : SELECT <SEQUENCENAME>.CURRVAL FROM DUAL; Select s1.currval from dual; To use in INSERT statement: Insert into student values (s1.nextval,’raj’,’MCA’,’LIMBDI’,55.50); ALTERING SEQUENCE : ALTER  SEQUENCE <SEQUENCE NAME> 

[ INCREMENT BY <Integer value> START WITH <Integer value> MAXVALUE <Integer value>/ NOMAXVALUE MINVALUE <Integer value>/ NOMIN VALUE CYCLE  / NOCYCLE CACHE  <Integer value>/ NOCACHE ORDER / NOORDER  ] 

DROPING SEQUENCE: Sequence can be dropped by using drop command (DDL Command) or Oracle.Synatx is follow: DROP SEQUENCE <SEQUENCENAME> ; drop sequence s1;    

Page 62: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

4. Snapshot :­ • A snapshot is a recent photocopy of a table from database or in some cases, a subset of rows/column of a table. 

• The SQL statement that create and subsequently maintains a snapshot normally read data from a database residing on the server. 

• A snapshot is created on the destination system with the create snapshot SQL command. The remote table is immediately defined and populated from the master table. 

• In a distributed computing environment, the snapshots are defined considering the following reasons : 

• Response time improves when a local read only copy of table exists – this can be many time faster than reading data directly from a remote database. 

• Once a snapshot is built on a remote database, if the node containing the data from which the snapshot is built in not available, the snapshot can be used without the need to access the unavailable database. 

• The query that creates the snapshot closely resembles the code used to create a view. The secret to keep a snapshot up to date is the specification of it’s refresh interval. When defining a snapshot, The DBA specifies this interval, and oracle 8i from then on automatically manages the propagation of data from the tables upto which the snapshot is built. 

• Snapshot are used to dynamically replicate data between distributed databases. The master table will be updatable but snapshot can be either read‐only or updatable. Read‐only snapshots are the most common types of snapshots implemented.  There are two types of snapshots available. 

1. Simple snapshot 2. Complex snapshot 

 Simple Snapshot : 

• In a simple snapshot, each row is based on a single row in a single remote table.  • Simple snapshots are thus a subset of the snapshots that can be created. • Simple snapshot consist of either single table or a simple SELECT statement of rows from a 

single table.   Complex Snapshot : 

• A row in a complex snapshots may be based on more than one row in remote table, such as via a group by operation or on the result of a multi‐table join.  

• A complex snapshot consist of joined tables, views, or grouped and complex SELECT statements queries.  

• Snapshots with a subquery must be of the primary key type (see "Primary Key" for more information about primary key snapshots). Additionally, the defining query of a snapshot with a subquery is subject to several other restrictions to preserve the snapshot's fast refresh capability 

• Syntax to create snapshot is as follow : • CREATE SNAPSNOT <SNAPSHOTNAME> AS <SELECT STATEMENT> [FOR UPDATE] • As we discuss above you must have to remember the following point at the time of snapshot 

creation. • Snapshot can be create on a particular from the current user on which we are working. • To create Snapshot a target table on which we are going to create snapshot must consist a 

Page 63: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

primary key on single column. • Snapshot once created you can not insert value in newly created snapshot otherwise if you try 

to insert record in snapshot following error will be generated. Snapshot is a recent photocopy of your table so you can not perform any DML operation on snapshot. You are only allowed to view the content of snapshot.  

• Once a snapshot is created on any table then if you insert record on target table that newly inserted record is not available in snapshot because it is the photocopy of table. You can avoid that problem by make your snapshot up to date.  Following Transaction will clear your concept for snapsnot. SQL>connect scott/tiger SQL>create table student ( rno number(3) primary key, nm varchar2(15), per number(5,2)); Table created; SQL>insert into student values (1,’raj’,’55); SQL>insert into student values (2,’jay’,’65); SQL>insert into student values (3,’rajesh’,’50); SQL> connect system/manager SQL> create snapsnot mysnap_stud as select * from scott.student; Snapshot created; SQL>select * from mysnap_stud;  //here output will display all the records SQL> insert into mysnap_stud values (5,’hari’,’71); ORA‐01733: virtual column not allowed here SQL>delete from mysnap where name='jay'; ORA‐01752: cannot delete from view without exactly one key‐preserved table. SQL>Commit; 

From Here the concept of snapshot will be cleared you can also use subquery for the complex snapshot creation. 

Snapshot can also be altered by using ALTER SNAPSHOT command and Also drop snapshot by using DROP SNAPSHOT command. 

When a snapshot is dropped , it it has a snapshot log associated with, only the rows required for maintaining that snapshot are dropped. Dropping a master table upon which a snapshot is based does not drop the snapshot. Any Subsequent refreshes however, will fail.    

Page 64: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

5. Not Null Constraint:  • Business rules that are applied to data being stored in a table, are called Constraints. 

Constraints super controls the data being entered into a table for permanent storage. • Once a constraint is attached to a table column, any SQL INSERT or UPDATE statement 

automatically cause these constraints to be applied to data prior it is being inserted into the table column for storage. 

• Constraints are stored as a part of the global table definition by the oracle engine in its system  tables. 

• A Null value is different from a blank space or a Zero. A NULL value can be inserted into column of any data type. 

• Setting a NULL value is appropriate when the actual value is unknown, or when a value would not be meaningful. 

• If the column has a NULL value, oracle ignores any QNIQUE,FOREIGN KEY,CHECK constraints that may be attached to the column. 

• Oracle has changed its rule about empty string and null value in newer version of oracle. Now an empty string is treated as a null value in column. 

• By default, a table column can hold NULL values. • The NOT NULL constraint enforces a column to NOT accept NULL values. • The NOT NULL constraint enforces a field to always contain a value. This means that you 

cannot insert a new record, or update a record without adding a value to this field. • Not Null is a column Level Constraint which can be define at the column Level only. We can not 

define not null at table level as we use define other constraint at table level.  • In a single table we can use not null constraint more than one time there is no limitation on use 

of not null constraint. If a table consist of six column we can apply not null to all the column of table so there is no limitation on not null to use more than one time. 

• Syntax how to define Not null Constraint :  Create table <tablename> (   <Column1> <datatype> not null,   <Column1> <datatype>,[ not null]   <Column1> <datatype>  ); Create table student (   Rno integer unique,   Name varchar2(15) not null,   Class varchar2(15) not null,   City  varchar2(15) not null,   Per number(5,2) );  

• Here In above example we have define not null at column Level. Here we also define not null more than one time in table. So we can see that there is no limitation of using not null. 

• Now if you fire one of following two statement error will display as follow:  

Page 65: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

insert into student values (1,'Jay',NULL,'LIMBDI',5.75) ;  ERROR at line 1: ORA‐01400: cannot insert NULL into ("SCOTT"."STUDENT"."CLASS")  insert into student values (1,'Jay',’MCA’,'',5.75); ERROR at line 1: ORA‐01400: cannot insert NULL into ("SCOTT"."STUDENT"."CITY")  Not null constraint apply on particular column will be seen when we fired desc 

<tablename> command from SQL prompt. SQL> DESC STUDENT  Name                            Null?      Type  ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐  RNO                                          NUMBER(38)  NAME                            NOT NULL   VARCHAR2(15)  CLASS                            NOT NULL   VARCHAR2(15)  CITY                               NOT NULL   VARCHAR2(15)  PER                                         NUMBER(5,2) To view the constraint from user_constriants table we can fire following command. SQL> SELECT  CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME FROM 

USER_CONSTRAINTS WHERE TABLE_NAME='STUDENT’; CONSTRAINT_NAME       C     TABLE_NAME ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ SYS_C00812                     C     STUDENT SYS_C00813                     C    STUDENT SYS_C00814                     C     STUDENT  Here C is a constraint type and ‘C’ refers  the Check constraints but not null is considered at 

C in USER_CONSTRAINTS table.    

Page 66: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

6. Primary Key : A constrain is a mechanism in a relation database that some rules on data inserted into a column of table. Constrain are used to ensure accuracy and consistency of data in a database. Data integrity is this assurance of accurate and consistent data in a database. To establish a “parent‐child” or “Master – Slave” relationship between two table having common column , We may use of referential integrity constraint. This is an example of one to many relationship. To implement this we should define a column in the current table as a primary key and the same column in the child table as  a foreign key referring to the corresponding parent entry. 

• A primary key is a one or more column in a table used to uniquely identify each row in the table. 

• It can be defined either in the CREATE or ALTER table statement • A table can have only one primary key. • It defines the column as the mandatory column because NOT NULL attribute is active. • The data held across the column must be UNIQUE. • The single column primary key is called simple key. • A Primary Key can be apply only one time in a table. We can not define two primary key in a 

single table. We can define composite primary key instead. • Primary key can be define at Column Level as well as Table Level. • One table can combine up to 16 columns in a Composite Primary Key. • Primary key is a combination of Unique and Not null Constraints. 

 Features of primary key: 

• Its main purpose is the record uniqueness. • It will not allow duplicate values. • It will not allow null values. • Primary key is not compulsory but it is recommended. • It cannot be LONG or LONG RAW data type. • Unique index is created automatically if there is primary key. 

 Primary Key at the Time of Table Creation :  Syntax: 

1) Primary key defined at column level: <Column name> <data type> (<size>) PRIMARY KEY Ex: 

Create table info (No number (3) primary key, name varchar (20), city varchar (20));  2) Primary key defined at table level: PRIMARY KEY (<column name>, <column name>)            Ex:  Create table product 

(pno number (3), pname varchar (20),  price number (3), primary key (pno, price));        

Primary Key After the table creation at the time of Table Alteration:  

Page 67: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

Syntax :­  ALTER TABLE <TABLENAME> ADD PRIMARY KEY(<COLUMN1>[,<COLUMN2>]); Example :‐  Alter table product add primary key (pno);    (Simple Primary Key) Example :‐  Alter table product add primary key (pno, price);   (Composite primary key)  One Primary Key applied on table we can also remove that primary key using following syntax.  Syntax :­  ALTER TABLE <TABLENAME> Drop  PRIMARY KEY; Example :‐  Alter table product drop primary key ;  When primary key is applied to a table it does not allow duplicate record or it does not accept null value on the column where primary key is define. It will display  one or the following error message when primary key constraint is violated. It does not display message that primary key constraint is violated.  ORA­00001: unique constraint (SCOTT.SYS_C00834) violated 

ORA­01400: cannot insert NULL into ("SCOTT"."PRODUCT"."PNO")  Primary constraint which is apply on table is stored in system table named USER_CONSTRAINTS. USER_CONSTRAINTS keep the details of constraint along with the column name and constraint type and owner  of table. Constraint type for Primary key is ‘P’. To view the table contains primary key or not you can fire following SELECT statement. CONSTRAINT_NAME                C     TABLE_NAME ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ SYS_C00835                           P     PRODUCT   

    

Page 68: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

7. DEFAULT VALUE :­ When you create a database table, you have the option to specify a DEFAULT value. 

Using default values on database columns helps to insulate database design issues from application code 

At the time of table creation a default value can be assigned to a column, When a record is loaded into the table and column is left empty, the oracle engine will automatically load this column with the default value specified. The data type  of the default value should match with the data type of the column. The DEFAULT clause can be used to specify a default value  for a column. Syntax :‐    <COLUMNAME> <DATATYPE>(<SIZE>) DEFAULT <VALUE> ; Example  :‐    Create table student 

(   Rno number(3),   Name varchar2(15),   City varchar2(15),   Class varchar2(15) default ‘MCA’,   Per number(5,2) ); 

 Once a table is created having specified DEFAULT Clause the ORACLE engine automatically takes default value in specified column if we does not enter any value in that specified column.   SQL> Insert into student (rno,name,city,per) values (11,’kishan’,’LIMBDI’,85); Here SQL  will automatically takes the default value in CLASS column as we  specify the default value ‘MCA’. Means that if we want to use default value we must have to specified the names of column in which we are going to insert value. If we not use column name at the time at record insertion an error will be generate.  SQL> Insert into student  values (12,’krunal’,’LIMBDI’,55); ORA‐00947: not enough values To override the default value we simply have to insert the record as we  insert record in simple table.  SQL>Insert into student values (12,'krunal','LIMBDI','BCA',55); In above example the default value is override and new specified value is stored in table. Here now if we fire SELECT statement output will be like this:  SQL>Select * from student;  RNO NAME            CITY            CLASS                 PER ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐   11 kishan          LIMBDI          MCA                    85   12 krunal          LIMBDI          BCA                    55  

Page 69: RDBMS Using Oracle :: Wel Come To ORACLE - Weeblyprajapatirajnikant.weebly.com/uploads/7/6/1/4/7614398/oracle.pdf · RDBMS Using Oracle Prepared By, Rushabh P Madhu (92287 23322)

RDBMS Using Oracle  

Prepared By, Rushabh P Madhu (92287 23322)  

 When we specify the default value for any particular column we must have to aware from following things:  The data type of default value and the data type of column name must match with each other. Character and date value must be specified in single quote. Default value can be applied to more than one time in a single table. Following example will demonstrate the default value for more than two column.  create table student ( rno number(4), nm varchar2(15), city varchar2(15) default 'LIMBDI', CLASS VARCHAR2(15) DEFAULT 'MCA', PER NUMBER(5,2) ) /