pl sql interview qns

Upload: satya1401

Post on 03-Apr-2018

233 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Pl SQL Interview Qns

    1/182

    1. How to implement ISNUMERIC function in SQL *Plus ?

    Method 1:

    Select length (translate (trim (column_name),' +-.0123456789',' ')) from dual ;

    Will give you a zero if it is a number or greater than zero if not numeric (actually givesthe count of non numeric characters)

    Method 2:

    select instr(translate('wwww','abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),'X')FROM dual;

    It returns 0 if it is a number, 1 if it is not.

    2. How to Select last N records from a Table?

    select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm)where a > ( select (max(rownum)-10) from clm)

    Here N = 10

    The following query has a Problem of performance in the execution of the following

    query where the table ter.ter_master have 22231 records. So the results are obtained afterhours.

    Cursor rem_master(brepno VARCHAR2) ISselect a.* from ter.ter_master awhere NOT a.repno in (select repno from ermast) and(brepno = 'ALL' or a.repno > brepno)Order by a.repno

    What are steps required tuning this query to improve its performance?

    ?Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO

    ?Be sure to get familiar with EXPLAIN PLAN. This can help you determine theexecution path that Oracle takes. If you are using Cost Based Optimizer mode, then besure that your statistics on TER_MASTER are up-to-date.?Also, you can change your SQL to:

    SELECT a.*

  • 7/29/2019 Pl SQL Interview Qns

    2/182

    FROM ter.ter_master aWHERE NOT EXISTS (SELECT b.repno FROM ermast bWHERE a.repno=b.repno) AND(a.brepno = 'ALL' or a.repno > a.brepno)ORDER BY a.repno;

    3. What is the difference between Truncate and Delete interms of Referential Integrity?

    DELETE removes one or more records in a table, checking referentialConstraints (to see if there are dependent child records) and firing anyDELETE triggers. In the order you are deleting (child first then parent)There will be no problems.

    TRUNCATE removes ALL records in a table. It does not execute any triggers.Also, it only checks for the existence (and status) of another foreign keyPointing to the table. If one exists and is enabled, then you will get

    The following error. This is true even if you do the child tables first.

    ORA-02266: unique/primary keys in table referenced by enabled foreign keys

    You should disable the foreign key constraints in the child tables beforeissuing the TRUNCATE command, then re-enable them afterwards.

    CLIENT/SERVER

    What does preemptive in preemptive multitasking mean ?

    Preemptive refers to the fact that each task is alloted fixed time slots and at the end of thattime slot the next task is started.

    What does the OLTP stands for ?

    OLTP stands for On Line Transaction Processing

    What is the most important requirement for OLTP ?

    OLTP requires real time response.

    In a client server environment, what would be the major work that the client deals with ?

    The client deals with the user interface part of the system.

    Why is the most of the processing done at the sever ?

    To reduce the network traffic and for application sharing and implementing businessrules.

  • 7/29/2019 Pl SQL Interview Qns

    3/182

    What does teh term upsizing refer to ?

    Applications that have outgrown their environment are re-engineered to run in a largerenvironment. This is upsizing.

    What does one do when one is rightsizing ?

    With rightsizing, one would move applications to the most appropriate server platforms.

    What does the term downsizing refer to ?

    A host based application is re-engineered to run in smaller or LAN based environment.

    What is event trigger ?

    An event trigger, a segment of code which is associated with each event and is fired whenthe event occurs.

    Why do stored procedures reduce network traffic ?

    When a stored procedure is called, only the procedure call is sent to the server and not thestatements that the procedure contains.

    What are the types of processes that a server runs ?

    Foreground process andBackground process.

    What is a event handler ?

    An event handler is a routine that is written to respond to a particular event.

    What is an integrity constraint ?

    An integrity constraint allows the definition of certain restrictions, at the table level, onthe data that is entered into a table.

    What are the various uses of database triggers ?

    Database triggers can be used to enforce business rules, to maintain derived values andperform value-based auditing.

    What is a transaction ?

    A transaction is a set of operations that begin when the first DML is issued and end when

  • 7/29/2019 Pl SQL Interview Qns

    4/182

    a commit or rollback is issued. BEGIN COMMIT/ROLLBACK are the boundries of atransaction.

    Why are the integrity constraints preferred to database triggers ?

    Because it is easier to define an integrity constraint than a database trigger.

    Why is it better to use an integrity constraint to validate data in a table than to use astored procedure ?

    Because an integrity constraint is automatically checked while data is inserted into atable. A stored has to be specifically invoked.

    What are the three components of a client server model ?

    A Client,

    A Server andA Network/Communication software.

    What are the advantages of client/server model ?

    Flexibility of the system, scalability, cost saving, centralised control and implementationof business rules, increase of developers productivity, portability, improved network andresource utilization.

    What are the disadvantages of the client/server model ?

    Heterogeneity of the system results in reduced reliablity. May not be suitable for allapplications. Managing and tuning networks becomes difficult.

    What are the different topologies available for network ?

    Star,Bus,Ring.

    What is the first work of Client process ?

    A client process at first establishes connection with the Server.

    What are the responsibilities of a Server ?

    1. Manage resources optimally across multiple clients.2. Controlling database access and security.3. Protecting the databse and recovering it from crashes.4. Enforcing integrity rules globally.

  • 7/29/2019 Pl SQL Interview Qns

    5/182

    In a Client/Server context, what does API (Application Programming Interface) refer to ?

    An API, in a Client/Server context, is a specification of a set of functions forcommunication between the client and the server.

    Give some examples of standard API??s ?

    Open Database Connectivity (ODBC),Integrated Database Application Programming Interface (IDAPI),XOpenSQL/CLI

    What is the main advantage of developing an application using an API ?

    The application can be connected to any back end server that is supported by the API.

    What is the main disadvantage of developing an application using an API ?

    The application cannot use any special features of the backend server.

    Why is an event driven program referred to a passive program ?

    Because an event driven program is always waiting for something to happen beforeprocessing.

    What are the four types of events ?

    1. System Events.2. Control Events3. User Events4. Other Events.

    What is the difference between file server and a database server ?

    A file server just transfers all the data requested by all its client and the client processesthe data while a database server runs the query and sends only the query output.

    What is inheritance ?

    Inheritance is a method by which properties and methods of an existing object areautomatically passed to any object derived from it.

    What are the two components of ODBC ?

    1. An ODBC manager/administrator and

  • 7/29/2019 Pl SQL Interview Qns

    6/182

    2. ODBC driver.

    What is the function of a ODBC manager ?

    The ODBC Manager manages all the data sources that exists in the system.

    What is the function of a ODBC Driver ?

    The ODBC Driver allows the developer to talk to the back end database.

    What description of a data source is required for ODBC ?

    The name of the DBMS, the location of the source and the database dependentinformation.

    How is a connection establised by ODBC ?

    ODBC uses the description of the datasource available in the ODBC.INI file to load therequired drivers to access that particular back end database.

    RDBMS FUNDAMENTALSI. INTRODUCING DATABASES :Concept of a Database :Traditional Approach : In this approach, independent application programs access theirown independent data files. This results in many problems in data storage and retrieval.Database Approach : In this approach, all application access a common database, whichis a centralized data storage system. This approach has the following advantages :Redundancy of data storage is reduced, Inconsistency in data is eliminated & Datasharing between applications is possible.Interacting with a Database :Database Management System (DBMS) : DBMS is a software that interfaces betweenapplications and a database for all data processing activities.Users of a DBMS : End Users, Application Programmers and Database Administratorsuse a DBMS, either directly or indirectly.How users interact with a Database :1. End users send queries to the DBMS through applications.2. The DBMS translates the queries.3. The DBMS retrieves data from the database.4. The DBMS sends data to the application, which present the data to the end users.Functions of a DBMS :Function of DBMS Description Provided by usingDefining the data structure Defining structure of data to be stored in database DataDefinition Language (DDL)Manipulating Data Retrieving, adding, modifying, deleting data. Data ManipulationLanguage (DML)Data Security Preventing unauthorized access to data. User-ids and Passwords.

  • 7/29/2019 Pl SQL Interview Qns

    7/182

    Control of Data Access Allowing users to use only relevant data Data Control Language(DCL)Architecture of a Database :Need for an Architecture : The details about complexity and structure of data in adatabase in not required by end-users. Therefore, differentiating what the end-users see

    and what is actually there in a database is important.Architecture of a Database : The architecture of a database comprises a set of three levelsat which a database can be viewed.External Level or View, Conceptual Level or View & Internal Level or View.II. USING RELATIONAL DATABASE :Basics of Relational Database :Relational Database Management System (RDBMS) : RDBMS is the most popular formof DBMS used in the world. It uses a relational database to organize data. A relationaldatabase comprise relations, which are represented as tables.Relation : A relation stores information about an object in the real world. A relation isrepresented as a table.

    Attribute : Each attribute of a relation stores a piece of information about an object.Attributes are represented as columns in a tables and can be arranged in any order. Eachattribute in a relation is unique and contain atomic values i.e. Atomic value contain asingle value of data and Non-Atomic values contain a set of values. The number ofattributes in a relation is called the degree of the relation.Tuple : A row in a table is called a tuple of the relation. The number of tuples in arelation is known as the cardinality of the relation. Tuples in a table are unique and can bearranged in any order.Domain : A domain is a set of valid atomic values that an attribute can take. Within asingle database, an attribute cannot have different domains associated with it. A domaincan include a null value, if the value for the domain is unknown or does not exist.Identifiers for Relations :Primary Key : An attribute that uniquely identifies a row in a table is called its primarykey. A relation can have only one primary key. The primary key cannot have any nullvalues. In case no unique key is found in a relation, two or more attributes can be treatedas the primary key. Such keys are called Composite Keys.Candidate Key : A relation can have more than one attribute that uniquely identifies atuple. Any one of these keys can be selected as the primary key. All such attributes arecalled Candidate Keys. All candidate keys that are not primary keys are called AlternateKeys.Foreign Key : An attribute that is not a candidate key is called a Nonkey. A nonkeyattribute of a relation whose value matches the primary key in some other table is calledForeign Key OR is a column in a table that uniquely identifies rows from a differenttable.III. INTERPRETING DATA :Entities and Relationships :Entity : An entity is an object that exists in the real world and is distinguishable fromother objects. Each entity is represented as a table in a relational database.Types of Entities : Entities can be classified in two ways - based on existence and basedon subsets.

  • 7/29/2019 Pl SQL Interview Qns

    8/182

    Based on existence, entities can be classified as Dominant and Weak entities.Based on subsets, entities can be classifies as Supertypes and Subtypes.Relationships : A relationship is an association between two entities.Types of Relationships : Relationships are classified into three types based on theoccurrence of the related entities.

    One-to-One(1-1), One-to-Many(1-M) & Many-to-Many(M-M).Using E/R Diagram : A E/R diagram represent entities and relationships in a databasesystem.Reducing E/R Diagrams to Relations :Mapping Entities : A dominant entity is mapped to a new relation. A weak entity ismapped to a new relation. The primary key of the corresponding dominant entity isincluded as the foreign key in the weak entity relation.Supertypes and subtypes are mapped to separate relations. The primary key of thesupertype becomes the primary key of the subtype.Mapping Relationships : A 1-1 relationship is mapped using a foreign key. The primarykey of either of the entities is include as a foreign key in the relation of the other entity.

    This relationship is rare, because data elements related in this way are normally placed inthe same table.A 1-M or M-1 is mapped by introducing a foreign key. A primary key is the ??one?? sideof the relationship, and the foreign key is the ??many?? side of the relationship. Thisrelationship are most common.A M-M involves the creation of a new relation. M-M are problematic and cannot beadequately expressed directly in a relational db. It is expressed using intersection tables.An intersection table contains two (or more) foreign keys, relating the primary key valuesof two (or more) tables to each other. The role of an intersection table is to convert theM-M into two 1-M relationships that can be easily handled by the database.IV. SIMPLIFYING DATA :Need for Simplifying Data :Normalization : Normalization is a formal process of developing data structures in amanner that eliminates redundancy and promotes integrity. You need to simplifystructure of data in relations for easy storage and retrieval. The process of simplifyingrelations is called normalization. The new relations that are obtained after normalizationare called normalized relations.Normalization has three well defined steps :The relations that you get at the end of the first step are said to be in 1NF.The relations that you get at the end of the second step are said to be in 2NF.The relations that you get at the end of the third step are said to be in 3NF.Simplifying Data to 1NF (Eliminate Repeating Groups) : A repeating group is a set ofcolumns that store similar info that repeats in the same table. To simplify data to 1NF,you ensure that all attributes values in a relation have atomic values. If there are attributesin a relation with non-atomic values, move these attributes to a new relation and choosean appropriate primary key for it. E.g. SupItem Table Item field having atomic.Simplifying Data to 2NF (Eliminate Redundant Data) :Redundant data is data that is expressed multiple times unnecessarily, or depends only onpart of a multi-valued key.Functionally Dependent Attributes : Functionally Dependent Attributes are those that

  • 7/29/2019 Pl SQL Interview Qns

    9/182

    belong to a single entity or relationship and depend on its unique identifier. To simplifydata to 2NF, you ensure that all nonkey attributes in a relation are functionally dependenton the whole key and not part of the key.Conversion from 1NF to 2NF : To convert a relation in 1NF to 2NF, move all nonkeyattributes that are not wholly dependent on the primary key, to a new relation. Then,

    choose an appropriate primary key for the new relation. E.g. Separating Sup. table andItem table.Simplifying Data to 3NF (Eliminate Columns not Dependent on the Key) :Columns in each table should be a group of columns in which the data in each columncontributes to the description of each row in the table.Transitively Dependent Attributes : Transitively Dependent Attributes in a relation arethose that are dependent on a nonkey attribute and not the primary key. To simplify datato 3NF, you ensure that there are no attributes in a relation that are transitively dependenton other attributes.Conversion from 2NF to 3NF : To convert a relation in 2NF to 3NF, move all transitivelydependent attributes to a new relation. Then, choose an appropriate primary key for the

    new relation. E.g. Status is dependent on City in Sup. table, so move those two toseparate table.Simplifying Data to 4NF (Isolate Independent Multiple Relationships) :V. STORING & RETRIEVING DATA :Language Support for an RDBMS :SQL :SQL is the language that provides command to interact with the data in thedatabase. SQL consists of three components - DDL, DML & DCL.DDL : DDL comprises commands you can use to create and modify the databasestructure.DML : DML comprises commands you can use to add, modify, delete and query data inthe database.DCL : DCL comprises commands you can use to control the user access to the database.Organizing the Database :Base Tables : A database comprises base tables, which have the following features :They physically exist on the disk, Each of them has a unique name & they contain datathat is crucial to an organization.Their attributes have data types such as character, integer, decimal, date and time.CREATE TABLE : This is a DDL command in SQL that creates a new table in adatabase.Syntax : CREATE TABLE table-name (column-name data-type [[size]]NOT NULL/DEFAULT default-value]]CHECK (column-name > 0)UNIQUE (column-name)PRIMARY KEY (column-name)FOREIGN KEY (column-name) REFERENCES table-name)ALTER TABLE : This is a DDL command in SQL that modifies the structure of anexisting table.Syntax : ALTER TABLE table-nameADD (column-name data-type [[size]] [[NOT NULL DEFAULT]]...)primary key definition / foreign key definition

  • 7/29/2019 Pl SQL Interview Qns

    10/182

    DROP PRIMARY KEY / DROP FOREIGN KEY)DROP TABLE : This is DDL command in SQL that deletes the an existing table. Onceyou delete a table, all data contained in it is lost and cannot be recovered. The storagespace used by this table is also released.Syntax : DROP TABLE table-name

    Interacting with a Database :SELECT : This is a DML command in SQL that retrieves data from the database in theform of query results. The command supports the following keywords and clauses :FROM This keyword specifies the name of the table.* This keyword selects all the columns of the table.WHERE This keyword gives the search condition that specifies the data to be retrieved.AND This operator is used to combine two or more search conditions.ORDER BY This keyword sorts the query result on one or more columns.GROUP BY This keyword groups the query result and lets you generate summary resultfor each group.NULL values This value indicates that the data is not present.

    Subquery This is the query that is place inside the main query. It passes its query result tothe main query.INSERT : This is a DML command in SQL that you use to add data in rows of a table.SYNTAX : INSERT INTO table-name (column-names) VALUES (constant/NULL)UPDATE : This is a DML command in SQL that you use to change data on rows of atable.Syntax : UPDATE table-name SET column-name-value WHERE conditionDELETE : This is a DML command in SQL that removes one or more rows of data froma table.Syntax : DELETE FROM table-name WHERE condition.End-user's View of a Database :Views : Views are relations that are derived from one or more source tables. Views havethe following features:Views let you restrict the access to data so that end-users see data relevant to them.Views do not physically exist in the database and only their definition is stored by anRDBMS.An RDBMS accesses the source tables for data to be retrieved from a view.Any changes that users make to views do not reflect in the source tables if the view hasbeen created using a Join condition.Views created WITH CHECK OPTION allows for an added measure of security in aview. For example, the user will not be able to insert or update a row that could not beselected by the view-with check option prevents this from happening.CREATE VIEW : A view can be created using the CREATE VIEW command.Syntax : CREATE VIEW view-name (column-names) AS query.Retrieving Data from a View : Once you create a view, you can retrieve data from itusing the SELECT command, just as you do for a table.

    Restricting Access to a Database :GRANT : This is a DCL command in SQL that you use to grant a specific set ofauthorities to one or more users.

  • 7/29/2019 Pl SQL Interview Qns

    11/182

    Syntax : GRANT (SQL command) (column-names) ON table-name TO user-name.REVOKE : This is a DCL command in SQL that you use to take away a specific set ofauthorities from one or more users.Syntax : REVOKE (SQL command) ON table-name TO user-name.VI. ENSURING INTEGRITY OF DATA :

    The concept of Data Integrity :Data Integrity : Data Integrity refers to the correctness and completeness of data in adatabase.Integrity Constraints : Integrity constraints allows only correct changes to be made to adatabase. There are two types of integrity constraints - entity integrity and referentialintegrity.Entity Integrity : Entity Integrity ensures that for each row in a table, the value of theprimary key is unique and is not null.Referential Integrity : Referential Integrity ensures that for each row in a table, the valueof the foreign key is present in the reference table.Grouping commands related to a task :

    Transaction Processing : A transaction is a sequence of one or more SQL commands thattogether form a logical task. Transaction Processing ensures that when the RDBMS ismaking changes related to a single task, either all changes are made as a unit or nochanges are made.Commit : Commit is an SQL command that indicates the successful end of a transaction.After an RDBMS executes this command all the changes are made to the database.Rollback : Rollback is an SQL command that cancels a transaction before it is complete.The rollback command removes the changes of all previous commands in a transactionfrom the buffer.Controlling Concurrent Data Access :Concurrency Control : All RDBMS must ensure that the transactions of concurrent usersdo not interfere with each other. If it does not handle the transactions properly, theproblems of lost update, uncommitted data, or inconsistent data might occur.Lost Update Problem : Lost update problem occurs when an update made by a transactionis lost due to an update made by another transaction.Uncommitted Data Problem : Uncommitted data problem occurs when a transactionaccesses data that has been updated by a previous transaction that has not yet ended.Inconsistent Data Problem : Inconsistent data problem occurs when a transaction accessesdata from the database and simultaneously another transaction is changing that data.Locking : Locking is a facility provided by an RDBMS to ensure that a transaction doesnot interfere with any other transaction. Locking prevents the problem of lost update,uncommitted data and inconsistent data. An RDBMS provided two types of locks forlocking a part of the database - shared locks and exclusive locks.Shared Locks : If a transaction is only reading data from a database, it gets a shared lockon that part of the database. Other transactions can also get a shared lock on that part ofthe database to read data. However, they cannot change the data.Exclusive Locks : If a transaction is updating data in a database, it gets an exclusive lockon that part of the database. No other transaction can read or change this data.

    Client Server Computing Model

  • 7/29/2019 Pl SQL Interview Qns

    12/182

    I. Client Server Paradigm :Introduction : In the past decade, organizations have restructured and become global. Theglobalization and restructuring have led to a need for distributed and flexible informationaccess. That traditional computing paradigms like host-based and master/slave processingdo not adequately address the information requirements of modern business. That the

    client/server model provides an architecture that harness contemporary technology tomeet the computing needs of the modern business organization. Also called DistributedApplication Processing or Co-Operative Application ProcessingHost Based Processing - The Centralized Paradigm : Centralized computing treatedapplications as an integrated unit. Applications ran on a single processor. The sameprocessor generated the user interface and manipulated data. Dumb terminals were usedfor data access and display. Disadvantages are : Data was centralized and often notaccessible to those who needed it. The host computed did all the work, was frequentlyoverloaded, and response times were often poor. Hardware choices and scalability werelimited by proprietary architecture's. User interfaces were unfriendly, Data access wasinflexible and governed by available 3GL programs.

    Master/Slave - The First Distributed Computing Paradigm : As PC's and intelligentterminals became available, a limited amount of processing was transferred to theterminal. Intelligent terminals often validated data and provided editing functions. Suchterminal were called Slaves. Slaves were controlled by Master computer which did themain processing and stored all data. It had one distinct advantage. It reduced the load onthe main processor. However, the other problems associated with host-based processingremained.Client/Server - A Distributed Computing Paradigm : The client/server paradigm evolvedas an attempt to address the new computing needs of business and utilize newtechnologies.Advantages : Client/Server makes it possible to harness the computing power availableon PCs and other workstations in an organization. Response times are improved asprocessors are not overloaded. Hardware and software choices can be applicationoriented as they do not necessarily have to run on a proprietary computer. Network trafficis reduced because the processing power available at the end user terminal makes itunnecessary to send detailed instructions over the network as in the case of host based &master/slave systems. Computing power can be added in smaller units making the systemeasily scaleable.Disadvantages :The inherent heterogeneity makes System Integration, Administration &Maintenance a formidable challenge.ORACLE 7 is an exceptional RDBMS & also an excellent DB server because it supportsall major OSfor both clients & servers i.e. MSDOS, Netware, Unixware, OS/2 etc. Oracle Networksoftware SQL*NET support all major network communication protocols TCP/IP,SPX/IPS, Named Pipes & DECNET. It has got client server feature that developers canuse to minimize network traffic between clients & servers. Has features that makes iteasy to administer a complicated client server system.Client/Server Approach : The client/server paradigm optimizes the use of computerresources by distributing application processing among multiple processors. Theclient/server model computers are classified as Clients and Servers, where Clients are

  • 7/29/2019 Pl SQL Interview Qns

    13/182

    requesters of services and Servers are provider of services. Typically, clients handle userinterface function & server handle data management function.Client/Server Architecture requires Processing to be distributed over more than onecomputing system. Client-initiated client/server interactions. Server control over theservices that can be requested by the client. Servers to arbitrate between conflicting client

    requests. A communication system that enables clients & servers to communicate.Multitasking can be defines as the capability of an OS to run multiple applicationsconcurrently. A Multitasking OS allocates a certain amount of CPU time to each task. InPreemptive multitasking, the OS controls the amount of CPU time allocated to a task. Innon-preemptive multitasking, the application controls the CPU time and the CPU isreleased only after the task is completed.Multithreading is an extension of multitasking. It allows multitasking within anapplication. Programs and subroutines within a program can execute concurrently in amultithreaded environment. Several user process for a single server process.Database Server should have preemptive multitasking & multithreading capability.Support a standard RDBMS. Support a standard Network Operating System.

    Tools such as RDBMS, Application Software, Application Program Interfaces, StoredProcedures, Remote Procedure Call (RPC) & Application Development Tools are animportant part of client/server systems. Such tools improve productivity and also play arole in making client/server systems more open. An API is a set of functions thattranslates client requests into a format that the server can understand. RPC is essentially amessaging system which allows stored procedures to be invoked. Many RPCs allowsprocedures to be invoked across heterogeneous platforms and also provide the requireddata translation services.There are several application designs possible in the client/server model depending onhow application processing is distributed.In Distributed Presentation, the presentation function is divided between the client & theserver. Useful in situations where PC or workstations are connected to mainframes. Usedto enhance the user interface of mainframe based applications.In Remote Presentation, the entire presentation part of the application resides on adifferent computer than the one that has the logic function. Used in applications whereuser interaction is completely static and predetermined.In Distributed Logic, the logic function is placed on more than one platform thus,improving response time by allowing the logic to execute simultaneously on severalprocessors.In Remote Data Management, the application logic resides on different computer than theone that has the data and the DBMS. Easy to implement and often provide end-users withtotally transparent access to data.In Distributed Data Management, the data and DBMS is distributed among multiplenodes and distribution of application logic.Goals of Client/Server Paradigm is the end-user. Client/Server seeks to provide end-usertransparent access to the computing resources of the organization. The goal is referred toas single system image. There are four attributes of single system image :Location Transparency : Users must be able to access data without knowing the locationof the data. Users should not have to learn & use different commands for accessing datafrom different locations.

  • 7/29/2019 Pl SQL Interview Qns

    14/182

    Interoperability requires that applications and processing tasks be freely portable acrossheterogeneous computing resources.Consistent User Interfaces require that applications retain the same user interface acrossheterogeneous computing platforms. Common computing tasks are representedconsistently across applications.

    Enterprise-wide Resource Sharing is the common thread that links all of an enterprise'scomputing resourceII. Concepts for Client/Server :Introduction : RDBMS's standardize data storage and access and are therefore ideal forimplementing client/server systems. The physical structure of a network is calledNetwork Topology i.e. refers to the way the cabling of a network is physically structured.The rules that govern the process of data transmission in a network are collectivelyreferred to as Network Protocol. Graphical User Interfaces improve productivity becausethey reduce learning timeand are easier to use.Distributed Database Support : The capability of an RDBMS to manage databases lying

    at more than one location. To provide distributed database support, an RDBMS must beable to provide transparent access to data, Join tables on different platforms, Handle andmanage distributed queries and Ensure that transactions are successfully completed on allrelevant databases.Network : Network has six basic functions, Naming, Segmentation, Segmenting, FlowControl, Synchronization, Priority & Error Control. There are three types of networktopologies, Bus, Star & Ring. There are three types of transmission media, Twisted Pair,Coaxial Cable & Optic Fibre. There are three types of data transmission methods,Centralized, Distributed & Random.GUIs : GUI must support mouse events, keyboard events, menu events, resizing events,activation/deactivation events and initialize/terminate events. GUI should be portable,should support wide variety of development tools & be an industry standard.III. Client/Server Software :Back-end Software : It is made up of Database Servers & Network Operating Systems.The database server manages data on the system & maintains data integrity. Databaseserver requires some special features. Compatibility i.e. must be able to work on differentoperating systems. SQL Implementation i.e. must support standard ANSI SQL since itcan communicate with different SQL dialects. Stored Procedures i.e. must be able to useSP as they are analyzed, compiled and optimized. Referential Integrity i.e. allows theserver to synchronize change to columns that are part of multiple tables. Declarative RIestablishes precise rules for use of columns that are common across tables. Built into dbsoftware and enforced by default. In Procedural RI, each db command is associated witha trigger. When command is issued, the trigger sets of a series of commands that makethe necessary changes. Disadvantage is programmers must write triggers leading toerrors. Multithreading i.e. support execution of multiple tasks simultaneously. DistributedDatabase Support i.e. able to divide database tasks among multiple CPUs. Also, able tojoin tables located on different servers, & manage SQL queries sent to different servers.Concurrency Control i.e. support automatic escalation, the server locks a record, if asingle record is being modified. A page, if several records are being modified. A table, ifseveral pages are being modified. Transaction Control i.e. protect transactions from

  • 7/29/2019 Pl SQL Interview Qns

    15/182

    system failures. In two phase commit, all workstations are notified of database changes,and if system fails, all sites rollback.NOS controls the transmission of data across the network and manages the sharing ofhardware and software resource on the network. Four important features are OperatingEnvironment Support, Workstation Support, Security & Protocol Support.

    Development Tools are made up of SQL/3GL programming tools & Front-enddevelopment tools.End User Tools are made up of Decision Support Tools and PC-based add-ons.IV. Migrating to Client/Server :Evaluating the Client/Server Option : To evaluate the following before deciding onclient/server. Application requirements, Geographical requirements & ProductivityGains. Client/Server is most suitable for applications are decision support or on-linetransaction processing (OLTP). The distances are site or city & both developer & end-user productivity are expected to increase.Planning for Migration : Planning is needed to reduce problems with network load,training & systems maintenance. Migration plan must include analysis, selection,

    prototyping & implementation as activities. Planning must include end-users, developersand system administrators as resources. To specify system requirements for end-users,developers, system managers and the business as a whole. To evaluate business prioritiesto eliminate stagnation & disruption.Implementing Client/Server : The Systems Integration Life Cycle (SILC) is made up ofpreparation, detailing and execution. Managing SILC projects involves planning,controlling & completing. System maintenance involves ensures reliability, ensuringserviceability and monitoring performance. The training must cover end-users,developers & system administrators.

    ORACLEI. SQL*PLUS :SQL is an English like language consisting of commands to store, retrieve, maintain &regulate access to your database.SQL*PLUS is an application that recognizes & executes SQL commands & specializedSQL*Plus commands that can customize reports, provide help & edit facility & maintainsystem variables.NVL : Null value function converts a null value to a non-null value for the purpose ofevaluating an expression.Numeric Functions accept numeric I/P & return numeric values. They are MOD, SQRT,ROUND, TRUNC & POWER.Date Functions are ADD_MONTHS, LAST_DAY, NEXT_DAY,MONTHS_BETWEEN & SYSDATE.Character Functions are INITCAP, UPPER, LOWER, SUBSTR & LENGTH. Additionalfunctions are GREATEST & LEAST.Group Functions returns results based upon groups of rows rather than one result per row,use group functions. They are AVG, COUNT, MAX, MIN & SUM.TTITLE & BTITLE are commands to control report headings & footers.COLUMN command define column headings & format data values.BREAK command clarify reports by suppressing repeated values, skipping lines &

  • 7/29/2019 Pl SQL Interview Qns

    16/182

    allowing for controlled break points.COMPUTE command control computations on subsets created by the BREAKcommand.SET command changes the system variables affecting the report environment.SPOOL command creates a print file of the report.

    JOIN is the form of SELECT command that combines info from two or more tables.Types of Joins are Simple (Equijoin & Non-Equijoin), Outer & Self join.Equijoin returns rows from two or more tables joined together based upon a equalitycondition in the WHERE clause.Non-Equijoin returns rows from two or more tables based upon a relationship other thanthe equality condition in the WHERE clause.Outer Join combines two or more tables returning those rows from one table that have nodirect match in the other table.Self Join joins a table to itself as though it were two separate tables.Set Operators supported by Oracle are :Union is the product of two or more tables.

    Intersect is the product of two tables listing only the matching rows.Minus is the product of two tables listing only the non-matching rows.Correlated Subquery is a subquery that is evaluated once for each row processed by theparent statement. Parent statement can be Select, Update or Delete. Use CRSQ to answermultipart questions whose answer depends on the value in each row processed by parentstatement.Multiple columns can be returned from a Nested Subquery.Sequences are used for generating sequence numbers without any overhead of locking.Drawback is that after generating a sequence number if the transaction is rolled back,then that sequence number is lost.Synonyms is the alias name for table, views, sequences & procedures and are created forreasons of Security and Convenience. Two levels are Public - created by DBA &accessible to all the users. Private - Accessible to creator only. Advantages arereferencing without specifying the owner and Flexibility to customize a more meaningfulnaming convention.Indexes are optional structures associated with tables used to speed query executionand/or guarantee uniqueness. Create an index if there are frequent retrieval of fewer than10-15% of the rows in a large table and columns are referenced frequently in theWHERE clause. Implied tradeoff is query speed vs. update speed. Oracle automaticallyupdate indexes. Concatenated index max. is 16 columns.Data types :Max. columns in a table is 255. Max. Char size is 255, Long is 64K & Number is 38digits.Cannot Query on a long column.Char, Varchar2 Max. size is 2000 & default is 1 byte.Number(p,s) p is precision range 1 to 38, s is scale -84 to 127.Long Character data of variable length upto 2GB.Date Range from Jan 4712 BC to Dec 4712 AD.Raw Stores Binary data (Graphics Image & Digitized Sound). Max. is 255 bytes.Mslabel Binary format of an OS label. Used primarily with Trusted Oracle.

  • 7/29/2019 Pl SQL Interview Qns

    17/182

    Order of SQL statement execution : Where clause, Group By clause, Having clause,Order By clause & Select.Transaction is defined as all changes made to the database between successive commits.Commit is an event that attempts to make data in the database identical to the data in theform. It involves writing or posting data to the database and committing data to the

    database. Forms check the validity of the data in fields and records during a commit.Validity check are uniqueness, consistency and db restrictions.Posting is an event that writes Inserts, Updates & Deletes in the forms to the database butnot committing these transactions to the database.Rollback causes work in the current transaction to be undone.Savepoint is a point within a particular transaction to which you may rollback withoutrolling back the entire transaction.Set Transaction is to establish properties for the current transaction.Locking are mechanisms intended to prevent destructive interaction between usersaccessing data. Locks are used to achieveConsistency : Assures users that the data they are changing or viewing is not changed

    until the are thro' with it.Integrity : Assures database data and structures reflects all changes made to them in thecorrect sequence.Locks ensure data integrity and maximum concurrent access to data. Commit statementreleases all locks. Types of locks are given below.Data Locks protects data i.e. Table or Row lock.Dictionary Locks protects the structure of database object i.e. ensures table's structuredoes not change for the duration of the transaction.Internal Locks & Latches protects the internal database structures. They are automatic.Exclusive Lock allows queries on locked table but no other activity is allowed.Share Lock allows concurrent queries but prohibits updates to the locked tables.Row Share allows concurrent access to the locked table but prohibits for a exclusive tablelock.Row Exclusive same as Row Share but prohibits locking in shared mode.Shared Row Exclusive locks the whole table and allows users to look at rows in the tablebut prohibit others from locking the table in share or updating them.Share Update are synonymous with Row Share.Deadlock is a unique situation in a multi user system that causes two or more users towait indefinitely for a locked resource. First user needs a resource locked by the seconduser and the second user needs a resource locked by the first user. To avoid dead locks,avoid using exclusive table lock and if using, use it in the same sequence and use Commitfrequently to release locks.Mutating Table is a table that is currently being modified by an Insert, Update or Deletestatement.Constraining Table is a table that a triggering statement might need to read either directlyfor a SQL statement or indirectly for a declarative Referential Integrity constraints.Pseudo Columns behaves like a column in a table but are not actually stored in the table.E.g. Currval, Nextval, Rowid, Rownum, Level etc.SQL*Loader is a product for moving data in external files into tables in an Oracledatabase. To load data from external files into an Oracle database, two types of input

  • 7/29/2019 Pl SQL Interview Qns

    18/182

    must be provided to SQL*Loader : the data itself and the control file. The control filedescribes the data to be loaded. It describes the Names and format of the data files,Specifications for loading data and the Data to be loaded (optional). Invoking the loadersqlload username/password controlfilename

    PL/SQL :Data types are NUMBER, CHAR/VARCHAR2, DATE & BOOLEAN.Arrays are not allowed & only one identifier per line is allowed.Attributes of PL/SQL objects are %TYPE, %ROWTYPE.PL/SQL Block is a standard PL/SQL code segment. Block consists of three parts.Declarative Section for variables, constants & exceptions. This section is optional.Executable Section which is mandatory.Exception Handlers which is optional.PL/SQL supports only DML i.e. INSERT, UPDATE, DELETE & SELECT...INTO.SQL Functions can be referenced within a SQL statement i.e. Numeric(SQRT,ROUND,POWER),

    Character (LENGTH,UPPER), DATE (ADD_MONTHS,MONTHS_BETWEEN) &Group (AVG,MAX,COUNT). Most SQL functions are available outside SQL statementexcept for group functions.Code Simple Loops repeats a sequence of statements multiple times.Syntax : LOOPEND LOOP;Code Numeric FOR Loops repeat a sequence of statements a fixed number of times.Syntax : FOR IN [[ REVERSE ]] .. LOOPEND LOOP; is implicitly of type number. Defined only within the loop & Value can bereferenced in an expression, but a new value cannot be assigned to the index within theloop.Code While Loops repeats a sequence of statements until a specific condition is no longerTRUE.Syntax : WHILE LOOPEND LOOP; can be any legal PL/SQL condition & statements will be repeated as long ascondition evaluates to TRUE.Code GOTO Statements jumps to a different place in the PL/SQL block.Syntax : GOTO label_name;Legally use a GOTO a statement that is in the same sequence of statements as the GOTO.In the sequence of statements that encloses the GOTO statement (outer block).Labels can label any statement. Used as targets for GOTO statements, use labels forblocks and loops, Label a block to allow referencing of DECLAREd objects that wouldotherwise not be visible because of scoping rules, Label a block to allow a variable to bereferenced that might be hidden by a column name, Label a loop to allow an object to bereference that would otherwise not be visible because of scoping rules & Label an EXIT

  • 7/29/2019 Pl SQL Interview Qns

    19/182

    as a convenient way to specify exits from outer loops.Cursors are associated with every SQL DML statement processed by PL/SQL. Two typesare Explicit i.e. Multiple row SELECT statements & Implicit i.e. INSERT, UPDATE,DELETE & SELECT...INTO statements. Implicit cursor is called the SQL cursor-itstores info concerning the processing of the last SQL statement not associated with an

    explicit cursor. OPEN, FETCH & CLOSE do not apply. All cursor attributes apply.Cursor has to be explicitly defined when a query returns multiple rows to process beyondthe first row returned by the query & to keep track of which row is currently beingprocessed.Declare the cursor to associate its name with a SELECT statement.Syntax : DECLARECURSOR IS ;Open the cursor to process the SELECT statement and store the returned rows in thecursor.Syntax : OPEN ;

    Fetch data from the cursor and store it in specified variables.Syntax : FETCH INTO ;Close the cursor to free up resources. Cursors must be closed before they can bereopened.Syntax : CLOSE Explicit Cursor Attributes are %NOTFOUND, %FOUND, %ROWCOUNT &%ISOPEN.Reference the current cursor row with the WHERE CURRENT OF statement. The cursormust be declared with a FOR UPDATE OF clause.Syntax : WHERE CURRENT OF Reference Cursors FOR Loops to specify a sequence of statements to be repeated oncefor each row that is returned by the cursor with the Cursor FOR Loop.Syntax : FOR IN LOOP--statements to be repeated go hereEND LOOP;Cursor FOR loops (CFL) are similar to Numeric For Loops(NFL). CFL specify a set ofrows from a table using the cursor's name. NFL specify an integer range. CFL recordtakes on vales of each row. NFL index takes on each value in the range. Record_name isimplicitly declared asrecord_name cursor_name%ROWTYPEWhen a CFL is initiated, an implicit OPEN cursor_name is initiated.For each row that satisfies the query associated with the cursor, an implicit FETCH isexecuted into the components of record_name.When there are no more rows left to FETCH, an implicit CLOSE cursor_name isexecuted and the loop is exited.Declare cursors to use parametersSyntax : DECLARECURSOR [[(param_name param_type)]]IS ;Exception Handlers : In PL/SQL, errors are called exceptions. When an exception is

  • 7/29/2019 Pl SQL Interview Qns

    20/182

    raised, processing jumps to the exception handlers. An exception handler is a sequence ofstatements to be processed when a certain exception occurs. When an exception handleris complete, processing of the block terminates. Two types are Predefined InternalExceptions which corresponds to approximately 20 common ORACLE errors & Raisedautomatically by PL/SQL in response to an ORACLE error.

    Eg.too_many_rows,no_data_found,invalid_cursor,value_errori.e.arithmetic,numeric,string,conversion or constraint error occurred, zero_divide,dup_val_on_index,cursor_already_open etc.User-Defined Exceptions must be declared & must be RAISEd explicitly.Only one handler per block may be active at a time & If an exception is raised in ahandler, the search for a handler for the new exception begins in the enclosing block ofthe current block.Exception-Init : Exceptions may only be handled by name not ORACLE error number.So, name an ORACLE error so that a handler can be provided specifically for that error.Syntax : PRAGMA EXCEPTION_INIT (,);

    SQLCODE & SQLERRM provides info on the exception currently being handled &especially useful in the OTHERS handler.SQLCODE returns the ORACLE error number of the exception, or 1 if it was a user-defined exception.SQLERRM returns the ORACLE error message associated with the current value ofSQLCODE & can also use any ORACLE error number as an argument.SQLCODE & SQLERRM cannot be used within a SQL statement. If no exception isactive SQLCODE = 0 & SQLERRM = 'normal, successful completion'.

    SQL*FORMS :Form is a tool for developing and executing forms based interactive applications that canaccess info from ORACLE database.Blocks describes each section or subsection of the form and serves as the basis of defaultdatabase interaction.Fields represents columns or data entry areas and describes how data should be displayedand validated and how an operator should interact with the data while it is entered.Pages is a collection of display info such as constant texts and graphics. All fields have tobe displayed on some page.Pop-Up Pages Non-Pop-Up PagesAppear in windows Overlay the entire screenCreated by selecting pop-up page attribute Default type of pageCan be larger or smaller than the screen Can only be the size of the screenCan appear anywhere on the screen Must be positioned at the upper left hand corner ofthe screenCan be a section (view) of a page Must fill the entire text regionMany pages can appear on the screen at one time Only one non-pop-up page can appearon the screen

    Page Size specifies the size of the pop-up page.View Size specifies the size of the view that appears on the screen i.e. how much of the

  • 7/29/2019 Pl SQL Interview Qns

    21/182

    pop-up is shown.View Location specifies where on the screen the view of the pop-up page appears; the Xand Y coordinates of the screen define the upper left corner of the view.View Page specifies the initial location of the view on the page, i.e. the part of the pop-uppage that is shown; the X & Y coordinates of the page define the upper left corner of the

    view.Screen Painter is used to edit screen images, add constant text and graphic elements.Zoom In : Displays the form or spread table for the objects that are owned by the currentobject.Zoom Out : Displays the form or spread table for the object that owns the current object.Validation Unit is a characteristic which determines the max. amount to data to beentered before form initiates validation. It corresponds to a unit of data which can befield, record, block or form.Navigation is performed to move the cursor from one location to another.Cursor is an instance of field, outside the form or undefined.Row Id is a column created by ORACLE when a table is created. It contains a value for

    each row which uniquely identifies that row. When a block is created, forms add a non-displayable, non-up dateable field named row id. Forms uses row id to determine whatrows to fetch from db or reserve in db and what rows to update or delete during posting.It helps forms to manage transactions and is used to update a table that is not associatedwith a block in the form.Trigger is a piece of PL/SQL code that is executed or triggered by an event while theform is running. It validates data entry, performs calculations, control the flow ofapplication & replace or enhance default processing.Trigger Point is a temporal space in an event with which a specific trigger type isassociated.Types of Triggers : Most key triggers are function key triggers; they have a one-to-onerelationship with specific keys.Function Key Triggers : Fires when a particular Forms function key is pressed.Replace or supplement default function key functionality, Perform multiple or complexfunctions & Disable function keys.Key Startup : Fires at the end of the entering the form event. Considered as key triggerbecause its action is similar to an operator pressing a startup function key.Set up form default, Send a message to the operator as soon as the form comes up on thescreen & Perform an automatic query upon entering the form.Key Others : Associate a key-others trigger with all keys that can have key triggersassociated with them but are not currently defined by a function key triggers.Key Fn : Attach key-Fn triggers to any one of ten key sequences that normally do notperform any SQL*Form operations. Before attaching key triggers to these keys, runOracle*Terminal to map the keys to the appropriate functions.Navigational Triggers : Fires when entering or leaving a form, block, record or field.Restrict access to a form, Print messages, Derive a complex default value, Keep arunning total & Perform calculations.Validation Triggers : Validation is an internal process by which Forms determineswhether the data in an object is correct. Validation triggers fire when validation isperformed. Validation occurs when the operator has entered or changed data in an object

  • 7/29/2019 Pl SQL Interview Qns

    22/182

    and then tries to leave the object. Validation does not occur when the operator is in EnterQuery mode. Validation or Navigation triggers cannot contain Restricted PackagedProcedures.Fires as last part of field validation, Changes, Calculates & Validates a field value.Query Triggers : Fires when entering & executing a query, and when counting query hits.

    Defined only at the block or form level. Pre-Query fires once before block is queried.Post-Query fires once for every record fetched by the query.Error & Message Handling Triggers : Write these triggers to replace the defaultSQL*Forms error or informative messages. On-Error & On-Message trigger fires whenForms displays an error or an informative message respectively.Trap & recover from an error, Replace a standard message with a custom message.Transactional Triggers : Fires during commit processing - an event that makes the data inthe database identical to the data in the form.Sets up special locking requirements, Update an audit trial, Prevent Insert/Update/Deleteactions & Modify Insert/Update/Delete actions.Packaged Procedure is a predefined piece of PL/SQL procedure that executes a

    SQL*Forms function.Restricted Packaged Procedure is any packaged procedure that affects the basic functionsof SQL forms. It is used only in Key triggers, user named triggers that are invoked by keytriggers & On-New-Field-Instance trigger.Do_Key packaged procedure executes the key trigger that corresponds to the specifiedpackaged procedure. If no such trigger executes, then the specified packaged procedureexecutes. This behavior is analogous to the user pressing the corresponding function key.Syntax : DO-KEY (package procedure name)Packaged Function is a predefined piece of PL/SQL function that evaluates some aspectof the current SQL*Forms session and returns a value.Name_In packaged function returns the contents of the variable to which you apply it.Returned value is in the form of character string. Also use Name_In to return number anddates as character strings and then convert those strings to the appropriate data types.Call packaged procedure runs an indicated form while keeping the parent form active.SQL form runs the called form with the same options as the parent form. When calledform is exited thro' the EXIT function or as a result of navigational failure, processingresumes in parent form at the point where the call occurred.Call_Form runs an indicated form while keeping the parent form active.Open_Form opens an indicated form to create multiple form application called form ismodal.New_Form exits the current form and enters the indicated form.Key-Duprec trigger copies the values of each field in the record with the next lowersequence number to the corresponding fields in the current record. The current recordmust not correspond already to a row in the database. If it does, an error occurs and callsthe Duplicate_Record packaged procedure.Primary Key Field Attributes indicates that the field is a unique characteristics for arecord or part of unique key. To ensure that an inserted record or updated record does notduplicate an existing record, give the critical field the primary key characteristics andgive the block the primary key characteristics.Anonymous Block is a PL/SQL block without a name and this block can be executed

  • 7/29/2019 Pl SQL Interview Qns

    23/182

    from the trigger in which it is defined. It does not require BEGIN & END keywords. Ithas to be included if it has Declaration section.Form Level Procedure are callable PL/SQL blocks. The full PL/SQL syntax, includingdeclarations and keywords BEGIN & END are required. They cannot contain anonymousblock. These procedures can use any command that a trigger can use. They can also take

    arguments and return values, just as subroutines do in 3GL. It can be called from otherprocedures & triggers. Advantages areReduce the amount of logic the designer needs to write for any task, Leads to moreefficient & consistent applications, Can be called by another procedure or trigger & Canpass parameters.User Exits is a subroutine which is written and linked into SQL forms executable files. Itis a link to pass data from forms to host language programs and receives the result. Itperforms complex data manipulation, pass data to forms from OS files, manipulate longraw data, support PL/SQL blocks and control real time devices such as printer or robot. Itreturns a integer value which indicates Success, Failure or Fatal Error.Types :

    Oracle PreCompiler User Exits : Incorporates Oracle Precompiler interface. Allow towrite a subroutine using one of the following host language & embedded SQLcommands. Host language are ADA, C, COBOL, FORTRAN, PASCAL & PL/1. Withembedded SQL commands, an Oracle Precompiler user exit can access oracle databases.Also access SQL*Forms variables & fields. Because of this feature, most of user exits isOracle Precompiler user exits.Oracle Call Interface User Exits : Incorporates Oracle Call Interface. Allows to write asubroutine that contains call to Oracle database but cannot access SQL*Forms variable &fields.Non-Oracle User Exits : Does not incorporate either precompiler interface or OCI. Non-Oracle user exit might be entirely written using C. Cannot access Oracle database &SQL*Forms variable & fields.PL/SQL Variable is a local variable that is active only within the anonymous block orform level procedure in which it has been declared.Global Variable is a forms variable that is active in any trigger within a form and is activethrough out the session. Stores a character string of upto 255 characters long. Before avariable is active, it should be initialized thro' a trigger or it will be initialized first timeyou assign a value to it. Delete any variable with ERASE package procedure. Globalvariable declared in one form can be used in called form. Used to store data values thatshould not be stored inside a block or you want to share between forms during formsession.Syntax : GLOBAL.variable_name Oracle Naming Conventions.System Variable is a SQL*Forms variable to keep track of some internal SQL*Formsstate. Able to reference the value of system variable in order to control the way anapplication behaves. Value of system variable corresponds to the current form. They areBlock_Status,Record_Status,Form_Status,Current_Block,Current_Field,Current_Form,Current_Value,Cursor_Block,Cursor_Field,Cursor_Record,Cursor_Value,Last_Record,Last_Query,Message_Level,Record_Status,Trigger_Block,Trigger_Field & Trigger_Record.Features of Oracle 7 :

  • 7/29/2019 Pl SQL Interview Qns

    24/182

    Stored Procedures is commonly used procedures can be written once in PL/SQL andstored in the database for repeated use by applications. This ensures consistent behavioramong applications and reduce development & testing time. Centralizing the applicationlogic and can be accessed from any Oracle tools.Difference between Stored Procedure and Oracle Forms Procedure :

    Stored Procedure Oracle Forms ProcedureStored within the database. Stored within the Oracle Forms Appln.Documented within the data dictionary. Documented from the Oracle Forms Appln.Executed from any db tool or appln. Executed from an Oracle Forms appln. only.May reference db stored procedures only. May reference Oracle Forms procedures inaddition to db stored procedures.Made available to applns. by means of db security. Made available to Oracle forms appln.by means of form-level security and the Copy/Reference facility.Invoked independently of, and in addition to, Oracle Forms procedures. Invokedindependently of, and in addition to, stored procedures.Stored Package is a group of related Stored Procedures, Functions & other package

    constructs stored together as a unit in the db. Stored Package provides the dbadministrator or appln. developer organizational benefits, they also offer increasedfunctionality and db perfomance.QEP for Stored Procedures is generated at compile time.Benefit from Stored Procedures & Functions : In addition to modularizing appln.development, other benefits areImprove Data Security and Integrity :Control indirect access to db objects from non-privileged users with security privileges.Ensure that related actions are performed together, or not at all, by funneling activity forrelated tables thro?? a single path.Improve Performance :Avoid reparsing for multiple users by exploiting shared SQL.Avoid PL/SQL parsing at runtime by parsing at compile time.Reduce the number of calls to the database and decrease network traffic by bundlingcommands.Conserve Memory :Store a single copy of code in the db to avoid multiple copies of the same code for diff.applns.Share sql to avoid multiple cursors for different applns.Improve Maintenance :Modify routines online without interfering with other users.Modify one routine to affect multiple applications.Modify one routine to eliminate duplicate testing.Database Triggers is a stored procedure that is implicitly fired when an Insert, Update orDelete statement is issued against the associated table. Complex business rules thatcannot be enforced using declarative integrity constraints can be enforced using triggers.It is similar to procedures that are stored in the databases and implicitly fired when a tableis modified.Guidelines :Use triggers to guarantee that when a specific operation is performed, related actions are

  • 7/29/2019 Pl SQL Interview Qns

    25/182

    performed.Use DB triggers for centralized global operations that should be fired for triggeringstatement regardless of which user or database application issued the statement.Do not define triggers to duplicate the functionality & do not create Recursive triggers.Triggers will be compiled when it is fired. So, limit the size of triggers. Compilation of

    triggers smaller in size will have insignificant effect on system performance. If the triggerhas to be execute many lines of code, include the code in the Stored Procedure.Mutating Error in DB triggers is when a select statement within the scope of the triggerselects rows corresponding to the trigger table itself. It can be solved by placing the selectstatement in a stored procedure and calling the stored procedure from the scope of thetrigger.Differences between Oracle 6.0 & 7.0 :Only not null was implemented in 6 where as in 7 all the integrity constraints areimplemented i.e. Not Null, Primary, Foreign, Check, Default & Unique constraints.Database Triggers, Stored Procedures, Functions & Packages are available in 7.Roles : ORACLE provides for easy & controlled privilege management thro?? the use of

    Roles. Roles are named groups of related privileges that are granted to users or otherroles. The properties are Reduced granting of privileges, Dynamic privilege management,Selective availability of privileges & Application awareness.Schemas is a collection of objects i.e. tables, views etc. and schema exists for each oracleuser.Profiles is assigned to each user that specifies limitations on several system resourcesavailable to the user i.e. the number of concurrent sessions the user can establish, theCPU processing time, the amount of logical I/O, the allowed amount of idle time for the user??s session & the allowed amountof connect time for the user??s session.Cost Based Optimizer is available. It uses statistics about tables, along with info about theavailable indexes to select an execution plan for SQL statements. This allows eveninexperienced users to submit complex queries without having to worry about theperformance. If we know the better execution path, provide hints to it to allow it to selectthe proper execution path.Table Replication is a snapshot of a table.Multi threaded architecture several user process for a single server process and the userprocess can be configured.Declarative Referential Integrity establishes precise rules for use of columns that arecommon across tables. Built into db software and enforced by default.

    SQL*REPORTWriter :Features :Application development tool for designing & executing reports. ANSI standard SQLused to retrieve records in the report. Menu-driven, simple spreadsheet-style screens.Default values for report format. Ability to customize report format, date & numberformats. Complex data relationships. Calculations & summaries. Text processing andhighlighting features. Reports can be viewed immediately on-line for corrections.Generate reports interactively or in a production environment. Parameters provide run-time flexibility. Report management facility for easy report maintenance & Integration

  • 7/29/2019 Pl SQL Interview Qns

    26/182

    with Oracle application tools.Components :Query - retrieves data from the database. Group - used to cluster columns returned fromthe query. Fields - containers for data values. Summary - calculated summary function ona field. Text - physical areas of report. Report - dimensions, security and history of the

    report. Parameters - entered at run-time to control production, data values.Queries : Every report must contain atleast one query. Query retrieves data for the reportfrom database tables or views. Queries can be unrelated i.e Master/Master report. Relatedqueries form a hierarchy, in which child query is executed once for each record returnedby the parent. Can create relationships between queries. No limit to the number of queriesin a report. No limit to the level of relationships (nesting) in queries. i.e. Master/Detail(parent/child) queries. Matrix queries i.e. Two parents/One child queries.On-line report can be viewed either in Browse i.e. Page by page or Window i.e. scrollshorizontally and vertically through a page.Groups : A group is a set of one or more columns. Every report must contain at least onegroup. Each query automatically generates one group consisting of all columns in the

    query.Break Groups : A break is a set of groups generated from one query. Can create newgroups (break groups) that group records by the distinct values of a column or set ofcolumns. Group settings provide format control.Field : A field is a container for values derived from columns or calculated column valuesin the SELECT statement. Computed fields created by user. System variables (pagenumber, number of pages, date etc.). User exits & DML statements.Summaries : Summaries calculate subtotals, grand totals, running totals & other standardfunctions on field values. All summaries are manually created. Multiple summaries maybe computed on any field, including fields derived from user exits & system variables.Summary settings provide format control. Summaries may be referenced in queries.Text Objects : Text objects represent the physical layout of the report. Text objects areused to manipulate positions of fields & summaries. Customize text. Add pagenumbering. Changes made on field, group & summary setting screens are reflected on allassociated text objects that have not been edited. Text object changes are not dynamicallyreflected in field, group & summary settings.Parameters : Parameters contain default values that can be modified for each report orwith each interactive run. Parameters may be placed in queries, user exits & text. Thedefault parameter value, width & data type applying to a report may be changed on theparameter screen. Parameters may be selected for appearance or may be changed at run-time on the run-time parameter form. Parameters may be entered from the command linewith the sqlrep or runrep command.System Parameters provide production control. They are DESTYPE-Device type i.e.Screen, File, Printer, Sysout & Mail. DESNAME-Destination of report i.e. File name,Printer name & Oracle*Mail user id or user list. DESFORMAT-Printer format (usedwhen sending the report to a file, printer, stream, or Oracle*Mail). COPIES-Number ofcopies to print (used when sending the report to the printer). CURRENCY-Symbols touse for the dollar sign. THOUSANDS-Symbol to use for the comma. DECIMAL-Symbolto use for the period.Query Parameters can be created to specify data for the report at run-time.

  • 7/29/2019 Pl SQL Interview Qns

    27/182

    Bind Parameter binds in a specific value when the query is run. To create a bindparameter Include the parameter in the SELECT statement; precede the name with acolon. Specify a default value on the parameter screen, or enter the value at run-time.Lexical Parameter : Insert a SQL clause when the query is run. May be used to replaceWHERE, GROUP BY, ORDER BY, HAVING, CONNECT WITH, START WITH

    clauses. To create a lexical parameter Create a new record on the parameter screen. Enterthe parameter name, data type & width. Enter the default value (SQL clause) on theParameter screen. Include the parameter in the SELECT statement; precede the parametername with &. Use the default value, or specify the value at run-time.SQL*ReportWriter Utilities : SQLREP - Program used to design reports. GENREP -Generates a runfile for a report that has not been executed via the Action menu. RUNREP- Runs the reports (stored as runfiles) & creates final output. May be loaded on systemswithout SQLREP to produce reports. DUMPREP - Creates an ASCII file containingreport definitions. LOADREP - Loads report definitions into an ORACLE database.PRINTDEF - Creates printer definitions. TERMDEF - Created terminal definitions.MOVEREP - SQL*ReportWriter V1.0 to V1.1 conversion program.

    Matrix Reports : A matrix report has the following characteristics :Matrix report is a grid containing three sets of data. Matrix Report require exactly threequeries: two parents & one child. Each query has only one group. Each group must beidentified as a matrix group. Print direction is Down for one group, Across for one group,and Cross tab for the third (the group of the child query). Summaries are placed bydefault in the group subfoots of the print group.

    PRO*C :Oracle Precompiler is a programming tool that allows to embed SQL statements in a highlevel source program. Precompiler accepts the source program as input, translates theembedded SQL statements into standard Oracle runtime library calls & generates amodified source program that can be compiled, linked & executed in the normal way.Why use Precompiler : It allows to pack the power & flexibility of SQL into applicationprograms. A convenient, easy to use interface lets your application access Oracle directly.Help to fine tune the application & saves time because the precompiler & not the usertranslates each embedded SQL statement into several native language Oracle calls.Oracle Precompilers are full featured tools that support professional approach toembedded SQL programming. FIPS flagger helps to develop portable applications & toidentify nonconforming SQL elements.Embedded SQL Statements are divided intoExecutable DeclarativeCall to runtime library SQLLIB To declare Oracle objects, communication areas & SQLvariables.Connect to Oracle, to define query & manipulate data, to control access to data & toprocess transactions. Placed wherever host language host language executable statementscan be placed. Placed wherever host language declarations can be placed.For SQL statements, begin with keywords EXEC SQL & end with SQL statementterminator. For PL/SQL block, begin with EXEC SQL EXECUTE & END EXEC.Host Variables are key to communication between Oracle and the program. Host variableis a scalar or array variable declared in the host language & shared with Oracle. Program

  • 7/29/2019 Pl SQL Interview Qns

    28/182

    uses i/p host variable to pass data to Oracle. Oracle uses o/p host variable to pass data &status info to the program. In SQL statements, the variable are prefixed with a colon.Indicator Variables is an integer variable that indicates the value or condition of its hostvariable. Use indicator variable to assign nulls to i/p host variable & to detect nulls ortruncated values in o/p host variables.

    Oracle Precompiler offers two error handling mechanisms :SQLCA is a data structure copied into your host program. It defines program variablesused by Oracle to pass run time status info to the program. E.g. Check to see if a Deletewas successful & how many rows were deleted. SQLCA is used to provide diagnosticchecking & event handling.ORACA is a data structure copied into your host program to handle ORACLE specificcommunications. When we need more run time info than SQLCA provides, we useORACA. ORACA helps to monitor PRO*C programs use of ORACLE resources such asSQL statement executor & the cursor cache, an area of memory reserved for memorymanagement.SQLDA is a structure copied into your host program to process dynamic SQL statements

    that contains unknown number of select-list items or place holders for bind variables.Whenever, we can specify actions to be taken automatically when oracle detects an erroror warning condition. Actions include continuing with the next statement, calling asubroutine, branching to a labeled statement.Precompiling adds a step to the traditional development process, but it lets to write veryflexible applications.PL/SQL blocks can be embedded in PRO*C. Stored Procedures can be called fromPRO*C. Pointers can be used in PRO*C but it can't be used in SQL statements.VARCHAR implementation in C after Precompilation : For most applications, use Cpseudo type VARCHAR instead of standard C character arrays because Oracle does notnull terminate strings. After precompilation, expands the Varchar declaration into astructure with array & length number.Data Type Equivalencing is conversion from Oracle to C data type.

    SQL*DBA :Auditing : To aid in the investigation of suspicious db use. Statement Auditing is theauditing of specific SQL statements. Privilege Auditing is the auditing of the use ofpowerful system privileges. Object Auditing is the auditing of access to specific schemaobjects.Audit Trial : Results of audited operations are stored in a table in data dictionary.Physical DB Structure : ORACLE db consists of atleast one or more data files, two ormore redo log files & one or more control files. The files of a db provide the actualphysical storage for db info.Logical DB Structure : ORACLE db consists of one or more tablespaces, the dbschema??s objects (i.e. tables, views, indexes, clusters, sequences, sp). Tablespaces,Segments, Extents dictate how physical space of a db is used.Tablespaces : A db is divided into logical storage units called TS. TS is used to grouprelated logical structures together. Each db is logically divided into one or more TS. Oneor more data files are explicitly created for each TS to physically store the data of alllogical structures in a TS. Combined size of the data file is the total storage capacity of

  • 7/29/2019 Pl SQL Interview Qns

    29/182

    TS. Combined storage capacity of the TS??s is the total storage capacity of the db.Online & Offline TS : A TS can be online (accessible) or offline (not accessible). A TScan be offline to make portion of the db unavailable while allowing normal access for theremainder of the db to make administrative tasks easier.Schema is a collection of objects. Schema Objects are the logical structures that directly

    refer to the db??s data. Schema objects includes tables, views, sequences, synonyms,stored procedures, indexes, clusters & db links. No relation between ts & schema.Objects in same schema can be in diff. ts & vice versa.Index Clusters are group of one or more tables physically stored together because theyshare common columns & are often used together. The related columns of the tables in acluster is called cluster key. The data in a cluster key of an index cluster is store onlyonce for multiple tables, so disk access time improves.Hash Clusters : Also cluster table data in a manner similar to normal cluster. A row isstored in a hash cluster based on the result of applying a hash function to the row??scluster key value. All rows with the same hash key value are stored together on disk.Hash clusters are better than using indexed table or indexed clusters when a table is

    queried with equality queries. For such queries, the specified cluster key is hashed. Theresulting hash key value points directly to the area on disk that stores the specified rows.Database Links is a name object that describes a path from one db to another. DB linksare implicitly used when a reference is made to a global object name in a distributed db.Data Blocks : At the finest level of granularity, an ORACLE db??s data is stored in datablocks. One data block corresponds to a specific number of bytes of physical db space ona disk. A data block size is specified when the db is created. A db uses & allocates freedb space in ORACLE data blocks.Extents is the next level of logical db space. An extent is a specific number of contiguousdata blocks, obtained in a single allocation, used to store a specific type of info.Segments is the next level of logical db storage above extent. A segment is a set ofextents allocated for a certain logical structure. Different types areData Segment : Each non clustered table has a data segment. All the table??s data isstored in the extents of its data segment. Each cluster has a data segment.Index Segment : Each index has a index segment that stores all of its data.Rollback Segment : One or more rollback segments are created by the db administratorfor a db to temporarily store undo info.Temporary Segments are created by ORACLE when a SQL statement needs a temporarywork area to complete execution. When the statement finishes execution, the temp.segments extents are returned to the system for future use. ORACLE allocates space forall types of segments in extents. Therefore, when the existing extents of a segment arefull, ORACLE allocates another extent for that segment as needed. Because extents areallocated as needed, the extents of a segment may or may not be contiguous on disk.Data Files : ORACLE db should have atleast one or more physical data files. It containsall db data. A data file can be associated with only one db. Once created, a data filecannot change in size. One or more data files form a logical unit of db storage called atablespace.Redo Log Files : ORACLE db should have atleast two or more redo log files. The set ofredo log files for a db is collectively known as the db??s redo log. The primary functionis to record all changes made to data. Should a failure prevent modified data from being

  • 7/29/2019 Pl SQL Interview Qns

    30/182

    permanently written to the data files, the changes can be obtained from redo log & workis never lost. Redo Log files are critical in protecting a db against failures. To protectagainst a failure involving the redo log itself, ORACLE allows a mirrored redo log so thattwo or more copies of the redo log can be maintained in diff. disks.The use of Redo Log Files : The info in redo log file is used only to recovered the db

    from a system or media failure that prevents db data from being written to a db??s datafiles.Rolling Forward is the process of applying the redo log during a recovery operation.Control Files : ORACLE db should have atleast one control file. A control file recordsthe physical structure of the db. It contains db name, names & locations of db??s data &redo log files & time stamp of db creation. Control files can be mirrored for protection ofcontrol files.The use of Control Files : Every time an instance of an ORACLE db is started, its controlfile is used to identify the db & the redo log files that must be opened for db operation toproceed. DB??s control file is also used if db recovery is necessary.Data Dictionary : ORACLE db should have a data dictionary. The data dictionary of a

    ORACLE DB is a set of tables & views that are used as a read only reference about thedb. It stores info about physical & logical structure of db. It also stored the info aboutvalid users of an ORACLE db, info about integrity constraints defined for tables in the db& how much space is allocated for a schema object and how much of it is being used. DDis created when a db is created. The dd is critical to the operation of the db, which relieson the dd to record, verify and conduct ongoing work.ORACLE has three basic memory structures to function - System Global Area (SGA),Program or Process Global Area (PGA) & Context Areas.SGA is a shared memory region allocated by ORACLE that contain data & control infofor one Oracle db instance. It is written to only by RDBMS processes. SGA & OracleBackground processes make up an Instance. SGA is allocated when an instance starts anddeallocated when the instance is shut down. Data in SGA is shared among all userscurrently connected to the database. For optimal performance, the entire SGA should beas large as possible, to store as much data in memory as possible & minimize disk I/O.Most Oracle servers support only one Instance per Server. SGA contains DatabaseBuffers, Redo Log Buffers & Shared Pool. These areas have fixed sizes are created at theinstance startup.DB Buffers Cache of the SGA store the most recently used blocks of db data; the set ofdb buffers in an instance is the db buffer cache. These buffers can contain modified datathat has not been permanently written to the disk. Because the most recently used is keptin memory, less disk I/O is necessary and performance is increased. It consists of twoblocks Data Segment Block & Rollback Segment Block.During the course of transaction, changes to data are not written to the database file butthese steps take place (a) Each statement executed in the transaction modifies theappropriate data segment block in the DB pool buffer. (b) Info that can be used to undothe transaction is stored in a Rollback block in the db buffer pool. (c) A record of eachchange made to Data & Rollback block is entered in a Redo Log Buffer. Whentransaction is committed, info in the redo log buffer is written to Redo Log File which areused in Recovery operations.Redo Log Buffer of the SGA stores redo entries - a lot of changes made to the db. The

  • 7/29/2019 Pl SQL Interview Qns

    31/182

    redo entries stored in the redo log buffers are written to an online redo log file, which isused if db recovery is necessary. It size is static.Shared Pool is a portion of the SGA that contains shared memory constructs such asShared SQL areas. A shared SQL area is required to process every unique SQL statementsubmitted to a db. It contains info such as the parse tree and execution plan for the

    corresponding statement. A single shared SQL areas is used by multiple applns. that issuethe same statement, leaving more shared memory for other uses.PGA is a memory buffer that contains data & control info for a single client process.PGA is allocated on the server for each client that connects to the server. It contains infoabout connection & maintains info so that user can communicate with oracle. PGAincludes Context Areas. PGA is a writeable, non-shared memory area. It is exclusive tothe user processes & is read & written only by Oracle processes acting on behalf of theuser.Context Areas is a memory buffer of the Server that contains the current status of oneSQL statement.Virtual Memory is an OS feature that offers more apparent memory than is provided by

    real memory. Simulates memory by swapping RAM & Secondary storage.Processes is a mechanism in an OS that can execute a series of steps. Some OS uses theterms job or tasks. A process normally has its own memory area in which it runs. It hastwo general type of processesUser (Client) Processes is created and maintained to execute the software code of anappln. program (Pro*C) or an ORACLE tool (SQL*DBA). It also manages thecommunication with the server process thro?? program interface.ORACLE Processes are called by other processes to perform functions on behalf of theinvoking process. Diff. types of Oracle processes areServer Processes : ORACLE creates server processes to handle requests from connecteduser processes. A server process is in charge of communicating with the user process andinteracting with ORACLE to carry out requests of the associated user process. Can beconfigured to vary the number of user processes per server processIn a dedicated server config, a server process handles requests for a single user process. Amulti threaded config. allows many user process to share a small number of serverprocesses, minimizing the number of server processes and maximizing the utilization ofavailable system resources & the user and server processes should be separate.Background Process : ORACLE creates a set of background processes for each instance.They consolidate functions that would otherwise handled by multiple ORACLE programsrunning for each user process. They asynchronously perform I/O & monitor otherORACLE processes to provide increased parallelism for better performance & reliability.BG processes are given below.Database Writer (DBWR) processes writes modified blocks from the database buffercache to the database files. Blocks are written in proper order to maintain databaseintegrity. DBWR is optimized to minimize disk writes. DBWR writes only when moredata needs to be read into the SGA and too few db buffers free. The least recently useddata is written to the data files first.Log Writer (LGWR) processes writes redo log entries to disk when transaction iscommitted & the log buffer fills. Redo Log data is generated in the redo log buffer of theSGA.

  • 7/29/2019 Pl SQL Interview Qns

    32/182

    Checkpoint (CKPT) : At specific times, all modified db buffers in the SGA are written tothe data files by