Complete SQL Commands PR
Complete SQL Commands PR
3. What is a Tablespace?
A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to
grouped related logical structures together.
6. What is schema?
A schema is collection of database objects of a User.
The Information in a redo log file is used only to recover the database from a system or media
failure prevents database data from being written to a database's data files.
40. Can an Integrity Constraint be enforced on a table if some existing table data does not
satisfy the constraint?
No.
42. What is difference between UNIQUE constraint and PRIMARY KEY constraint?
A column defined as UNIQUE can contain Nulls while a column defined as PRIMARY KEY can't
contain Nulls.
56. What are the Referential actions supported by FOREIGN KEY integrity constraint?
UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion of
referenced data.
DELETE Cascade - When a referenced row is deleted all associated dependent rows are deleted.
59. What is the maximum number of CHECK constraints that can be defined on a column?
No Limit.
SYSTEM ARCHITECTURE:
2. What is SGA?
The System Global Area (SGA) is a shared memory region allocated by ORACLE that contains data
and control information for one ORACLE instance.
8. What is Cursor?
A Cursor is a handle (a name or pointer) for the memory associated with a specific statement.
9. What is PGA?
Program Global Area (PGA) is a memory buffer that contains data and control information for a
server process.
Archiver (ARCH) copies the on-line redo log files to archival storage when they are full. ARCH is
active only when a database's redo log is used in ARCHIVELOG mode.
Recover (RECO) is used to resolve distributed transactions that are pending due to a network or
system failure in a distributed database. At timed intervals, the local RECO attempts to connect to remote
databases and automatically complete the commit or rollback of the local portion of any pending
distributed transactions.
DATA MANIPULATION
8. What are the different approaches used by Optimizer in choosing an execution plan?
Rule-based and Cost-based
9. What are the factors that affect OPTIMIZER in choosing an Optimization approach?
The OPTIMIZER_MODE initialization parameter Statistics in the Data Dictionary the
OPTIMIZER_GOAL parameter of the ALTER SESSION command hints in the statement.
10. What are the values that can be specified for OPTIMIZER MODE Parameter?
COST and RULE
11. Will the Optimizer always use COST-based approach if OPTIMIZER_MODE is set to "Cost'?
Presence of statistics in the data dictionary for at least one of the tables accessed by the SQL
statements is necessary for the OPTIMIZER to use COST-based approach. Otherwise OPTIMIZER chooses
RULE-based approach.
13. What are the values that can be specified for OPTIMIZER_GOAL parameter of the ALTER
SESSION Command?
CHOOSE, ALL_ROWS, FIRST_ROWS and RULE.
14. What is the effect of setting the value "CHOOSE" for OPTIMIZER_GOAL, parameter of the
ALTER SESSION Command?
The Optimizer chooses Cost based approach and optimizes with the goal of best throughput if
statistics for at least one of the tables accessed by the SQL statement exist in the data dictionary.
Otherwise the OPTIMIZER chooses RULE based approach.
15. What is the effect of setting the value "ALL_ROWS” for OPTIMIZER_GOAL parameter of
the ALTER SESSION command?
This value causes the optimizer to the cost-based approach for all SQL statements in the session
regardless of the presence of statistics and to optimize with a goal of best throughput.
16. What is the effect of setting the value ‘FIRST_ROWS’ for OPTIMIZER_GOAL parameter
of the ALTER SESSION command?
This value causes the optimizer to use the cost-based approach for all SQL statements in the
session regardless of the presence of statistics and to optimize with a goal of best response time.
17. What is the effect of setting the 'RULE' for OPTIMIER_GOAL parameter of the ALTER
SESSION Command?
This value causes the optimizer to choose the rule-based approach for all SQL statements in a
session regardless of the presence of statistics.
1. What are the different types of PL/SQL program units that can be defined and stored in
ORACLE database?
Procedures and Functions, Packages and Database Triggers
2. What is a Procedure?
A Procedure consist of a set of SQL and PL/SQL statements that are grouped together as a unit to
solve a specific problem or perform a set of related tasks.
4. What is a Package?
A Package is a collection of related procedures, functions, variables and other package
constructs together as a unit in the database.
8. What are the differences between Database Trigger and Integrity constraints?
A declarative integrity constraint is a statement about the database that is always true. A
constraint applies to existing data in the table and any statement that manipulates the table.
A trigger does not apply to data loaded before the definition of the trigger; therefore, it does not
guarantee all data in a table conforms to the rules established by an associated trigger.
A trigger can be used to enforce transitional constraints where as a declarative integrity constraint
cannot be used.
DATABASE SECURITY
SELECTIVE AVAILABILITY OF PRIVILEGES - The roles granted to a user can be selectively enable
(available for use) or disabled (not available for use). This allows specific control of a user's privileges in
any given situation.
4. What is a profile?
Each database user is assigned a Profile that specifies limitations on various system resources
available to the user.
5. What are the system resources that can be controlled through Profile?
The number of concurrent sessions the user can establish the CPU processing time available to
the user's session the CPU processing time available to a single call to ORACLE made by a SQL statement
the amount of logical I/O available to the user's session the amount of logical I/O available to a single call
to ORACLE made by a SQL statement the allowed amount of idle time for the user's session the allowed
amount of connect time for the user's session.
6. What is Auditing?
Monitoring of user access to aid in the investigation of database use.
Commit - Phase - If all participants respond to the coordinator that they are prepared, the
coordinator asks all nodes to commit the transaction, if all participants cannot prepare, and the
coordinator asks all nodes to roll back the transaction.
5. What is a SNAPSHOT?
Snapshots are read-only copies of a master table located on a remote node which is periodically
refreshed to reflect changes made to the master table.
4. What are the different modes of mounting a Database with the Parallel Server?
Exclusive Mode If the first instance that mounts a database does so in exclusive mode, only that
Instance can mount the database.
Parallel Mode If the first instance that mounts a database is started in parallel mode, other
instances that are started in parallel mode can also mount the database.
No.
11. What are the advantages of operating a database in ARCHIVELOG mode over operating it in
NO ARCHIVELOG mode?
Complete database recovery from disk failure is possible only in ARCHIVELOG mode.
Online database backup is possible only in ARCHIVELOG mode.
Rolling back transactions that have been explicitly rolled back or have not been committed as
indicated by the rollback segments regenerated in step a.
Releasing any resources (locks) held by transactions in process at the time of the failure.
Resolving any pending distributed transactions undergoing a two-phase commit at the time of the
instance failure.
DATABASE ADMINISTRATION
Introduction to DBA
1. What is a Database instance? Explain
A database instance (Server) is a set of memory structure and background processes that access
a set of database files.
he memory structure that are used to store most queried data from database. This helps
up to improve database performance by decreasing the amount of I/O performed against data file.
3. What is a Schema?
The set of objects owned by user account is called the schema.
These locks will be released automatically when a commit/rollback operation performed or any
one of these processes being killed externally.
MEMORY MANAGEMENT
1. What is SGA? How it is different from Ver 6.0 and Ver 7.0?
The System Global Area in a Oracle database is the area in memory to facilitates the transfer of
information between users. It holds the most recently requested structural information between users. It
holds the most recently requested structural information about the database. The structure is Database
buffers, Dictionary cache, and Redo Log Buffer and Shared SQL pool (ver. 7.0 only) area.
5. What are the factors causing the reparsing of SQL statements in SGA?
Due to insufficient Shared SQL pool size.
Monitor the ratio of the reloads takes place while executing SQL
statements. If the ratio is greater than 1 then increase the SHARED_POOL_SIZE.
10. How will you swap objects into a different table space for an existing database?
Export the user
Run the script newfile.sql after altering the tablespaces. Import from the backup for the necessary
objects.
1. List the Optional Flexible Architecture (OFA) of Oracle database? Or how can we organise the
tablespaces in Oracle database to have maximum performance?
4. How free extents are managed in Ver. 6.0 and Ver. 7.0?
Free extents cannot be merged together in Ver. 6.0.Free extents are periodically coalesces with
the neighboring free extent in Ver. 7.0
5. Which parameter in Storage clause will reduce no. of rows per block?
PCTFREE parameter
Row size also reduces no of rows per block.
Deactivate Rollback Segment R0 and activate the newly created rollback segments.
13. How the space utilization takes place within rollback segments?
It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an extent is
in use then it forced to acquire a new extent (No. of extents is based on the optimal size)
A single transaction may wipeout all available free space in the Rollback Segment Tablespace.
This prevents other user using Rollback segments.
Transaction Begins.
An entry is made in the RES header for new transactions entry. Transaction acquires blocks in an
extent of RBS
The entry attempts to wrap into second extent. None is available, so that the RBS must extent.
18. How will you estimate the space required by non-clustered tables?
Calculate the total header size
Calculate the available dataspace per data block
Calculate the combined column lengths of the average row
Calculate the total average row size.
Calculate the average number rows that can fit in a block
Calculate the number of blocks and bytes required for the table.
After arriving the calculation, add 10 % additional space to calculate the initial extent size for a
working table.
19. Is possible to use raw devices as data files and what are the advantages over file. System files?
Yes.
I/O will be improved because Oracle is bye-passing the kernel which writing into disk.
Disk Corruption will be very less.
21. How to implement the multiple control files for an existing database?
Shutdown the databse
Copy one of the existing control file to new location
Edit Config ora file by adding new control file.name
Restart the database.
22. What is meant by Redo Log file mirrorring ? How it can be achieved?
Process of having a copy of redo log files is called mirroring.
This can be achieved by creating group of log files together, so that LGWR will automatically
writes them to all the members of the current on-line redo log group. If any one group fails then database
automatically switch over to next group. It degrades performance.
Improved performance because most OS support volume shadowing can direct file I/O request to
use the shadow set of files instead of the main set of files. This reduces I/O load on the main set of disks.
Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads.
The tar command cannot be used for physical file backup, instead we can use dd command which
is less flexible and has limited recoveries.
28. List the factors that can affect the accuracy of the estimations?
The space used transaction entries and deleted records do not become free immediately after
completion due to delayed cleanout.
Inserts of, updates to and deletes of rows as well as columns larger than a single datablock, can
cause fragmentation a chained row pieces.
Instead grant the ability to access the procedures that access the tables.
When procedure executed it will execute the privilege of procedures owner. Users cannot access
tables except via the procedure.
5. What are the roles and user accounts created automatically with the database?
DBA - role contains all database system privileges.
SYS user account - The DBA role will be assigned to this account. All of the basetables and views
for the database's dictionary are store in this schema and are manipulated only by ORACLE.
SYSTEM user account - It has all the system privileges for the database and
additional tables and views that display administrative information and
internal tables and views used by oracle tools are created using this username.
SQL * Loader - It loads data from standard operating system files (Flat files) into ORACLE
database tables.
Export (EXP) and Import (imp) utilities allow you to move existing data in ORACLE format to and
from ORACLE database.
7. What are the minimum parameters should exist in the parameter file (init.ora)?
DB NAME - Must set to a text string of no more than 8 characters and it will be stored inside the
datafiles, redo log files and control files and control file while database creation.
DB_DOMAIN - It is string that specifies the network domain where the database is created. The
global database name is identified by setting these parameters (DB_NAME & DB_DOMAIN)
CONTORL FILES - List of control filenames of the database. If name is not mentioned then default
name will be used.
Assign each role to group of users. This will simplify the job of assigning privileges to individual
users.
1. What are the steps to switch a database's archiving mode between NO ARCHIVELOG
and ARCHIVELOG mode?
3. How can we specify the Archived log file name format and destination ?
A Transaction is a logical unit of work that comprises one or more SQL statements executed by a
single user.
- To collect statistics about object used by the optimizer and store them in the data dictionary.
- To delete statistics about the object used by object from the data dictionary.
- To validate the structure of the object.
- To identify migrated and chained rows of the table or cluster.
A flag to indicate whether a read consistent version of all the exported objects should be
maintained.
The name of the file which log of the export will be written.
A flag to indicate whether the import should ignore errors encounter when issuing CREATE
commands.
A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database
objects will be exectued.
Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT.
Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT.
Transactional Control: COMMIT & ROLLBACK
Session Control: ALTERSESSION & SET ROLE
System Control: ALTER SYSTEM.
2. What is a transaction ?
Transaction is logical unit between two commits and commit and rollback.
TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database triggers do
not fire on TRUNCATE
DELETE allows the filtered deletion. Deleted records can be rolled back or committed.
Database triggers fire on DELETE.
Join is a query which retrieves related columns or rows from multiple tables.
Subquery is a query whose return values are used in filtering conditions of the main query.
INSTR (String1,String2(n,(m)),
INSTR returns the position of the mth occurrence of the string 2 in string1. The search begins
from nth position of string1.
2. What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 character long, blockno,
rownumber are the components of ROWID.
8. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for
each type?
CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For
CHAR it is 255 and 2000 for VARCHAR2.
9. How many LONG columns are allowed in a table? Is it possible to use LONG columns in
WHERE clause or ORDER BY?
Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY
clause.
To Modify the datatype of a column the column must be empty.To add a column with NOT NULL
constrain, the table must be empty.
13. If an unique key constraint on DATE column is created, will it validate the rows that are
inserted with SYSDATE?
It won't, Because SYSDATE format contains time attached with it.
16. How to access the current value and next value from a sequence? Is it possible to access
the current value in a session before accessing next value?
Sequence name CURRVAL, Sequence name NEXTVAL.
It is not possible. Only if you access next value in the session, current value can be accessed.
20. If a View on a single base table is manipulated will the changes be reflected on the base
table?
If changes are made to the tables which are base tables of a view will the changes be reference
on the view.
FORMS BASIC
3. Name the two files that are created when you generate the form give the file extension ?
INP (Source File)
FRM (Executable File)
BLOCK
5. Committed block sometimes refer to a BASE TABLE? True or False.
False.
6. Can we create two blocks with the same name in form 3.0?
No.
7. While specifying master/detail relationship between two blocks specifying the join condition
is a must? True or False.
True.
Database
A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is
designed, built and populated with data for a specific purpose
DBMS
It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that
provides the users with the processes of defining, constructing and manipulating the database for various applications.
Database system
Advantages of DBMS?
Ø Redundancy is controlled.
Ø Unauthorized access is restricted.
Ø providing multiple user interfaces.
Ø Enforcing integrity constraints.
Ø Providing backup and recovery.
Ø Physical level: The lowest level of abstraction describes how data are stored.
Ø Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those
data.
Ø View level: The highest level of abstraction describes only part of entire database.
Data Independence
Data independence means that ―the application is independent of the storage structure and access strategy of data‖. In other words,
The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Ø Physical Data Independence: Modification in physical level should not affect the logical level.
Ø Logical Data Independence: Modification in logical level should affect the view level.
A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or
more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data
dictionary.
Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth
in the database. Hence accounts for logical data independence.
Data Model
A collection of conceptual tools for describing data, data relationships data semantics and constraints.
4. A collection of conceptual tools for describing data, data relationships data semantics and constraints.
a)data model
b)E-R model
c)object oriented model
d)none
5. This data model is based on real world that consists of basic objects called entities and of relationship among these
objects
a)data model
b)E-R model
c)object oriented model
d)none
7. A data base schema that is specified by a set of definitions expressed by a special language is called
a)DDL
b)VDL
c)DML
d)SDL
9. The process of analyzing the given relation schemas based on their Functional Dependencies is known as
a)Dependency
b)normalization
c)both a and b
d)none
10. A relation schema R is in ____ if it is in 1NF and every non-prime attribute, A in R is fully functionally dependent on
primary key.
a)1 NF
b)2 NF
c)3 NF
d)BCNF
11. A relation schema R is in ____ if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a
candidate key
a)1 NF
b)2 NF
c)3 NF
d)BCNF
12. The set of attributes that can uniquely identify weak entities and that are related to same owner entity is
a)Partial key
b)alternate key
c)artificial key
d)compound key
13. All Candidate Keys excluding the Primary Key are known as ___
a)Partial keys
b)alternate keys
c)artificial keys
d)compound keys
14. When one of the data elements stored within a construct is utilized as the primary key, then it is called the?
a)alternate key
b)natural key
c)compound key
d)partial key
15. The technique for determining how quickly specific data can be found is known as__
a)normalization
b)data manipulating
c)indexing
d)none of these
17. The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to
as
a)query generation
b)query optimization
c)dependency
d)redundancy
18. The concept which is used to model a relationship between a collection of entities and relationships...
a)atomicity
b)aggregation
c)deadlock
d)both a and b
19. By taking ______, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes
a)dead lock
b)atomicity
c)aggregations
d)checkpoints
21. Concatenation of every row in one relation with every row in another
a)product
b)join
c)insertion
d)none of these
22. Concatenation of rows from one relation and related rows from another
a)product
b)join
c)insertion
d)none of these
25. _____is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table
a)database
b)database trigger
c)both a and b
d)none of these
32. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By CUSTOMER Union Select 'EAST',
CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMER
The above is
a) Not an error
b) Error - the string in single quotes 'NORTH' and 'SOUTH'
c) Error - the string should be in double quotes
d) Error - ORDER BY clause
33. _____is a program module that provides the interface between the low-level data stored in database, application programs
and queries submitted to the system
a)storage manager
b)buffer manager
c)transaction manager
d)file manager
34. ____is a program module, which is responsible for fetching data from disk storage into main memory and deciding what
data to be cache in memory
a)storage manager
b)buffer manager
c)transaction manager
d)file manager
35. ____is a program module, which ensures that database, remains in a consistent state despite system failures and
concurrent transaction execution proceeds without conflicting
a)storage manager
b)buffer manager
c)transaction manager
d)file manager
36. _______is a program module, which manages the allocation of space on disk storage and data structure used to represent
information stored on a disk
a)storage manager
b)buffer manager
c)transaction manager
d)file manager
37. copying the three sets of files (database files, redo logs, and control file) when the instance is shut down is known as ____
a)cold backup
b)hot backup
38. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
a)DDL
b)DML
c)VDL
d)DSL
39. What operator performs pattern matching?
a)LIKE
b)NULL
c)NOT NULL
d)IS NULL
40. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES',
'NO' );
a)1
b)YES
c)NO
d)YESNO
RDBMS Concepts
1. What is database?
A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is
designed, built and populated with data for a specific purpose.
2. What is DBMS?
It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that
provides the users with the processes of defining, constructing and manipulating the database for various applications.
4. Advantages of DBMS?
Redundancy is controlled.
Unauthorized access is restricted.
Providing multiple user interfaces.
Enforcing integrity constraints.
Providing backup and recovery.
Physical level: The lowest level of abstraction describes how data are stored.
Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire database.
Entity Integrity: States that ―Primary key cannot have NULL value‖
Referential Integrity: States that ―Foreign Key can be either a NULL value or should be Primary Key value of other relation.
Extension - It is the number of tuples present in a table at any instance. This is time dependent.
Intension - It is a constant value that gives the name, structure of table and the constraints laid on it.
System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose
was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with
performance at least comparable to that of existing system.
Its two subsystems are
Research Storage
System Relational Data System.
10. How is the data structure of System R different from the relational structure?
Data independence means that ―the application is independent of the storage structure and access strategy of data‖. In other words,
The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.
Physical Data Independence: Modification in physical level should not affect the logical level.
Logical Data Independence: Modification in logical level should affect the view level.
NOTE: Logical Data Independence is more difficult to achieve
A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or
more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data
dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring
and growth in the database. Hence accounts for logical data independence.
A collection of conceptual tools for describing data, data relationships data semantics and constraints.
14. What is E-R model?
This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are
described in a database by a set of attributes.
This model is based on collection of objects. An object contains values stored in instance variables with in the object. An object
also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values
and the same methods are grouped together into classes.
The collections of entities of a particular entity type are grouped together into an entity set.
An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key
of its parent entity, then it is said to be Weak Entity set.
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains. A relation
is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2,
..., vn).
Relationship type defines a set of associations or a relationship set among a given set of entity types.
A data base schema is specifies by a set of definitions expressed by a special language called DDL.
This language is to specify the internal schema. This language may specify the mapping between two schemas.
The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called
data storage-definition language.
This language that enable user to access or manipulate data as organised by appropriate data model.
Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data.
Non-Procedural DML or High level: DML requires a user to specify what data are needed without specifying how to get those data.
It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand.
The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be
Record-at-a-time.
The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is
said to be Set-at-a-time or Set-oriented.
It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation.
It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are
DSL ALPHA, QUEL.
40. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus
The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL
The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g.
ILL, DEDUCE.
It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the
properties
Minimizing redundancy
Minimizing insertion, deletion and update anomalies.
A Functional dependency is denoted by X Y between two sets of attributes X and Y that are subsets of R specifies a constraint
on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] =
t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y.
Every dependency in F has a single attribute for its right hand side. We cannot replace any dependency X->A in F with a dependency
Y->A where Y is a proper subset of X and still have a set of dependency that is equivalent to F. We cannot remove any dependency from F and
still have set of dependency that is equivalent to F.
Multivalued dependency denoted by X->->Y specified on relation schema R, where X and Y are both subsets of R, specifies the
following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the
following properties
t3[x] = t4[X] = t1[X] = t2[X]
t3[Y] = t1[Y] and t4[Y] = t2[Y]
t3[Z] = t2[Z] and t4[Z] = t1[Z]
where [Z = (R-(X U Y)) ]
It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition.
The domain of attribute must include only atomic (simple, indivisible) values.
It is based on concept of full functional dependency. A functional dependency X ->Y is full functional dependency if removal of any
attribute A from X means that the dependency does not hold any more.
A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key.
A relation schema R is in 3NF if it is in 2NF and for every FD X->A either of the following is true
X is a Super-key of R.
A is a prime attribute of R.
In other words, if every non prime attribute is non-transitively dependent on primary key.
A relation schema R is said to be in 4NF if for every Multivalued dependency X->->Y that holds over R, one of following is true
X is subset or equal to (or) XY = R.
X is a super key.
A Relation schema R is said to be 5NF if for every join dependency {R1, R2, ..., Rn} that holds R, one the following is true
Ri = R for some i.
The join dependency is implied by the set of FD, over R in which the left side is key of R.
A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply
enforcing the domain constraint and key constraint on the relation.
54. What are partial, alternate,, artificial, compound and natural key?
Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as
Discriminator.
Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys.
Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a
unique number to each record or occurrence. Then this is known as developing an artificial key.
Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a
unique identifier for the construct is known as creating a compound key.
Natural Key: When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key.
55. What is indexing and what are the different kinds of indexing?
Indexing is a technique for determining how quickly specific data can be found.Types:
Binary search style indexing
B-Tree indexing
Inverted list indexing
Memory resident table
Table indexing
56. What is system catalog or catalog relation? How is better known as?
A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This
information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary.
The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query
optimization.
Join Dependency: A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ..., Rn} is said to hold over a relation R if
R1, R2, R3, ..., Rn is a lossless-join decomposition of R . There is no set of sound and complete inference rules for JD.
Inclusion Dependency: An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns.
A foreign key constraint is an example of inclusion dependency.
Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes
before all its changes are reflected on disk. This property is called durability.
Atomicity: Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS
ensures this by undoing the actions of incomplete transactions.
Aggregation: A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to
express a relationship among relationships.
In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify
deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts.
A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during
restart in the event of subsequent crashes.
It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and
provides user-interface management.
Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a
hierarchical schema uses a tree data structure example for such a system is IMS.
A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be
classified into data definition language and data manipulation language.
Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is
written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is
executed for each row of the parent, this is called a correlated subquery.
A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause.
Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated
subquery.
E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM)
69. What are the primitive operations common to all record management systems?
70. Name the buffer in which all the commands that are typed in are stored
„Edit‟ Buffer
72. Are the resulting relations of PRODUCT and JOIN operation the same?
No.
PRODUCT: Concatenation of every row in one relation with every row in another.
JOIN: Concatenation of rows from one relation and related rows from another.
Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the
system-level data structures used by the kernel to manage the database
You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary
functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges;
manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages
space usage within its table-space structures
I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction
Control, Memory Management, Lock Management
75. Which part of the RDBMS takes care of the data dictionary? How
Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the
kernel.
The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical
storage location.
79. Define SQL and state the differences between SQL and other conventional programming Languages
SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures.
The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations
should be performed rather than how to perform them.
80. Name the three major set of files on disk that compose a database in Oracle
There are three major sets of files on disk that compose a database. All the files are binary. These are
Database files
Control files
Redo logs
The most important of these are the database files where the actual data resides. The control files and the redo logs support the
functioning of the architecture itself. All three sets of files must be present, open, and available to Oracle for any data on the database to be
useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the
database using a backup, if there is one.
The Oracle system processes, also known as Oracle background processes, provide functions for the user processes—functions that
would otherwise be done by the user processes themselves
Oracle database-wide system memory is known as the SGA, the system global area or shared global area. The data and control structures in
the SGA are shareable, and all the Oracle background processes and user processes can use them. The combination of the SGA and the
Oracle background processes is known as anOracle instance
82. What are the four Oracle system processes that must always be up and running for the database to be useable
The four Oracle system processes that must always be up and running for the database to be useable
include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor).
1. What are database files, control files and log files. How many of these files should a database have at least? Why?
Database Files
The database files hold the actual data and are typically the largest in size. Depending on their sizes, the tables (and other objects) for
all the user accounts can go in one database file—but that's not an ideal situation because it does not make the database structure very flexible
for controlling access to storage for different users, putting the database on different disk drives, or backing up and restoring just part of the
database.
You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in the
tables and other objects, the number (or location) of the files is immaterial. The database files are fixed in size and never grow bigger than the
size at which they were created
Control Files
The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you
typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the
location of the database and redo logs, and the synchronization information to ensure that all three sets of files are always in step. Every time
you add a new database or redo log file to the database, the information is recorded in the control files.
Redo Logs
Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user
objects or system objects. If any type of failure occurs, the changes recorded in the redo logs can be used to bring the database to a consistent
state without losing any committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs
automatically without intervention from the DBA.
The redo log files are fixed in size and never grow dynamically from the size at which they were created.
2. What is ROWID?
The ROWID is a unique database-wide physical address for every row on every table. Once assigned (when the row is first inserted
into the database), it never changes until the row is deleted or the table is dropped. The ROWID consists of the following three components, the
combination of which uniquely identifies the physical storage location of the row. Oracle database file number, which contains the block with the
rows Oracle block address, which contains the row
The row within the block (because each block can hold many rows)
The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. Application developers also use it in
SQL statements as a quick way to access a row once they know the ROWID
3. What is Oracle Block? Can two Oracle Blocks have the same address?
Oracle "formats" the database files into a number of Oracle blocks when they are first created—making it easier for the RDBMS
software to manage the files and easier to read data into the memory areas.
The block size should be a multiple of the operating system block size. Regardless of the block size, the entire block is not available for holding
data; Oracle takes up some space to manage the contents of the block. This block header has a minimum size, but it can grow.
These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve performance, but it should be done only
when the database is first created.
Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have the same block address if they are in
different database files.
A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a
table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one
table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written
in PL/SQL.
5. Name two utilities that Oracle provides, which are use for backup and recovery.
Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities
are Export and Import.
The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file.
The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the data
If Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be
recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed.
6. What are stored-procedures? And what are the advantages of using them.
Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL
statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce
network traffic.
7. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name
PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this
mechanism enables execution to continue if the error is not severe enough to cause procedure termination.
The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of
control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If
there are no more executable statements in the block, control returns to the caller.
User-Defined Exceptions
PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming
an exception as in the following example:
ot_failure EXCEPTION;
In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows:
EXCEPTION
when OT_FAILURE then
out_status_code := g_out_status_code;
out_msg := g_out_msg;
The following is an example of a subprogram exception:
EXCEPTION
when NO_DATA_FOUND then
g_out_status_code := 'FAIL';
RAISE ot_failure;
Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the
exception is used to invoke all user-defined exceptions.
System-Defined Exceptions
Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a
complete list of internal exceptions.
In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not
been established.
The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL
does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are
also considered.
PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or
internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the
package name fully qualifies any procedure or function reference.
(a) i & iii because theta joins are joins made on keys that are not primary keys.
(a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since C B is a FD given, where neither C is a Key nor B is a
prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF. Thus the given FDs is in 1NF.
(d) Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS
It is a program module that provides the interface between the low-level data stored in database, application programs and queries
submitted to the system.
It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in
memory.
It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction
execution proceeds without conflicting.
It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data.
Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-
alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools.
Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution.
PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursors
Implicit
Explicit
16. What is cold backup and hot backup (in case of Oracle)?
Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight
file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy.
If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work
performed on the database since the last backup is lost.
Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the
files. The cold backup is not an available option.
So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-
tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making
changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to
copy those files to the desired backup destination.
The database must be running in ARCHIVELOG mode for the hot backup option. If a data loss failure does occur, the lost database files
can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the
most consistent state without any loss of committed transactions.
17. What are Armstrong rules? How do we say that they are complete and/or sound
Reflexive rule :
If Y is subset or equal to X then X Y.
Augmentation rule:
If X Y then XZ YZ.
Transitive rule:
If {X Y, Y Z} then X Z.
Decomposition rule :
If X YZ then X Y.
Union or Additive rule:
If {X Y, X Z} then X YZ.
Pseudo Transitive rule :
If {X Y, WY Z} then WX Z.
Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are
called complete because using these three rules we can generate the rest all inference rules.
18. How can you find the minimal key of relational schema?
Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find
the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency.
Given a relation R and a set of FDs F, dependency preservation states that the closure of the union of the projection of F on each
decomposed relation Ri is equal to the closure of F. i.e.,
((R1(F)) U … U (Rn(F)))+ = F+ if decomposition is not dependency preserving, then some dependency is lost in the decomposition.
Proactive Update: The updates that are applied to database before it becomes effective in real world .
Retroactive Update: The updates that are applied to database after it becomes effective in real world .
Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world .
Equi Join: This is the most common type of join which involves only equality comparisions.
Oracle Sample Programs
declare
v_marks student.marks%type;
v_rno student.rno%type;
begin
select marks,rno into v_marks,v_rno from student where rno=&rno;
else
update student set grade='Fail' where rno=v_rno;
end if;
END;
/
/* Get emp details */
declare
v_ename emp.ename%type;
v_sal emp.salary%type;
begin
select ename,salary into v_ename,v_sal from emp where empno=&empno;
dbms_output.put_line('your name is '||v_ename);
dbms_output.put_line('you are getting ' ||v_sal ||' dollars');
exception
when No_data_found then
dbms_output.put_line('No such employee present');
when too_many_rows then
dbms_output.put_line('Too many records found');
end;
/
declare
mrec emp%rowtype;
begin
select ename,salary into mrec.ename,mrec.salary from emp where empno=&empno;
dbms_output.put_line('your name is '||mrec.ename);
dbms_output.put_line('you are getting ' ||mrec.salary ||' dollars');
exception
when No_data_found then
dbms_output.put_line('No such employee present');
when too_many_rows then
dbms_output.put_line('Too many records found');
end;
/
declare
x number;
begin
for x in 1..10
loop
dbms_output.put_line(x);
end loop;
end;
declare
x number:=1;
begin
while(x<=10)
loop
dbms_output.put_line(x);
x:=x+1;
end loop;
end;
/
Declare
x number:=2;
begin
loop
dbms_output.put_line(x);
x:=x+2;
exit when x = 22;
end loop;
END;
/
declare
eng number;
maths number;
science number;
total number;
per number;
begin
eng:=&englishmarks;
maths:=&mathsmarks;
science:=&sciencemarks;
total:=eng+maths+science;
per:=total/3;
declare
eng number;
maths number;
science number;
total number;
per number;
begin
eng:=&englishmarks;
maths:=&mathsmarks;
science:=&sciencemarks;
total:=eng+maths+science;
per:=total/3;
CURSORS
declare
cursor c1 is select empno,ename,salary from emp order by empno desc;
mrec emp%rowtype;
begin
open c1;
for i in 1..2
loop
fetch c1 into mrec.empno,mrec.ename, mrec.salary;
insert into empdup(empno,ename,salary) values(mrec.empno,mrec.ename, mrec.salary);
exit when c1%notfound;
end loop;
close c1;
end;
/
/* Program to extract top 5 records from the students and insert them into the toppers table */
DECLARE
cursor c1 is select name, grade from student order by marks desc;
mrec student%rowtype;
BEGIN
open c1;
loop
fetch c1 into mrec.name,mrec.grade;
exit when c1%rowcount=5;
insert into toppers (name, grade) values(mrec.name,mrec.grade);
end loop;
close c1;
dbms_output.put_line('Successfully inserted rows in Toppers table');
END;
/
DECLARE
display first name of women of all ages in the People table
CURSOR Get_Women IS
SELECT First_Name FROM People WHERE Gender = 'F';
Then we OPEN it, FETCH it until the EOF, and CLOSE it. These last three operations are done implicitly
by the FOR LOOP --below:
BEGIN
FOR Get_Women_cur IN Get_Women LOOP
DBMS_OUTPUT.PUT_LINE(Get_Women_cur.First_Name);
END LOOP;
END;
/
ISOPEN: Boolean
- is the cursor open or closed?
FOUND:Boolean - did the cursor retrieve a row?
NOTFOUND: Boolean - The reverse of FOUND. TRUE when a row could not be retrieved.
ROWCOUNT: NUMBER, which row is it? 1st, 2nd, etc. This is not the equivalent of a RecordCount in the
dynaset or Recordset. This is actually the current record number.
Using these indicators, we can control the loop:
DECLARE
display first name of women of all ages in the PEOPLE table
CURSOR Get_Women IS
SELECT First_Name FROM People WHERE Gender = 'F';
Name_Rec Get_Women%ROWTYPE;
BEGIN
OPEN Get_Women;
LOOP
FETCH Get_Women INTO Name_Rec;
EXIT WHEN Get_Women%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(Name_Rec.First_Name);
END LOOP;
CLOSE Get_Women;
END;
/
begin
c:=a+b;
dbms_output.put_line('The sum is :' || c);
end;
/
The oracle engine performs the following steps to execute a procedure or function....Verifies user
access, Verifies procedure or funtion validity and executes the procedure or function. Some of the advantages of
using procedures and functions are: security, performance, memory allocation, productivity, integrity.
Most important the difference between procedures and functions: A function must return a value back to
the caller. A function can return only one value to the calling pl/sql block. By defining multiple out parameters
in a procedure, multiple values can be passed to the caller. The out variable being global by nature, its value is
accessible by any pl/sql code block including the calling pl/sql block.
CREATE OR REPLACE PROCEDURE [schema] procedure name (argument {IN, OUT, IN OUT} data type,
..) {IS, AS}
variable declarations; constant declarations; BEGIN
pl/sql subprogram body;
EXCEPTION
exception pl/sql block;
END;
CREATE OR REPLACE FUNCTION[schema] functionname(argument IN data type, ..) RETURN data type
{IS, AS}
variable declarations; constant declarations; BEGIN
pl/sql subprogram body;
EXCEPTION
exception pl/sql block;
END;
The above syntax i think is self explainatory...but i will give u some details...IN : specifies that a value
for the argument must be specified when calling the procedure or function. argument : is the name of an
argument to the procedure or function. parentheses can be omitted if no arguments are present. OUT : specifies
that the procedure passes a value for this argument back to its calling environment after execution. IN OUT :
specifies that a value for the argument must be specified when calling the procedure and that the procedure
passes a value for this argument back to its calling environment after execution. By default it takes IN. Data
type : is the data type of an argument.
CREATE A PROCEDURE THAT DELETE ROWS FROM ENQUIRY WHICH ARE 1 YRS BEFORE
CREATE A PROCEDURE THAT TAKES ARGUMENT STUDENT NAME AND FIND OUT FEES PAID BY
THAT STUDENT
SUM OF 2 NOS
DELETION PROCEDURE
declare
a number;
b number;
begin
sample(3000, b)
dbms_output.put_line(1th value of b is 11 b);
end ;
declare
sal1 number := 7999;
begin
getsal(sal1);
dbms_output.put_line('The employee salary is' || sal1);
end ;
u can make a procedure and functions similarly.....also if u wanna drop a function then use drop
function functionname and for procedure use drop procedure procedurename
Here is a procedure that will get the first names of the women:
PROCEDURE Get_Women_names IS
-- display first name of women of all ages in the People table
CURSOR Get_Women IS
SELECT First_Name FROM People WHERE Gender = 'F';
BEGIN
FOR Get_Women_cur IN Get_Women LOOP
DBMS_OUTPUT.PUT_LINE(Get_Women_cur.First_Name);
END LOOP;
END;
/
Functions
Here is a procedure that will get the first names of the women:
PROCEDURE Get_Women_names IS
-- display first name of women of all ages in the People table
CURSOR Get_Women IS
SELECT First_Name FROM People WHERE Gender = 'F';
BEGIN
FOR Get_Women_cur IN Get_Women LOOP
DBMS_OUTPUT.PUT_LINE(Get_Women_cur.First_Name);
END LOOP;
END;
/
Function(Definition)
A function is a logically grouped set of SQL and PL/SQL statements that perform a specific task.
Function is a named pl/sql code block that have been compiled and stored in one of the oracle engines's
system tables.
To make function dynamic parameters can be passed before execution. A function can then
change the way it works depending upon the parameters passed prior to its execution.
Function is made up of a declarative part, an executable part and an optional exception-handling part.
Creating a function:
==================
Function to display salary of employees based on empno.
BEGIN
select salary into msal from emp where empno=mempno;
return(msal);
END;
/
Calling a Function:
=================
BEGIN
dbms_output.put_line(f1(4));
END;
/
end if;
return(display);
END;
/
Triggers
Trigger contains PL/SQL code which gets executed when any event occurs in the table.
E,g; INSERT, UPDATE, DELETE.
TRIGGERS
Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or
delete statement is fired.
Syntax:
=======
CREATE [OR REPLACE] TRIGGER triggername
[before | after]
[delete | Update | insert ]
ON Table
[For each row]
[when condition]
Pl/sql block
Replace option retains the trigger permissions in order to drop and re-create a trigger with the same
name.
For each row option creates a trigger that will be fired once for each row that is updated.
This type of trigger is called ROW LEVEL TRIGGER.
if for each row is ommited, then trigger is executed once for that statement. (STATEMENT LEVEL
TRIGGER)
When - This condition can be specified to further restrict the trigger is executed.
Restrictions may include the checks for old and new values.
Example:
For Each Row
when(old.fees>300)
begin
.........pl/sql statement.
"Creating Triggers"
----------------------------
Trigger to restrict users if they try to delete any record from the emp table
Trigger to change the case of letters when any updation or insertion takes place in emp
Trigger to show the previous, latest and difference in salary after updating emp table
begin
insert into updations values(:old.empno, :old.ename, :old.salary, :old.desig,:old.doj);
end;
/
A database trigger that allows changes to employee table only during the business hours(i.e. from 10 a.m
--to 5.00 p.m.) There is no restriction on viewing data from the table
To STICK IN SAL FIELD BY TRIGGER MEANS WHEN U ENTER GREATER THAN 5000, THEN
THIS TRIGGER IS EXECUTED
Trigger to insert sysdate into the tran_table when any insertion occurs in test table
Trigger to insert data in tran table whenever any record is upated, deleted or inserted in emp table
"Dropping Triggers"
Drop command drops the trigger definition along with its associated permissions.
"Disabling Triggers"
“Enabling Triggers”
Declare
given_number varchar(5) := '&enterno';
str_length number(2);
inverted_number varchar(5);
Begin
str_length := length(given_number);
For cntr in reverse 1..str_length
loop
inverted_number := inverted_number || substr(given_number, cntr, 1);
end loop;
dbms_output.put_line('The Given no is ' || given_number);
dbms_output.put_line('The inverted number is ' || inverted_number);
end;
/
Declare
a number;
s1 number default 0;
Begin
a:=1;
loop
s1:=s1+a;
exit when (a=100);
a:=a+1;
end loop;
dbms_output.put_line('Sum between 1 to 100 is '||s1);
End;
/
basic number;
da number;
hra number;
pf number;
netsalary number;
begin
basic:=&basic;
da:=basic * (41/100);
hra:=basic * (15/100);
EXCEPTION HANDLING
Errors in pl/sql block can be handled...error handling refers to the way we handle the errors in pl/sql
block so that no crashing stuff of code takes place...This is exactly the same as we do in C++ or java.
There are two type:
1. Pre-defined exceptions
2. User defined exceptions
SYNTAX
begin
sequence of statements;
exception
when --exception name then
sequence of statements;
end;
Declare
s1 emp.sal %type;
begin
select sal into s1 from emp where ename='Sam';
if(no_data_found) then
raise_application_error(20001, 'sam is not there');
end if;
if(s1 > 10000) then
raise_application_error(20002, 'sam is earing a lot');
end if;
update emp set sal=sal+500 where ename='Sam';
end;
/
INTERESTING Example OF USER DEFINED EXCEPTIONS
Declare
zero-price exception;
price number(8);
begin
select actualprice into price from item where ordid =400;
if price=0 or price is null then
raise zero-price;
end if;
exception
when zero-price then
dbms_output.put_line('raised xero-price exception');
end;
/
Example 2:
----------------
create or replace type details_type as object
(job varchar(20),mgr number,hiredate date,sal number,comm number,deptno number);
/
Packages
A package consists of the specification section, where we declare variables, tables and procedures,
followed by a package body, where we actually build the procedures. In our example we'll only have one such
procedure, but as we said before, we try to put birds of a feather in one cage, and procedures of the same ilk in
the same package.
We need an array (table) to hold the first names. To declare a table, we have to first define a user type:
In the code below I use the term AS. This is the ADA equivalent of IS. You may use either in PL/SQL. They
are the same:
PACKAGE Human_Resources AS
-- we tell the package that we use a table and which procedure to expect.
TYPE tbl_fnames IS TABLE OF people.first_name%TYPE
INDEX BY BINARY_INTEGER;
PROCEDURE first_names (p_gender IN people.gender%TYPE, fname OUT tbl_fnames);
END Human_Resources;
In SQL*PLUS we create or replace the package by doing a CREATE OR REPLACE, and following it by
pasting the code. We then type a slash (/) and press enter.
create or replace type supertype as object(A number, B number, member procedure disp, member function MF1( x number, y number)
return number) not final;
DEFINITION:
DESC SUBTYPE
create or replace type subtype under supertype (overriding member procedure disp, overriding member function MF1( x number,y
number) return number);
BODY OF SUBTYPE
declare
sup1 sup_type;
sub1 sub_type;
P number;
Q number;
begin
sup1:=super type(10,20);
sub1:=super type(10,20);
sup1.disp;
sub1.disp;
P:=sup1.MF1(10,20);
Q:=sub1.MF1(10,20);
dbms_output.put_line('super type value'||P);
dbms_output.put_line('super type value'||Q);
end;
/*RETRIEVING THE FIRST 8 RECORDS OF THE EMP_DUP TABLE BY USING THE CURSORS*/
declare
cursor emp_cursor is select empno,ename from emp_dup;
r emp_cursor%rowtype;
begin
open emp_cursor;
loop
fetch emp_cursor into r;
dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||r.ename);
exit when emp_cursor%rowcount>=8;
end loop;
close emp_cursor;
end;
/*RETRIEVING THE DETAILS OF THE EMPLOYEES WHOSE DEPARTMENT WAS 20 USING THE CURSORS*/
declare
cursor dept_cursor is select * from emp_dup where deptno=20;
r emp_dup%rowtype;
begin
open dept_cursor;
loop
fetch dept_cursor into r;
dbms_output.put_line('THE EMPLOYEE DETAILS FOR DEPT20 WAS'||r.empno||' ' ||r.ename||' '||r.job||' '||r.sal||r.deptno);
exit when dept_cursor%rowcount>=5;
end loop;
close dept_cursor;
end;
declare
cursor temp_insert is select empno,ename from emp_dup;
emp_record temp_insert%rowtype;
begin
open temp_insert;
loop
fetch temp_insert into emp_record;
exit when temp_insert%notfound;
insert into temp_list(empid,tname) values(emp_record.empno,emp_record.ename);
end loop;
close temp_insert;
end;
/*RETRIEVING THE EMPLOYEE RECORDS FOR DEPARTMENT 20 USING CURSOR FOR
LOOPS*/
declare
cursor emp_cur is select deptno,ename from emp_dup where deptno=20;
begin
for emp_record in emp_cur
loop
dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||emp_record.deptno||' '||emp_record.ename);
exit when emp_cur%notfound;
end loop;
end;
/*RETRIEVING THE EMPLOYEE RECORDS FOR DEPARTMENT 20 USING CURSOR FOR LOOP SUBQUERY*/
begin
for emp_rec in (select empno,ename,job,deptno from emp_dup where deptno=20)
loop
dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||emp_rec.empno||' ' ||emp_rec.ename||'
'||emp_rec.job||' '||emp_rec.deptno);
exit when sql%notfound;
end loop;
end;
declare
cursor emp_job is select * from emp_dup;
r emp_job%rowtype;
begin
open emp_job;
loop
fetch emp_job into r;
dbms_output.put_line('EMPLOYEE #:'||r.empno||'held the job of' ||r.job||'from'||r.hiredate);
exit when emp_job%rowcount>5;
end loop;
close emp_job;
end;
declare
cursor emp_sal is select distinct sal from emp_dup order by sal desc;
r emp_dup.sal%type;
begin
open emp_sal;
loop
fetch emp_sal into r;
dbms_output.put_line('THE TOP SALARY WISE'||r);
insert into top_dogs(salary) values(r);
exit when emp_sal%rowcount>&order_sal;
end loop;
close emp_sal;
end;
/*UPDATING THE SALARY FOR 10% THOSE SALARIES ARE LESS THAN 3000 BY USING "UPDATE OF" CLAUSE AND
WHERE "CURRENT OF" IN THE CURSORS*/
declare
cursor upd_curr is select e.empno,e.ename,e.job,e.sal, d.deptno,d.loc,d.dname from emp e,dept d where e.deptno=d.deptno
and d.deptno=30 for update of sal NOWAIT;
begin
for emp_rec in upd_curr
loop
if emp_rec.sal<3000 then
update emp set sal=emp_rec.sal*1.10 where current of upd_curr;
end if;
end loop;
end;
/*FOR GETTING INTO THE DISPLAY OF THE DEPT AND EMP TABLES TOGETHER*/
declare
cursor emp_dept is select d.deptno,d.dname,e.ename,e.job,
e.hiredate,e.sal from emp e,dept_id d where e.deptno=d.deptno;
begin
for emp_record in emp_dept
loop
if emp_record.deptno <>30 then
dbms_output.put_line('departmentnumber:'||emp_record.deptno|| 'department name'||emp_record.dname);
end if;
end loop;
for emp_record in emp_dept
loop
if emp_record.deptno<>30 then
dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate ||emp_record.sal);
end if;
end loop;
for emp_record in emp_dept
loop
if emp_record.deptno=30 then
dbms_output.put_line('departmentnumber:'||emp_record.deptno|| 'department name'||emp_record.dname);
end if;
end loop;
for emp_record in emp_dept
loop
if emp_record.deptno=30 then
dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate||emp_record.sal);
end if;
end loop;
end;
declare
cursor emp_dept is select distinct d.deptno,d.dname,e.ename,e.job, e.hiredate,e.sal from emp e,dept_id d where e.deptno=d.deptno;
a dept_id.deptno%type;
b dept_id.dname%type;
begin
select d.deptno,d.dname into a,b from dept_id d where deptno =10;
dbms_output.put_line('departmentnumber:'||a|| 'department name'||b);
select d.deptno,d.dname into a,b from dept_id d where deptno =20;
dbms_output.put_line('departmentnumber:'||a|| 'department name'||b);
for emp_record in emp_dept
loop
if emp_record.deptno<>30 then
dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate||emp_record.sal);
end if;
end loop;
select d.deptno,d.dname into a,b from dept_id d where deptno =30;
dbms_output.put_line('departmentnumber:'||a|| 'department name'||b);
for emp_record in emp_dept
loop
if emp_record.deptno=30 then
dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate||emp_record.sal);
end if;
end loop;
end;
/*DISPLAYING THE TOP TEN EARNERS OF THE COMPANY BY USING THE CURSORS*/
declare
cursor emp_cur is select * from emp order by sal;
cur emp_dup%rowtype;
begin
open emp_cur;
loop
fetch emp_cur into cur;
if emp_cur%found then
dbms_output.put_line('THE TOP TEN EARNERS OF THE EMPLOYEE TABLE WAS'||cur.ename||cur.sal
||cur.job||cur.deptno);
end if;
exit when emp_cur%rowcount=10;
end loop;
close emp_cur;
end;
declare
cursor emp_upd is select * from emp_dup where deptno=20;
upd emp_upd%rowtype;
begin
open emp_upd;
loop
fetch emp_upd into upd;
if upd.sal<2000 and upd.job='CLERK' then
delete from emp_dup where SAL<2000 AND JOB='CLERK' AND DEPTNO=20;
elsif upd.job='MANAGER' then
upd.sal:=upd.sal+upd.sal*0.15;
update emp_dup set sal=upd.sal where deptno=20;
elsif upd.job='CLERK' then
upd.sal:=upd.sal+upd.sal*0.01;
update emp_dup set sal=upd.sal where deptno=20;
/*else
upd.sal:=upd.sal+100;
update emp_dup set sal=upd.sal where deptno=20;*/
end if;
exit when emp_upd%notfound;
end loop;
/* if upd.sal<4040 then
delete from emp_dup where deptno=20;
end if; */
close emp_upd;
end;
declare
cursor emp_cur is select deptno,min(sal) "minimum" from emp group by deptno;
begin
for m in emp_cur
loop
dbms_output.put_line('the deptno and their minimum salaries was'|| m.deptno||m.minimum);
end loop;
close emp_cur;
end;
4)declare
cursor emp_print is select * from emp_dup;
c emp_print%rowtype;
begin
open emp_print;
loop
fetch emp_print into c;
if emp_print%found then
dbms_output.put_line('THE EMPLOYEE DETAILS ARE'||c.empno||' '||c.sal||' '||c.deptno);
end if;
exit when emp_print%notfound;
end loop;
end;
/*THE FOLLOWING PL/SQL CODE DISPLAYS THE DETAILS OF EMPLOYEES BELONGING TO DEPARTMENT NO10 GETTING
SALARY=4000 AND STORES THE DETAILS OF EMPLOYEES BELONGING TO DEPARTMENT NO30 AND GETTING
SALARY=4000 IN THE TEMP TABLE*/
declare
cursor emp_insert is select empno,ename,sal,deptno from emp_dup where deptno=20 and
sal=4000;
c1 emp_insert%rowtype;
begin
open emp_insert;
loop
fetch emp_insert into c1;
insert into temp; values(c1.empno,c1.ename,c1.sal,30);
exit when emp_insert%notfound;
end loop;
close emp_insert;
end;
/*THE FOLLOWING PROGRAM DISPLAYS THE NAME OF THAT MANAGER WHO HAS JOINED THE ORGANIZATION IN THE
YEAR 1981.IF THERE IS NO OUTPUT OR IF THERE IS MORE THAN ONE OUTPUT THEN INSTEAD OF GIVING ERROR THE
PROGRAMM WILL GIVE PROPER MESSAGE*/
declare
v_ename varchar2(15);
v_job varchar2(15):='MANAGER';
begin
select ename,job into v_ename,v_job from emp_dup where hiredate like '%81' and job=v_job;
dbms_output.put_line('THE JOB AND HIS NAME WAS'||v_ename||v_job);
exception
when no_data_found then
dbms_output.put_line('NO SUCH EMPLOYEE WAS HIRED IN 81');
when too_many_rows then
dbms_output.put_line('MORE THAN ONE EMPLOYEE WAS HIRED IN 81');
end;
create or replace type vtype1 as object(pno varchar2(20),pdesc varchar2(20),udm number,price number);
create table vendor_master (ven_code varchar2(20),ven_name varchar2(20) ,prod_details vendor1)nested table prod_details tore as vtemp;
Explicit Conversion
Oracle has provided built-in functions to use for converting one datatype to another. The most
commonly used conversion functions are the TO_DATE function, which allows you to convert a CHAR value
to a DATE value, and the TO_CHAR function, which allows you to convert from a CHAR value to a DATE
value. An explicit conversion occurs when you compare a DATE value to a CHAR value and use the
function
It has always been bad practice to rely on implicit conversions because it can result in poor
performance.
TO_DATE or TO_CHAR to convert the DATE into a CHAR or the CHAR into a DATE.
The following example shows how to accomplish this conversion:
This converts the values ‘01-JAN-2000’ and ‘01-JAN-2001’ into a DATE datatype of format ‘dd-
mon-yyyy’ and compares it to the value of the start_date column. If a match is made, then the counter is
incremented and the results will show how many rows exist that meet the criteria.
Implicit Conversion
When you create code that requires conversion of datatypes and you do not use the conversion
function, PL/SQL attempts to convert the datatype of a value implicitly. With this feature, you can use
literals, variables, and parameters of one datatype while another datatype is expected.
In order to accomplish an implicit conversion, you need only compare one datatype to another.
The following two examples accomplish the same task and return the same results, though one is an
explicit conversion and the other is implicit.
SELECT count(1) FROM pa_projects_all WHERE start_date >= ‘01-JAN-2000’ AND completion_date <=
‘01-JAN-2001’
/
COUNT(1)
---------
958
You can see here that Oracle will convert the data implicitly or allow you to convert the data
yourself. Both scenarios return the same results. It is your responsibility to ensure that values are
convertible. For instance, PL/SQL can convert the CHAR value ‘01-JAN-2000’ to a DATE value, but it
cannot convert the CHAR value ‘TOMORROW’ to a DATE value. Similarly, PL/SQL cannot convert a
VARCHAR2 value containing alphabetic characters to a NUMBER value.
2)/*DISPLAYING THE NAME AND UPDATED SALARY WHEN THE EMPLOYEE NUMBER HAS BEEN ENTERED AND IT HAS
BEEN DONE BY MEANS OF A PROCEDURE*/
create or replace procedure proc_in_out(eno in number,name out varchar2,salary out number) as e emp%rowtype;
begin
select * into e from emp_dup where empno=eno;
if e.job='MANAGER' then
e.sal:=e.sal+1000;
update emp_dup set sal=e.sal where empno=eno;
elsif e.job='CLERK' then
e.sal:=e.sal+500;
update emp_dup set sal=e.sal where empno=eno;
else e.sal:=e.sal+800;
update emp_dup set sal=e.sal where empno=eno;
end if;
name:=e.ename;
salary:=e.sal;
end proc_in_out;
3)/*BY USING PROCEDURE INVOKING THE UPDATED SALARY AND EMPLOYEE NAME BY GIVING THE UPDATED SALARY
AS OUT PARAMETER IN WHICH BY SIMPLY GIVING THE EMPLOYEE NUMBER*/
create or replace procedure proc_in_out1(eno in number,name out varchar2,salary in number,saly out number) as e emp%rowtype;
begin
select * into e from emp where empno=eno;
if e.job ='MANAGER' then
e.sal:=e.sal+salary;
update emp set sal=e.sal where empno=eno;
elsif e.job ='CLERK' then
e.sal:=e.sal+salary;
update emp set sal=e.sal where empno=eno;
else
e.sal:=e.sal+salary;
update emp set sal=e.sal where empno=eno;
end if;
name:=e.ename;
saly:=e.sal;
exception
when no_data_found then
dbms_output.put_line('NO SUCH EMPLOYEE EXISTS');
when too_many_rows then
dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS');
end proc_in_out1;
4)/*INCREASING THE SALARY BY 10% ACCORDING TO THE EMPLOYEE ID HAS BEEN PASSED*/
create or replace procedure proc_in_out(empid in number,name out varchar2,esal out number,ecomm out number) as
begin
create or replace procedure proc_dept(v_deptno in number default 60,v_dname in varchar2 default 'unknown',v_loc in varchar2 default 'HYD')
as
begin
insert into dept values(v_deptno,v_dname,v_loc);
end proc_dept;
b)declare
empid number:=7499;
begin
aise_sal(empid);
end;
b)create or replace procedure emp_proc as cursor emp_cur is select empno,ename from emp_dup;
begin
for emp_rec in emp_cur
loop
raise_sal(emp_rec.empno);
exit when emp_cur%notfound;
end loop;
end emp_proc;
10)/*CREATE A NEW PROCEDURE THAT ADDS THE NEW EMPLOYEE FOR THE EMPLOYEE TABLE*/
11)/*UPDATING THE JOB BY PASSING THE EMPLOYEE NUMBER AS PARAMETER BY USING THE PROCEDURES*/
create or replace procedure get_order_lines(order_number in number,output1 out varchar2) as cursor c2(header_id in number) is select
line_number,substr(ordered_item,1,20) item, ordered_quantity,unit_selling_price from oe_order_lines_all oel where HEADER_ID = header_id;
line_number number(10);
ordered_item varchar2(25);
ordered_qty number(10);
unit_selling_price number(10);
HEADER_ID NUMBER(10);
begin
open c2(HEADER_ID);
loop
fetch c2 into line_number,ordered_item,ordered_qty,unit_selling_price;
dbms_output.put_line(line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price);
output1:= line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price ;
end loop;
close c2;
exception
when no_data_found then null;
end;
var t1 number;
begin
select order_number into ord_number from dual;
select header_id into header_id from oe_order_headers_all where order_number= ord_number;
dbms_output.put_line(header_id);
output2 := header_id;
end;
var t1 varchar2(1000);
BEGIN
select header_id into head_id from dual;
DBMS_OUTPUT.PUT_LINE(HEAD_ID);
select
line_number,substr(ordered_item,1,20) item,ordered_quantity,unit_selling_price,nvl((ordered_quantity*unit_selling_price),0) Amount into
line_number,ordered_item,ordered_qty,unit_selling_price,order_amnt from oe_order_lines_all where header_id = head_id ;
dbms_output.put_line(line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price||' '||order_amnt);
output1:= line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price||' '||order_amnt ;
exception
when NO_DATA_FOUND then null;
end;
SQL Queries and Programs Examples Part - 2
declare
a number;
begin
select sal into a FROM emp where empno = 7839;
dbms_output.put_line(a);
EXCEPTION
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
declare
a emp%ROWTYPE;
begin
select * into a FROM emp where empno = 7839;
dbms_output.put_line(a.empno||' '||a.ename||' '||a.sal);
EXCEPTION
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
declare
my_grade salgrade.grade%type;
my_losal salgrade.losal%type;
my_hisal salgrade.hisal%type;
begin
select grade, losal, hisal into my_grade,my_losal,my_hisal FROM salgrade where grade = 3;
dbms_output.put_line(my_grade||' '||my_losal||' '||my_hisal);
EXCEPTION
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
declare
x number:=20;
y number:=10;
begin
declare
x number:=5;
z number:=99;
begin
dbms_output.put_line('x='||x||' '||'y='||y||' '||'z='||z);
end;
dbms_output.put_line('x='||x||' '||'y='||y);
end;
---------------------------------------------------------------------------------------------------------------------------
<<outer>>
declare
x number:=20;
begin
<<inner>>
declare
x number:=5;
begin
<<deep>>
declare
x number:=7;
begin
dbms_output.put_line('x='||x||' '||'Outer x='||outer.x||' '||'Inner x='||Inner.x);
end;
end;
end;
---------------------------------------------------------------------------------------------------------------------------
declare
a number;
begin
select sal into a FROM emp where empno = 7777;
dbms_output.put_line(a);
EXCEPTION
when NO_DATA_FOUND THEN
dbms_output.put_line('Caught NDF exception');
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
declare
name varchar2(30):='&Name';
ct number := 1;
begin
loop
exit when ct = 10;
dbms_output.put_line(ct||' '||name);
ct := ct + 1;
end loop;
dbms_output.put_line('Alias out of the loop!!');
end;
---------------------------------------------------------------------------------------------------------------------------
declare
name varchar2(30):='&Name';
ct number := 1;
begin
while ct <> 10
loop
dbms_output.put_line(ct||' '||name);
ct := ct + 1;
end loop;
dbms_output.put_line('Alias out of the loop!!');
end;
---------------------------------------------------------------------------------------------------------------------------
declare
name varchar2(30):='&Name';
begin
for ct in 1..10
loop
dbms_output.put_line(ct||' '||name);
end loop;
dbms_output.put_line('Alias out of the loop!!');
end;
---------------------------------------------------------------------------------------------------------------------------
declare
name varchar2(30):='&Name';
begin
for ct in reverse 1..9
loop
dbms_output.put_line(ct||' '||name);
end loop;
dbms_output.put_line('Alias out of the loop!!');
end;
---------------------------------------------------------------------------------------------------------------------------
declare
name varchar2(30):='&Name';
begin
for ct in reverse 1..9
loop
dbms_output.put_line(ct||' '||name);
return; --Is equivalent of "exit" in C.
end loop;
dbms_output.put_line('Alias out of the loop!!');
end;
---------------------------------------------------------------------------------------------------------------------------
begin
for i in 1..5
loop
for j in 1..5
loop
for k in 1..5
loop
exit when k = 3;
dbms_output.put_line(i||' '||j||' '||k);
end loop;
end loop;
end loop;
end;
begin
<<outer>>
for i in 1..5
loop
for j in 1..5
loop
for k in 1..5
loop
exit outer when k = 3;
dbms_output.put_line(i||' '||j||' '||k);
end loop;
end loop;
end loop;
end;
---------------------------------------------------------------------------------------------------------------------------
begin
for i in 1..5
loop
for j in 1..5
loop
dbms_output.put(j*i||' ');
end loop;
dbms_output.put_line(' ');
end loop;
end;
---------------------------------------------------------------------------------------------------------------------------
begin
for i in (select * from emp)
loop
dbms_output.put_line(i.empno||' '||i.ename||' '||i.job);
end loop;
end;
declare
gender varchar2(1) := '&Gender';
begin
if gender = 'F' then
dbms_output.put_line('Hello Mam.');
elsif gender = 'M' then
dbms_output.put_line('Hello Sir.');
else
dbms_output.put_line('Invalid Option.');
end if;
end;
---------------------------------------------------------------------------------------------------------------------------
declare
a number := 10;
b number := 20;
c number:=30;
begin
if a > b then
if a > c then
dbms_output.put_line(a||' is greatest.');
else
dbms_output.put_line(c||' is greatest.');
end if;
else
if b > c then
dbms_output.put_line(b||' is greatest.');
else
dbms_output.put_line(c||' is greatest.');
end if;
end if;
end;
---------------------------------------------------------------------------------------------------------------------------
declare
below_cr_lt EXCEPTION;
my_sal number;
begin
select sal into my_sal from emp
where empno = 7839;
declare
tn varchar2(30) := '&Table_Name';
cn varchar2(30) := '&Column_Name';
type refCursorType is ref cursor;
rcv refCursorType;
str varchar2(30);
val varchar2(30);
begin
dbms_output.put_line(cn);
str := 'Select '||cn||' from '||tn;
open rcv for str;
loop
fetch rcv into val;
exit when rcv%notfound;
dbms_output.put_line(val);
end loop;
close rcv;
end;
---------------------------------------------------------------------------------------------------------------------------
declare
n ff.a%type;
begin
insert into ff(a) values(98);
commit;
select a into n from ff where a = 98;
dbms_output.put_line(n);
EXCEPTION
when DUP_VAL_ON_INDEX then
dbms_output.put_line('Insertion failed as such a value already exists.');
when NO_DATA_FOUND then
dbms_output.put_line('No such number.');
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
declare
cursor c1 is select * from dept;
drec dept%rowtype;
begin
open c1;
open c1;
loop
fetch c1 into drec;
exit when c1%notfound;
dbms_output.put_line(drec.dname||' '||drec.loc||' '||drec.deptno);
end loop;
close c1;
exception
when CURSOR_ALREADY_OPEN then
dbms_output.put_line('Forgot!! You have an open cursor.');
when INVALID_CURSOR then
dbms_output.put_line('Hey!!! You have not opened the cursor.');
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
declare
cursor c1 is select * from dept;
drec dept%rowtype;
begin
open c1;
if c1%ISOPEN then
dbms_output.put_line('Cursor is open.');
else
dbms_output.put_line('Cursor has to be opened.');
end if;
loop
fetch c1 into drec;
exit when c1%rowcount = 3;
dbms_output.put_line(drec.dname||' '||drec.deptno);
end loop;
close c1;
end;
declare
min_bal constant number := 500;
over_drawn exception;
withdrawl_amt number := 1000;
mybal number;
begin
select bal into mybal from acct where no = 2;
if mybal - withdrawl_amt < 500 then
raise over_drawn;
else
update acct set bal = bal - withdrawl_amt where no = 2;
commit;
end if;
exception
when over_drawn then
dbms_output.put_line('Sorry!! sir/madam minimum balance is Rs.500/-.');
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
begin
lock table acct in exclusive mode nowait;
exception
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
declare
table_locked exception;
pragma exception_init(table_locked, -00054);
begin
lock table acct in exclusive mode nowait;
exception
when table_locked then
dbms_output.put_line('The table is locked. Please try after some time.');
when others then
dbms_output.put_line(sqlerrm(sqlcode));
end;
---------------------------------------------------------------------------------------------------------------------------
declare
cursor c1 is select * from ratio for update;
rrec ratio%rowtype;
begin
open c1;
loop
fetch c1 into rrec;
exit when c1%notfound;
begin
update ratio set r = rrec.a / rrec.b where current of c1;
commit;
exception
when ZERO_DIVIDE then
update ratio set r = 0 where current of c1;
commit;
end;
end loop;
close c1;
end;
---------------------------------------------------------------------------------------------------------------------------
declare
no_data_found exception;
n number;
begin
select sal into n from emp where empno = 7777;
dbms_output.put_line('Employee no 7777 is drawing'||n);
exception
when standard.no_data_found or no_data_found then
dbms_output.put_line('Caught no data found');
when others then
dbms_output.put_line('Caught others exception');
dbms_output.put_line(sqlerrm(sqlcode));
end;
DECLARE
BEGIN
BT.CREATE_ACCT('AHMED',5000039);
FOR I IN (SELECT * FROM ACCT)
LOOP
DBMS_OUTPUT.PUT_LINE(I.ACCTNO||' '||I.NAME||' '||I.BAL);
END LOOP;
BT.DEPOSIT(1, 50000);
FOR I IN (SELECT * FROM ACCT)
LOOP
DBMS_OUTPUT.PUT_LINE(I.ACCTNO||' '||I.NAME||' '||I.BAL);
END LOOP;
BT.WITHDRAWL(1, 25000);
FOR I IN (SELECT * FROM ACCT)
LOOP
DBMS_OUTPUT.PUT_LINE(I.ACCTNO||' '||I.NAME||' '||I.BAL);
END LOOP;
END;
---------------------------------------------------------------------------------------------------------------------------
SQL> CREATE TABLE ABC(A NUMBER , B DATE);
Table created.
SQL> ED
Wrote file afiedt.buf
Trigger created.
1 row created.
SQL> ED
Wrote file afiedt.buf
SQL> /
Trigger created.
1 row deleted.
SQL> /
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
A REC IS BEING INSERTED.
14 rows created.
SQL> COMMIT;
Commit complete.
14 rows deleted.
SQL> ROLL
Rollback complete.
A B
------- ---------
7369 17-DEC-80
7499 20-FEB-81
7521 22-FEB-81
7566 02-APR-81
7654 28-SEP-81
7698 01-MAY-81
7782 09-JUN-81
7788 09-DEC-82
7839 17-NOV-81
7844 08-SEP-81
7876 12-JAN-83
A B
---------- --------
7900 03-DEC-81
7902 03-DEC-81
7934 23-JAN-82
4 rows selected.
Table created.
---------------------------------------------------------------------------------------------------------------------------
select * from emp
Table Type Example.
declare
type ty_tab is table of number;
v_tab ty_tab := ty_tab();
begin
for i in 1..50
loop
v_tab.extend;
v_tab(i) := (i);
end loop;
v_tab.delete(5); v_tab.delete(10); v_tab.delete(15);
for i in v_tab.first..v_tab.last
loop
if v_tab.exists(i) then
dbms_output.put_line(i||' '||v_tab(i));
else
dbms_output.put_line(i||' has been deleted.');
end if;
end loop;
end;
/
table 1: mm_m_matgrp
create table mm_m_matgrp( mat_grp number(1) primary key, descr varchar2(70) not null, abvr varchar2(6), crt_by varchar2(10), crt_dt
date, upd_by varchar2(10), upd_dt date);
table2 : mm_m_matmain
create table mm_m_matmain( mat_grp number(1) constraint mt_grp_pk references mm_m_matgrp(mat_grp), mat_main number(2)
primary key, descr varchar2(70) not null, abvr varchar2(6), crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date);
table 3 : mm_m_matsub
create table mm_m_matsub( mat_grp number(1) constraint mt_grp_fk references mm_m_matgrp(mat_grp), mat_main number(2)
constraint mt_main_fk references mm_m_matmain(mat_main), mat_sub number(2) primary key, descr varchar2(70) not null, abvr varchar2(6),
crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date);
table 4 : mm_m_mat
create table mm_m_mat( mat_grp number(1) not null, mat_main number(2) not null, mat_sub number(2) not null, mat_sub2 number(2)
not null, mat_cd number(7) primary key, descr varchar2(70) not null, abvr varchar2(6), uon varchar2 (10) not null, silo_stk_ind number(1),
moist_ind number(1),no_wb_ind number(1), crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date);
GV
declare
cursor deptcur is
select deptno from dept;
--emp cursor
cursor empcur(v_deptno dept.deptno%type) is
select ename from emp where deptno = v_deptno;
begin
for deptrec in deptcur loop
dbms_output.put_line('depertment no ...'|| deptrec.deptno);
for emprec in empcur(deptrec.deptno) loop
dbms_output.put_line('emp name ..'|| emprec.ename);
end loop;
end loop;
end;
NESTED TABLE
step1:creation of a type
step5:selecting
PL SQL Table
declare
type ty_tab is table of number index by binary_integer;
v_tab ty_tab ;
begin
for i in 1..10
loop
v_tab(i*4) := (i);
end loop;
dbms_output.put_line(v_tab.count);
v_tab.delete(5); v_tab.delete(10); v_tab.delete(15);
for i in v_tab.first..v_tab.last
loop
if v_tab.exists(i) then
dbms_output.put_line(i||' '||v_tab(i));
end if;
end loop;
end;
/
SQL Queries and Programs Examples Part - 5
RTRIM('XYXYXYX
--------------
xyxyxyxyxybose
ROUND(15.59,-1)
---------------
20
TRUNC(15.59,-1)
---------------
10
NLS_INIT
--------
I Jsland
NLS_INIT
--------
I Jsland
REPLACE('JACKA
--------------
black and blue
TRANSLA
-------
9xxx999
7. Instring?
Capital
-------
IJsland
SQL> SELECT NLS_INITCAP ('ijsland', 'NLS_SORT = Xfrench') "Capitalized" FROM DUAL;
Capital
-------
Ijsland
PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and data types are similar to that of
ADA. The PL/SQL language includes object oriented programming techniques such as encapsulation, function overloading, and information
hiding (all but inheritance). PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle database.
Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the
two is the best?" and "Will Oracle ever de support PL/SQL in favor of Java?‖
Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport PL/SQL. In fact, all indications are
that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native
compilation of Pl/SQL code to binaries.
PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two
language environments:
PL/SQL:
JAVA:
Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One can detect code changes by looking at
the LAST_DDL_TIME column in the USER_OBJECTS dictionary view.
Example:
4. How can one search PL/SQL code for a string/ key value?
The following query is handy if you want to know where a certain table, field or expression
is referenced in your PL/SQL source code.
SELECT TYPE, NAME, LINE FROM USER_SOURCE WHERE UPPER(TEXT) LIKE '%&KEYWORD%';
One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or database) level trigger (available from
Oracle 8.1.7). This way one can easily revert to previous code should someone make any catastrophic changes? Look at this example:
CREATE TABLE SOURCE_HIST -- Create history table
AS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.* FROM USER_SOURCE WHERE 1=2;
PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code. This is done via
a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original). This way you
can distribute software without having to worry about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still
understand and know how to execute such scripts. Just be careful, there is no "decode" command available.
set serveroutput on
begin
dbms_output.put_line('Look Ma, I can print from PL/SQL!!!');
end;
/
DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much,the output buffer will overflow. In that case,
set the buffer size to a larger value,
eg: set serveroutput on size 200000
If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember,and then EXEC NULL;. If you haven't cleared
the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer when it executes this
dummy PL/SQL block.
Included in Oracle 7.3 is an UTL_FILE package that can read and write operating system files. The directory you intend writing to has to
be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT
with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/tmp', 'myfile', 'w');
UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a file!!!\n');
UTL_FILE.FCLOSE(fileHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, 'ERROR: Invalid path for file or path not in INIT.ORA.');
END;
/
One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE" statement.
Users running Oracle versions below 8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL).
begin
EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';
end;
NOTE: The DDL statement in quotes should not be terminated with a semicolon.
Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL statements
(statements created at run-time). Look at these examples.Note that statements are NOT terminated by semicolons:
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements.
Look at these examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;
/
The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as
the database changes to meet new business needs.
%ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor.
Example:
DECLARE
v_EmpRecord emp%ROWTYPE;
%TYPE is used to declare a field with the same type as that of a specified table's column.
Example:
DECLARE
v_EmpNo emp.empno%TYPE;
NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated to NULL. Look at this code example
to convince yourself.
declare
a number := NULL;
b number := NULL;
begin
if a=b then
dbms_output.put_line('True, NULL = NULL');
elsif a<>b then
dbms_output.put_line('False, NULL <> NULL');
else
dbms_output.put_line('Undefined NULL is neither = nor <> to NULL');
end if;
end;
13. How does one get the value of a sequence into a PL/SQL variable?
As you might know, one cannot use sequences directly from PL/SQL. Oracle (for some silly reason) prohibits this:
i := sq_sequence.NEXTVAL;
However, one can use embedded SQL statements to obtain sequence values:
There is no direct way to execute operating system commands from PL/SQL in Oracle7. However, one can write an external program
(using one of the precompiler languages, OCI or Perl with Oracle access modules) to act as a listener on a database pipe (SYS.DBMS_PIPE).
Your PL/SQL program then put requests to run commands in the pipe, the listener picks it up and run the requests. Results are passed back on
a different database pipe. For an Pro*C example, see chapter 8 of the Oracle Application Developers Guide.
In Oracle8 one can call external 3GL code in a dynamically linked library (DLL or shared object). One just write a library in C/ C++ to do
whatever is required. Defining this C/C++ function to PL/SQL makes it executable. Look at this External Procedure example.
16. How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?
Contrary to popular believe, one should COMMIT less frequently within a PL/SQL loop to prevent ORA-1555 (Snapshot too old) errors.
The higher the frequency of commit, the sooner the extents in the rollback segments will be cleared for new transactions, causing ORA-1555
errors.
To fix this problem one can easily rewrite code like this:
... to ...
FOR records IN my_cursor LOOP
...do some stuff...
i := i+1;
IF mod(i, 10000) THEN -- Commit every 10000 records
COMMIT;
END IF;
END LOOP;
If you still get ORA-1555 errors, contact your DBA to increase the rollback segments.
NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard.
17. I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?
PL/SQL respect object privileges given directly to the user, but does not observe privileges given through roles. The consequence is
that a SQL statement can work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following solutions: Grant direct access on the
tables to your user. Do not use roles!
"Mutating" means "changing". A mutating table is a table that is currently being modified
by an update, delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered
"mutating" and raises an error since Oracle should not return data that has not yet reached its final state. Another way this
1) CREATE
2) ALTER
Ex:-
Alter (column to be modify must be empty to reduce the size or to Change the datatype)
3) DROP
Ex:
Alter table drop column
Alter table
set unused (last_name)
4) TRUNCATE
-Remove all records from a table, including all spaces Allocated for the records are removed
5) OMMENT
Delete Truncate
DML - It is DDL
It will mark the records to delete - WE CAN'T ROLLBACK
We can rollback - WE CAN'T APPLY CONDITIONS
latter we use that space - It will releases the space and we can
QUERIES:
1) Copy the rows of emp to emp1, if both are structure remains the same?
3) Copying the structure of emp to emp1 “As it is” Here data also copied? But here constraints will not be copyed?
4) I want to copy the only structure of emp in emp1? Here no data will be copied?
In Operator:
1) list the emp those who are either clerks are analysis?
Between operator:
2)display the empno, name, sal, annual sal of all the emp in the descending order of annual sal?
Select eno, ename, sal,sal*12 annusal from emp order by annusal desc;
4) write a query to display emp details of those working on dept 30 as clerks with out commotion?
Select * from emp where deptno=30 and job=‘clerk‘ and commotion is null;
5) Display the analyst & manager to the annual sal more than 30,000 working under some manager with out commotion with
experience less than 30 years and whose name should not be equal to „blenk‟ and who empno not equal to 7788 in
descending order of salary?
Select * from emp Where job in(‗analyst‘,‘mamager‘) and Sal * 12 > 30,000 and mgr is not null and comm. Is null and (hiredate-
sysdate)/365 < 30 and Name ! = ‗black‘ and empno != 7788 Order by sal desc;
Like operator:
3) list the emp who joined in the month which is started with A?
DML
1) SELECT
2) INSERT
3) UPDATE
Ex:
Update emp Set deptno = (select deptno from dept where dname = ‗account‘) where deptno= (select deptno from dept where dname =
‗research‘);
2) DELETE
-deletes all records from a table, the space for the records remain
Ex:-
2) CALL
3) EXPLAINS PLAN
4) LOCK TABLE
-control concurrency
5) MUTATINGTABLE
- Mutating Table is a table that is currently being modified by a DML statement. For a Trigger, this is the table on which the table is
defined.
3) TCL
1. COMMIT
3. ROLLBACK
4. SET TRANSACTION
-Change transaction options like what rollback segment to use Save point
Rollback:
- Oracle Issues implicit commit before and after any DDL statement. Even if your DDL statement does not execute then also it Issues
commit statement
-If we issue commit all savepoints will be erased and all locks are released
DCL:
1) GRANT:
--- Is used to issue the privileges to other valid users of data base
1) User level
--is granted by the DBA.
2) Object level
--These can be granted by one user to another user
Ex:
1. Give select, update permit ions to the user demo on emp?
2. Grant all permitions to the user‘s sys and system on salgrade table?
2) REVOKE:
Note: 1) user_pri_objects
2) user_table_pri
3) user_col_pri
Intigrity constants:
2. unique : it will not allow duplicate values and it accept null values can be defined at the
column level and table level
3. check: it will check with column definition before accept. check constraint defines a
CONDITION that each row must satisfy references to the currval, nextval, level, rownum pseudo
columns calls to sysdate uid user, and userenv. check cons. can be defined at the column level
and table level
1. foriegn key: foreign keys provide referential integrity rules wither within a table or b/w Tables
- give reference to the primary key column.
On delete cascade- deletes the dependent rows in the child table when a row in the parent table is deleted.
Cascade constraint- the cascade constraints clause drops all referential integrity constraints that refer to the primary and unique keys
defined on the dropped columns
-the cascade constraints clause also drops all multicolumn constraints defined in the dropped columns.