184
ORACLE 11g.......................15 Advantages of ORACLE .............15 History of Oracle ................16 DATA BASE.......................16 Database Management System(DBMS) . 16 Eg: Dbase, FoxPro, Paradox etc... 16 RDBMS ..........................16 Eg: MS-Access, Oracle, Ms-SQL Server, Sybase etc...............17 Advantages of Rdbms ..............17 Difference between DBMS AND RDBMS ................................ 17 DBMS............................... 17 RDBMS........................... 17 Types Of Management Systems . . .17 The Basic Objects Of Rdbms: ......18 Attribute ........................18 Relation .........................18 Oracle9i - The eBusiness Platform 19 Oracle 11g – Key Infrastructure Areas........................... 19 Oracle 11g - Key application areas ................................ 19 Scalability and Performance.....19

novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ORACLE 11g...........................................................15Advantages of ORACLE.........................................15History of Oracle .....................................................16

DATA BASE.......................................................16Database Management System(DBMS) ..................16Eg: Dbase, FoxPro, Paradox etc...............................16

RDBMS...............................................................16Eg: MS-Access, Oracle, Ms-SQL Server, Sybase etc...................................................................................17Advantages of Rdbms .............................................17

Difference between DBMS AND RDBMS .........17DBMS..........................................................................17

RDBMS................................................................17Types Of Management Systems .........................17

The Basic Objects Of Rdbms: .................................18Attribute ..................................................................18Relation ...................................................................18

Oracle9i - The eBusiness Platform......................19Oracle 11g – Key Infrastructure Areas................19Oracle 11g - Key application areas......................19Scalability and Performance................................19Oracle 11g - Providing an End-to-End Security Infrastructure........................................................20Oracle 11g - Development Platform for eBusiness Applications.........................................................20Oracle 11g - Manageability..................................20Oracle 11g - Windows Integration.......................20

Product of ORACLE...............................................21

Page 2: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

BACKEND TOOLS FRONTEND TOOLS....................................................................21DBMS (SQL & PLSQL) DBA....21

E.F.CODD RULES: ............................................22Oracle Data types ................................................22The following are different data types supported by ORACLE........................................................23Rules for define a table name. .............................24

SQL * PLUS............................................................25Commands ...........................................................25DDL.....................................................................25

Syntax......................................................................25Example :.................................................................26ALTER COMMAND..............................................261. Add.......................................................................262. Modify..................................................................263. Drop.....................................................................26Syntax:.....................................................................26Alter Table <table_name> Drop column <column_name>.......................................................26

Examples on Alter Command..............................26Create a table with the following structure..........26

Rename Command...................................................27Syntax: ......................Rename <old_table_name> to <new_table_name>..................................................27

DML....................................................................27Insert command........................................................27Syntax:.....................................................................27

Page 3: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Examples on Insert Command.............................27First Create a table...................................................27To insert values into all Columns............................27

Similarly insert some more values as follows......28To insert values into specified Columns..................28Update Command...................................................28Syntax:.....................................................................28Examples:.................................................................28To update only one column value............................28Delete Command......................................................28Syntax : Delete From <table name> where <condition>..............................................................29Ex : To Delete A Single Row................................29Ex : To Delete Multiple Rows (More Than One Row).........................................................................29

TCL.....................................................................30Syntax : commit;......................................................30Syntax : Rollback To [Savepoint] Savepoint_Name..................................................................................31Syntax :....................................................................31

DCL.....................................................................31Examples :............................................................33

Between ...................................................................33Syntax : .....[ Not ] Between <Begin Expression And End Expression>......................................................33

Examples :............................................................33Examples :................................................................34

Built In Function in Oracle..................................35

Page 4: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Character Functions or Text Functions or String Functions .............................................................37Date and Time Functions ....................................40Add_Months : ......................................................40Last_day : ............................................................40Next_Day............................................................41months_between ..................................................41Count ...................................................................41Sum(sal) ..............................................................42

Syntax : Sum(distinct <numerical column>)..........42Examples :................................................................42

Max(sal) : ............................................................42Syntax : Max(numerical column)...........................42Example :.................................................................42

Min(sal) : .............................................................42Syntax : Min(numerical column)............................42Example:..................................................................42Write a query to find minimum sal earning by an employee in the emp table.......................................42

Avg(sal) : .............................................................42Syntax : Avg(distinct <numerical column>)..........42Example :.................................................................42Group By Clause .....................................................42Having Clause .........................................................43Examples :................................................................43Order By Clause ......................................................43To_char : .................................................................45

Page 5: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

NVL FUNCTION..............................................46Constraints ...........................................................48

Note : Constraints can be imposed in two ways......48Table Level :............................................................48Column Level :........................................................48

NOT NULL.........................................................49Syntax:.....................................................................49Not Null in Column Level.......................................49Adding Not Null Using Alter Command for Existing Table........................................................................49Note :........................................................................49Example :.................................................................49Create table sample1(sno number(3), sname varchar2(20) not null);.............................................49Error Comes.............................................................49Unique Constraint ...................................................49Syntax: (For Column Level)....................................50Syntax: (For Table Level)........................................50Example : Imposing unique constraint Table Level 50Example : Imposing unique constraint Column Level..................................................................................50Default Constraint : .................................................50Note : Only Column level definition can be applied to “Default constraint”.............................................50Syntax : for column level.........................................50Create Table <Table Name>(Column1 <Data Type><Size> default <value>,.................................50Example :.................................................................50

Page 6: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Example : 2..............................................................51SNO ...........................................................SNAME

51Check Constraint .....................................................51Syntax : (column Level)...........................................51Example:..................................................................51Syntax : (Table Level).............................................52Example :.................................................................52Primary Key Constraint ...........................................52Syntax: .....................................................Table Level

52Ex:............................................................................52Error Comes.............................................................52Syntax : ................................................Column Level

52Example :.................................................................52Error Comes.............................................................52Example 2................................................................52Error Comes.............................................................53Foreign Key Constraint ...........................................53There are five major restrictions related to foreign key............................................................................53Syntax : (Column Level)..........................................53Syntax : (Table Level).............................................53Making relationships between two tables ...............532. Next Create the Child Table.................................53

3. Next insert the values in to mother table first,. 54101 Mahesh 6500.............................................54

Page 7: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ERROR : (since there is no such account number present in the mother table)......................................54SQL> select * from banktrans;................................54Dropping Relationship Tables .................................54Note :........................................................................54

Joins .....................................................................58Table and column alias names.............................58

Types of Joins..........................................................58General Syntax :.......................................................58Equi Join ..................................................................58Example :.................................................................58List the employee numbers, names, department numbers and dept names..........................................58Using Table Aliases ................................................59Non Equi Join ..........................................................59Example :.................................................................59Outer Join ................................................................59Left Outer Join ........................................................59Example :.................................................................59Right Outer Join ......................................................60Example :.................................................................60Rules to place ( + ) Operator....................................60Full outer joins. .......................................................60Here it will show both the extra field from two table...................................................................................60P.OUTER JOIN.......................................................60NATURAL JOIN....................................................60Self Join ...................................................................61

Page 8: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select e1.ename,e1.deptno from emp e1,emp e2......61where e2.ename='FORD' and e1.deptno=e2.deptno;..................................................................................61Cross Join (oracle 9i concept) .................................61Syntax.......................................................................62Example :.................................................................62

SUB QUERY......................................................62Sub Queries Or Nested Queries...............................62Using Sub Queries,..................................................63Using sub Query,......................................................63ERROR at line 1:.....................................................64ORA-01427: single-row subquery returns more than one row*******DELETE & UPDATE...................64

SET OPEREATOR.............................................67Union, Intersect and Minus Operators.....................67Syntax :....................................................................67Syntax :....................................................................68Syntax :....................................................................69Special Operators used in Sub Queries....................69All, Any and Some Operators .................................69ANY Operator .........................................................69Example :.................................................................70ALL Operator ..........................................................70Example :.................................................................70SOME Operator .......................................................71Example :.................................................................71Syntax :....................................................................71Create View <view name>......................................71

Page 9: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Advantages of Views ...........................................71Types of View.....................................................71

Simple View............................................................72Syntax :....................................................................72

Examples :............................................................72We can change column names in a view at the time of creation ....................................................72

Create a view, which shows all employees details who belong to dept 20..............................................72

We can Create a view, using another view .........72To Create Read Only Views ................................72

Example :.................................................................72ERROR at line 1:.....................................................73ORA-01732: data manipulation operation not legal on this view..............................................................73ERROR at line 1:.....................................................73ORA-01732: data manipulation operation not legal on this view..............................................................73Composite View......................................................73Syntax :....................................................................73Create view <view name> as select <fields list> from..................................................................................73ERROR at line 1:.....................................................73ORA-01776: cannot modify more than one base table through a join view..................................................73Dropping a view......................................................74Drop view <view name>..........................................74Note :........................................................................74

Page 10: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

SEQUENCE........................................................75Syntax :....................................................................75Start with : it is a keyword to specifying the starting value in the sequence creation.................................75Maxvalue : specifies the maximum value or limit that the sequence can generate........................................75Order : generates the sequences in the order of request......................................................................75

Attatching Sequence............................................76Example :.................................................................76Using Insert Command............................................76Syntax :....................................................................76Insert into <table name>(columns list) values(sequencename.nextval,……);.......................76ERROR at line 1:.....................................................76Using Update Command..........................................76Syntax :....................................................................76Update <table name> set <column Name>=<sequencename.nextval>, ------;................76

Updating only one value......................................76Updating Multiple Values....................................77

Altering a Sequence.....................................................77Syntax :....................................................................77Example...................................................................77

Again Altering the above sequence.....................77Drop sequence : .......................................................77Syntax : drop sequence <sequence name>............77Note :........................................................................78

Synonym..............................................................78

Page 11: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Clusters ................................................................79Syntax :...................................................................79To create any cluster ................................................79

Note :....................................................................79First create the cluster,.........................................79Next create the index,...........................................80Attaching the cluster to the table,.........................80

Example :.................................................................80SNO SNAME.......................................................80SNO SNAME.......................................................80SNO SNAME.......................................................80SNO SNAME.......................................................80

ERROR at line 1:.....................................................81ORA-00942: table or view does not exist................81Drop cluster .............................................................81Syntax : drop Cluster <cluster name>.....................81

INDEX................................................................81Types of index. ....................................................81

Simple Index ...........................................................82ERROR at line 1:.....................................................82ORA-00942: table or view does not exist................82Creating Unique indexes on a Single column .........82Syntax :....................................................................82Example :................................................................82Error :.......................................................................83Ora-00001: unique constraint (scott.idx_temp) violated.....................................................................83Note :........................................................................83ERROR at line 1:.....................................................83

Page 12: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ORA-01408: such column list already indexed.......83Composite index ......................................................83Syntax :....................................................................83Composite unique index ..........................................83Syntax :....................................................................83Bitmap index ...........................................................83Syntax :....................................................................83Drop index ...............................................................84Syntax : Drop index <index name>.........................84To View Index .........................................................84

Clusters ................................................................84Syntax :...................................................................85To create any cluster ................................................85

Note :....................................................................85First create the cluster,.........................................85Next create the index,...........................................85Attaching the cluster to the table,.........................85MERGE...............................................................86RANKING..........................................................86PRIVILEGES......................................................86Table Lock ...........................................................89SPOOL 'C:\ravi.txt'; ENTER...............................90NEXT SELECT * FROM EMP ENTER.............90SPOOL OFF ENTER...........................................90THEN OPEN C....................................................90PIVOT.................................................................90NORMALIZATION...........................................91PL/SQL PROGRAMMING................................93

Page 13: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PLSQL DATA TYPES.......................................93IF condion ...........................................................98LOOP Condition ...............................................101Types Of Loops .................................................101DECODE...........................................................108CASE.................................................................108Exp of Boolean Datatypes. ................................109CURSOR...........................................................110Types Of Cursor ................................................110IMPLICIT ..........................................................111STRONG CORSOR..........................................111WEEK CURSOR..............................................112CORSOR WITH FOR LOOP...........................113WITH WHILE LOOP.......................................114WITH GROUP BY CLAUSE...........................114WITH JOINS.....................................................114WITH CASE FUNCTION................................115EXCEPTION.....................................................116PL/SQL FUNCTION........................................123PROCEDURE...................................................128PACKAGE........................................................137TRIGGER..........................................................139VARRAY..........................................................144BULK BINDING..............................................145NESTED TABLE..............................................145PARTITION TABLE........................................146

Page 14: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database
Page 15: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ORACLE 11g

IntroductionIt is the most existing software for computers available in the market. Over more than

10 years the ORACLE RDBMS developed and improved a full featured. The ORACLE family of database predicted includes several powerful development and generation tools. These tools provides complete specialty for the system design and developing for the design and testing of software product.

Advantages of ORACLE1. Back up and recovery2. Portability3. Performance4. Multiple data base support5. Security6. Convertibility7. Compatibility8. Data Integration9. Centralized Administration10. Multi User Data Access

History of OracleOracle first time released in 1979 with RDBMS concepts.

Oracle 7.0 is released with RDBMS Concepts Oracle 7.3 is released with RDBMS Concepts Oracle 8.0 is released with ORDBMS Oracle 8i is released with Internet features

Page 16: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Oracle 9i is released with Extended Internet features Oracle10g is released with Gride Features Oracle 11g is released with Extended Gride Features

DATA BASEIt is a collection of data items stored together in one or more data files with minimum

redundancy in order to serve data to one ore more applications simultaneously

DBMS Environment

Database Management System(DBMS)It is a software used to create, destroy and Maintain database or in another words It

is a Tool or Software that is integrated with a set of programs it will perform the following tasks

1. Adding Records2. Updating Records3. Modifying Records4. Deleting Records5. Arranging Records in to an Order

Eg: Dbase, FoxPro, Paradox etc..RDBMS

Relational data mode is currently the most popular one of database management systems because it is conceptually simple and understandable by information systems, professionals and many end users.

This Model represents data in terms of relations using the concepts set theory, relational algebra and relational calculus

Eg: MS-Access, Oracle, Ms-SQL Server, Sybase etc.

A Typical Example of a Relation

Advantages of Rdbms1. It provides minimum data redundancy and minimum data in consistency.2. It eliminates the difficulties in accessing and manipulating data.3. It offers uniform security and privacy control.4. Data sharing can be accomplished easily.5. It provides data integration.

Page 17: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Difference between DBMS AND RDBMSDBMS RDBMS

The concept of relation ship is missing in DBMS if it exists it is very less

Based on the concept of relation ships.

Speed of operation is very slow

Speed of operation is very fast

Hardware and software requirements are less

Hardware and software requirements are high.

Platform used is normally DOS and Windows

Platform used can be many UNIX, WINDOWS, DOS, VAX etc.

Uses the concept of a file Uses the concept of TableDBMS normally called 3rd generation language

RDBMS normally called 4th generation language.

E.F Codd develops the relational data base model in 1970. He is a statistician; he provided 12 rules for an RDBMS. If a software an RDBMS, then it most satisfies these 12 rules.

Types Of Management Systems

File management system *************************

1. There is no security of data.

2. It is not supporting to multiple users.

3. To select insert update delete record it is very difficult.

Hierarchic database ********************

Use to store the information with reverse tree structure.

Network database ******************

Use to store the information with physical link.

Relational database (RDBMS) ************************** Use to maintain the relation between two-dimensional tables.

ONE - ONE

Page 18: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ONE -MANY

MANY - MANY

If any database supports more than six rules of Mr.E.f codds rule

That database is known as complete relational database management system.

The Basic Objects Of Rdbms:1. Entity2. Attribute3. Relation

Entity THE RELATIONALA true statement regarding an object is called entity. I.e. the object may be person on

place or any thing. Entities in the data base are implemented by Table.

For Eg: roll no 25 in a class is an entity, since it uniquely identified a person in the class.

AttributeAn additional quality of entity is called attribute. Attributes are implementing using

columns.

Eg: eno, ename, sal etc.Relation

The relation object specifies relation between two or more entities for staring a valid data into the database.

These relations are implemented using constraints. These constraints are called mapping cardinalities. These are useful in describing the relationship sets.

there are different ways to create relationship between 2 or more tables. that is called e-r modeling.

Oracle9i - The eBusiness PlatformOracle9i continues Oracle8i’s focus on the Internet by providing a series of specific

capabilities and product bundles targeted at eBusiness environments. In addition, Oracle9i continues to add features and capabilities that extends existing investment in mission-critical infrastructure.

Oracle 11g – Key Infrastructure Areas Availability Scalability and Performance Security Development Platform Manageability Windows2000 Integration

Oracle 11g - Key application areas Internet Content Management

Page 19: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

eBusiness Integration Packaged Applications Business Intelligence Platform Achieving Continuous Data Availability

Oracle9i dramatically extends Oracle’s leadership in Internet database availability, critical for any eBusiness application. Key focus areas in Oracle9i include:

Providing an industry leading zero data loss data protection environment Reducing offline maintenance requirements with support for more online

operations Providing fast and precise repair of damaged databases Enabling end-users to identify and correct their own mistakes.

Scalability and PerformanceOracle9i allows eBusiness to scale to tens of millions of users performing millions of

transactions per hour. Key focus areas include:

Transparent cluster scalability and performance Scalable session state management Optimized features critical for eBusiness

Oracle 11g - Providing an End-to-End Security InfrastructureOracle9i continues to provide the most secure application development and

deployment platform in the industry. Key focus areas include:

Strong, three-tier security Standards-based Public Key Infrastructure (PKI) Deep Data Protection Improved user and security policy management Data Encryption Oracle Label Security Oracle Internet Directory

Oracle 11g - Development Platform for eBusiness ApplicationsOracle11g continues to offer the best development platform for eBusiness and traditional application development. Key focus areas include:

Enterprise Java Engine XML type and XDK SQL and PL/SQL improvements

Oracle 11g - ManageabilityManagement is one of the key areas of improvement for Oracle9i. There are five

aspects to our approach taken with management in Oracle9i:

Page 20: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Make the database self managing in certain key areas Streamline and improve the operational management of an Oracle9i database Provide tools and techniques that significantly simplify and reduce the task time

required to administer Oracle9i Enable fine-grained, automatic resource management Provide an end-to-end system management solution that manages the entire

Oracle stack, not just the database.

Oracle 11g - Windows IntegrationOracle9i continues Oracle’s lead as the platform of choice for organizations deploying on Windows 2000. Key focus areas are:

Close integration with Windows 2000 Facilitated development and deployment on MS Windows platforms

Product of ORACLE SQL * PLUS SQL *DBA SQL*NET SQL*FORMS SQL*REPORTS SQL*NEBYS SQL*GRAPHS SQL*LOADER ORACLE*FINANCIAL PRO*C PRO*COBAL PRO*FORTRAN

BACKEND TOOLS FRONTEND TOOLS

SQL/PLSQL (ORACLE) JAVA (ORACLE)

SQLSERVER (MS) .NET (MS)

MYSQL (OSDB) ORACLEFORMS(D2K) (ORACLE)

DB2 (IBM)

MS ACCESS (MS)

Page 21: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

DBMS (SQL & PLSQL) DBA

Creating Tables Store The Data Creating Data Base

And Retrive The Data Increase and Decrease The DB Size

Creating New User ID

Lock,Unlock and Delete The User ID

Recovaring The Data

E.F.CODD RULES:1. Information Rule : information is to be represented as data stored in

cells.2. Representing NULL values: NULL must be used in a constant manner, if

NULL is treated as zero for missing numeric value and as blank for missing character values, then this violates this rule. NULL should be simply the missing data and have no values.

3. Language: Since RDBMS is a package we may not define programs using RDBMS. All most all-supporting language is SQL on IBM corporation.

4. Insert, Update, Delete : This feature specifies that the user must be capable of applying insert, update, delete operations at any time on any table.

5. BackEnd: An RDBMS must act as the backend software and with must be support provider for establishing connection from any client software to server software.

6. Client server architecture : It specifies accessing data of the server from client, manipulating in the client and once again sending back data to the server.

7. Supporting constraints or rules : Main purpose of constraints is inserting valid data into the database. The constraints does not allow insertion of NULL values, duplicate values into the columns and also allows establishing relation ships between tables for inserting common data or similar values.

8. Logical Data independency: this feature specifies that the data must be independent of the logical operations like imposing constraints and executing different programs using the data existing in the table.

9. Non-Subversion Rule: It specifies the system must allow the user for executing the programs defined in the earlier versions. For Eg: the programs defined in oracle 7.3 must be executed in oracle 8.0 with out any errors.

Page 22: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

10. Physical data independency: This feature specifies that even through the position on physical location of the table changes there will must not be any effect in the table data.

11. Normalizing the data : It specifies that they should not be any repetition on the data exists in the data base.

12. Data Transformation: This feature specifies data transferring between the RDBMS and also data transferring with in the RDBMS i.e. between the databases and users using import and export features.

Oracle Data types

The information in a database is maintained in the form of table, each table consists of rows and columns to store the data. A particular column in a table must contain similar data, which is of a particular type.

The following are different data types supported by ORACLE

1. CHAR This data type is used to store fixed length character of the specified length. Where the maximum size is 2000 bytes for columns/rows.

Syntax: char (size)Example : Result char(4)

VARCHAR2 This data type is used to store variable length characters.

Maximum it can take is 4000 bytes for columns/row.

Syntax: varchar2 (size)Example : sname varchar2(15)

2. NUMBER this data type is used to store both numbers and numbers with decimal pointes. It can take maximum precision up to 38 digits after decimal.

Syntax: Number(value, precisions)Example : Empno number(5) Pure Integers

Sal number(6,2) Numbers With Decimals

3. DATE This data type is used to store date and time in a table. The date data types stores year (including the century) . the month, the days, hours, minutes, seconds. The maximum size is 7 bytes for each row in a table.

Syntax: DateExample : Doj Date

4. LONG This data type is used to store variable length character containing up to 2 GB of information.

Syntax: Long Example : Remarks Long

Page 23: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Restriction of Long There are some restrictions of long data type.

1) Only one column is defined as long for table.2) Long columns con not be indexed.3) Long columns can’t appear in integrity constraints.4) Long columns can’t be used in SQL expressions.5) Long columns cannot be referenced by the SQL function

5. CLOB This data type is used to store variable length character containing up to 4 GB of information.

6. BLOB This data type is used to store Photos,Video Clips up to 4 GB of information.

7. BFILE This data type is used to store Binary Data,Files Path up to 4 GB of information

8. RAW This data type is used to store Binary Data up to 2000Bytes of information.

9. LONG RAW This data type is used to store Binary Data up to 2GB of information.

10.TIMESTAMP Date and time with fractional seconds.

11. INTERVAL YEAR TO MONTH Stored as an interval of years and months.

12. INTERVAL DAY TO SECOND Stored as an interval of days to hours minutes and seconds. 13. BINARY_INTEGER The range of binary_integer is -2147483647 to 2147483647

14. BOOLEAN Return true or false

Rules for define a table name.

1. The table name must not exceed 30 charactor. 2. The table name must begin with a alphabet between a and z. 3. The table name must not keep any spaces.

Page 24: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

4. The table name cannot be the same as a oracle reserved key word. 5. The table name cannot be the same as an existing database object with the same schema.

SQL * PLUS This is a basic shell for quarries and reports and data base manipulating apart from

the basic ability to issue SQL and PL/SQL commands, it has a number of extensions to permit programming and report formatting.

What is SQLSQL is an acronym of Structure Query Language. It is built to work around related

data bases that are sets of related information stored in tables. ‘IBM’ as the language to inter face with its prototype relational database management system introduced SQL. The first commercially available SQL relation data base management was introduced in 1979 by ORACLE Corporation.

Through SQL a user can do Enter, edit, store, retrieve and run SQL commands. Format, perform calculate, store and print query result in the form of

reports. List column definition of any table. Access and copy data between SQL databases.

SHOW USER....SET LINES...SYSDATE..TIMESTAMP..DICTIONARY...TAB..SQL PROMPT....DESC EMP,create new id1. uid : this function is used to show the user id of the currently active user

syntax : uid Example : select uid from dual;

Commands

DDL Create : It is use to create a table

Syntax

Page 25: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Create table <table name> (<column1> <Data Type> [Size],

<column2> <Data Type> [Size],

<column N> <Data Type> [Size]);

Example : Create Table Sample ( sno number(3), sname varchar2(10));

ALTER COMMAND It is used to change the structure of the Table i.e. adding new column, changing the

data type and size. The alter command can have 3 types of sub commands. They are:

1. Add2. Modify3. Drop

4.Rename(It’s a 10g command)1. ADD: By using this command we can add new columns to the existing table.

Syntax: Alter Table <Table_Name> add (

Column1 <data_type>[<size>],Column2 <data_type>[<size>],

- - - - -,Column(n) <data_type>[<size>])

2. Modify: It is used to change the Data Type and size of the existing columns. If you can change the Data Type and Size you must satisfy the following rules.

a. By using Modify command in alter we cannot change the column name.b. We can not Change the Positions of the existing or new columnsc. We cannot decrease the length (Size) of an existing column, if that column

is having values. But we can increase the size of the existing column even if the data is present

Syntax:Alter Table <Table_Name> Modify (

Column1 <data_type>[<size>],Column2 <data_type>[<size>],

- - - - -,Column(n) <data_type>[<size>])

3. Drop This command is introduced in Oracle 8i. It is used to remove the column of a table.

Syntax:Alter Table <table_name> Drop column <column_name>

Examples on Alter CommandCreate a table with the following structure

Create table students(roll number(3), sname varchar2(20), sub1 number(3), sub2 number(3), sub3 number(3));

Page 26: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Insert some values into that table GET BACK @DD AND ALSO DELETE COMND

4.Rename This command is used to rename column name.

Syntax

ALTER T TNAME RENAME OLDCNAME TO NNAME;

Drop This command is used to Drop a table

Syntax Drop table t_name;

(GET BACK FLASHBACK T TNAME TO BEFORE DROP)

Rename CommandIt is used to change the name of the Object like table.

Syntax: Rename <old_table_name> to <new_table_name>

Example: Rename sample to samples;Example: Rename samples to sample;

DML

Insert commandThe insert command is used to append the new records /rows / values at the end of the

object (Table or View).

Syntax:Insert into <table_name> (columns list) values (value1, value2,….,value N)

Examples on Insert CommandFirst Create a table

Create Table Sample ( sno number(3), sname varchar2(10), class varchar2(10));

To insert values into all Columns Insert into sample values (100, “Nithya”, ”First”);

Page 27: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

After entering the above query on the SQL prompt, press the enter key, if you entered the query correctly, it displays a message “ 1 Record Inserted “ otherwise it displays an error message.

Similarly insert some more values as follows Insert into sample values (101, “Saloni”, ”Second”); Insert into sample values (102, “Aruna”, ”Third”);

To insert values into specified Columns Insert into sample(sno,class) values (103, “Fourth”);

Update Command This command is used to update or modify all or specified column values with new

values.

Syntax:Update < Table Name > set <column1> = <value1>, <column2>=<value2>,

-------<column N>=<value N> where <condition>

Examples:To update only one column value

Update sample set sno=500 where sno=100;

1.Q: CHANGE THE DEPTNO OF JAMES TO 20 AND INC SAL 20%

UPDATE EMP SET DEPTNO=20 ,MGR=7788,SAL=SAL+(SAL*20/100)WHERE ENAME='JAMES';

2.Q: REPLACE COMM OF ALL SALESMAN OF SALES DEPT WITH 30% OF THEIR OWN SAL AND RECEIVING COMM ,COMM IS LESS THAN SAL BUT NOT ZERO....

UPDATE EMP SET COMM=SAL*30/100WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES') ANDJOB='SALESMAN' ANDCOMM<SAL AND COMM<>0;

3.Q: REPLACE THE SAL OF HIGHEST PAID EMPS OF RESEARCH DEPT WITH THE HIGHEST SAL OF DEPTNO 10

UPDATE EMP SET SAL=(SELECT MAX(E.SAL) FROM EMP E,DEPT D WHERE D.DNAME='RESEARCH' ANDE.DEPTNO=D.DEPTNO);

UPDATE EMP SET ENAME=LOWER(ENAME);

Delete CommandThis Command Is Used To Delete All Or Specified Rows In A Table

Page 28: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Syntax : Delete From <table name> where <condition>Ex : To Delete A Single Row

Delete from sample where sno=109;

Ex : To Delete Multiple Rows (More Than One Row) Delete from sample where sno=106 or sno=108;

Q: DELETE ALL THE EMPS WORKING IN THE DEPT WHERE JAMES MGR IS WORKING...

A: DELETE FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE

EMPNO=(SELECT MGR FROM EMP WHERE ENAME='JAMES'));

**************************************************Q: DELETE ALL THE EMPS WHO ARE SENIOR TO JAMES AND JUNIOR TO FORD ,SAL MORE THAN SMITH AND LESS THAN BLAKE......

A: DELETE FROM EMP WHERE HIREDATE<(SELECT HIREDATE FROM EMP WHERE

ENAME='JAMES') AND

HIREDATE>(SELECT HIREDATE FROM EMP WHERE ENAME='FORD') ANDSAL>(SELECT SAL FROM EMP WHERE ENAME='SMITH') ANDSAL<(SELECT SAL FROM EMP WHERE ENAME='BLAKE');

Q: DELETE ALL EMPS BELONG TO GRADE 1 RECEIVING NO COMM AND WORKING UNDER SOME MANAGERS......

A: DELETE FROM EMP WHERE EMPNO IN(SELECT EMPNO FROM EMP E,SALGRADE S WHERE

S.GRADE=1 AND E.SAL BETWEEN S.LOSAL AND S.HISAL) AND COMM IS NULL AND

MGR IS NOT NULL;

*************************************************Q: DELETE ALL THE EMPS WHOSE SAL IS MORE THAN AVG SAL OF ALL EMPS WHO ARE MANAGERS TO OTHERS

A: DELETE FROM EMP WHERE SAL>(SELECT AVG(SAL) FROM EMP WHERE EMPNO

IN(SELECT MGR FROM EMP));****************************************************Q: DELETE ALL THE EMPS WHO ARE SENIOR TO THE SENIORMOST EMP OF GRADE 4,DONT DELETE GRADE 5 EMPS

A: DELETE FROM EMP WHERE HIREDATE>(SELECT E.HIREDATE FROM EMP E,SALGRADE

S WHERE S.GRADE=4 AND E.SAL BETWEEN S.LOSAL AND S.HISAL) AND

EMPNO NOT IN(SELECT E.EMPNO FROM EMP E,SALGRADE S WHERE S.GRADE=5 AND

Page 29: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

E.SAL BETWEEN S.LOSAL AND S.HISAL);

If emp table having any duplicate record delete that.

delete from emp where rowid in(select rowid from emp e where rowid !=(select max(rowid) from emp where e.empno=empno))

write a query to display the duplicate salary. select * from emp where sal in( select sal from emp where rowid not in( select max(rowid) from emp group by sal))

DELETE DUPLICATE RECORD.

DELETE FROM EMP WHERE ROWID IN (SELECT ROWID FROM EMP E WHERE ROWID != (SELECT MAX(ROWID) FROM EMP WHERE E.EMPNO=EMPNO))

DELETE FROM EMP WHERE ROWID IN (SELECT ROWID FROM EMP E WHERE ROWID NOT IN (SELECT MAX(ROWID) FROM EMP WHERE E.SAL=SAL))/

TCL

Commit The changes made by the user are not physically written to the table, giving only the

user a view of his/her work. While the other users, having access to these tables, continue to get the old information. The “Commit” command is used to make the changes permanent to the database.

A commit statement guarantees all of the transactions, modifications are made permanent part of the data base. By default, all your transactions are temporarily stored in the database.

Syntax : commit;SQL * Plus has the facility to automatically commit all the work, without explicitly

issuing the Commit command

Set AutoCommit ON : Enable Autocommit feature

Set AutoCommit OFF : Disables Autocommit feature (default)

RollbackThis Rollback command is used to undo work done in the current transaction. Ie the

user can continue with any number of inserts, updates and / or deletetion, and still undo the work, issuing the Rollback Command.

Page 30: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Syntax : Rollback To [Savepoint] Savepoint_Nameoptional

SavePointSavepoint identifies a point in a transaction to which one can later rollback with the

Rollback command. It is helpful when a transaction contains a large number of SQL statements and the user wants to commit only once when all are done. If required, one can rollback to a particular transaction. It works in a Last In First Out (LIFO) manner

Savepoint command Sets a save point within a transaction or to identify a point in a transaction to which you can later roll back.

Syntax : Savepoint savepoint_name;Note : Save point works as LIFO manner (Last In First Out). We can not rollback only middle part of the transaction. If you rollback to middle part, then last part also affects with the rollback command.

DCL

GRANT

This command is used to give the permission.

REVOKE This command is used to stop the permission

DRL

Select This command is used to REtrive the data from the db

Operators 1. Arithmetic operator. + , * , - , / .

2.Comparison operator. = ,>, <, >=, <=, <>, != in ,not in, between ,not between, like , not like ,is null ,is not null.

Page 31: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

3. logical operator. and ,or ,not

4. concatenate operator. ||

QUERIES

select sysdate-hiredate from emp where ename='smith';

select (sysdate-hiredate)/365 from emp where ename='smith';

select (sysdate-hiredate)/365 EXP from emp where ename='smith';

Select distinct(job) from emp where deptno=30;

Select * from emp where deptno=30 and job='salesman';

1. List The Employees Belonging To The Department 20 Select * from emp where deptno = 20 ;

2. List The Name And Salary Of The Employees Whose Salary Is More Than 1000 Select ename, sal from emp where sal > 1000 ;

3. List The Names Of The Clerks Working In The Department 20

Select ename, job from emp where job = ‘Clerk’ and deptno = 20 ;

4. List The Names Of Analysts And Salesman Select ename, job from emp where job =

‘ANALYST’ or job=‘SALESMAN’ ;

5. List the details of the employees who have joined before the end of september 1981.

Select * from emp where hiredate <= ’30-Sep-1981’ ;

6. Select ename,job,sal,comm,sal+comm from emp;

Page 32: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

7. Select ename,job,sal,sal-100 debitsal,sal*12 asal ,sal/30 dsal from emp;

8. Select * from emp where deptno=20;

9. Select * from emp where sal<2000;

10. Select * from emp where deptno!=30;

IN The IN operator is used to determine if a given value matches any value in a sub query or in a list Syntax : [ Not ] In <List of Values>

Examples : 1. List the employees details whose employee id’s are 7369,7499,7788

select * from emp where empno=7369 or empno=7499 or empno=7788; select * from emp where empno in (7369,7499,7788);

2. List the employees details whose employee id’s are not 7369,7499,7788

select * from emp where empno!=7369 and empno!=7499 and empno!=7788;

3. select * from emp where empno not in (7369,7499,7788);4. Select * from emp where deptno in(10,20);5. Select * from emp where job not in('clerk','manager');

Between The Between operator is used to specify a range of values. It retrieves

the values by depending on the condition, on the range of any columnSyntax : [ Not ] Between <Begin Expression And End Expression>Note : Unlike in ordinary English, “Between” is an inclusive operator ie both the values will be included in the range. The Not Between is an Exclusion operator

Examples : List the employees details whose salary is >=3000 and <=5000

select * from emp where sal>=3000 and sal<=5000; select * from emp where sal between 3000 and 5000;

List the employees details whose salary is not between 3000 and 5000

select * from emp where not sal>=3000 and sal<=5000;

select * from emp where sal not between 3000 and 5000;

Page 33: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Like Operator The Like Operators is only used with Char and Varchar2 data types to match a

pattern of characters

It determines whether or not a given character string matches the specified pattern.

A pattern can include regular characters and wild card characters. During pattern matching regular characters must exactly match the characters specified in the character string.

Oracle supports two types of wild cards, they are1. _ ( underscore ) : Represents a Single Character2. % ( Percentage ) : Represents Multiple Characters

Select * from emp where hiredate like '%81'; Select * from emp where hiredate like '03%'; select * from emp where hiredate like '%dec%'; Select * from emp where ename like 'a%'; Select * from emp where ename like 'j%s'; Select * from emp where ename like '_l%'; Select * from emp where ename like '%a%' Select * from emp where ename liKe'%A_S%' Select * from emp where ename like 'a%' S elect * from emp where ename not like '%g'

1. List the details of the employees whose names Second Character is letter ‘A’ select * from emp where ename like ‘_A%’;

2. List the details of the employees whose names Exact Length is 5 characters only select * from emp where ename like ‘_ _ _ _ _’;

syntax : [ Not ] Like < Pattern >Note : This Like Operator can only be used with Varchar2 and Char data types only.Examples :

3. List the details of the employees whose names not starting letter is ‘S’ select * from emp where ename not like ‘S%’;

4. List the details of the employees whose names not Ends with letter ‘N’ select * from emp where ename not like ‘%N’;

5. Select ename,job from emp where sal>= 1000 and job like '%man%';6. Select * from emp where job='clerk' or deptno=20;7. Select * from emp where mgr is null;8. Select * from emp where mgr is not null;

Page 34: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

9. Select * from emp where job='clerk' or job='salesman' and sal>1500;

10. Select * from emp where (job='clerk' or job='salesman') and sal>1500;

11. Select * from emp where comm is null;12. Select * from emp where comm is not null;13. select * from emp where deptno=30 and job='salesman';14. Select * from emp where deptno=10 or job='analyst';15. Select ename||' '||'is a'||' '||job||' '||'working under deptno'||' '||deptno from emp;

16. Select * from emp where (deptno=20 or job='manager') and sal<2000;

SQL FUNCTIONS

Built In Function in OracleSQL Functions are of two types, they are

1. Single Rows Functions : These functions will have effect on a single row of the table

2. Group Functions : These functions will have effect on a group of row’s

1 Charactor functions := Ascii,Chr,length,lower,upper,reverse,translate,replace, concat,ltrim,rtrim,lpad,rpad,initcap,instr,substr.

2. Numeric function.(arthimetic) :=

abs,power,ceil,floor,greatest,least,round,trunc,mod

3. date function := add_months,months_between,next_day,last_day

4 Conversion function = to_char,to_date,to_number

5 Aggrigate function = count,sum,min,max,avg

6 Nvl functions := Nvl , Nvl2 , Nullif , Coalesce

7.case,decode..

1. Abs : This function is used to convert any negative expression into positive

Page 35: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Syntax : Abs (Numeric Expression)Example : Select abs(-100) from Dual ; 100

Select abs(300-500) from Dual ; 200 Select abs(-20*30) from Dual ; 600

Sqrt (Square Root) : This function is used to find the square root value for the given number

Syntax : Sqrt ( Number )Example : select sqrt(2) from dual ; 1.4142select sqrt(16) from dual ; 4select sqrt(sal) from emp;select sqrt(4*sqrt(2)) from dual;Power :This function is used to find the power value ie x to the power of y value

Syntax : Power(x,y)Example : select power(2,3) from dual ; 8select power(5,3) from dual ; 125select power(sal,2) from emp;Round :This function is used to round off the given numeric expression according to specified length or precision

Syntax : Round(Numeric Expression, Length)Example : select round(98.52) from dual; 99

Select round(65.567,1) from dual ; 65.6Select round(65.567,2) from dual ; 65.57

Select ename,job,sal,sal/30 dsal ,round(sal/30) sal,round(sal/30,2) sal from emp;Select round(sysdate,'year') from dual;Select round(sysdate,'month') from dual;Select round(to_date('16-oct-87'),'day') from dual;Select round(‘dy-dd-mon-yy’,’week’) from dual;

Ceil : This function returns the nearest integer greater than the given numeric expression

Syntax : Ceil(Numeric Expression)Example : Select ceil(-23.567) from dual ; -23Select ceil(23.567) from dual ; 24

Floor : This function returns the nearest integer smaller than the given numeric expression

Syntax : Floor(Numeric Expression)Example : Select floor(-23.567) from dual ; -24 Select floor(23.567) from dual ; 23

Page 36: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Log : this function is used to find the logarithm value for the given number and for the given base

Syntax : Log(Number, Base Value)Example : select log(10,10) from dual; 1select log(2,10) from dual; 3.3219

Character Functions or Text Functions or String Functions|| or Concat : Glues or concatenates two strings together. The ‘|’ symbol is called as vertical bar or pipe

Syntax : string1 || string2 ( for || Function)Syntax : Concat(string1 , string2) ( for concat Function)

Example : select concat ( city, country) from location; is same as select city || country from location;

GREATESTSelect greatest(45.65,78.65,98.65) from dual;Select ename,sal,comm,greatest(sal,comm) max from emp;

LEAST

Select least(45.65,78.65,98.65) from dual;Select ename,sal,comm,Least(sal,comm) min from emp;

MOD this function is used to find the reminder

Select mod(106,10) from dual;

ASCII :

This Function Returns The Ascii Code Value Of The Left Most Character From The Given Character Expression

Syntax : Ascii(Character Expression)Example : select Ascii(‘a’) from dual ; 97select Ascii(‘A’) from dual ; 65Chr : This Function Returns The Ascii Character For The Given Ascii Value

Syntax : Chr(Ascii Value)Example : select chr(65) from dual ; ASelect chr(97) from dual ; aLength : This Function Is Used To Find The Length Of The Given Character Expression

Syntax : Length ( character expression )Example : select length (‘sairam’) from dual; 6select length (ename) from emp;Upper :

Page 37: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

This Function Is Used To Convert All Characters In To Upper CaseSyntax : Upper (Character Expression)

Example : select upper (‘sairam’) from dual; SAIRAM

6 .Lower :

This Function Is Used To Convert All Characters In To Lower CaseSyntax : Lower (Character Expression)

Example : select lower (‘SAIRAM’) from dual; sairam

7.Ltrim : This Function Removes Any Spaces From The Left Side of The String

Syntax : Ltrim(String)Example : Select ltrim('malayalam','ma') from dual;

This Function Removes Any Space From The Right Side of The StringSyntax : Rtrim(String)

Example : Select rtrim('malayalam','am') from dual;9.Trim : (Oracle 9i)

If You Are Trimming The Exact Same Data From Both The Beginning And Then End Of The String, Then You Can Use The Trim Function In Place Of An Ltrim/Rtrim Combination

Syntax : Trim(String)Example: Select trim('m' from 'malayalam') from dual;

10.Substr : (Sub String)

This function returns a part of the string from the specified Position to the specified number of charactersSyntax: Substr(String, Start Postion,Number of Characters)

Example : select substr(‘disk operating system’,6,9) from dual; --> operating11.Lpad :

This function is used to append the given text to the left side of anycolumn or String or lpad function allows you to “pad” the left side of a column with any set of Characters.

Syntax : Lpad (<Expression>,<Size>,<String Expression>)Example : select lpad(sal,7,’Rs. ‘) from emp;

output

Rs. 800Rs.1200

Example : select lpad(sal,10,’Rs. ‘) from emp;

output

Rs. Rs. 800Rs. Rs.1200

12 .Rpad :

Page 38: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

This function is used to append the given text to the right side of any column or string or lpad function allows you to “pad” the left side of a column with any set of characters.

Syntax : Rpad(<Expression>,<Size>,<String Expression>)Example : select Rpad(sal,7,’Rs. ‘) from emp;

output

800Rs. 1200Rs.

Example : select Rpad(sal,10,’Rs. ‘) from emp;

output

800Rs. Rs. 1200Rs. Rs

13. Initcap :This function takes the initial letter of every word in a string or column and

converts just those letters to upper case.

Syntax : initcap (String)Example : select Initcap(ename) from emp;

select Initcap(‘WELCOME TO ALL’) from dual; Welcome To All

14.Translate : This function is used to translate the source expression into target expression that

is present in the main string

Syntax : Translate(Main String, Source Expression, Target Expression)

Example : select Translate (‘jack’,’j’,’b’) from dual; back

select Translate (‘back and bill’,’b’,’j’) from dual; jack and jill

it will translate only one char

Date and Time Functions

Sysdate : This Function Returns The System Date And Time. By default it will show only

the data but not the time. To show time also, we have to user To_Char conversion function

Syntax : SysdateExample : select sysdate from dual;

To add five minutes

Page 39: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select to_char(sysdate +05/1440,'hh:mi:ss am') from dual;

To subtract ten minutesselect to_char(sysdate -10/1440,'hh:mi:ss am') from dual;

To change date format. alter session set nls_date_format='dd-month-yyyy'

select sysdate-1 from dualto find last date...+1 to tomrow...

Add_Months : This function is used to add the number of months to the months part of the

accepted dates. ( we can give positive/negative values )

Syntax : Add_Months(Date, Number)Example : select sysdate, add_months(sysdate,5) from dual;

Output

SYSDATE ADD_MONTH

------------ ---------------14-FEB-05 14-JUL-05

Last_day : This Function Is Used To Return The Last Day Of Accepted Date (0r) Last Day

Of the Month

Syntax : Last_day ( date expression )Example : select sysdate, Last_Day(sysdate) from dual;

OutputSYSDATE LAST_DAY(

----------- --------------14-FEB-05 28-FEB-05

Next_DayThis function is used to find the Next day of the given weekday name

Syntax : Next_Day(Date Expression, Week day name)1. Example : select sysdate, next_day(sysdate, ‘Monday’) from dual;

Output SYSDATE NEXT_DAY(

--------- ----------------14-FEB-05 21-FEB-05

Page 40: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

months_betweenThis function is used to find number of months between the given two dates

Syntax : months_between(date expression1, date expression2)Example : 1

2. select months_between(sysdate,to_date(‘20-oct-05’,’dd-mon-yy’)) from dual;

MONTHS_BETWEEN(SYSDATE,TO_DATE(‘20-OCT-05’,’DD-MON-YY’))2.432654

To eliminate decimal points, give the following form

3. select round(months_between(sysdate,to_date(‘20-oct-05’,’dd-mon-yy’))) from dual

ROUND(MONTHS_BETWEEN(SYSDATE,TO_DA2

4. select round(months_between(to_date(‘20-oct-05’,’dd-mon-yy’),sysdate)) from dual;

CountThe count function is used to find the number of records or non – null columns values

in the given column or expression

Syntax : count(* | distinct <column name>)Examples :

write a query to count total number of records in the given table

select count(*) from emp;write a query to count, how many types of jobs available in the emp table

select count(job) from emp;

select count(*) from emp WHERE JOB='MANAGER';select count(*) from emp WHERE DEPTNO=30;Select deptno,count(*) from emp group by deptno;

Sum(sal)This command is used to find the sum of all Values of given numerical columns.

Syntax : Sum(distinct <numerical column>)Examples :Write a query to find sum of sal for all employees in the emp table

select sum(sal) from emp;

Page 41: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Max(sal) : This command is used to find the maximum value from the given numerical column.

Syntax : Max(numerical column)Example :

Write a query to find maximum sal earning by an employee in the emp tableselect max(sal) from emp;

Min(sal) : This command is used to find the minimum value from the given numerical column.

Syntax : Min(numerical column)Example:Write a query to find minimum sal earning by an employee in the emp table

select min(sal) from emp;

Avg(sal) : This command is used to find the average value from the given numerical column.

Syntax : Avg(distinct <numerical column>)Example :Write a query to find average salary of all employee in the emp table

select avg(sal) from emp;

Group By ClauseThe group by clause is used with “select” to combine a group of rows based on the

values of a particular column or expression. Aggregate functions are used to return summary information for each group. The aggregate functions are applied to the individual groups.

List The Department Numbers And Number Of Employees In Each Department

select deptno, count(*) from emp group by deptno ;

List the jobs and number of employees in each job

select job, count(*) from emp group by job;

List The Total Salary, Maximum And Minimum Salary And The Average Salary Of Employees Job Wise

Page 42: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select job, sum(sal), avg(sal), max(sal), min(sal) from emp group by job ;

Select deptno,job,max(sal) from emp group by cube(job,deptno);

Select deptno,job,sum(sal),count(*) from emp group by job,deptno;

Select deptno,job,sum(sal),count(*) from emp group by cube(job,deptno);

Having ClauseThe having clause is used to specify which groups are to be displayed that means it

restricts the groups which returns on the basis of aggregate functions

(Or)

This is used to define condition on the columns used after the group by clause. It is used to restrict the number of rows by specifying a condition with the grouped columns

Examples :List The average salary of all the Departments employing more than 5 people

select deptno, avg(sal) from emp group by deptno having count(*)>5;

List the jobs of all the employees whose maximum salary is >=5000

select job, max(sal) from emp group by job having max(sal)>=5000;

Order By ClauseThe order by clause is used to arrange the rows in Ascending or in descending order.

By default the select statement displays in ascending order. If you want to display in descending order, specify the “desc” keyword after the column name.

Multiple columns are ordered one within another, and the user can specify whether to order them in ascending or in descending order.

1. List The Empno,Ename,Sal In Ascending Order By Salary select empno,ename,sal from emp order by sal;

2. List The Employee Name In Ascending Order And Their Salaries In Descending Order

select ename ,sal from emp order by ename, sal desc;

Select deptno,sum(sal) from emp group by deptno having sum(sal)>8000

Select deptno,max(sal) from emp group by deptno;

Select min(hiredate) from emp;

Select job,min(hiredate) from emp group by job;

Select deptno,count(*),sum(sal),avg(sal) from emp group by deptno;

Page 43: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Select deptno,min(sal) from empWhere deptno in(20,30,10)Group by deptno;

Select deptno,count(*) from empGroup by deptnoHaving count(*) >2

Select deptno,sum(sal) from emp Group by deptnoHaving sum(sal) <5000

Select deptno,job,mgr,sum(sal) from empGroup by grouping sets((deptno,job),(job,mgr))/

Select job,min(sal) from emp group by job having min(sal)>2000 order by job

Select deptno,avg(sal) from emp group by deptno;

To_char : This function is used to change the format of accepted date into any predefind

format.

Syntax : To_char(<Date Expression>, <Format>)

Predefined Format’s Aremm/dd/yy yy.mm.dddd/mm/yydd.mm.yydd-mm-yymon yymon dd, yyhh:mm:ssmon dd yyyy hh:mi:mm (Am or Pm)

Page 44: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

mm-dd-yyyy mm dddd mon yyyy hh:mi:ss:mm (24 hour format)hh:mi:ss:mmm (24 hour)dy (to find week day number)day (week day name)

dd (number of days in month)

yyyy (year in four digits)

yy (year of Last two digits)

year (spelt in terms of words)

month (month name)

w (week number)

Example : 1select sysdate,to_char(sysdate,’dd mm yy’) from dual;

SYSDATE TO_CHAR(S

--------- ---------15-FEB-05 15 02 05

select sysdate,to_char(sysdate,’month dd day w’) from dual;

select to_char(sysdate,'ddsp-month-yyyy')from dual;

select to_char(to_date('2-jan-90'),'day-ddspth-month-year')from dual;

select to_char(to_date(empno,'j'),'jsp')from emp;

select to_char(to_date(comm,'j'),'jsp')from emp;

error: julian date must be between 1 and 5373484Select to_char(to_date(comm,'j'),'jsp')from emp

Where comm is not null and comm<>0

> select to_char(sysdate,'ddspth-month-year')from dual;

> select to_char(sysdate,'ddspth-month-year,hh:mm:ss')from dual;

> select to_char(sysdate,'hhpm:mi:ss') from dual;

> select to_char(to_date('28-mar-2007'),'ddspth-month-year,hh24:mm:ss')from dual;

(out put)

Page 45: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

sTO_CHAR(TO_DATE('28-MAR-2007'),'DDSPTH-MONTH-YEAR,H

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

twenty-eighth-march -two thousand seven,00:03:00

1. To_Date : this function is used to convert any character expression into a date expression according to the format you specified

Syntax : To_Date(<date expression>, <format>)

Example :insert into student(jdate) values(‘jan-10-05’)

ERROR at line 1:ORA-01858: a non-numeric character was found where a numeric was expected

insert into student(jdate) values(to_date(‘jan-10-05’,’mon-dd-yy’));

select round (to_date('05-mar-2007'),'year') from dual;

NVL FUNCTION

NVL :- Use to place any value if column contains null value.

select nvl(comm,1)comm from emp

NVL2 :- Nvl2 returns second not null argument.

select nvl2(10,20,30) from dual;

select nvl2(null,20,30) from dual;

select empno,ename,job,sal,comm,nvl2(comm,11,22) from emp;

NULLIF :- Nullif compare two value if both are same function returns

null if both are not same function returns first arguments.

select nullif(10,10) from dual;

select empno,ename,job,sal,comm,nullif(comm,500) from emp;

COALESCE :- The COALESCE function returns the first not null

expression of the list.

select coalesce(10,20,30,40) from dual;

select empno,ename,job,comm,coalesce(comm,sal,55) from emp

Page 46: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PSUDO COLUMNS The psudo columns are will not create by users they will create by defaults…so they are pre –defined columns…..

ROWID,ROWNUM,CURRENT VALUE,NEXT VALUE

You can find rowid,rownum in tables and current value,next value in sequence.

Select rowed,rownum from t_name; Select seq_name.nextval from dual;

Select seq_name.currval from dual;

Page 47: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Constraints

These are the conditions or rules that we impose on any column for entering valid data into the table. Constraints are a part of the table definition that are used to limit the values entered into its columns.

Note : Constraints can be imposed in two ways 1. Table Level and2. Column Level

Table Level :Imposing constraints on a table level by specifying the constraint type at the end of

the columns is called Table Level Constraints. In Table Level, the Constraint key word followed by Constraint name must be defined otherwise error comes.

Column Level :Imposing constraints on a column by specifying the constraint type beside the column

name is called Column Level Constraints

Constraints can be defined in two ways

1. In the Table Definition itself2. Using Alter Command

The following are a list of constraintsS

1. NOT NULL CONSTRAINT2. UNIQUE CONSTRAINT3. PRIMARY KEY CONSTRAINT4. CHECK CONSTRAINT5. DEFAULT6. REFERENCES (FOREIGN KEY CONSTRAINT )

NOT NULL The Not Null constraint specifies that a column can not contain Nulls. To satisfy this

constraint every row in the table must contain a value for the column.

if you do not specify not null, the column can contain nulls by default

Syntax:Not Null in Column Level

Create table <Table Name> ( Column <Data type><size> Not Null,Column2 <Data Type><size> ,-------);Adding Not Null Using Alter Command for Existing Table

Alter Table <Table Name>

Page 48: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Modify (<Column Name > <data type> (size) not null)Note :

1. Column must be empty to impose the not Null constraint with alter table statement.

2. Table Level is not applicable for Not Null constraint

Example : Create table sample1(sno number(3), sname varchar2(20) not null);

insert into sample1 values(&sno,’&sna’);

Enter value for sno: 100Enter value for sna: Mahesh

Enter value for sno: 101Enter value for sna: (nothing is entered)

Error Comesmandatory (NOT NULL) column is missing or NULL during insert

Unique ConstraintThis constraint does not allow duplicate values into any column.

Syntax: (For Column Level)Create Table <Table Name>(Column1 <Data Type><Size> Unique,

Column2 <Data Type><Size>,--------); Syntax: (For Table Level)Create Table <Table Name>(Column1 <Data Type><Size>,

Column2 <Data Type><Size>,--------,Constraint <Constraint Name> Unique <Column Name>);

( Or )Example : Imposing unique constraint Table Levelcreate table customer(cno number(3),cname varchar2(20),

constraint con_un unique(cno)); insert into customer values(&cno,’&cname’);

Enter value for cno: 100Enter value for cname: Mahesh

Enter value for cn: 100Enter value for c: Nithya

Error Comesunique constraint (SCOTT.CON_UN) violated

Example : Imposing unique constraint Column Levelcreate table customer1(cno number(3) unique ,cname varchar2(20));

insert into customer1 values(&cno, ‘&cname’);

Page 49: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Enter value for cno: 100Enter value for cname: Mahi

Enter value for cn: 100Enter value for c: Prasad

Error Comesunique constraint (SCOTT.SYS_C00385) violated

Default Constraint :The default constraint is used to specify a default value for the column, when you

want to given default values. You can give default value as NULL or some other value.

Note : Only Column level definition can be applied to “Default constraint”Syntax : for column levelCreate Table <Table Name>(Column1 <Data Type><Size> default <value>,

Column2 <Data Type><Size>,--------);Example :

create table sample2(sno number(3) default 10,sname varchar2(20), phone

varchar2(10) default null)

insert into sample2 values(1,’Mahesh’,’11111’) insert into sample2 values(2,’Prasad’,’22222’) insert into sample2(sno, sname) values (3,’Nithya’) insert into sample2(sno, sname) values (4,’Saloni’) select * from sample2;

SNO SNAME PHONE

--------- -------------------- ---------- 1 Mahesh 11111 2 Prasad 22222 3 Nithya 4 Saloni

Example : 2 create table sample3(sno number(3) default 100, sname varchar2(10) not null);

insert into sample3 values(200,’Nithya’) insert into sample3 values(201,’Aruna’) insert into sample3(sname) values(‘Mahesh’) insert into sample3(sname) values(‘Saloni’)

select * from sample3;SNO SNAME --------- ---------------- 200 Nithya 201 Aruna 100 Mahesh

Page 50: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

100 Saloni

Check ConstraintThe check constraint explicitly defines a condition. It will put restrictions on the range of the column values and the values to be accepted into the column. The condition of a check constraint can refer to any column in the table. But it can not refer to any column in other tables.Syntax : (column Level)Create table <table name> (<column1> <datatype> [size] check(condition),

<column2><data type> <size>,-----);Example:Create table items(itemno number(3) check(itemno>=100),itemname varchar2(10));

Insert into items values (100,’Rice’) insert into items values(101,’Paste’) insert into items values(99,’Chacolate’) Error comes

Syntax : (Table Level)Create table <table name>

(<column1> <datatype> [size],<column2><data type> <size>,constraint <constraint name> check(<column name> with

condition));Example :create table item1(itno number(3), Itname varchar2(10),

Constraint con_check check (itno>=100));

Insert into item1 values (100,’Rice’) insert into item1 values(101,’Paste’) insert into item1 values(99,’Chacolate’) Error comes

Primary Key ConstraintIt avoids null values and also it does not allows duplicate values. Ie A Primary key is

nothing but combination of not null and unique constraints

To Impose Primary Key On Any Column, You Can Use Either Table Level Or Column LevelSyntax: Table Levelcreate table <tablename>(column1 <datatype><size>,

column2 <datatype><size>,--------,

constraint <constraint name> primary key <column name>);

Ex: create table items1(itemno number(3),itemname varchar2(20),

constraint con_pk primary key(itemno));

insert into items1 values(100,’Rice’);

Page 51: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

insert into items1 values(100,’paste’);

Error Comesunique constraint (SCOTT.CON_PK) violatedSyntax : Column Levelcreate table <tablename>(column1 <datatype><size> primary key ,

column2 <datatype><size>,--------);

Example : create table items2(itemno number(3) primary key, itemname varchar2(20));

insert into items2 values(100 ,’Wheat’); insert into items2 values(100 ,’Rice’);

Error Comesunique constraint (SCOTT.CON_PK) violated

Example 2 insert into item values(null ,’Wheat’);

Error Comesmandatory (NOT NULL) column is missing or NULL during insertForeign Key Constraint

This is used to establish relationship between 2 or more tables for inserting common or similar values into the related columns of the table.

The table from which we are establishing relation is called child table. Because the related column in the child table depends on another table for its values.

The table on which other tables are depending on the table, to which we are establishing a relation is called Mother table.

If two tables are having this relationship then the system checks whether the new value that we are inserting is related column of child table exists in the mother table or not.

There are five major restrictions related to foreign key1. The Mother table column related must have primary key2. We can not drop the mother table with out child table provided. 3. The data type and the size of the related columns in both the tables must be same

and name can be different4. We can establish relation to any number of tables5. We can not impose foreign key which are having values.

Syntax : (Column Level)Create Table <Table Name>

(<column1><data type><size>

References <Mother Table>(<column name>),<column2><data type><size>,

<columnN><data type><size>);

Page 52: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Syntax : (Table Level)Create Table <Table Name>

(<column1><data type><size>

<column2><data type><size>,

<columnN><data type><size>,constraint <constraint Name> foreign key(child column)

References <Mother Table> (<column name>));Making relationships between two tables1. First Create the Mother Table or Parent Table

create table bankmast(accno number(3) primary key,

accna varchar2(10) not null,

balance number(8,2));

2. Next Create the Child Table create table banktrans

(acno number(3) references bankmast(accno),

trmode char(1),trdate date,

amount number(8,2));

3. Next insert the values in to mother table first, insert into bankmast values(&accno,’&accna’,&bal);

select * from bankmast;ACCNO ACCNA BALANCE--------- ---------- ----------- 100 Priya 5000 101 Mahesh 6500 102 Saryu 4500 103 Nandhini 7600

4. Next insert values into child table insert into banktrans values(&acno,’&trmode’,’&trdate’,&amt); insert into banktrans values(100,’D’,’5-May-05’,5000); insert into banktrans values(102,’W’,’15-Apr-05’,2000); insert into banktrans values(104,’D’,’10-Feb-05’,10000);

ERROR : (since there is no such account number present in the mother table)

ORA-02291: integrity constraint (SCOTT.SYS_C00674) violated - parent key not found

SQL> select * from banktrans;ACNO T TRDATE AMOUNT

Page 53: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

--------- --- ------------- ------------ 100 d 05-MAY-05 5000 102 w 01-JUN-05 2000

Dropping Relationship TablesNote :

1. if you try to drop the mother table when child table is present, it will give an error message

drop table bankmast;ERROR :

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

2. To drop the mother table, First Drop the Child table and then drop the mother table

Drop table banktrans;Drop table bankmast;

******************* OR ************************

CONSTRAINTS *********************************A set of pre define rules apply on table column at the time of creating tableor after creating table call constraints.

Page 54: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

On two way you can create constraints.

Table level constraints := After define the column.Column level constraints := At the time of define column.

Types of constraints. *************************************1. Domain level constraints > Not null Check

2. Integrity constraints > Unique key Primary key

3. References constraints > Foreign key

Rule of constraints. **********************************1. Not null - It will not accept null values. On one table user can define more than one not null constraints.

2. Check - User can provide condition like sal between 500 and 5000 job in('president','manager','clerk','analyst',salesman'); On one table user can define more than one check constraints.

3. Unique key- It will not accept duplicate values. It will accept null values. On one table user can define more than one unique constraints.

4. Primary key. It will not accept duplicate values. It will not accept null values. On one table one primary key can possible. One unique index will automatically create. This table is known as parent table.

5. Composit primary key - Using more than one column user can create one primary key that is composit primary key. It will not accept duplicate values.

6. Foreign key - It will accept duplicate values which is available in primary key. On one table user can define more than one foreign key. It will accept null values. This table is known as child table.

Page 55: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

On delete cascade - If child record is exists user cannot delete parent record using on delete cascade on foreign key constraint user can delete parent record. Same time automatically it will delete the child record.

On delete set null - If child record is exists user cannot delete parent record using on delete set null on foreign key constraint user can delete parent record. In case of on delete set null those child record will be there but it will place null values in child column cell.

***************************************************************************************************************************CREATE TABLE DEPT(DEPTNO NUMBER(4) CONSTRAINT PK_DEPT PRIMARY KEY,

DNAME VARCHAR2(10) CONSTRAINT CHK_DNAME CHECK(DNAME IN('RESEARCH','FINANCE','HR','ACCOUNTING')), LOC VARCHAR2(10), PHONE NUMBER(11))/CREATE TABLE EMP1(EMPNO NUMBER(4) UNIQUE,ENAME VARCHAR2(10) NOT NULL,JOB VARCHAR2(10), MGR NUMBER(4), DOJ DATE,SAL NUMBER(4) CONSTRAINT CHK_SAL CHECK(SAL BETWEEN 500 AND 5000),COMM NUMBER(4),DEPTNO NUMBER(4), CONSTRAINT FK_DEPT FOREIGN KEY(DEPTNO) REFERENCES DEPT(DEPTNO))

/

ALTER TABLE EMP ADD CONSTRAINT CHK_SAL CHECK(SAL BETWEEN 500 AND 5000);

create table ck (name varchar2(4) check (length(name)=4))> In this column you can not insert >4 and <4 charactor. It will take perticular 4 charactor. > create table con (ename varchar2(4) check (ename in('ddd','jkjk')),check(length(ename)=4))

> create table che (sno number(6) constraint p_k primary key, sname varchar2(10) not null, fee number(4) check(fee between 1000 and 5000),

Page 56: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

pap1 number(3) unique, loc varchar2(10) check (loc in('hyd','mum')))

Joins

One of the most important features of SQL is the ability to define relationships between multiple tables and draw information from them in terms of these relationships, all within a single command.

With joins we can combine columns from different tables. The connection between tables is established through the WHERE clause

Table and column alias namesThe full name of a column of a table actually consists of the table name followed by a

dot and then the column name e.g. emp.empno, emp.ename etc

User can omit the table names if one is querying only single table at a time. Even when querying on multiple tables one can still be able to omit the table names provided that all the column names are different.

Types of JoinsThere are five types of joins, they are

1. Equi Join ( = )2. Non Equi Join ( < , > , >=, <=, !=)3. Outer Join ( + )4. Self Join 5. Cross Join (Introduced in Orace 9i)

General Syntax :Select < select list > from <table1>,<table2>,-----, <table N>

Where <table1.column1>=<table2.column2> and ------Equi Join

When two tables joined together using equality operator, then it is called Equi Join. Table prefixes are utilized to prevent ambiguity and the Where clause specifies the columns being joined

Page 57: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Example :List the employee numbers, names, department numbers and dept names

Select empno,ename,emp.deptno,dname from emp,dept where emp.deptno=dept.deptno;

Here, the deptno column exists in both the tables. To avoid ambiguity, the column name should be qualified with the table name ( or with an alias of table name)

Both the table names need to be specified(emp and dept) the where clause defines the joining condition ie joining the deptno of emp table to the deptno of dept table. Here, it checks for the equality of values in these columns

Using Table AliasesIt can be very tedious to type table names repeatedly. Temporary labels ( or aliases)

can be used in the FROM clause. These temporary names are valid only for the current select statement. Table aliases should also be specified in the select clause. Table aliases can be up to 30 characters in length, but the shorter they are the better.

Example : List Employee Numbers, Names, Department Numbers, And Department Names From Emp And Dept Tables Using Aliases

select e.empno, e.ename, e.deptno, d.dname from emp e, dept d where e.deptno=d.deptno;

Non Equi JoinUsing this we can retrieve data from two or more tables by specifying a condition on

the common column with any non-equi join operators (>, <, >=, <=,!=)

Example :Write a query to display those employees details whose salary of emp1 table >= salary of emp table employees

select eno,ena,emp1.sal,emp.sal from emp1,emp where emp1.sal>=emp.sal

select e.ename,e.job,e.sal,s.grade,d.dname from emp e,salgrade s,dept dwhere e.sal between s.losal and s.hisal

and e.deptno=d.deptno and d.dname='sales' and s.grade=2;

select e.empno,e.ename,e.job,e.sal from emp e,dept dwhere e.deptno=d.deptno and d.dname='sales' and e.sal <=1500;

Outer JoinIt is used to retrieve the common data from both tables and all values from the table

having outer join operator (+)

There are 4 types of outer joins1. Left Outer Join2. Right Outer Join3. Full Outer Join4. Partition Outer Join

Page 58: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Left Outer Join It is used to retrieve all rows from the table having the outer join

operator which is left side to the outer join and common values from another

table

Example : Display the list of employees working in each department. Display the department

information even if no employee belongs to that department

select empno,ename,sal,emp.deptno,dname,loc from emp, dept where emp.deptno(+)=dept.deptno;

select e.ename,e.sal,d.dname from emp e left outer join dept d on e.deptno=d.deptno;

Right Outer JoinIt is used to retrieve all rows from the table having the outer join

operator which is right side to the outer join and common values from another

table

Example : Display the list of employees working in each department. Display the employee

information even if no such department belongs to the dept table

select empno,ename,sal,emp.deptno,dname,loc from emp, dept where emp.deptno=dept.deptno(+);

select e.ename,e.sal,d.dname from emp e right outer join dept d on e.deptno=d.deptno

if the symbol (+) is placed on the other side of the equation then all the employee details with no corresponding department name and location , will be displayed with NULL values in Dname and Loc columns

Rules to place ( + ) Operator1. The outer join symbol (+) can not be on both the sides2. We can not outer join the same table to more than one other table in a single

Select statement3. A condition involving an outer join may not use the IN operator or be linked

to another condition by the OR operator.

Full outer joins.

Here it will show both the extra field from two table.

select d.deptno,d.dname,d.loc from emp e full outer join dept d on e.deptno=d.deptno where e.ename is null;

Page 59: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select e.ename,e.sal,d.dname from emp e full outer join dept d on e.deptno=d.deptno;

P.OUTER JOIN

select e.deptno,j.job,sum(e.sal) from(select distinct job from emp) j left outer join emp e

partition by(deptno) on e.job=j.jobgroup by e.deptno,j.job;

NATURAL JOIN In natural join it will join the common column. select ename,job,dname,loc from dept natural join emp;

Note: eque joins its like a natural join.

Self JoinTo join a table to itself means that each row of the table is combined with itself with

every other row of the table. The self join can be viewed as a join of two copies of the same table. The table is not actually copied, but SQL performs the command as though it were.Retrieve those emp records who are earn more than avg salary of there dept.

select e.ename ename,e.sal salary,e.deptno dept,avg(ee.sal) avfrom emp e,emp ee where e.deptno=ee.deptnoand e.sal >(select avg(sal) from emp where deptno=e.deptno)group by e.ename,e.sal,e.deptno;

Example : list out the names of the manager with the employees in the emp table

Select w.ename, m.ename from emp w, emp m where w.mgr=m.empno;

Retrieve those employees record whose salary same as ford's salary.

select e1.ename,e1.sal from emp e1,emp e2 where e2.ename='ford' and e1.sal=e2.sal;

Retrive those employees record whose deptno equal to ford's deptno. select e1.ename,e1.deptno from emp e1,emp e2 where e2.ename='FORD' and e1.deptno=e2.deptno;

select w.ename||' is a '||w.job|| ' working under ' || m.job||' '|| m.ename from emp w,emp m where w.mgr=m.empno;

Page 60: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Cross Join (oracle 9i concept)

A cross joins returns what’s known as a Cartesian product. This means that the join combines every row from the left table with every row in the right table. This type of join can be used in situations where it is desired, to select all possible combinations of rows and columns from both tables. This kind of join is usually not preferred as it may run for a long time and produce a huge result set that may not be useful

Syntax Select <select list > from table1 alias cross join table2 alias

Example : Display the list of employees working in each department. Display the employee

information even if no such department belongs to the dept table and also display the department details even if no employee belongs to that department

select empno,ename,sal,emp.deptno,dname,loc from emp Cross join dept

Join with using clause . select e.ename,e.job,d.loc from emp e join dept d using (deptno);

SUB QUERYSub Queries Or Nested Queries

A query within another query is called a sub query. We can define any number of sub queries with in a query. But the system executes the inner most query first. If we are using relational operators between the queries then the sub query must return a single value.

The Following Points should be kept in Mind While using SubQueries

1. The inner Query must be enclosed in parentheses2. The Inner query must be on the right hand side of the condition3. The sub query may not have an order by clause4. The Order By clause appears at the end of the main select statement5. Sub queries are always executed from the most deeply nested to the least deeply

nested

Page 61: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Note : If we use operators “in” and “not in” then the sub query followed by the operators can return more than one value.

Example Queries

1. List the employee’s Details who belong to the department of “Ward”

In general, first we have to know; what the department of “Ward” and then we can display all the employee’s details belonging to “Ward”

select * from emp where ename=’WARD’;

select * from emp where deptno=30;

Using Sub Queries,

select * from emp where deptno=(select deptno from emp where ename=’WARD’);

2. List the employee’s details whose salary is greater than the average salary of all the employees

In general, first we have to know; average sal of all employee’s and then we can display all the employee’s details whose salary is > average salary of all employees

select avg(sal) from emp;select * from emp where sal>=2161;

Using Sub Queries,

select * from emp where sal>(select avg(sal) from emp);

3. Write a Query to find the details of the department whose manager’s empcode ‘7698’

In general, first we have to know; department number whose manager empcode is “7698” and then we can display all the department details of that employee

select * from dept;

select deptno from emp where mgr=’7698’

Page 62: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Using sub Query,

select * from dept where deptno=(select deptno from emp where mgr=’7698’)

ERROR at line 1:ORA-01427: single-row subquery returns more than one row

select * from dept where deptno in (select deptno from emp where mgr=’7698’)

Or you can give, like this

select * from dept where deptno=(select distinct deptno from emp wheremgr=’7698’);

4. List the details of all the employee’s who earn lowest salary in each department

select * from emp where sal in(select min(sal) from emp group by deptno)

SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE LOC=(SELECT D.LOC FROM EMP E,DEPT D WHERE E.ENAME='WARD' AND E.DEPTNO=D.DEPTNO));

SELECT * FROM EMP WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE LOC=(SELECT LOC FROM DEPT WHERE DEPTNO=(SELECT DEPTNO FROM EMP WHERE MGR=(SELECT EMPNO FROM EMP WHERE ENAME='SCOTT'))));

SELECT * FROM EMP WHERE MGR=(SELECT MGR FROM EMP WHERE HIREDATE=(SELECT MIN(HIREDATE) FROM EMP));

In which year maximum employees are joining

select * from emp where to_char(hiredate,'yyyy')=(select y from (select to_char(hiredate,'yyyy') y,count(empno) nfrom emp emp group by to_char(hiredate,'yyyy')order by n desc) where rownum<=1);

Department wise rank salary

select d.dname,e.ename,e.sal,e.deptno,dense_rank() over (partition by d.deptno order by e.sal desc) as drank from emp e,dept d where e.deptno=d.deptno;

Total table rank salary

Page 63: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select empno,ename,job,sal,deptno,dense_rank() over (partition by 'a' order by sal desc) as drank from emp;

Delete from emp where deptno=30;Retrieve those deptno no in which dept does not have any employee

select * from dept d where exists(select deptno from emp where deptno=d.deptno);

Retrieve those employees record who are working under KING

select * from emp where mgr=(select empno from emp where ename ='king');

Retrieve those employees record who are working under jones and clark ;

select * from emp where mgr in(select empno from emp where ename in('jones','clark'));

Retrieve those employee record who are working under sales and operations detp

select * from emp where deptno in(select deptno from dept where ename in('sales','operations')

SELECT E.* FROM EMP E,SALGRADE S WHERE DEPTNO IN(SELECT DEPTNO FROM DEPT WHERE LOC IN('NEW YORK','DALLAS')) AND S.GRADE IN(1,2) AND E.SAL BETWEEN S.LOSAL AND S.HISAL AND COMM IS NULL /

select * from emp where deptno=(select deptno from emp where ename='smith');

select * from emp where job=(select job from emp where ename='allen')

select * from emp where sal=(select min(sal) from emp); select * from emp where sal> (select sal from emp where ename='allen');

Page 64: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select * from emp where hiredate < (select hiredate from emp where ename='scott');

select * from emp where job <>(select job from emp where ename='smith');

select * from emp where deptno=(select deptno from dept where loc='chicago')

select * from emp where mgr <>( select empno from emp where ename='king');

select * from emp where sal=(select min(sal) from emp);

select * from emp where hiredate=(select min(hiredate) from empwhere deptno=10 );

select * from emp where mgr not in(select empno from emp where ename in('blake','king'));

select * from emp where sal> (select sal from emp where empno=7788);

Retrieve those employee record whos joining date first half of the month.

select * from emp where to_char(hiredate,'dd') <15;

Retrive that dname in which dname does not have any employee using subquery

select * from dept where deptno not in (select distinct(deptno) from emp);

Retrive those employee record who are working under experience manager.

select * from emp where mgr= (select empno from emp where hiredate= (select min(hiredate) from emp where job='manager'));

Display the employees whose sal is same Ford and Ward.

select * from emp where sal in(select sal from emp where ename in('ford','ward'))

Dept wise min sal

select * from emp where sal in(select min(sal) from emp group by deptno);

Page 65: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select * from emp where (deptno,sal) in(select deptno,min(sal) from emp group by deptno);

Job wise junior

select * from emp where hiredate in(select max(hiredate) from emp group by job)

3. Correlated subquery. Correlate subqueries are used for row-by-row processing .Each subquery is executed once for every row of the outer query.

Top five sal

select * from (select * from emp order by sal desc) where rownum<=5;

Write a co-related sub query to retrive second highest sal.

select * from emp where sal=(select distinct e.sal from emp e where 2=(select count(distinct Sal) from emp where e.sal<=sal));

E.SAL SAL******* ******** 5000 5000 3000 3000 3000 2975 2975 2850 2850 2450 2450 1600 1600 1500 1500 1300 1300 1250 1250 1100 1250 950 1100 850 950 800

Retrieve those deptno record in which department does not have any employee (using exests operator)

select * from dept d where not exists(select deptno from emp where deptno=d.deptno);

Page 66: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

SET OPEREATOR

Union, Intersect and Minus Operators These operators are used to combine the results from one or more tables. These

operators are union, intersect and minus

These operators join tables by column rather than by row.

Union OperatorsThe union operator is used when you want to see the results of multiple queries

together combining their output

Duplicate values are always eliminated from the resulting table of a union, unless the union all is specified

Syntax : Select statement

union [All]

EXAMPLES

Display the employees whose sal is same Ford and Ward.

select * from emp where sal in (select sal from emp where ename='ford' union select sal from emp where ename='ward');

union all Operators The union all operator is used to retrive all data that is it will display Duplicate values.

EXAMPLES

select * from empunion allselect * from dept;

Intersect OperatorThis operator returns all the rows in one table that also resides in other table. Ie only

the common values in both the table

Page 67: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Syntax : Select statementIntersectSelect statement

EXAMPLES

select * from dept where deptno not in ( select deptno from emp intersect select deptno from dept);

select * from emp where hiredate in(select hiredate from emp where deptno=20intersectselect hiredate from emp where deptno=30)

Retrieve those dept record which dept does not have emp

select * from dept where deptno not in ( select deptno from emp intersect select deptno from dept);

Minus OperatorThis operator returns all the rows in the first table minus rows in the second table. In

other words, it returns the rows present in the first table but not present in the second table.

Syntax :Select statement

MinusSelect statement

EXAMPLES

write a query to retrive fourth highest salary using set operator.

select * from emp where sal =(select sal from (select distinct sal from emp order by sal desc) where rownum<=4minusselect sal from(select distinct sal from emp order by sal desc) where rownum<=3)

write a query to retrive sl . no 6 record. using set operator.

Page 68: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select * from emp where rowid=(select rowid from emp where rownum<=6minusselect rowid from emp where rownum<=5)

Retrive that dname in which dname does not have any employee

select dname from dept where deptno= ( select deptno from dept minus select deptno from emp);

Special Operators used in Sub Queries All, Any and Some OperatorsANY Operator

This operator retrieves values from the first query, which is satisfied with any of the value returned by the sub query

Syntax : Select <select list> <Any Operator> Any(select <select list>);Example :

List All the employee details whose salary is greater than the lowest salary of an employee belonging to department number 20

select * from emp where sal > any(select sal from emp where deptno=20);

List All the employee details whose salary is same any of ford or james

select * from emp where sal=any(select sal from emp where ename in('ford','james');

List The Employee Details Of Those Employees Whose Salary Is Greater Than Any Of The Managers

select * from emp where sal > any(select sal from emp where job=’MANAGER’);

ALL OperatorThis operator retrieves values from the first query, which should be satisfied with all

the value returned by the sub query

Syntax : Select <select list> <Any Operator> All(select <select list>);

Page 69: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Example :

List The Employee Names Whose Salary Is Greater Than The Highest Salary Of All Employees Belonging To Department 20

Select * from emp where sal >all(select sal from emp where deptno=20);

List The Details Of The Employees Earning More Than The Highest Paid Managers

select * from emp where sal > ALL (select sal from emp where job=’MANAGER’);

select * from empwhere deptno=10 and sal>all(select sal from emp where deptno=20);

SOME OperatorThis operator is similar to Any Operator, which retrieves values from the first query,

satisfied with any of the value returned by the sub query.

Syntax : Select <select list> <Any Operator> some(select <select list>);

Example :List All the employee details belonging to emp1 table, whose salary is less than the

salary of an employee belonging to emp2 table

Select * from emp1 where sal<some(select sal from emp2);

VIEWS

A view is like a window through which data on a table can be viewed or changed. It is a virtual table that is – it does not have any data of its own, but derives the data from the table it is associated with. It manipulates data in the underlying base table.

Syntax : Create View <view name>

[ ( column1, column2,----)] as Select <select list>

Page 70: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Advantages of Views Using some view user can manipulate data. View look like a table with some restriction .

so it is also called as virtual table.

View occupies no database memory because view contain no data of their own.

Views are also used to hide the original names of the columns of the table.

Types of ViewThere are two types of view

1. Simple View2. Composite View3. With Read Only View4. With Check Option View

Simple View When a view is create basing on a single table then it is called a simple view , Dml

operation can possible.

Syntax :Create view <view name>

as Select <select list> from <table1>;

Examples : 1. Create a view, which shows all employees details whose salary is between 2000

and 3000

Create view empsal as select * from emp where sal>=2000 and sal<=3000;

select * from empsal;

Update empsal set sal=1000 where sal=3000;

Insert into empsal (empno,ename,mgr,sal,deptno) values(1111,'Lucky',7839,20000,10);

Delete from empsal where sal=3000;

Page 71: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

We can change column names in a view at the time of creation

Create a view, which shows all employees details who belong to dept 20

create view dept20(emp_no, emp_name, salary) as select empno, ename, sal from emp;

We can Create a view, using another view

Create view ravi as select * from empsal;

To Create Read Only ViewsWe can create read only view. When a view is created with any arithmetic expression

or with any group by functions then it cannot be modified or changed with insert or update or delete statements. So this can be called as a Read Only Views.

Example :Creates a view, with all department numbers and number of Employee’s working

under each department

create view deptgroup as select deptno,count(*) “no of emps” from emp group by deptno;

Note : When Ever We Apply Any Dml Operation On This View, We Will Get An Error Message

insert into deptgroup values(40,2); *ERROR at line 1:ORA-01732: data manipulation operation not legal on this view

Delete from deptgroup where deptno=10 *ERROR at line 1:ORA-01732: data manipulation operation not legal on this view

Composite View A view created by retrieving data from 2 or more tables. A composite view can not be

updated or we can not apply any DML operations except select statement. Because it contains different columns from different tables. But you can insert values by using Instead of Trigger…..

Syntax :Create view <view name> as select <fields list> from

<table1>,<table2>,……..

create view which should show all columns in emp and dept table whose deptno in emp is equal to deptno in dept table

Create view empdept as select empno, ename, sal, dname, loc, dept.deptno from emp, dept

Page 72: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

where emp.deptno=dept.deptno

select * from empdept;

Insert into empdept values(1000,’hello’,5000,’Production’,’tirupati’,20);

ERROR at line 1:ORA-01776: cannot modify more than one base table through a join viewNote : Since here two table values are included. So at a time we cann’t insert or modify two tables data at a time.

But by using Instead of Trigger you can insert values.

View with check option.

User can provide condition.User can insert values by following check condition.

EXAMPLE

create view tej as select * from emp where sal<3000 with check option;

Select * from tej;

Here user cant insert values in sal column below 3000.

Dropping a viewDrop View : This command is used to drop any view from the databaseDrop view <view name>Example : Drop View empdept;

Note :1. To show all Views details

Select * from all_Views;

MATERIALIZED VIEW

A view whos query result is stored in db..that is mview...dba can create it....

conn sys as sysdba

create materialized view mat_view345 refresh force start with sysdate next

Page 73: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

sysdate+1 with primary key as select * from emp where deptno in(20,30);

select * from mat_view345;

update emp set sal=2000;commit;

select * from emp;select * from mat_view345;

SEQUENCEThe sequence is a database object, which is used to generate unique integers for use as

primary key for a column. There are two steps while working with a sequence.

Syntax :Create sequence <sequence name >

Start with <value>Increment by <value>

Maxvalue / [nomaxvalue] <value>Minvalue / [nominvalue] <value>

Cycle/nocycleCache/nocache <value>

Order/noorder

Start with : it is a keyword to specifying the starting value in the sequence creation

Increment by : this parameter accepts the number by which we want to increment the value in the sequence. If you want to decrement you must specify the negative value. By default the increment value is ‘1’ (not zero)

Maxvalue : specifies the maximum value or limit that the sequence can generate

Nomaxvalue : if you cannot specify the maximum limit, use this parameter. The default value is Nomaxvalue.(not compulsory)

Page 74: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Minvalue : specifies the sequences minimum value or limit. It represent the number upto which you want to decrement the value.

Nominvalue : The default value is Nomaxvalue.(not compulsory)

Cycle : specifies that the sequence continues to generate value after reaching either its maximum or minimum value.

Nocycle : it represents that the sequence should stop generation of numbers when the max value is reached. This is the default one.

Cache : it specifies how many values of the sequence oracle pre allocates and keeps in the memory for the fast access. This keyword generates ‘n’ numbers immediately after creating sequence. Where ‘n’ is the number followed by cache. Default is ‘20’

Nocache : this is the default one.

Order : generates the sequences in the order of requestNoorder : this is the default one

Attatching Sequence

If sequence is created it can be attached to the table for storing the value of the sequence into the table or for generating the column values according to the parameters in the sequence.

There are two ways the sequence can be attached1. Insert Command2. Update Command

currval : specifies sequence current value nextval : specifies sequence next value

Example :Using Insert Command

Syntax :Insert into <table name>(columns list) values(sequencename.nextval,……);First create a dummy table

create table temporary(sno number(3), name varchar2(10));

Next, create a sequence with the following way

create sequence myseq start with 100 increment by 1 maxvalue 110 minvalue 100;

insert into temporary values(myseq.nextval,’&name’);

similarly insert values in to the temporary table, when the sequence.nextval reaches to 110, it automatically gives an error message.

Page 75: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ERROR at line 1:ORA-08004: sequence MYSEQ.NEXTVAL exceeds MAXVALUE and cannot be instantiated

select * from temporary;

Using Update Command Syntax :Update <table name> set <column Name>=<sequencename.nextval>, ------;

create a sequence with the following way

create sequence myseq start with 1 increment by 1 maxvalue 10 minvalue 1;

Updating only one valueupdate temporary set sno=myseq.nextval where name=’kk’;

Updating Multiple Values

update temporary set sno=myseq.nextval;

select * from temporary;

Altering a Sequence A sequence can be altered using the Alter Command. But we can not alter the start

with value.

Syntax :Alter sequence <sequence name >

Increment by <value>Maxvalue /NoMaxValue <value>Minvalue /NoMinValue <value>

Cycle / NoCycleCache/NoCache <value>

Order/noorderExample create sequence myseq2 start with 100 increment by 1 maxvalue 110 minvalue 100;

we altered the above sequence

Alter sequence myseq2 increment by 2 maxvalue 120;

Update sample set sno=myseq2.nextval;

select * from sample;

Page 76: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Again Altering the above sequence

Alter sequence myseq2 nomaxvalue;

update sample set sno=myseq2.nextval;

now you can update the values as many times as you want, since there is no maximum limit to stop the generation of numbers.

Drop sequence :This command is used to drop any sequence

Syntax : drop sequence <sequence name>Example : drop sequence myseq2;Note :

Even though u altered the sequence, it will generate numbers from where it has left before altering the sequence and continues according to ur altered form.

Synonym

Synonym is an oracle database object to create permanent alias

name for database table. It is use to provide alternate

name for the database table. synonym is use to give

security for the database table by hiding the original

name of the Table.

Public synonym := DBA can create this synonym and any user can access.

private synonym := user can create for current user.

PUBLIC SYNONYM :

CONN SYS AS SYSDBA

create public synonym employee99 for scott.emp;

Page 77: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

created....

grant all on employee1 to public;

CONN SCOTT/TIGER

select * from employee1;

PRIVATE SYNONYM

One user can create and give grant to other user....

create synonym department9 for scott.dept;

grant all on department9 to username;

select * from scott.department9;

select * from user_synonyms;

Clusters

Tables that are frequently accessed together may be physically stored together. Clustering is a method of storing tables that are closely related and are often joined together, into the same area on the disk.

A cluster is created to hold the tables. A cluster contains the values of a table according to the column that we define. When ever we insert values into the table the same values are automatically stored in the database object name cluster.

Cluster can be created by using create cluster command. To create a cluster use the following syntax.

Syntax :Create cluster <cluster name> (columns specifications,------)

To create any cluster

1. First create a cluster with the column names that you want

Page 78: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

2. Next create an index on that cluster. Otherwise the cluster will not work properly

3. Next create a table with the cluster specification and list of columns4. Now insert some values into that table, if you see the cluster the same values will

be available from the cluster also.

Note : 1. We can not insert or update or delete any row from the cluster2. We can not even drop the cluster until the source table is present3. To drop the cluster, first we have to drop the source table and then we can drop

that particular cluster.

Creation of cluster for a table

First create the cluster,

create cluster sampleclust (sno number(3), sname varchar2(10));

Next create the index,

create index idx_sampleclust on cluster sampleclust;

Attaching the cluster to the table,

create table sample2 (sno number(3),sname varchar2(10)) cluster

sampleclust(sno,sname);

Example :

1. To display details of the Tableselect * from sample2;

SNO SNAME--------- ---------- 100 Nithya 101 Saloni 102 Aruna

2. To display details of the Tableselect * from cluster sampleclust;

SNO SNAME--------- ---------- 100 Nithya 101 Saloni 102 Aruna

Page 79: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

3. Even if you delete any row in the table, that will not affected to the cluster1. delete from sample2 where sno=100;2. select * from sample2;

SNO SNAME--------- ---------- 101 Saloni 102 Aruna

3. select * from cluster sampleclust;

SNO SNAME--------- ---------- 100 Nithya 101 Saloni 102 Aruna

4. delete from sampleclust where sno=102

ERROR at line 1:ORA-00942: table or view does not existNote : We can not delete any data from the cluster

Drop clusterThis command is used to drop any cluster

Syntax : drop Cluster <cluster name>

To drop any clusterDrop table sample2;Drop cluster sampleclust;

INDEX

It is a database object used to sort the values of a column for retrieving data fastly from a table. By default the rows in a table are identified with their row id’s

When ever you create an index on a table, the system gives index id’s which are stored in the index. If a table is having index then the system retrieves the rows basing on the index id’s else it retrieves value using row id’s.

Page 80: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Types of index.

Normal index (or) Simple index . Any index created on a single table is called a simple index.

Unique index . (It will not accept duplicate value)

Reverse index . IN NORMAL INDEX IN REVERSE INDEX

*************** ****************

A100001 100001A

A100002 200001A

A100003 300001A

A100004 400001A

Composit index: Using more than one column user can create

composit index.

Bitmap index . If column contain large no of duplicate value

Simple Index

Syntax : create index <index name> on <table name>(column);

Example: create index i_d on emp(ename);

Note : We can not see the Details of Index file

select * from i_d;

ERROR at line 1:ORA-00942: table or view does not exist

Note : we can not create any index on views.

Creating Unique indexes on a Single column

Syntax :Create unique index <index name> on <table name> (<column>)

Page 81: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Note : Unique index can be created on any table, except it does not contain any duplicate values on the column for which you are creating a unique index.Example :

create unique index idx_temp on sample1(sno);

insert into sample1 values(&sno,’&sname’);enter any value for sno: 1enter any value for sname : Mahesh

enter any value for sno: 2enter any value for sname : Prasad

enter any value for sno: 1enter any value for sname : Nithya

Error : Ora-00001: unique constraint (scott.idx_temp) violatedNote :

1. Once if u create any index on a particular column, then that column can not be re indexed. To re index on that column, first remove that existing index using drop index command and then create new index on that column

2. If you create an index on an existing index, it will show an error message

create unique index idx_temp1 on temporary(sno) *ERROR at line 1:ORA-01408: such column list already indexed

Composite indexAn index created on 2 or more columns in a table is called composite index.

Syntax :Create index <index name> on

<table name> (<column1>, <column2>,-------)

Example:

create index e_ename on emp(ename,job);

Composite unique index

We can create unique index on two or more columns also using composite unique index.

Page 82: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Syntax :Create unique index <index name> on <table name>

(<column1>,<column2>,-------);

Bitmap index

Syntax :Create bitmap index <index name> on <table name>

(<column1>);

Example:

Create bitmap index e_deptno on emp(deptno);

Drop indexThis command is used to drop any index

Syntax : Drop index <index name>

Ex : Drop Index Idx_Sample;

To View Index

1. user_indexes : contains all user defined index’s information

Example :

select * from user_indexes;

select index_name, table_name, table_owner from user_indexes;

2. All_indexes : contains all user defined index’s and pre defined index’s information.

Example : select * from all_indexes;

select index_name, table_name, table_owner from all_indexes;

Clusters

Page 83: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Tables that are frequently accessed together may be physically stored together. Clustering is a method of storing tables that are closely related and are often joined together, into the same area on the disk.

A cluster is created to hold the tables. A cluster contains the values of a table according to the column that we define. When ever we insert values into the table the same values are automatically stored in the database object name cluster.

Cluster can be created by using create cluster command. To create a cluster use the following syntax.

Syntax :Create cluster <cluster name> (columns specifications,------)

To create any cluster

5. First create a cluster with the column names that you want 6. Next create an index on that cluster. Otherwise the cluster will not work

properly7. Next create a table with the cluster specification and list of columns8. Now insert some values into that table, if you see the cluster the same values will

be available from the cluster also.9. You can not create cluster on already created cluster ,if you want create cluster

on created cluster then you have to create the table again with same data.

Note : 4. We can not insert or update or delete any row from the cluster5. We can not even drop the cluster until the source table is present6. To drop the cluster, first we have to drop the source table and then we can drop

that particular cluster.

Creation of cluster for a table

First create the cluster,create cluster sampleclust (sno number(3), sname varchar2(10));

Next create the index,create index idx_sampleclust on cluster sampleclust;

Attaching the cluster to the table,create table sample2 (sno number(3),sname varchar2(10)) cluster

sampleclust(sno,sname);

Example:Create cluster c35(deptno number(4));

Page 84: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Create index i_d36 on cluster c35;

Create table dept35

(deptno number(4) ,

dname varchar2(14),

loc varchar2(13)) cluster c35(deptno);

create table emp35

(empno number(4) ,

ename varchar2(10),

job varchar2(9),

mgr number(4),

hiredate date,

sal number(7, 2),

comm number(7, 2),

deptno number(4))

cluster c35(deptno);

Insert values into two tables and display them.

MERGE

CREATE TABLE EMP15 AS SELECT * FROM EMP;

merge into emp15 A usingemp B on (A.empno=B.empno)when matched thenupdate set A.sal=B.sal+100;

RANKING

Select ename,job,sal,deptno,dense_rank() over(partition by null order by sal desc ) as rank from emp;

Note: In null place use deptno then vl get deptno wise rank

In this way you can Rank all emps by sal ,exp ect……

Page 85: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PRIVILEGES Database security or privileges can be classified into two categories.System security and data security . Privileges are the right to execute the particular SQL statement.

System privileges :- DBA can grant privileges to users.Object privileges :- User can grant privileges to users.

System privileges.

Create sessionCreate tableCreate synonymCreate viewCreate sequenceCreate procedureCreate triggerCreate typeCreate userDrop user

Object privileges.

Select ,update ,insert ,delete ,execute ,alter,all,index.

SELECT 'DROP TABLE'||' '||TNAME||' '||'PURGE'||';' FROM TAB WHERE TNAME NOT IN('EMP','DEPT','SALGRADE')

SELECT 'DROP VIEW'||' '||TNAME||';' FROM TAB

SELECT 'DROP CLUSTER'||' '||TNAME||';' FROM TAB

SELECT 'DROP SYNONYM'||' '||TNAME||';' FROM TAB

CONN SYS AS SYSDBAEnter password: Connected. DROP USER SCOTT CASCADE;

Page 86: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

User dropped.

GRANT CONNECT,RESOURCE TO SCOTT IDENTIFIED BY TIGER;

Grant succeeded.

CONN SCOTT/TIGERConnected.

To check the under a role which system privileges available

Select * from session_privs

Select * from session_roles

Select * from user_role_privs

Select * from role_sys_privs

Select * from dba_sys_privs where grantee='resource';

Select * from dba_role_privs;

TO CREATE USER ID…..CONN TO DBA…(CONN SYS AS SYSDBA/TIGER)

Create user username identified by p.word;

To Change P.Word

Alter user user_name identified by new p.word;

GIVE PERMISSION….TO NEW ID

Grant connect,resource to username;

GIVE PERMISSION TO CREATE…

Grant create session to username;

TO Take Permission Rerurn

Revoke create table from username;

Page 87: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ALLOW MEMORY

Alter user username (orbit) quota 5mb on users;

TO LOCK ACCOUNT…

Alter user username account lock;

UNLOCK….

Alter user username account unlock;

Table Lock

When user performing data manipulation operation the oracle serverprovides data security through dml locking

SHARE LOCK - Many user can lock one user table.

EXCLUSIVE LOCK- One user can lock one table.

DEAD LOCK - If two user lock one table in share mode and both are trying to do dml on same table at that time dead lock will raise.

ROW LEVEL LOCK- User can lock one or more than one row. After using rollback the lock will be open.

If table is lock DRL can possible but DML cannot possible.

If table is lock at that time other users are trying to do dml operationon that table that user will be hang.

Example

GRANT ALL ON SCOTT.EMP TO ORBIT;

In Scott

Lock table scott.emp in share mode;

THEN ORBIT CANT DO DML (UPDATE) ON EMP…TABLE LOCKED…IT WILL HANG…

IF U WANT TO UNLOCK

ROLLBACK; (In scott)

Page 88: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Lock table scott.emp in exclusive mode;

THEN ANOTHER USER CANT LOCK THAT TABLE…IT VILL BE HANG……

ROW LEVEL LOCK…..

Select * from emp where ename=’smith’ for update of ename;

THEN ORBIT CANT DELETE SMITH ROW

Select * from dep for update of deptno;

Now deptno column is locked.

Select * from dep where dname='sales'for update of dname;

Now dname sales is locked.

SPOOL 'C:\ravi.txt'; ENTER

NEXT SELECT * FROM EMP ENTERSPOOL OFF ENTER

THEN OPEN C

PIVOT

The new pivot sql clause will allow quick rollup,similar to an ms-excel pivot table,where u can display multiple rows on one column with sql.....

Syntax:

Select....From...Pivot(xml)(pivot_clausePivot_for_clausePivot_in_clause)Where...

PIVOT_CLAUSE : defines the column to be aggregated(pivot is an aggregate operator.

PIVOT_FOR_CLAUSE: defines the columns to be grouped or pivoted.

PIVOT_IN_CLAUSE: defines the filter for the column in the pivot_for_clause..

Example:

Page 89: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Select * from (select deptno ,job from emp e)Pivot(count(job) for job in('president','manager','analyst','salesman','Clerk')) order by deptno;

NORMALIZATION Normalization is a scientific method to breaking down the complex table structure to simple table structure by using somerules and regulation.

1st normal form.

The table is known as 1st normal form when each cell of table contains one value.Its avoid the repeating group.

Entity--------------Employee Empno Projectcode Dname Hour**************************************************** E101 P10 Sales 75 ---------------------------------------------------- E101 P11 Sales 66 ---------------------------------------------------- E102 P12 Finance 45 ---------------------------------------------------- E102 P10 Finance 56---------------------------------------------------- E103 P11 Research 51---------------------------------------------------- E103 P12 Research 52---------------------------------------------------- E104 P10 Software 62---------------------------------------------------- E104 P11 Software 64----------------------------------------------------

2nd Normal form.

The Table is known as second normal form when the table already infirst normalform and each non key attributes are functionally dependent on whole key not any part of key.

Whole key :=(empno+projectcode) Part of key :=empno , projectcode

Page 90: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Functionally dependent

Column A is functionally dependent on column B when each cell of column B should be one value of column A.

A B ************* *************

Hour is functionally dependent on whole key (T/F) Hour is functionally dependent on empno (T/F) Dname is functionally dependent on whole key (T/F) Dname is functionally dependent on projectcode (T/F)

Employee. Empno projectcode Hour ************************************* E101 P10 75 Loans E101 p11 66 empno dept l_type amount E102 p12 45 ********************************************************** E102 p10 56 E101 SALES CAR 300000 E103 p11 51 E101 SALES HOUSE 150000 E103 p12 52

Dept Empno Dept ********************* E101 Sales E102 Finance E103 Research E104 Software

3rd normal form

The table is known as third normalform when it is already insecond normalform and each nonkey attributes are functionallydependent on primary key only.

Employee

Empno Dname Depthead Projcode***************************************************** E101 Sales D1 p10 E102 Finance D2 p11 E103 Research D3

Page 91: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

E104 Software D4 E105 Sales D1 E106 Finance D2 E107 Research D3

Entity = Entity is an object about which information needs to be know. Examples are employee ,department , order ,cusotmer

Attributes = Columns are represented as attributes Examples are empno,ename,job,sal.

Tuples = Rows are represented as tuples 7788 smith manager 5000

PL/SQL PROGRAMMING

Procedural language or programming language structure query language

extension to sql. Using sql user cannot work with variable,exception,

looping structure,conditional statement,curosr,type.To perform this type

of task oracle provides plsql. Benefits of plsql is Easy maintenance,

Improved the data security, Improved the performance,Improved the

code clarity and Reusability.

Page 92: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PLSQL DATA TYPES

1. CHAR

2. VARCHAR2

3. NUMBER

4. DATE -- All scalar data types

5. BINARY_INTEGER

The range of binary_integer is -2147483647 to 2147483647

6. PLS_INTEGER The range of pls_integer is -2147483647 to 2147483647 It is similar to binary integer but pls_integer values are faster. 7. BOOLEAN Return true , false or null. 8. COMPOSIT DATA TYPE :- Pl/sql record,plsql table,varray,nested table

Plsql blocks are two types

1. Anonymous block .

DECLARE (Optional) Variable ,cursor,user define exception,type. BEGIN (Mandatory) Sql /plsql statements EXCEPTION (Optional) END (Mandatory)

2. Named block . (Procedures,functions,package,trigger).

pl/sql is also a programming language of procedure type.

Page 93: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

pl=procedure language.

To print the output pl/sql provide a packaged procedure

dbms_output.put_line();

The o/p of the dbms statesments are printed by command

SQL>set serveroutput on;

Attribute data typesAttribute data types is a column data type.Attribute data type is to inherit

the specification of database to the program variable of pl/sql.

Arrtibute data types are based on pointer concept.to inherit the

specification of database columns into pl/sql for its variables.

Attribute data types are based on dynamic memory allocation ,which improves the purpose of program with min usage of memory.

Types of attributes

1.% type

This attribute data type is used to declare the scaler pl/sql variables those are inheritary the specifications of specific column of database tableon a view.

<tablename>.<col>%typeeg.declarev_empno emp.empno%type;

2.%row type

This attribute datatype is used to declare a structured variable in pl/sql block,which is refering the entire structure of a table or view or synonyms or cursor.structure variable is a variable having some internal components each of one scaler type.

<tablename>%rowtypeeg.declare

Page 94: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

v_emp emp%rowtype;

Control StructuresControl structures enable the program to change the logical flow of statements within PL/SQLwith a number of control structures. PL/SQL supports two basic programming control structures:conditional and iteration branching. These four structurescan be combined in any way to solve a given problem.The following sections cover these structures in more detail.

Conditional ControlYou can execute a statement or sequence of statements conditionally with the if-then statement.Sometimes it is necessary to take alternative actions, depending on a condition or circumstance.

1.write a program to add two numbers and display the o/p

declarea number(3):=10;b number(3):=9;c number(3);begin

Page 95: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

c:=a+b;dbms_output.put_line(c);end;/

Note : For entering data from user a number(3):=&a; should be used.

2.write a program to accept two different numbers and find addition,substraction,multiplication and devision of given number.

declarea number(2):=&a;b number(2):=&b;s number(3);su number(3);m number(3);d number(3);begins:=a+b;su:=a-b;m:=a*b;d:=a/b;dbms_output.put_line('ADDITION '||s);dbms_output.put_line('SUBSTRACTION '||su);dbms_output.put_line('MULTIPLICATION '||m);dbms_output.put_line('DIVITION '||d);end;3.write a prog to accept empno,ename,sal,DOB,DOJ.Display all the details along with age of the emp,exp of employee,asal,dsal as per current month round to nearest rupees and also display all the allowances(TA+DA+HRA) and gross salary.

declareempno number(3):=&empno;ename varchar2(10):='&ename';sal number(10):=&sal;dob date:='&dob';doj date:='&doj';age number(3);exp number(3);asal number(5);dsal number(5,2);da number(5);ta number(5);hra number(5);grosal number(15);beginage:=months_between(sysdate,dob);exp:=months_between(sysdate,doj);asal:=sal*12;dsal:=sal/to_char(last_day(sysdate),'dd');da:=sal*10/100;

Page 96: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ta:=sal*20/100;hra:=sal*5/100;grosal:=da+ta+hra;dbms_output.put_line('asal='||asal);dbms_output.put_line('Exp= '||exp);dbms_output.put_line('Asal= '||asal);dbms_output.put_line('dsal= '||dsal);dbms_output.put_line('Gross sal '||grosal);dbms_output.put_line('age '||age);dbms_output.put_line('da '||da);dbms_output.put_line('TA '||ta);dbms_output.put_line('hra '||hra);end;/

IF condion

If-Then Statements The simplest form of the conditional control statement is the if-then statement. The syntaxfor the if-then statement is as follows:if condition thenstatement(s);end if;The statements that immediately follow the conditional if statement are executed only if thecondition evaluates to True. If the condition evaluates to False, the statements are not processedand are passed over.

If-Then-Else Statements A more likely scenario is that you will have different distinct sets of statements to execute dependingon the conditional statement. The if-then-else statement provides a means to alwaysexecute statements in a conditional statement.The syntax of the if-then-else structure is very similar to the if-then syntax. The followingexample uses the if-then-else structure:if max_bal > 100000 then

Page 97: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

update mst_audit -- executed only if condition is trueset comments = ‘sell no more’;elseupdate mst_audit -- executed only if condition is falseset comments = ‘sell more’;end if.

4.write a prog to accept two number find the smaller no.

declarea number(3):=&a;b number(3):=&b;beginif a>b thendbms_output.put_line(a||' is the bigger one');else if a=b thendbms_output.put_line(a ||' and ' ||b|| 'are equal');else dbms_output.put_line(b||' is the bigger one');end if;end if;end;/

5 write a progm to accept two date value and find the recent one

declarea date:='&a';b date:='&b';beginif a<b thendbms_output.put_line(a||' is previous date');elsedbms_output.put_line(b||' is previous date');end if;end;/

6.write a progm to accept two different date and find the recent day of the week

declarea date:='&a';b date:='&b';beginif (to_char(a,'d')>to_char(b,'d')) thendbms_output.put_line(a ||' is recent day');else dbms_output.put_line(b ||' is recent day');

Page 98: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

end if;end;

7.w.a.p to accept name,sid,marks1,marks2,marks3 based on avg declare the result.If marks of any one subject is less than 35 declare as fail.

declarename varchar2(10):='&name';sid number(4):=&sid;marks1 number(4):=&marks1;marks2 number(4):=&marks2;marks3 number(4):=&marks3;avg number(3,2);beginavg:=(marks1+marks2+marks3/3);if (avg>=70) thendbms_output.put_line('DISTICTION');elsif (avg>=60 and avg<70) thendbms_output.put_line('FIRST division');elsif (avg>=50 and avg<60) thendbms_output.put_line('2nd division');elsif (avg>=35 and avg<50) then dbms_output.put_line('3rd division');elsedbms_output.put_line('FAIL');end if;end;/

8.write a progm to accept the product id,product desc,quanlity and unit price .Now calculate the bill.If the bill more than 500 & less than 1500 give a discount of 5%,if bill is more than 1500 then 10% discount.Display all the details along with the bill amount,discount,net payable.

declarepid number(4):=&pid;pdesc varchar2(10):='&pdesc';quan number(5):=&quan;unit_pr number(6,2):=&unit_pr;bill number(8,2);disc number(5,2);net_pay number(8,2);beginbill:=quan*unit_pr;if bill>1500 then

Page 99: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

disc:=bill*10/100;net_pay:=bill-disc;else if (bill<1500 and bill>500) then

disc:=bill*5/100;net_pay:=bill-disc;

else disc:=0;end if;end if;dbms_output.put_line('pid '||pid);dbms_output.put_line('bill '||bill);dbms_output.put_line('discount '||disc);dbms_output.put_line('Net '||net_pay);end;/

Home Work:write a progm to accept 3 numbers and find the biggest from them.

LOOP ConditionLoop is execution of a sequence of statesments repeatedly.

Iterative ControlIterative control statements enable you to execute a sequence of statements multiple times. Thesimplest form of an iterative statement is the loop.

Loop Statements

The syntax for the loop statement is

loopstatement(s)end loop;

Types Of Loops

1.simple loop2.while loop3.for loop4.Revarse for loop

SIMPLE LOOP

To Print Numbers

Declare

Page 100: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

A number:=1;BeginLoopExit when a>20;Dbms_output.put_line(a);A:=a+1;End loop;End;/ REVERSE NO DeclareA number:=100;BeginLoopExit when a < 1;Dbms_output.put_line(a);A:=a - 1;End loop;End;To Print The No Is Prime Or Not

DeclareA number:=&no;B number;C number:=0;I number:=1;BeginLoopExit when i > a;B:=mod(a,i);If b=0 thenC:=c+1;End if;I:=i+1;End loop;If c=2 thenDbms_output.put_line('prime');ElseDbms_output.put_line('not prime');End if;End;/

Syntax for while loop

The while-loop structure repeats a statement until a condition is no longer true. The syntaxfor the while loop is as follows:

while condition loop

Page 101: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

statement(s)end loop

9.write a prog to print a series of numbers from that no to specified no.

declaren number(3):=&n;a number(3):=&a;beginwhile(a<=n)loopdbms_output.put_line(a);a:=a+1;end loop;end; /

10.w.a p accept a number and print all the even numbers from 1 upto given number.declarea number(3):=&a;b number(3):=1;c number(4);beginwhile (b<=a)loopc:=mod(b,2);if c=0 thendbms_output.put_line(b);end if;b:=b+1;end loop;end;

To Print The No is Even Or Odd

DeclareNo number:=&no;BeginIf mod(no,2)=0 thenDbms_output.put_line(' the no is even no');ElseDbms_output.put_line(' the no is odd no');End if;End;

Page 102: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

To Print The No Is Prime Or Not

DeclareA number:=&no;B number;C number:=0;I number:=1;BeginWhile i <= a loopB:=mod(a,i);If b=0 thenC:=c+1;End if;I:=i+1;End loop;If c=2 thenDbms_output.put_line('prime');ElseDbms_output.put_line('not prime');End if;End;/

.w.a.p to accept a date and print all the 7 days of a week along with date values.

declarea date:='&a';b date;beginb:=a+6;while a<=b loopdbms_output.put_line(to_char(a,'day DD Month yyyy'));a:=a+1;end loop;end;/*******************************

.w.a.p to accept a date and print all the 12 months of a year from given date.

declarea date:='&a';b date;beginb:=add_months(a,11);

Page 103: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

while a<=bloopdbms_output.put_line(to_char(a,'Month'));a:=add_months(a,1);end loop;end;/

w.a.p to accept the year in 4 digit format and print all the dates if sundays of the year and also at the end print no of sundays of that year

declarey number(5):=&yyyy;d1 date;d2 date;cnt number(2):=0;begind1:='01-jan-'||y;d2:='31-dec-'||y;while d1<d2loopif to_char(d1,'d')=1 thendbms_output.put_line(d1);cnt:=cnt+1;end if;d1:=d1+1;end loop;dbms_output.put_line('total no of sundays '||y||' year is '||cnt);end;

For Loop Statements The for loop is a mechanism to cycle through a loop a fixed number of times. A for loop iteratesover and over for a specified number of times. The syntax for the for loop is as follows:for counter in lower-bound..upper-bound loopstatement(s)end loop;

12.w.a.p to accept a number and to print multiplication table of that number.

declare a number(4):=&a;b number(3);beginfor i in 1..10

Page 104: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

loopb:=a*i;dbms_output.put_line(a||'*'||i||'='||b);end loop;end;/

13.to print factorial of given number

declaren number(3):=&n;fact number(5):=1;beginfor i in 1..nloopfact:=fact*i;end loop;dbms_output.put_line('THE FACTORIAL OF THE GIVEN NUMBER '||fact);end;/

To Print The No Is Prime Or Not

DECLARE A NUMBER:=&N; B NUMBER:=0; C NUMBER:=0; BEGIN FOR I IN 1..A LOOP B:=MOD(A,I); IF B=0 THEN C:=C+1; END IF; END LOOP; IF C=2 THEN DBMS_OUTPUT.PUT_LINE('PRIME'); ELSE DBMS_OUTPUT.PUT_LINE('NOT PRIME'); END IF; END;/ Revarse for loop

BeginFor i in reverse 1..10 loopDbms_output.put_line(i);End loop;End;

Page 105: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Loop inside loopDeclareA number:=1;BeginLoopExit when a>=10;For i in 1..10 loopDbms_output.put_line(a||'*'||i||' '||'='||a*i);End loop;A:=a+1;End loop;End;

write a pl/sql block to make the string half capital and half small.

declarea varchar2(100):='&char';v_count number(5);v_upper varchar2(100);v_div number(4);beginv_count:=length(a);v_div:=v_count/2;v_upper:=upper(substr(a,1,v_div))||lower(substr(a,v_div));dbms_output.put_line(v_upper);end;

For First Part in Lower Second in Upper

declarea varchar2(100):='&char';v_count number(5);v_upper varchar2(100);v_div number(4);beginv_count:=length(a);v_div:=v_count/2;v_upper:=lower(substr(a,1,v_div))||upper(substr(a,v_div));dbms_output.put_line(v_upper);end;

DECODE

WRITE A PLSQL PROGRAMME PASS ONE EMPLOYEE NUMBER AND CHECK IF THAT EMPLOYEE IS A PRESIDENT TAX=50%

Page 106: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

FOR MANAGER TAX=40%FOR ANALYST TAX=30%FOR SALESMAN TAX=20%FOR CLERK TAX=10%. USING DECODE FUNCTION.

Declare e_ename varchar2(10);E_job varchar2(10);E_sal number(4);E_deptno number(4); e_tax number; begin select ename,job,sal,deptno,decode(job,'president',sal*.5, 'manager',sal*.4, 'analyst',sal*.3, 'salesman',sal*.2, 'clerk',sal*.1) into e_ename,e_job,e_sal,e_deptno,e_tax from emp where empno=7788; dbms_output.put_line (e_ename||' '||e_job||' '||e_sal||' '||e_tax); end;/

CASE

WRITE A PLSQL PROGRAMME TO PROVIDE INCREMENT FOR DEPTNO 10 100 RUPEESDEPTNO 20 200 RUPEESDEPTNO 30 300 RUPEESDEPTNO 40 400 RUPEES.

Declare rec emp%rowtype;V_tax number; begin select * into rec from emp where empno=7788; v_tax:=case rec.deptno when 10 then rec.sal+100 when 20 then rec.sal+200 when 30 then rec.sal+300 when 40 then rec.sal+400 end; dbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.sal||' '|| rec.deptno||' '||v_tax); end;

Page 107: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Exp of Boolean Datatypes.

Declare e_empno number:=&empno; e_ename varchar2(10); e_sal number(6); e_hiredate date; chk_years boolean; a number:=0; begin select empno,ename,hiredate,sal into e_empno,e_ename,e_hiredate, e_sal from emp where empno=e_empno; a:=round((sysdate-e_hiredate)/365); if a>=29 then chk_years :=true; else chk_years :=false; end if; if chk_years=true then update emp set sal=sal+1000 where empno=e_empno; else dbms_output.put_line('junior employee'); end if; dbms_output.put_line(a); end;

Page 108: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

CURSOR Oracle allocates an area of memory known as context area for processing the sql statements called cursor.A cursor declaration consists of a name that you assign to the cursorand the select statement that you want to execute. Using pl/sql if query returns One row or more than one row at that time cursor is required.

Types Of Cursor Implicity cursor -use to retrieve only one row.Explicity cursor -use to retrieve more than one row.Reference cursor -use to retrieve data from more than one table.Parameterise curosr - user can pass parameterStrong cursor - Used to retrieve data from one tableWeek cursor - Used to retrieve data from more than one table

1. Table record (Select * from emp) Table and column and row base record2. Table base record. recemp%rowtype;

2. Programme define recordtypeemp_rec is record (e_empno number(4),e_ename varchar2(10),e_job varchar2(10),e_sal number(4),e_deptno number(4));

3.Cursor base record.rec c1%rowtype;

Page 109: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

IMPLICITDeclareE_empno number; e_ename varchar2(10); e_job varchar2(10); e_sal number(6); begin select empno,ename,job,sal into e_empno,e_ename,e_job,e_sal from emp where empno=7788; dbms_output.put_line(e_empno||' '||e_ename||' '|| e_job||' '||e_sal);End;

OR

DeclareRec emp%rowtype;BeginSelect empno,ename,job,sal into rec.empno,rec.ename,Rec.job,rec.sal from emp where empno=7788;Dbms_output.put_line(rec.empno||' '||rec.ename||' '||Rec.job||' '||rec.sal);Update emp set sal=5000Where empno=7788;End;/

STRONG CORSOR

DeclareTyp emy_type is ref cursor return emp%rowtype;Rec_ref my_type;Emp_rec emp%rowtype;Dept_rec dept%rowtype;Salgrade_rec salgrade%rowtype;BeginOpen rec_ref for select * from emp;LoopFetch rec_ref into emp_rec;Exit when rec_ref%notfound;Dbms_output.put_line(emp_rec.empno|| ' '||emp_rec.ename|| ' '||

Page 110: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Emp_rec.job|| ' '|| emp_rec.mgr|| ' '||emp_rec.hiredate|| ' '||Emp_rec.sal|| ' '||emp_rec.comm|| ' '||emp_rec.deptno);End loop;Close rec_ref;End;/

WEEK CURSOR

declaretype my_type is ref cursor;rec_ref my_type;emp_rec emp%rowtype;dept_rec dept%rowtype;salgrade_rec salgrade%rowtype;beginopen rec_ref for select * from emp;loopfetch rec_ref into emp_rec;exit when rec_ref%notfound;dbms_output.put_line(emp_rec.empno|| ' '||emp_rec.ename|| ' '||emp_rec.job|| ' '|| emp_rec.mgr|| ' '||emp_rec.hiredate|| ' '||emp_rec.sal|| ' '||emp_rec.comm|| ' '||emp_rec.deptno);end loop;close rec_ref;open rec_ref for select * from dept;loopfetch rec_ref into dept_rec;exit when rec_ref%notfound;dbms_output.put_line(dept_rec.deptno|| ' '||dept_rec.dname|| ' '||dept_rec.loc);end loop;close rec_ref;open rec_ref for select * from salgrade;loopfetch rec_ref into salgrade_rec;exit when rec_ref%notfound;dbms_output.put_line(salgrade_rec.grade|| ' '||salgrade_rec.losal|| ' '||salgrade_rec.hisal);end loop;close rec_ref;end;

Page 111: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

CORSOR WITH FOR LOOPdeclarecursor c1 is select distinct(job) from emp;rec1 emp.job%type;cursor c3(job1 varchar2) is select* from emp where job=job1;rec2 c3%rowtype;beginfor rec1 in c1loopexit when c1%notfound;dbms_output.put_line(rec1.job);dbms_output.put_line('--------------');open c3(rec1.job);loopfetch c3 into rec2;exit when c3%notfound;dbms_output.put_line(rec2.empno||' '||rec2.ename||' '||rec2.job||' '||rec2.mgr||' '||rec2.hiredate||' '||rec2.sal||' '||rec2.comm||' '||rec2.deptno);end loop;close c3;end loop;end;/

WITH WHILE LOOP

declarecursor c1 is select * from empwhere deptno not in (10,20);rec c1%rowtype;beginopen c1;fetch c1 into rec;while c1%found loop

Page 112: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

dbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.sal||' '||rec.deptno);fetch c1 into rec;end loop;end;

WITH GROUP BY CLAUSEDeclareCursor c1 is select job,sum(sal) gro from emp group by job;Rec c1%rowtype;BeginOpen c1;LoopFetch c1 into rec;Exit when c1%notfound;Dbms_output.put_line(rec.job||' '||rec.gro);End loop;Close c1; End;

WITH JOINSDeclareCursor c1 is select e.ename,e.job,e.deptnoedeptno,d.deptnoddeptno,d.dname,d.loc from empe,dept d where e.deptno=d.deptno;Rec c1%rowtype;BeginOpen c1;LoopFetch c1 into rec;Exit when c1%notfound;Dbms_output.put_line(rec.ename||' '||rec.job||' '||' '||rec.edeptno||' '||rec.ddeptno||' '||rec.dname||' '||rec.loc);End loop;End;

Page 113: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

WITH CASE FUNCTIONDeclare cursor c1 is select * from emp; rec c1%rowtype; v_tax number; begin

open c1; loop fetch c1 into rec; exit when c1%notfound; v_tax:=case rec.job when 'president' then .4 when 'manager' then .3 when 'analyst' then .2 when 'salesman' then .1 when 'clerk' then .05 end; dbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.sal||' '|| rec.deptno||' '||rec.sal*v_tax); end loop; end;

Page 114: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

EXCEPTION

An exception is an identifier in plsql that is raised during the executionofplsql block. You can trap any exception in the exception handlingsection of the plsql block.

Types of exception:

1. Predefined exception2. Userdefined exception3. Nonpredefine exception

1. Predefined exception:

A predefined exception is raised implicitly when a plsqlprogramm avoid oracle rules. Error code is 0 to -20000 no_data_found ,too_many_rows , dup_val_on_index invalid_cursor ,invalid_number , zero_divide , value_error ,cursor_already_open, others.

2. Userdefined exceptionUser defined exception must be raised explicitly using RAISEstatement. Error code is -20000 to -20999

3. nonpredefine exception Pragma exception_init

A named exception can be associated with a particular

NO_DATA_FOUND: If There is no data which is you want to retrieve then this error will come.

declarerec emp%rowtype;beginselect * into rec from emp where empno=&no;dbms_output.put_line(rec.empno|| 'is getting'||rec. sal);exceptionwhen no_data_found thendbms_output.put_line(' the employee with this number is not there');end;

Page 115: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

**************************************

declarerec emp%rowtype;beginselect * into rec from emp where empno=&no;dbms_output.put_line(rec.ename|| ' is getting '||rec. sal);exceptionwhen no_data_found thendbms_output.put_line(' the employee with this number is not there');update emp set sal=4500where empno=7788;end;

TOO_MANY_ROWS: If your query is giving more than two rows then this error will come.

DeclareE_ename varchar2(2); e_sal number(9); begin select ename,sal into e_ename,e_sal from emp where deptno=10; delete from dept;Dbms_output.put_line(e_ename||' '||e_sal);-- exception-- when too_many_rows then-- dbms_output.put_line('query returns more than one --rows'); end;/

Here we are getting rows from deptno…there are so many emps…whose details it will take that’s why it will give too many rows…..

DUP_VAL_ON_INDEX: If your column having unique or primary key constraints now you are trying to insert duplicate values then this error will come. Begin insert into customer11 (customer_id, first_name , last_name ) values (1,'nibash','mohanty'); exception

Page 116: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

when dup_val_on_index then dbms_output.put_line('duplicate value on an index'); update dept set dname='cuttack' where deptno=10; end;

If in the table already enter values ,,,if again u try to insert any same value then it will give error…….here index means contents.

VALUE_ERROR: ‘Error in variable define’

DeclareE_ename varchar2(4);E_sal number(4);BeginSelect ename,sal into e_ename,e_sal from empWhere empno=7788;Dbms_output.put_line(e_en/Ame||' '||e_sal);ExceptionWhen value_error thenDbms_output.put_line('error in variable define');Delete from salgrade where grade in(2,3);End;

INVALID_NUMBER: 'Error in date function'

Declare a varchar2(10); rec emp%rowtype; begin select to_char('01-jan-08','month') into a from dual; dbms_output.put_line(a); exception when invalid_number then dbms_output.put_line('error in date function'); select * into rec from emp where empno=7788; dbms_output.put_line(rec.ename||' '||rec.job||' '||rec.sal); end;/

Here to_char function is not consider to ’01-jan-80’ like num…if u want to print that ans….Select to_char(to_date(’01-jan-80’),’month’) from dual;

Page 117: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

ZERO_DIVIDE :

Declare a number:=50; b number:=0; c number; rec emp%rowtype; begin c:=a/b; dbms_output.put_line('result is'||' '||c); exception when zero_divide then dbms_output.put_line('you cannot divide any no by zero'); select * into rec from emp where empno=7788; dbms_output.put_line(rec.ename||' '||rec.job||' '||rec.sal); end;/

CURSOR_ALREADY_OPEN: DeclareCursor c1 is select * from emp;Rec c1%rowtype;BeginOpen c1;For rec in c1 loopDbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.sal);End loop;ExceptionWhen cursor_already_open thenDbms_output.put_line('cursor is already open');Delete from salgrade where grade =1;End;

INVALID_CURSOR: If Without open cursor you are trying to fetch data from cursor then this error will come.

DeclareTyp emy_type is ref cursor;Rec_type my_type;Emp_rec emp%rowtype;

Page 118: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Cursor c1 is select * from dept where deptno in(10,20);Rec c1%rowtype;BeginLoopFetch c1 into rec;Exit when c1%notfound;Dbms_output.put_line(rec.deptno||' '||rec.dname||' '||rec.loc);End loop;ExceptionWhen invalid_cursor thenDbms_output.put_line('error in cursor');Dbms_output.put_line(chr(10));Open rec_type for select * from emp;LoopFetch rec_type into emp_rec;Exit when rec_type%notfound;Dbms_output.put_line(emp_rec.empno|| ' '||emp_rec.ename|| ' '||emp_rec.job|| ' '||emp_rec.mgr|| ' '||emp_rec.sal|| ' '||emp_rec.deptno);End loop;Close rec_type;End;/

Raise Exception:

When manager record then raise exception

DeclareCursor c1 is select * from emp ;Rec c1%rowtype;Rjob exception;BeginOpen c1;LoopFetch c1 into rec;Exit when c1%notfound;BeginIf rec.job='manager' thenRaise rjob;End if;ExceptionWhen rjob thenDbms_output.put_line('manager record');End;Dbms_output.put_line(rec.ename||' '||rec.job||' '||rec.sal);End loop;Close c1;

Page 119: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

End;

When 3rd manager then exit from the loop.

declare n number:=0; cursor c1 is select * from emp ; rec c1%rowtype; rjob exception; begin open c1; loop fetch c1 into rec; exit when c1%notfound; begin if rec.job='MANAGER' then n:=n+1; if n=2 then raise rjob; end if; end if; exception when rjob then raise_application_error(-20001,'u are the 2nd manager'); end; dbms_output.put_line(rec.ename||' '||rec.job||' '||rec.sal); end loop; close c1; end; /

PRAGMA EXCEPTION_INIT: allow you to handle the oracle predefined mssage by your own msg,means you can instruct compiler to associate the . Declare salary number; found_nothing exception; pragma exception_init(found_nothing,100); begin select sal into salary from emp where ename='RAVI'; dbms_output.put_line(salary); exception when found_nothing then dbms_output.put_line(sqlerrm); end; /

Page 120: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

DeclareSalary number;found_nothing exception; pragma exception_init(found_nothing,100);BeginSelect sal into salary from empWhere ename='RAVI';Dbms_output.put_line(salary);ExceptionWhen found_nothing thenDbms_output.put_line('record not found');End;

When deptno not exist

Declare dept_not_exists exception; pragma exception_init(dept_not_exists,-2291); beginInsert into emp (empno,ename,sal,deptno)values(1001,'kiran',2400,50); exception when dept_not_exists then dbms_output.put_line('this dept not exists'); end;/

PL/SQL FUNCTION Function is a database object or a named PL/SQL block that returns a single value. You can pass information into a function through its parameter list.

It accept three parameter.

Page 121: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

IN , OUT , IN OUT ***************** IN := use to pass the value from main programme to sub programme This is default parameter.

OUT :=use to pass the value from sub programme to main programme.

IN OUT := use to pass the value from main programme to sub programme and sub programme to main programme.

********************************************************

Create or replace function fun_incr(pay in out number)return number isBeginPay:=pay+pay*0.1;Return pay;End;

DeclareNum myemp.empno%type;Pay myemp.sal%type;BeginNum:=&employee_number;Select sal into pay from myemp where empno=num;Pay:=fun_incr(pay);Update myemp set sal=pay where empno=num;End;

To Print Ename.

create or replace function f2(e_empno in number)return varchar2ise_ename varchar2(10);beginselect ename into e_ename from emp

Page 122: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

where empno=e_empno;return e_ename;end;/To Display Result

Select f2(7369) from dual;

To count how many emps in a table.

create or replace function f2(e_empno in number)return varchar2ise_ename varchar2(10);beginselect ename into e_ename from empwhere empno=e_empno;return e_ename;end;/

Select f2(7369) from dual;

To count how many column in a table.

Create or replace function f1 (t_name varchar2) return number is c number; begin select count(column_name) into c from user_tab_columns where table_name=t_name; return c; end;

Select f1('emp') from dual;

Example For Boolean Datatype:

Create or replace function chk_dept (e_empno in number) return boolean is

Page 123: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

e_deptno number; begin select deptno into e_deptno from emp where empno=e_empno; if e_deptno= 20 then return true; else return false; end if; end; /

Function created……..

Call the function

DeclareFlag boolean;Num emp.empno%type;BeginNum:=&employee_number;If(chk_dept(num)) thenDbms_output.put_line(num || 'works in dept num 20');ElseDbms_output.put_line(num || 'does not work in dept num 20');End if;End;

Write a function to return under a manager how many employee working.

create or replace function find_emp (e_ename varchar2) return number is e_name varchar2(10); n_emp number; begin select m.ename, count(w.ename) into e_name,n_emp from emp w,emp m where w.mgr=m.empno and m.ename=e_ename group by m.ename; return n_emp;

Page 124: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

end;/

select find_emp('KING') from dual;

To Print That Emps and Manager Name:

Create or replace procedure empl(m_ename varchar2)IsCursor c1 is select w.ename wename,w.job wjob,M.ename mename,m.job mjob from emp w,emp mWhere w.mgr=m.empno and m.ename=m_ename;Rec c1%rowtype;BeginIf find_emp(m_ename) >=3 thenOpen c1;LoopFetch c1 into rec;Exit when c1%notfound;Dbms_output.put_line(rec.wename||' '||rec.wjob||' '||Rec.mename||' '||rec.mjob);End loop;ElseDbms_output.put_line('junior manager');End if;End;

/Exec empl('king');

Write a program to print emp exp.

Create or replace function emp_year (e_empno in number) return number is n number; begin select round((sysdate-hiredate)/365) into n from emp where empno=e_empno; return n; end; /

If exp is more than 29 years then increase their sal 1.1% and update in the table

Page 125: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Create or replace procedure sal_incrIsCursor c1 is select empno,sal from emp;Rec c1%rowtype;N number;BeginFor rec in c1 loopN:=emp_year(rec.empno);If n>=29thenUpdate emp set sal=sal*1.1Where empno=rec.empno;End if;End loop;End;/

Execute sal_incr

One Example for all sql functions by using pl/sql programm

Create or replace function sb (str varchar2,n1 number,n2 number) return varchar2 is v varchar2(1000); begin v:=substr(str,n1,n2); return v; end;

PROCEDURE A named PL/SQL block that performs one or more actions is called as an executable PL/SQL statement or procedure. You can pass information in and out of a procedure through its parameter list. procedure is a named block or subprogramme . it accept three parameter. IN , OUT , IN OUT ***************** IN := use to pass the value from main programme to sub programme

Page 126: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

This is default parameter. OUT :=use to pass the value from sub programme to main programme. IN OUT := use to pass the value from main programme to sub programme and sub programme to main programme.

*******************************************************Create table myemp12 as select empno,ename,sal from emp;

Commit;Select * from myemp;

Create or replace procedure pro_incr12(num in number,pay out number)isBeginSelect sal into pay from myemp12 where empno=num;Pay:=pay+pay*0.1;Update myemp12 set sal=pay where empno=num;End;

To Call Procedure

DECLARENUM MYEMP12.EMPNO%TYPE;PAY MYEMP12.SAL%TYPE;BEGINNUM:=&EMPLOYEE_NUMBER;PRO_INCR12(NUM,PAY);END;

SELECT * FROM MYEMP12;

BY USING CORSOR

CREATE OR REPLACE PROCEDURE EMPQ1 (E_DEPTNO NUMBER)

Page 127: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

IS CURSOR C2 IS SELECT * FROM EMP WHERE DEPTNO=E_DEPTNO; REC C2%ROWTYPE; BEGIN OPEN C2; LOOP FETCH C2 INTO REC; EXIT WHEN C2%NOTFOUND; DBMS_OUTPUT.PUT_LINE(REC.EMPNO||' '||REC.ENAME||' '|| REC.JOB||' '||REC.MGR||' '||REC.HIREDATE||' '|| REC.SAL||' '||REC.COMM||' '||REC.DEPTNO); END LOOP; CLOSE C2; END;/

SET SERVEROUTPUT ON

EXECTE EMPQ1(10)

Write a procedure to retrive the data from deptno and that deptno's

sum salary,min hiredate,no of employees.

create or replace procedure p1(d_deptno number)iscursor c1 is select * from emp where deptno=d_deptno;rec c1%rowtype;s_sal number;s_hiredate date;s_count number;beginopen c1;loopfetch c1 into rec;exit when c1%notfound;dbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.mgr||' '||rec.hiredate||' '||rec.sal||' '||rec.comm||' '||

Page 128: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

rec.deptno);end loop;close c1;select sum(sal) into s_sal from emp where deptno=d_deptno;dbms_output.put_line('SUM SAL:--'||s_sal);select min(hiredate) into s_hiredate from emp where deptno=d_deptno;dbms_output.put_line('MIN HIREDATRE:--'||s_HIREDATE);select COUNT(*) into s_COUNT from emp where deptno=d_deptno;dbms_output.put_line('NO OF EMPLOYEE:--'||s_COUNT);end;/

EXECUTE P1(20)

WITH FOR LOOP...............

create or replace procedure fact_in(n in number)is fact number:=1;beginfor i in 1..nloopfact:=fact*i;end loop;dbms_output.put_line(fact);end;

EXECUTE FACT_IN(5)

************************************create or replace procedure mult(n number)isf number;beginfor i in 1..10 loopf:=n*i;dbms_output.put_line(n||'*'||i||'='||f);end loop;end;

EXECUTE MULT(3)

****************************************************

USING IN OUT......

Page 129: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

create or replace procedure FACT3(N IN OUT NUMBER) IS F NUMBER:=1; BEGIN FOR I IN 1..N LOOP F:=F*I; END LOOP; N:=F; END; /

DECLARE N NUMBER:=&N; BEGIN DBMS_OUTPUT.PUT_LINE('GIVEN VALUE:'||N); FACT3(N); DBMS_OUTPUT.PUT_LINE('FACTORIAL:'||N); END;

CREATE OR REPLACE PROCEDURE PROC2 (CHOICE VARCHAR2) IS E_SAL NUMBER; BEGIN IF CHOICE='SELECT' THEN SELECT SAL INTO E_SAL FROM EMP WHERE EMPNO=7788; ELSIF CHOICE='UPDATE' THEN UPDATE EMP SET SAL=2000 WHERE EMPNO=7566; ELSIF CHOICE ='INSERT' THEN INSERT INTO EMP(EMPNO,ENAME,JOB,DEPTNO) VALUES(7523,'KIRAN','MANAGER',10); ELSIF CHOICE='DELETE' THEN DELETE EMP WHERE EMPNO=7902; END IF; DBMS_OUTPUT.PUT_LINE(E_SAL); END;/

EXECUTE PROC2('SELECT')

LIKE THAT REMAIN ANS....

Page 130: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

***** Create or replace procedure tax_calc is cursor c1 is select * from emp ; rec c1%rowtype; emp_tax number; begin open c1; loop fetch c1 into rec; exit when c1%notfound or rec.ename='KING'; if rec.job='manager' then emp_tax:=rec.sal*1.3; elsif rec.job='analyst' then emp_tax:=rec.sal*1.2; elsif rec.job='salesman' then emp_tax:=rec.sal*1.1; elsif rec.job='clerk' then emp_tax:=rec.sal*1.05; end if; update emp set sal=sal-emp_tax where empno=rec.empno; end loop; end; /

************Create or replace procedure comm_calc is cursor c1 is select * from emp ; rec c1%rowtype; emp_comm number; begin open c1; loop fetch c1 into rec;

Page 131: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

exit when c1%notfound; if rec.job='analyst' then emp_comm:=rec.sal*.02; update emp set comm=emp_comm where empno=rec.empno; elsif rec.job='clerk' then emp_comm:=rec.sal*.05; update emp set comm=emp_comm where empno=rec.empno; end if; end loop; end;**************create or replace procedure result1(s_rollno number,s_name varchar2,s_pap1 number,S_pap2 number,s_pap3 number)IsS_tot number;S_per number(8,2);S_result varchar2(10);Flag varchar2(10):='true';BeginIf s_pap1 <=30 or s_pap2<=30 or s_pap3<=30 thenFlag:='false';End if;S_tot:=s_pap1+s_pap2+s_pap3;S_per:=s_tot*100/300;If s_per > 60 and flag='true' thenS_result:='first';ElsifS_per > 50 and s_per <60 and flag='true' thenS_result:='second';ElsifS_per > 35 and s_per <50 and flag='true' thenS_result:='third';ElseS_result:='fail';End if;Insert into result1 values (s_rollno,s_name,s_pap1,S_pap2,s_pap3,s_tot,s_per,s_result);End;/

**********Create or replace procedure rrIsCursor c1 is select * from emp;Rec c1%rowtype;Y number;BeginOpen c1;

Page 132: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

LoopFetch c1 into rec;Exit when c1%notfound;Y:=round((sysdate-rec.hiredate)/365);If y between 10 and 15 thenUpdate emp set SAL=rec.sal*1.15Where empno=rec.empno;Elsif y between 15 and 20 thenUpdate emp set SAL=rec.sal*1.25Where empno=rec.empno;ElseUpdate emp set SAL=rec.sal*1.35Where empno=rec.empno;End if;End loop;End;/

*********** Procedure with ref cursor

CREATE OR REPLACE PROCEDURE P (E_DEPTNO IN NUMBER,EMP_REC OUT EMP%ROWTYPE) IS TYPE EMPCURTYPE IS REF CURSOR; EMP_CV EMPCURTYPE; SQL_STMT VARCHAR2(2000); MY_JOB VARCHAR2(20):='MANAGER'; BEGIN SQL_STMT :='SELECT * FROM EMP WHERE JOB=:J'; OPEN EMP_CV FOR SQL_STMT USING MY_JOB; LOOP FETCH EMP_CV INTO EMP_REC; EXIT WHEN EMP_CV%NOTFOUND; DBMS_OUTPUT.PUT_LINE(EMP_REC.EMPNO||' '|| EMP_REC.ENAME||' '||EMP_REC.JOB||' '||EMP_REC.MGR||' '||EMP_REC.HIREDATE||' '||EMP_REC.SAL||' '||EMP_REC.DEPTNO); END LOOP; CLOSE EMP_CV; END;/

Page 133: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Write a procedure to retrive data from multiple table in run time.

Create or replace procedure dyno(t_name varchar2)IsType m_t is ref cursor;Rec m_t;Emp_rec emp%rowtype;Dept_rec dept%rowtype;Salg_rec salgrade%rowtype;BeginIf t_name ='emp' thenOpen rec for select * from emp;LoopFetch rec into emp_rec;Exit when rec%notfound;Dbms_output.put_line(emp_rec.empno||' '||emp_rec.ename||' '||emp_rec.job||' '||Emp_rec.mgr||' '||emp_rec.hiredate||' '||emp_rec.sal||' '||emp_rec.comm||' '||Emp_rec.deptno);End loop;Close rec;ElsifT_name='dept' thenOpen rec for select * from dept;LoopFetch rec into dept_rec;Exit when rec%notfound;Dbms_output.put_line(dept_rec.deptno||' '||dept_rec.dname||' '||dept_rec.loc);End loop;Close rec;ElseOpen rec for select * from salgrade;LoopFetch rec into salg_rec;Exit when rec%notfound;Dbms_output.put_line(salg_rec.grade||' '||salg_rec.losal||' '||salg_rec.hisal);End loop;Close rec;End if;End;

Page 134: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PACKAGE

package is a collection of PL/SQL objects that are packaged or grouped together within a special BEGIN-END syntax, It is a kind of "meta-block. OR database object"

With in package user can define * Cursors * Variables * Exception names * Procedures * Functions

Package is divide into two part

* Specification part. (Declaration part) * Body part. (Coding part)

create or replace package pro2isprocedure select1 (e_empno number);procedure del1 (e_empno emp.empno%type);procedure upd1 (e_ename emp.ename%type);function SAL1 (e_empno emp.empno%type)return number;end;

Page 135: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

create or replace package body pro2isprocedure select1 (e_empno number)ise_ename emp.ename%type;e_job emp.job%type;e_sal emp.sal%type;beginselect ename,job,sal into e_ename,e_job,e_sal from empwhere empno=e_empno;dbms_output.put_line(e_ename||' '||e_job||' '||e_sal);end select1;procedure del1 (e_empno emp.empno%type)isbegindelete from emp where empno=e_empno;end del1;procedure upd1 (e_ename emp.ename%type)isbeginupdate emp set ename='ROBERT'where ename=e_ename;end upd1;function SAL1 (e_empno emp.empno%type)return numberiss_sal number;beginselect sal into s_sal from emp where empno=e_empno;return s_sal;end SAL1;end;

EXECUTE PRO2.SELECT1(7788)SELECT PRO2.SAL1(7209) FROM DUAL;

Page 136: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

TRIGGER Trigger is as database object that execute in response to changes in table data or certain database events. There is a predefined set of events that can be invoke with a trigger

1. Row level trigger 2. Statement level trigger 3. Instead of trigger

FOR EACH ROW defines the trigger to be a row-level trigger. Row-level triggers fire once for each row affected.

The default is a statement-level trigger, which fires only once for each triggering statement.

Instead of trigger is use to insert data for complex view.

Row level trigger

Examples:

CREATE OR REPLACE TRIGGER CHK_DAY BEFORE INSERT OR UPDATE OR DELETE ON EMP FOR EACH ROW BEGIN IF TO_CHAR(SYSDATE,'DY') in('SUN') THEN RAISE_APPLICATION_ERROR(-20500,'YOU CANNOT DO DML ON SUNDAY'); END IF; END;

CREATE OR REPLACE TRIGGER CHK_TIME BEFORE INSERT OR UPDATE OR DELETE ON EMP FOR EACH ROW BEGIN

Page 137: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

IF TO_CHAR(SYSDATE,'hh24') BETWEEN 13 AND 15 THEN RAISE_APPLICATION_ERROR(-20500,'YOU CANNOT DO DML ON LUNCH TIME'); END IF; END;

CREATE OR REPLACE TRIGGER CHK_SAL BEFORE INSERT OR UPDATE OR DELETE ON EMP FOR EACH ROW BEGIN IF (:new.sal > :old.sal) THEN RAISE_APPLICATION_ERROR(-20500,'YOU CANNOT INCRESE SALARY'); END IF; END;/

CREATE OR REPLACE TRIGGER MY_T AFTER INSERT OR UPDATE OR DELETE ON EMP FOR EACH ROW BEGIN UPDATE DEPT SET DEPTNO =:NEW.DEPTNO WHERE DNAME='OPERATIONS'; END;

CREATE OR REPLACE TRIGGER CHK_COMM BEFORE INSERT OR UPDATE ON EMP FOR EACH ROW BEGIN IF :NEW.JOB <> 'SALESMAN' AND :NEW.COMM IS NOT NULL THENRAISE_APPLICATION_ERROR(-20650,'COMM ONLY FOR SALESMAN');END IF;END;/

User scott cannot insert,update or delete on emp by trigger;

create or replace trigger userscott before insert or update or delete on emp for each row begin if user='SCOTT' then raise_application_error(-20500,'User scott cannot insert,update,delete on emp'); end if; end;

Page 138: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

> Write a trigger after inserting one row to emp table delete one row from emp.

CREATE OR REPLACE TRIGGER DELTAB AFTER INSERT OR UPDATE OF SAL ON EMP DECLARE CURSOR C1 IS SELECT EMPNO FROM EMP; REC C1%ROWTYPE; N NUMBER:=0; BEGIN OPEN C1; LOOP FETCH C1 INTO REC; EXIT WHEN C1%NOTFOUND; END LOOP; N:=C1%ROWCOUNT; IF N>=14 THEN DELETE FROM EMP WHERE ROWNUM<=1; END IF; END;/

create or replace trigger check_manager_sal after insert or update of sal,deptno on emp declare cursor c1 is select job,sal from emp where job='MANAGER'; rec c1%rowtype; e_job varchar2(20); e_sal number; begin open c1; loop fetch c1 into rec; exit when c1%notfound; select job,sal into e_job,e_sal from emp where job='PRESIDENT'; if REC.SAL > E_SAL then raise_application_error (-20325, 'manager salary should not be more than president sal'); end if ; end loop; end;/

Page 139: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

STATEMENT LEVEL TRIGGER create or replace trigger log_on after logon on scott.SCHEMA begin update emp set sal=sal*1.1; end;/

create or replace trigger logon after logon on scott.schema begin update emp set sal=1000 where empno=7605; end;

scott user cannot drop a table.

CREATE OR REPLACE TRIGGER LOG_TRI BEFORE DROP ON SCOTT.SCHEMA BEGIN RAISE_APPLICATION_ERROR(-20500,'You cannot drop a table'); end;

Instead of triggercreate view comp_vuas select D.DEPTNO,d.dname,d.loc,e.empno,e.ename,e.job,e.mgr,e.hiredate,e.sal,e.comm,e.deptno EDEPTfrom emp e,dept d where e.deptno=d.deptno

insert into comp_vu values(80,'FINANCE','DELHI',4444,'ROBERT', 'MANAGER',4545,'01-JAN-05', 1000,20,80)

Page 140: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

insert into comp_vu values(80,'FINANCE','DELHI',4444,'SMITH','MANAGER',4545,'01-JAN-05',*ERROR at line 1:ORA-01779: cannot modify a column which maps to a non key-preserved table

Create or replace trigger insinstead of insert on comp_vubegininsert into dept values(:new.deptno,:new.dname,:new.loc);insert into emp values(:new.empno,:new.ename,:new.job,:new.mgr,:new.hiredate,:new.sal,:new.comm,:NEW.DEPTNO);end;

VARRAY

Page 141: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

Varray is an oracle data type ,used to support columns containing multivalued attributes,in this case,column that can hold a bounded varray of values...means you can insert multiple values at a time into type.......

**************************************************** CREATE TYPE COL75 IS VARRAY(4) OF NUMBER(2)/ CREATE TYPE COL76 IS VARRAY(4) OF NUMBER(3)/ CREATE TYPE COL65 IS VARRAY(4) OF NUMBER(4)/ CREATE TABLE ARRAY39(COLUMN1 COL75,COLUMN2 COL76,COLUMN3 COL65)/> INSERT INTO ARRAY39 VALUES(COL75(10,25,35,55), COL76(555,446,554,656),COL65(8250,1650,6630,2260))/ INSERT INTO ARRAY VALUES(COL1(36,95,56,25), COL2(505,485,554,626),COL3(5095,5950,6560,5560))/ COL COLUMN1 FOR A30 COL COLUMN2 FOR A30 COL COLUMN3 FOR A30 SELECT * FROM ARRAY;

OLUMN1 COLUMN2 COLUMN3----------------------------- ------------------------------ ------------------------------OL1(10, 25, 35, 55) COL2(555, 446, 554, 656) COL3(8250, 1650, 6630, 2260)OL1(36, 95, 56, 25) COL2(505, 485, 554, 626) COL3(5095, 5950, 6560, 5560)

UPDATE ARRAY29 SET COLUMN3=COL22(111,222,333,444);

BULK BINDING

CREATE TABLE DEPT78(DEPTNO NUMBER(4),

Page 142: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

DNAME VARCHAR2(10),LOC VARCHAR2(10));

> DECLARE TYPE DNO IS VARRAY(3) OF NUMBER(5); TYPE DNA IS VARRAY(3) OF DEPT78.DNAME%TYPE; TYPE LO IS VARRAY(3) OF VARCHAR2(20); A DNO; B DNA; C LO; BEGIN A:=DNO(10,20,30); B:=DNA('ACCOUNTS','SALES','PURCHASE'); C:=LO('HYD','MUM','DEL'); FORALL I IN 1..3 INSERT INTO DEPT78 VALUES(A(I),B(I),C(I)); END;/

NESTED TABLE

It is an oracle data type to used to support columns containing multivalues attributes,in this case ,columns that can hold an entire sub_table...it means one table in other table....

CREATE TYPE MY_TY272 AS OBJECT(SCODE NUMBER(10),SNAME VARCHAR2(10),LOC VARCHAR2(10),PHONE NUMBER(12));/>CREATE TABLE STUDENT42(SNAME VARCHAR2(10),SNO NUMBER(5),PAP1 NUMBER(5),PAP2 NUMBER(5),PAP3 NUMBER(5),MADDR MY_TY272)> INSERT INTO STUDENT42 VALUES ('JOHN',1,20,30,20,MY_TY272(100,'AP','AMEERPET',98562322))/ INSERT INTO STUDENT VALUES ('ROBERT',2,50,30,20,MY_TY(101,'UP','LUCK',9545462322))/>UPDATE STUDENT8 A SET A.MADDR.SCODE=200WHERE A.MADDR.LOC='ORISSA';

Page 143: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PARTITION TABLE Partitionning allows a table to be sudivided into smaller pieces,where each piece of such a data base is called a partition...each partiton has its own name..............min of 2gb data table needed partition.

RANGE PARTITION create table part (sno number,sname varchar2(10),fee number(4)check(fee > 1000))partition by range(fee)(partition p1 values less than (1100),partition p2 values less than (1200))

How to see the partition table.

select * from part partition (p1)

To add a partition to a table Alter table part add partition p3 values less than (1500);

alter table part add partition p3 values less than (maxvalue)

How to drop a partition.

alter table part drop partition p3

Alter table stud merge partitions p1,p2 into partition p8;

How to split a partition.

Alter table part split partition p3 at (1300) into (partition p4,partition p5)

When you split the partition p3 into p4 and p5 then p4 value will be 1300 and p5 value will be 1500.

After spliting the partition p3. partition p3 and p3 value will be deleted.

alter table part split partition p5 at (1450) into (partition p6,partition p7)

Page 144: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

select partition_name,high_value from user_tab_partitions where table_name='PART'

LIST PARTITION CREATE TABLE PART(SNO NUMBER,SNAME VARCHAR2(10), LOC VARCHAR2(10)) PARTITION BY LIST(LOC) (PARTITION SOUTH VALUES('HYD','CHE') TABLESPACE USER1, PARTITION NORTH VALUES('DEL','LUCK') TABLESPACE USER2)/

ALTER TABLE PART ADD PARTITION EAST VALUES('DIN') TABLESPACE USER2;

ALTER TABLE PART MOVE PARTITION EAST TABLESPACE USER1;

> INSERT INTO PART VALUES (1,'DDD','HYD')

> SELECT * FROM PART PARTITION (SOUTH)

> ALTER TABLE PART ADD PARTITION EAST VALUES ('CAL','PAT')

> ALTER TABLE STUD9 MERGE PARTITIONS SNO1,SNO3 INTO PARTITION SNO7/

HASH PARTITION

CREATE TABLE EEMP(ENO NUMBER PRIMARY KEY,ENAME VARCHAR2(10),DOJ DATE,SAL NUMBER(8,2), DNO NUMBER(2)) PARTITION BY HASH(DNO)( PARTITION P1,PARTITION P2)/

DATE PARTITION

CREATE TABLE STUDENT(SNO NUMBER(4),SNAME VARCHAR2(10),DOJ DATE)PARTITION BY RANGE(DOJ)(PARTITION P1 VALUES LESS THAN (TO_DATE('01-JAN-06','DD-MON-YYYY')),

Page 145: novae-itrocks.weebly.comnovae-itrocks.weebly.com/uploads/8/4/0/6/8406197/oracle_11g_m…  · Web viewORACLE 11g 15. Advantages of ORACLE 15. History of Oracle 16. DATA BASE 16. Database

PARTITION P2 VALUES LESS THAN (TO_DATE('01-JAN-07','DD-MON-YYYY')),PARTITION P3 VALUES LESS THAN (TO_DATE('01-JAN-08','DD-MON-YYYY')))/

INSERT INTO STUDENT VALUES(1,'SRIRAM',(TO_DATE('01-FEB-06','DD-MON-YYYY')))/

SPLIT PARTITIONS ALTER TABLE STUDENT SPLIT PARTITION R5 AT (TO_DATE('05-FEB-08','DD-MON-YYYY'))INTO (PARTITION R6,PARTITION R7); MERGE PARTITIONS ALTER TABLE STUDENT MERGE PARTITIONS R6,R7 INTO PARTITION R8/