ORACLE 11g ......................................................... 15 Advantages of ORACLE ....................................... 16 History of Oracle ................................................... 16 DATA BASE ...................................................... 16 Database Management System(DBMS) ................ 17 Eg: Dbase, FoxPro, Paradox etc.............................. 17 RDBMS ............................................................. 17 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 ....................... 18 The Basic Objects Of Rdbms: ............................... 18 Attribute ................................................................. 19 Relation .................................................................. 19 Oracle9i - The eBusiness Platform ..................... 19 Oracle 11g – Key Infrastructure Areas ............... 19 Oracle 11g - Key application areas ..................... 19 Scalability and Performance ............................... 20 Oracle 11g - Providing an End-to-End Security Infrastructure ....................................................... 20 Oracle 11g - Development Platform for eBusiness Applications ........................................................ 20 Oracle 11g - Manageability................................. 20 Oracle 11g - Windows Integration ...................... 20 Product of ORACLE .............................................. 21 BACKEND TOOLS FRONTEND TOOLS .................................................................. 21 DBMS (SQL & PLSQL) DBA .. 21 E.F.CODD RULES: ........................................... 22 Oracle Data types ............................................... 22 The following are different data types supported by ORACLE ...................................................... 23 Rules for define a table name. ............................ 24 SQL * PLUS ........................................................... 25 Commands ......................................................... 25 DDL ................................................................... 25 Syntax ..................................................................... 25 Example : ................................................................ 26 ALTER COMMAND ............................................. 26 1. Add ..................................................................... 26 2. Modify ................................................................ 26 3. Drop .................................................................... 26 Syntax: .................................................................... 26 Alter Table <table_name> Drop column <column_name> ..................................................... 26 Examples on Alter Command ............................. 26 Create a table with the following structure ......... 26 Rename Command .................................................. 27 Syntax: ...................... Rename <old_table_name> to <new_table_name> ................................................. 27 DML .................................................................. 27 Insert command....................................................... 27 Syntax: .................................................................... 27 Examples on Insert Command ............................ 27 First Create a table .................................................. 27 To insert values into all Columns ........................... 27 Similarly insert some more values as follows ..... 28 To insert values into specified Columns ................. 28 Update Command .................................................. 28 Syntax: .................................................................... 28 Examples: ............................................................... 28 To update only one column value ........................... 28 Delete Command .................................................... 28 Syntax : Delete From <table name> where <condition> ............................................................. 29 Ex : To Delete A Single Row ............................... 29 Ex : To Delete Multiple Rows (More Than One Row) ....................................................................... 29 TCL .................................................................... 30 Syntax : commit; ..................................................... 30 Syntax : Rollback To [Savepoint] Savepoint_Name ................................................................................ 31 Syntax : ................................................................... 31 DCL ................................................................... 31 Examples : .......................................................... 33 Between ................................................................. 33 Syntax : ...... [ Not ] Between <Begin Expression And End Expression> ..................................................... 33 Examples : .......................................................... 33 Examples : .............................................................. 34 Built In Function in Oracle ................................. 35 Character Functions or Text Functions or String Functions ........................................................... 37 Date and Time Functions ................................... 40 Add_Months : .................................................... 40 Last_day : ........................................................... 40 Next_Day ........................................................... 41 months_between ................................................ 41 Count ................................................................. 41 Sum(sal) ............................................................. 42 Syntax : Sum(distinct <numerical column>) ......... 42 Examples : .............................................................. 42 Max(sal) : ........................................................... 42 Syntax : Max(numerical column) .......................... 42 Example : ................................................................ 42 Min(sal) : ........................................................... 42 Syntax : Min(numerical column) ........................... 42 Example: ................................................................. 42 Write a query to find minimum sal earning by an employee in the emp table ...................................... 42 Avg(sal) : ........................................................... 42 Syntax : Avg(distinct <numerical column>).......... 42 Example : ................................................................ 42 Group By Clause .................................................... 42 Having Clause ........................................................ 43 Examples : .............................................................. 43 Order By Clause .................................................... 43 To_char : ................................................................ 45 NVL FUNCTION ............................................. 46 Constraints ......................................................... 48 Note : Constraints can be imposed in two ways ..... 48 Table Level : ........................................................... 48 Column Level : ....................................................... 48 NOT NULL ....................................................... 49 Syntax: .................................................................... 49 Not Null in Column Level ...................................... 49 Adding Not Null Using Alter Command for Existing Table ....................................................................... 49 Note : ...................................................................... 49 Example : ................................................................ 49 Create table sample1(sno number(3), sname varchar2(20) not null); ............................................ 49 Error Comes ............................................................ 49 Unique Constraint .................................................. 49 Syntax: (For Column Level) ................................... 50 Syntax: (For Table Level) ....................................... 50 Example : Imposing unique constraint Table Level 50 Example : Imposing unique constraint Column Level ................................................................................ 50 Default Constraint : ................................................ 50 Note : Only Column level definition can be applied to “Default constraint” ............................................ 50 Syntax : for column level ........................................ 50 Create Table <Table Name>(Column1 <Data Type><Size> default <value>, ............................... 50 Example : ................................................................ 50 Example : 2 ............................................................. 51 SNO ......................................................... SNAME 51 Check Constraint ................................................... 51 Syntax : (column Level) ......................................... 51 Example: ................................................................. 51 Syntax : (Table Level) ............................................ 52 Example : ................................................................ 52 Primary Key Constraint ......................................... 52 Syntax: .................................................... Table Level 52 Ex:........................................................................... 52 Error Comes ............................................................ 52 Syntax : ............................................... Column Level 52 Example : ................................................................ 52 Error Comes ............................................................ 52 Example 2 ............................................................... 52 Error Comes ............................................................ 53 Foreign Key Constraint .......................................... 53 There are five major restrictions related to foreign key .......................................................................... 53 Syntax : (Column Level) ........................................ 53 Syntax : (Table Level) ............................................ 53 Making relationships between two tables .............. 53 2. Next Create the Child Table................................ 53 3. Next insert the values in to mother table first, 54 101 Mahesh 6500 ............................................ 54 ERROR : (since there is no such account number present in the mother table)..................................... 54 SQL> select * from banktrans; ............................... 54 Dropping Relationship Tables ............................... 54 Note : ...................................................................... 54 Joins ................................................................... 58 Table and column alias names ............................ 58 Types of Joins ......................................................... 58 General Syntax : ..................................................... 58 Equi Join ................................................................ 58 Example : ................................................................ 58 List the employee numbers, names, department numbers and dept names ......................................... 58 Using Table Aliases ............................................... 59 Non Equi Join ........................................................ 59 Example : ................................................................ 59 Outer Join .............................................................. 59 Left Outer Join ....................................................... 59 Example : ................................................................ 59 Right Outer Join ..................................................... 60 Example : ................................................................ 60 Rules to place ( + ) Operator ................................... 60 Full outer joins. ...................................................... 60 Here it will show both the extra field from two table. ................................................................................ 60 P.OUTER JOIN ..................................................... 60 NATURAL JOIN ................................................... 60 Self Join ................................................................. 61 select e1.ename,e1.deptno from emp e1,emp e2 ..... 61 where e2.ename='FORD' and e1.deptno=e2.deptno; ................................................................................ 61 Cross Join (oracle 9i concept) ................................ 61 Syntax ..................................................................... 61 Example : ................................................................ 62 SUB QUERY ..................................................... 62 Sub Queries Or Nested Queries .............................. 62 Using Sub Queries, ................................................. 63 Using sub Query, .................................................... 63 ERROR at line 1: .................................................... 63 ORA-01427: single-row subquery returns more than one row*******DELETE & UPDATE .................. 63 SET OPEREATOR ............................................ 67 Union, Intersect and Minus Operators .................... 67 Syntax : ................................................................... 68 Syntax : ................................................................... 68 Syntax : ................................................................... 69 Special Operators used in Sub Queries ................... 70 All, Any and Some Operators ................................ 70 ANY Operator ....................................................... 70 Example : ................................................................ 70 ALL Operator ........................................................ 70 Example : ................................................................ 70 SOME Operator ..................................................... 71 Example : ................................................................ 71 Syntax : ................................................................... 71 Create View <view name>..................................... 71 Advantages of Views ......................................... 71 Types of View .................................................... 72 Simple View .......................................................... 72 Syntax : ................................................................... 72 Examples :........................................................... 72 We 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 ........ 72 To Create Read Only Views .............................. 73 Example : ................................................................ 73 ERROR at line 1: .................................................... 73 ORA-01732: data manipulation operation not legal on this view ............................................................. 73 ERROR at line 1: .................................................... 73 ORA-01732: data manipulation operation not legal on this view ............................................................. 73 Composite View .................................................... 73 Syntax : ................................................................... 73 Create view <view name> as select <fields list> from ................................................................................ 73 ERROR at line 1: .................................................... 74 ORA-01776: cannot modify more than one base table through a join view ................................................. 74 Dropping a view .................................................... 74 Drop view <view name> ......................................... 74 Note : ...................................................................... 74 SEQUENCE ...................................................... 75 Syntax : ................................................................... 75 Start with : it is a keyword to specifying the starting value in the sequence creation ................................ 75 Maxvalue : specifies the maximum value or limit that the sequence can generate ....................................... 75 Order : generates the sequences in the order of request ..................................................................... 76 Attatching Sequence ........................................... 76 Example : ................................................................ 76 Using Insert Command ........................................... 76 Syntax : ................................................................... 76 Insert into <table name>(columns list) values(sequencename.nextval,……);...................... 76 ERROR at line 1: .................................................... 77 Using Update Command ......................................... 77 Syntax : ................................................................... 77 Update <table name> set <column Name>=<sequencename.nextval>, ------; ............... 77 Updating only one value ..................................... 77 Updating Multiple Values ................................... 77 Altering a Sequence .................................................... 77 Syntax : ................................................................... 77 Example .................................................................. 77 Again Altering the above sequence..................... 78 Drop sequence : ..................................................... 78 Syntax : drop sequence <sequence name> ........... 78 Note : ...................................................................... 78 Synonym ............................................................ 78 Clusters .............................................................. 79 Syntax : .................................................................. 79 To create any cluster .............................................. 80 Note : .................................................................. 80 First create the cluster, ........................................ 80 Next create the index, ......................................... 80 Attaching the cluster to the table,........................ 80 Example : ................................................................ 80 SNO SNAME ..................................................... 80 SNO SNAME ..................................................... 81 SNO SNAME ..................................................... 81 SNO SNAME ..................................................... 81 ERROR at line 1: .................................................... 81 ORA-00942: table or view does not exist ............... 81 Drop cluster ........................................................... 81 Syntax : drop Cluster <cluster name> .................... 81 INDEX ............................................................... 82 Types of index. .................................................. 82 Simple Index .......................................................... 82 ERROR at line 1: .................................................... 82 ORA-00942: table or view does not exist ............... 82 Creating Unique indexes on a Single column ........ 83 Syntax : ................................................................... 83 Example : ............................................................... 83 Error : ...................................................................... 83 Ora-00001: unique constraint (scott.idx_temp) violated ................................................................... 83 Note : ...................................................................... 83 ERROR at line 1: .................................................... 83 ORA-01408: such column list already indexed ...... 83 Composite index .................................................... 83 Syntax : ................................................................... 83 Composite unique index ........................................ 84 Syntax : ................................................................... 84 Bitmap index .......................................................... 84 Syntax : ................................................................... 84 Drop index ............................................................. 84 Syntax : Drop index <index name> ........................ 84 To View Index ....................................................... 84 Clusters .............................................................. 85 Syntax : .................................................................. 85 To create any cluster .............................................. 85 Note : .................................................................. 85 First create the cluster, ........................................ 86 Next create the index, ......................................... 86 Attaching the cluster to the table,........................ 86 MERGE ............................................................. 87 RANKING ......................................................... 87 PRIVILEGES .................................................... 87 Table Lock ......................................................... 89 SPOOL 'C:\ravi.txt'; ENTER .............................. 91 NEXT SELECT * FROM EMP ENTER ............ 91 SPOOL OFF ENTER .......................................... 91 THEN OPEN C ................................................... 91 PIVOT ............................................................... 91 NORMALIZATION .......................................... 91 PL/SQL PROGRAMMING ............................... 94 PLSQL DATA TYPES ...................................... 94 IF condion .......................................................... 99 LOOP Condition .............................................. 102 Types Of Loops ............................................... 102 DECODE ......................................................... 108 CASE ............................................................... 109 Exp of Boolean Datatypes. .............................. 110 CURSOR ......................................................... 111 Types Of Cursor .............................................. 111 IMPLICIT ........................................................ 111 STRONG CORSOR ........................................ 112 WEEK CURSOR ............................................. 113 CORSOR WITH FOR LOOP .......................... 114 WITH WHILE LOOP ...................................... 114 WITH GROUP BY CLAUSE ......................... 115 WITH JOINS ................................................... 115 WITH CASE FUNCTION ............................... 116 EXCEPTION ................................................... 117 PL/SQL FUNCTION ....................................... 123 PROCEDURE .................................................. 129 PACKAGE ...................................................... 137 TRIGGER ........................................................ 139 VARRAY ........................................................ 144 BULK BINDING ............................................. 145 NESTED TABLE ............................................ 146 PARTITION TABLE ...................................... 147 ORACLE 11g Introduction It 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 ORACLE 1. Back up and recovery 2. Portability 3. Performance 4. Multiple data base support 5. Security 6. Convertibility 7. Compatibility 8. Data Integration 9. Centralized Administration 10. Multi User Data Access History of Oracle Oracle 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 Oracle 9i is released with Extended Internet features Oracle10g is released with Gride Features Oracle 11g is released with Extended Gride Features DATA BASE It 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 Records 2. Updating Records 3. Modifying Records 4. Deleting Records 5. 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 Rdbms 1. 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. Difference between DBMS AND RDBMS DBMS 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 Table DBMS normally called 3rd RDBMS normally called 4th generation language 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 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. Entity 2. Attribute 3. Relation Entity THE RELATIONAL A 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. Attribute An 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 Platform Oracle9i 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 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 Performance Oracle9i 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 Infrastructure Oracle9i 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 Applications Oracle11g 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 - Manageability Management is one of the key areas of improvement for Oracle9i. There are five aspects to our approach taken with management in Oracle9i: 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 Integration Oracle9i 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) SQLSERVER (MS) .NET MYSQL (OSDB) ORACLEFORMS(D2K) DB2 (IBM) MS ACCESS (MS) DBMS (SQL & PLSQL) Creating Tables Store The Data And Retrive The Data JAVA (ORACLE) (MS) (ORACLE) DBA Creating Data Base 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. 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: Date Example : 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 Restriction of Long There are some restrictions of long data type. 1) 2) 3) 4) 5) Only one column is defined as long for table. Long columns con not be indexed. Long columns can’t appear in integrity constraints. Long columns can’t be used in SQL expressions. 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. 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 SQL SQL 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 id 1. 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 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. Add 2. Modify 3. 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 columns c. 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 Command Create a table with the following structure Create table students(roll number(3), sname varchar2(20), sub1 number(3), sub2 number(3), sub3 number(3)); 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 Command It 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 command The 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 Command First 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”); 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/100 WHERE DEPTNO=(SELECT DEPTNO FROM DEPT WHERE DNAME='SALES') AND JOB='SALESMAN' AND COMM<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' AND E.DEPTNO=D.DEPTNO); UPDATE EMP SET ENAME=LOWER(ENAME); Delete Command This Command Is Used To Delete All Or Specified Rows In A Table 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') AND SAL>(SELECT SAL FROM EMP WHERE ENAME='SMITH') AND SAL<(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 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) Rollback This 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. Syntax : Rollback To [Savepoint] Savepoint_Name optional SavePoint Savepoint 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. 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; 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 column Syntax : [ 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; 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 are 1. _ ( underscore ) : Represents a Single Character 2. % ( 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. 6. 7. 8. 9. Select ename,job from emp where sal>= 1000 and job like '%man%'; Select * from emp where job='clerk' or deptno=20; Select * from emp where mgr is null; Select * from emp where mgr is not null; 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 Oracle SQL 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 7. case,decode.. := Nvl , Nvl2 , Nullif , Coalesce 1. Abs : This function is used to convert any negative expression into positive 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.4142 select sqrt(16) from dual ; 4 select 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 ; 8 select power(5,3) from dual ; 125 select 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.6 Select 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 ; -23 Select 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 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; 1 select 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; GREATEST Select 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 ; 97 select Ascii(‘A’) from dual ; 65 Chr : This Function Returns The Ascii Character For The Given Ascii Value Syntax : Chr(Ascii Value) Example : select chr(65) from dual ; A Select chr(97) from dual ; a Length : This Function Is Used To Find The Length Of The Given Character Expression Syntax : Length ( character expression ) Example : select length (‘sairam’) from dual; 6 select length (ename) from emp; Upper : This Function Is Used To Convert All Characters In To Upper Case Syntax : Upper (Character Expression) Example : select upper (‘sairam’) from dual; SAIRAM 6 .Lower : This Function Is Used To Convert All Characters In To Lower Case Syntax : 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 String Syntax : 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 characters Syntax: Substr(String, Start Postion,Number of Characters) Example : select substr(‘disk operating system’,6,9) from dual; --> operating 11. Lpad : This function is used to append the given text to the left 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 : Lpad (<Expression>,<Size>,<String Expression>) Example : select lpad(sal,7,’Rs. ‘) from emp; output Rs. 800 Rs.1200 Example : select lpad(sal,10,’Rs. ‘) from emp; output Rs. Rs. 800 Rs. Rs.1200 12 .Rpad : 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 : Sysdate Example : select sysdate from dual; To add five minutes select to_char(sysdate +05/1440,'hh:mi:ss am') from dual; To subtract ten minutes select 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 dual to 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; Output SYSDATE LAST_DAY( ----------- -------------14-FEB-05 28-FEB-05 Next_Day This 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 months_between This 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_DA 2 4. select round(months_between(to_date(‘20-oct-05’,’dd-mon-yy’),sysdate)) from dual; Count The 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; 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 table select 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 Clause The 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 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 Clause The 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 Clause The 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; Select deptno,min(sal) from emp Where deptno in(20,30,10) Group by deptno; Select deptno,count(*) from emp Group by deptno Having count(*) >2 Select deptno,sum(sal) from emp Group by deptno Having sum(sal) <5000 Select deptno,job,mgr,sum(sal) from emp Group 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 Are mm/dd/yy yy.mm.dd dd/mm/yy dd.mm.yy dd-mm-yy mon yy mon dd, yy hh:mm:ss mon dd yyyy hh:mi:mm (Am or Pm) mm-dd-yy yy mm dd dd 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 : 1 select 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 5373484 Select 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) 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 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; 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 and 2. 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 itself 2. Using Alter Command The following are a list of constraints 1. 2. 3. 4. 5. 6. S NOT NULL CONSTRAINT UNIQUE CONSTRAINT PRIMARY KEY CONSTRAINT CHECK CONSTRAINT DEFAULT 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> 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: 100 Enter value for sna: Mahesh Enter value for sno: 101 Enter value for sna: (nothing is entered) Error Comes mandatory (NOT NULL) column is missing or NULL during insert Unique Constraint This 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 Level create table customer(cno number(3),cname varchar2(20), constraint con_un unique(cno)); insert into customer values(&cno,’&cname’); Enter value for cno: 100 Enter value for cname: Mahesh Enter value for cn: 100 Enter value for c: Nithya Error Comes unique constraint (SCOTT.CON_UN) violated Example : Imposing unique constraint Column Level create table customer1(cno number(3) unique ,cname varchar2(20)); insert into customer1 values(&cno, ‘&cname’); Enter value for cno: 100 Enter value for cname: Mahi Enter value for cn: 100 Enter value for c: Prasad Error Comes unique 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 level Create 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) SNO 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; SNAME PHONE --------- -------------------- ---------1 Mahesh 11111 2 Prasad 22222 3 Nithya 4 Saloni Example : 2 create table sample3(sno number(3) default 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; 100, sname SNO SNAME --------- ---------------200 Nithya 201 Aruna 100 Mahesh 100 Saloni Check Constraint The 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 Constraint It 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 Level Syntax: Table Level create 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’); insert into items1 values(100,’paste’); Error Comes unique constraint (SCOTT.CON_PK) violated Syntax : Column Level create 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 Comes unique constraint (SCOTT.CON_PK) violated Example 2 insert into item values(null ,’Wheat’); Error Comes mandatory (NOT NULL) column is missing or NULL during insert Foreign 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 key 1. The Mother table column related must have primary key 2. 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 different 4. We can establish relation to any number of tables 5. 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>); 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 tables 1. 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 * ACCNO --------100 101 102 103 from bankmast; ACCNA BALANCE ---------- ----------Priya 5000 Mahesh 6500 Saryu 4500 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 --------- --- ------------- -----------100 d 05-MAY-05 5000 102 w 01-JUN-05 2000 Dropping Relationship Tables Note : 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 table or after creating table call constraints. On two way you can create constraints. Table level constraints Column level constraints := After define the column. := At the time of define column. Types of constraints. ************************************* 1. Domain level constraints > Not null Check 2. Integrity constraints 3. References constraints > Unique key Primary key > 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. 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), 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 names The 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 Joins There are five types of joins, they are 1. 2. 3. 4. 5. Equi Join ( = ) Non Equi Join ( < , > , >=, <=, !=) Outer Join ( + ) Self Join 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 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 Aliases It 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 Join Using 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 d where 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 d where e.deptno=d.deptno and d.dname='sales' and e.sal <=1500; Outer Join It 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 joins 1. 2. 3. 4. Left Outer Join Right Outer Join Full Outer Join Partition Outer Join 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 Join It 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 ( + ) Operator 1. The outer join symbol (+) can not be on both the sides 2. We can not outer join the same table to more than one other table in a single Select statement 3. 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; 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.job group 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 Join To 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) av from emp e,emp ee where e.deptno=ee.deptno and 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; 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 QUERY Sub 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 parentheses 2. The Inner query must be on the right hand side of the condition 3. The sub query may not have an order by clause 4. The Order By clause appears at the end of the main select statement 5. Sub queries are always executed from the most deeply nested to the least deeply nested 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’ 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 where mgr=’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) n from 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 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'); 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 emp where 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); 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 ******* 5000 3000 3000 2975 2850 2450 1600 1500 1300 1250 1250 1100 950 800 SAL ******** 5000 3000 2975 2850 2450 1600 1500 1300 1250 1100 950 850 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); 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 Operators The 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 emp union all select * from dept; Intersect Operator This operator returns all the rows in one table that also resides in other table. Ie only the common values in both the table Syntax : Select statement Intersect Select 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=20 intersect select 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 Operator This 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 Minus Select 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<=4 minus select 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. select * from emp where rowid= (select rowid from emp where rownum<=6 minus select 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 Operators ANY 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 Operator This operator retrieves values from the first query, which should be satisfied with all the value returned by the sub query Syntax : list>); Select <select list> <Any Operator> All(select <select 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 emp where deptno=10 and sal>all(select sal from emp where deptno=20); SOME Operator This 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> 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 View There are two types of view 1. 2. 3. 4. Simple View Composite View With Read Only View 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; 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 Views We 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 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 view Note : 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 view Drop View : This command is used to drop any view from the database Drop 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 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; SEQUENCE The 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/nocycle Cache/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) 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 request Noorder : 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 attached 1. Insert Command 2. 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. 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 value update 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 / NoCycle Cache/NoCache <value> Order/noorder Example 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; 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; 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 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 columns 4. 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 cluster 2. We can not even drop the cluster until the source table is present 3. 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 Table select * from sample2; SNO SNAME --------- ---------100 Nithya 101 Saloni 102 Aruna 2. To display details of the Table select * from cluster sampleclust; SNO SNAME --------- ---------100 Nithya 101 Saloni 102 Aruna 3. Even if you delete any row in the table, that will not affected to the cluster 1. 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 exist Note : We can not delete any data from the cluster Drop cluster This command is used to drop any cluster Syntax : drop Cluster <cluster name> To drop any cluster Drop 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. 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>) 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: 1 enter any value for sname : Mahesh enter any value for sno: 2 enter any value for sname : Prasad enter any value for sno: 1 enter any value for sname : Nithya Error : Ora-00001: unique constraint (scott.idx_temp) violated Note : 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 index An 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. 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 index This 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 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 properly 7. Next create a table with the cluster specification and list of columns 8. 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 cluster 5. We can not even drop the cluster until the source table is present 6. 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)); 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 then update 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…… 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 session Create table Create synonym Create view Create sequence Create procedure Create trigger Create type Create user Drop 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 SYSDBA Enter password: Connected. DROP USER SCOTT CASCADE; User dropped. GRANT CONNECT,RESOURCE TO SCOTT IDENTIFIED BY TIGER; Grant succeeded. CONN SCOTT/TIGER Connected. 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; 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 server provides 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 operation on 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) 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 ENTER SPOOL 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_clause Pivot_for_clause Pivot_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: 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 some rules 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 in first 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 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 in second normalform and each nonkey attributes are functionally dependent on primary key only. Employee Empno Dname Depthead Projcode ***************************************************** E101 Sales D1 p10 E102 Finance D2 p11 E103 Research D3 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. 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. 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 types Attribute 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>%type eg. declare v_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>%rowtype eg. declare v_emp emp%rowtype; Control Structures Control structures enable the program to change the logical flow of statements within PL/SQL with a number of control structures. PL/SQL supports two basic programming control structures: conditional and iteration branching. These four structures can be combined in any way to solve a given problem. The following sections cover these structures in more detail. Conditional Control You 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 declare a number(3):=10; b number(3):=9; c number(3); begin 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. declare a number(2):=&a; b number(2):=&b; s number(3); su number(3); m number(3); d number(3); begin s:=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. declare empno 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); begin age:=months_between(sysdate,dob); exp:=months_between(sysdate,doj); asal:=sal*12; dsal:=sal/to_char(last_day(sysdate),'dd'); da:=sal*10/100; 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 syntax for the if-then statement is as follows: if condition then statement(s); end if; The statements that immediately follow the conditional if statement are executed only if the condition evaluates to True. If the condition evaluates to False, the statements are not processed and are passed over. If-Then-Else Statements A more likely scenario is that you will have different distinct sets of statements to execute depending on the conditional statement. The if-then-else statement provides a means to always execute statements in a conditional statement. The syntax of the if-then-else structure is very similar to the if-then syntax. The following example uses the if-then-else structure: if max_bal > 100000 then update mst_audit -- executed only if condition is true set comments = ‘sell no more’; else update mst_audit -- executed only if condition is false set comments = ‘sell more’; end if. 4.write a prog to accept two number find the smaller no. declare a number(3):=&a; b number(3):=&b; begin if a>b then dbms_output.put_line(a||' is the bigger one'); else if a=b then dbms_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 declare a date:='&a'; b date:='&b'; begin if a<b then dbms_output.put_line(a||' is previous date'); else dbms_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 declare a date:='&a'; b date:='&b'; begin if (to_char(a,'d')>to_char(b,'d')) then dbms_output.put_line(a ||' is recent day'); else dbms_output.put_line(b ||' is recent day'); 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. declare name varchar2(10):='&name'; sid number(4):=&sid; marks1 number(4):=&marks1; marks2 number(4):=&marks2; marks3 number(4):=&marks3; avg number(3,2); begin avg:=(marks1+marks2+marks3/3); if (avg>=70) then dbms_output.put_line('DISTICTION'); elsif (avg>=60 and avg<70) then dbms_output.put_line('FIRST division'); elsif (avg>=50 and avg<60) then dbms_output.put_line('2nd division'); elsif (avg>=35 and avg<50) then dbms_output.put_line('3rd division'); else dbms_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. declare pid 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); begin bill:=quan*unit_pr; if bill>1500 then 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 Condition Loop is execution of a sequence of statesments repeatedly. Iterative Control Iterative control statements enable you to execute a sequence of statements multiple times. The simplest form of an iterative statement is the loop. Loop Statements The syntax for the loop statement is loop statement(s) end loop; Types Of Loops 1.simple loop 2.while loop 3.for loop 4.Revarse for loop SIMPLE LOOP To Print Numbers Declare A number:=1; Begin Loop Exit when a>20; Dbms_output.put_line(a); A:=a+1; End loop; End; / REVERSE NO Declare A number:=100; Begin Loop Exit when a < 1; Dbms_output.put_line(a); A:=a - 1; End loop; End; To Print The No Is Prime Or Not Declare A number:=&no; B number; C number:=0; I number:=1; Begin Loop Exit when i > a; B:=mod(a,i); If b=0 then C:=c+1; End if; I:=i+1; End loop; If c=2 then Dbms_output.put_line('prime'); Else Dbms_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 syntax for the while loop is as follows: while condition loop statement(s) end loop 9.write a prog to print a series of numbers from that no to specified no. declare n number(3):=&n; a number(3):=&a; begin while(a<=n) loop dbms_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. declare a number(3):=&a; b number(3):=1; c number(4); begin while (b<=a) loop c:=mod(b,2); if c=0 then dbms_output.put_line(b); end if; b:=b+1; end loop; end; To Print The No is Even Or Odd Declare No number:=&no; Begin If mod(no,2)=0 then Dbms_output.put_line(' the no is even no'); Else Dbms_output.put_line(' the no is odd no'); End if; End; To Print The No Is Prime Or Not Declare A number:=&no; B number; C number:=0; I number:=1; Begin While i <= a loop B:=mod(a,i); If b=0 then C:=c+1; End if; I:=i+1; End loop; If c=2 then Dbms_output.put_line('prime'); Else Dbms_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. declare a date:='&a'; b date; begin b:=a+6; while a<=b loop dbms_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. declare a date:='&a'; b date; begin b:=add_months(a,11); while a<=b loop dbms_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 declare y number(5):=&yyyy; d1 date; d2 date; cnt number(2):=0; begin d1:='01-jan-'||y; d2:='31-dec-'||y; while d1<d2 loop if to_char(d1,'d')=1 then dbms_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 iterates over and over for a specified number of times. The syntax for the for loop is as follows: for counter in lower-bound..upper-bound loop statement(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); begin for i in 1..10 loop b:=a*i; dbms_output.put_line(a||'*'||i||'='||b); end loop; end; / 13.to print factorial of given number declare n number(3):=&n; fact number(5):=1; begin for i in 1..n loop fact:=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 Begin For i in reverse 1..10 loop Dbms_output.put_line(i); End loop; End; Loop inside loop Declare A number:=1; Begin Loop Exit when a>=10; For i in 1..10 loop Dbms_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. declare a varchar2(100):='&char'; v_count number(5); v_upper varchar2(100); v_div number(4); begin v_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 declare a varchar2(100):='&char'; v_count number(5); v_upper varchar2(100); v_div number(4); begin v_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% 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 RUPEES DEPTNO 20 200 RUPEES DEPTNO 30 300 RUPEES DEPTNO 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.deptno||' '||v_tax); end; '||rec.job||' '||rec.sal||' '|| 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; 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 cursor and 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 -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 parameter Strong cursor - Used to retrieve data from one table Week cursor - Used to retrieve data from more than one table Implicity cursor 1. Table record (Select * from emp) Table and column and row base record 2. Table base record. recemp%rowtype; 2. Programme define record typeemp_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; IMPLICIT Declare E_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 Declare Rec emp%rowtype; Begin Select 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=5000 Where empno=7788; End; / STRONG CORSOR Declare Typ emy_type is ref cursor return emp%rowtype; Rec_ref my_type; Emp_rec emp%rowtype; Dept_rec dept%rowtype; Salgrade_rec salgrade%rowtype; Begin Open rec_ref for select * from emp; Loop Fetch 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; End; / WEEK CURSOR declare type my_type is ref cursor; rec_ref my_type; emp_rec emp%rowtype; dept_rec dept%rowtype; salgrade_rec salgrade%rowtype; begin open rec_ref for select * from emp; loop fetch 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; loop fetch 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; loop fetch 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; CORSOR WITH FOR LOOP declare cursor 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; begin for rec1 in c1 loop exit when c1%notfound; dbms_output.put_line(rec1.job); dbms_output.put_line('--------------'); open c3(rec1.job); loop fetch 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 declare cursor c1 is select * from emp where deptno not in (10,20); rec c1%rowtype; begin open c1; fetch c1 into rec; while c1%found loop dbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.sal||' '||rec.deptno); fetch c1 into rec; end loop; end; WITH GROUP BY CLAUSE Declare Cursor c1 is select job,sum(sal) gro from emp group by job; Rec c1%rowtype; Begin Open c1; Loop Fetch c1 into rec; Exit when c1%notfound; Dbms_output.put_line(rec.job||' '||rec.gro); End loop; Close c1; End; WITH JOINS Declare Cursor 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; Begin Open c1; Loop Fetch 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; WITH CASE FUNCTION Declare 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; EXCEPTION An exception is an identifier in plsql that is raised during the execution ofplsql block. You can trap any exception in the exception handling section of the plsql block. Types of exception: 1. Predefined exception 2. Userdefined exception 3. 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 exception User defined exception must be raised explicitly using RAISE statement. Error code is -20000 to -20999 3. nonpredefine exception Pragma exception_init A named exception can be associated with a particular NO_DATA_FOUND: will come. If There is no data which is you want to retrieve then this error declare rec emp%rowtype; begin select * into rec from emp where empno=&no; dbms_output.put_line(rec.empno|| 'is getting'||rec. sal); exception when no_data_found then dbms_output.put_line(' the employee with this number is not there'); end; ************************************** declare rec emp%rowtype; begin select * into rec from emp where empno=&no; dbms_output.put_line(rec.ename|| ' is getting '||rec. sal); exception when no_data_found then dbms_output.put_line(' the employee with this number is not there'); update emp set sal=4500 where empno=7788; end; TOO_MANY_ROWS: If your query is giving more than two rows then this error will come. Declare E_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 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’ Declare E_ename varchar2(4); E_sal number(4); Begin Select ename,sal into e_ename,e_sal from emp Where empno=7788; Dbms_output.put_line(e_en/ Ame||' '||e_sal); Exception When value_error then Dbms_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; 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: Declare Cursor c1 is select * from emp; Rec c1%rowtype; Begin Open c1; For rec in c1 loop Dbms_output.put_line(rec.empno||' '||rec.ename||' '||rec.job||' '||rec.sal); End loop; Exception When cursor_already_open then Dbms_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. Declare Typ emy_type is ref cursor; Rec_type my_type; Emp_rec emp%rowtype; Cursor c1 is select * from dept where deptno in(10,20); Rec c1%rowtype; Begin Loop Fetch c1 into rec; Exit when c1%notfound; Dbms_output.put_line(rec.deptno||' '||rec.dname||' '||rec.loc); End loop; Exception When invalid_cursor then Dbms_output.put_line('error in cursor'); Dbms_output.put_line(chr(10)); Open rec_type for select * from emp; Loop Fetch 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 Declare 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 Raise rjob; End if; Exception When rjob then Dbms_output.put_line('manager record'); End; Dbms_output.put_line(rec.ename||' '||rec.job||' '||rec.sal); End loop; Close c1; 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; / 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('record not found'); End; When deptno not exist Declare dept_not_exists exception; pragma exception_init(dept_not_exists,-2291); begin Insert 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. 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 is Begin Pay:=pay+pay*0.1; Return pay; End; Declare Num myemp.empno%type; Pay myemp.sal%type; Begin Num:=&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 varchar2 is e_ename varchar2(10); begin select ename into e_ename from emp 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 varchar2 is e_ename varchar2(10); begin select ename into e_ename from emp where 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 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 Declare Flag boolean; Num emp.empno%type; Begin Num:=&employee_number; If(chk_dept(num)) then Dbms_output.put_line(num || 'works in dept num 20'); Else Dbms_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; end; / select find_emp('KING') from dual; To Print That Emps and Manager Name: Create or replace procedure empl (m_ename varchar2) Is Cursor c1 is select w.ename wename,w.job wjob, M.ename mename,m.job mjob from emp w,emp m Where w.mgr=m.empno and m.ename=m_ename; Rec c1%rowtype; Begin If find_emp(m_ename) >=3 then Open c1; Loop Fetch c1 into rec; Exit when c1%notfound; Dbms_output.put_line(rec.wename||' '||rec.wjob||' '|| Rec.mename||' '||rec.mjob); End loop; Else Dbms_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 Create or replace procedure sal_incr Is Cursor c1 is select empno,sal from emp; Rec c1%rowtype; N number; Begin For rec in c1 loop N:=emp_year(rec.empno); If n>=29then Update emp set sal=sal*1.1 Where 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 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)is Begin Select 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 DECLARE NUM MYEMP12.EMPNO%TYPE; PAY MYEMP12.SAL%TYPE; BEGIN NUM:=&EMPLOYEE_NUMBER; PRO_INCR12(NUM,PAY); END; SELECT * FROM MYEMP12; BY USING CORSOR CREATE OR REPLACE PROCEDURE EMPQ1 (E_DEPTNO NUMBER) 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) is cursor c1 is select * from emp where deptno=d_deptno; rec c1%rowtype; s_sal number; s_hiredate date; s_count number; begin open c1; loop fetch 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||' '|| 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; begin for i in 1..n loop fact:=fact*i; end loop; dbms_output.put_line(fact); end; EXECUTE FACT_IN(5) ************************************ create or replace procedure mult(n number) is f number; begin for i in 1..10 loop f:=n*i; dbms_output.put_line(n||'*'||i||'='||f); end loop; end; EXECUTE MULT(3) **************************************************** USING IN OUT...... 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.... ***** 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; 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) Is S_tot number; S_per number(8,2); S_result varchar2(10); Flag varchar2(10):='true'; Begin If s_pap1 <=30 or s_pap2<=30 or s_pap3<=30 then Flag:='false'; End if; S_tot:=s_pap1+s_pap2+s_pap3; S_per:=s_tot*100/300; If s_per > 60 and flag='true' then S_result:='first'; Elsif S_per > 50 and s_per <60 and flag='true' then S_result:='second'; Elsif S_per > 35 and s_per <50 and flag='true' then S_result:='third'; Else S_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 rr Is Cursor c1 is select * from emp; Rec c1%rowtype; Y number; Begin Open c1; Loop Fetch c1 into rec; Exit when c1%notfound; Y:=round((sysdate-rec.hiredate)/365); If y between 10 and 15 then Update emp set SAL=rec.sal*1.15 Where empno=rec.empno; Elsif y between 15 and 20 then Update emp set SAL=rec.sal*1.25 Where empno=rec.empno; Else Update emp set SAL=rec.sal*1.35 Where 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; / Write a procedure to retrive data from multiple table in run time. Create or replace procedure dyno (t_name varchar2) Is Type m_t is ref cursor; Rec m_t; Emp_rec emp%rowtype; Dept_rec dept%rowtype; Salg_rec salgrade%rowtype; Begin If t_name ='emp' then Open rec for select * from emp; Loop Fetch 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; Elsif T_name='dept' then Open rec for select * from dept; Loop Fetch 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; Else Open rec for select * from salgrade; Loop Fetch 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; 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 pro2 is procedure 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; create or replace package body pro2 is procedure select1 (e_empno number) is e_ename emp.ename%type; e_job emp.job%type; e_sal emp.sal%type; begin select ename,job,sal into e_ename,e_job,e_sal from emp where empno=e_empno; dbms_output.put_line(e_ename||' '||e_job||' '||e_sal); end select1; procedure del1 (e_empno emp.empno%type) is begin delete from emp where empno=e_empno; end del1; procedure upd1 (e_ename emp.ename%type) is begin update emp set ename='ROBERT' where ename=e_ename; end upd1; function SAL1 (e_empno emp.empno%type) return number is s_sal number; begin select 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; 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 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 THEN RAISE_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; > 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; / 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 trigger create view comp_vu as select D.DEPTNO,d.dname,d.loc, e.empno,e.ename,e.job,e.mgr,e.hiredate, e.sal,e.comm,e.deptno EDEPT from 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) insert into comp_vu values(80,'FINANCE','DELHI',4444,'SMITH','MANAGER',4545,'01JAN-05', * ERROR at line 1: ORA-01779: cannot modify a column which maps to a non keypreserved table Create or replace trigger ins instead of insert on comp_vu begin insert 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 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), 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=200 WHERE A.MADDR.LOC='ORISSA'; 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) 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 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 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')), 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-MONYYYY'))) / SPLIT PARTITIONS ALTER TABLE STUDENT SPLIT PARTITION R5 AT (TO_DATE('05-FEB-08','DDMON-YYYY')) INTO (PARTITION R6,PARTITION R7); MERGE PARTITIONS ALTER TABLE STUDENT MERGE PARTITIONS R6,R7 INTO PARTITION R8 /