Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Oracle tutorial


Published on

Oracle for fresher.

Published in: Education
  • Be the first to comment

  • Be the first to like this

Oracle tutorial

  1. 1. 1Oracle and PL/SQL tutorialObjective: I am preparing this tutorial because I found if you know basics ofOracle/SQL/PL-SQL then you can have a chance to enter in IT Company orother Industries as a Database Admin. And there is lots of Scope in IT fordatabase handler. Now a days there are lots of database is available. MostPopular database is Oracle/SQL/Postgresql/Mysql/SQL Servre …..etc.Here I am trying to give some important information about SQL and PL/SQL.When we will start the discussion about database first you should haveknowledge about data.In my notes I will discuss some important interview questions. So pl. keeps allthe answer in your mind. It will definitely help you at the time of interview.Question: What is Data?Answer: Data is a collection of facts or which is typed from keyboard. It maybe numbers like 0 to 9, alphabets: A to Z or a to z.Question: What is Information?Answer: Collection of meaning full data is called information. Like APPLEDatabase: Database is an organized collection of data. Its content can easilyretrieve, update, add and delete. In database information can manage easily.Before giving introduction of Oracle we should know:DBMS – Database Management System. It is set of computer program orsoftware. It designed for specific purpose for creation, update, and retrieval oforganized data from database. It store in computer hard disk. In DBMScollection of data is stored in file. It is called database. It is used to controlcreation of data, maintain and retrieval of data.DBMS Approach: it is a shared collection of logically related data, designed tomeet the information needs of an organization. So database approach willrenew.What is the advantage of DBMS? - Control of data redundancy. - Data consistency. - More information from the same amount of data. - Sharing of data. - Improve data integrity. - Improve security. - Economy of scale. - Balance conflicting requirement. Lalit Shaktawat
  2. 2. 2 - Improve data accessibility and responsiveness. - Improve maintenance through data independence. - Increased concurrency. - Improve backup and recovery service.There are some disadvantages of DBMS………… - Complexity, Size, Cost of DBMSs, Additional H/W costs. - Cost of conversion, Performance, Higher impact of failure.I will not discuss more about DBMS. Because some time Company will ask thedifference between DBMS and RDBMS (Oracle). I will give the answer for thesame in later.What is Oracle?Oracle is RDBMS (Relational Database Management System). RelationalDatabase, data stores in a form of Row and Column in Table. A table iscategory of data like employee and column have information about data likeEmp_no, Emp_name………….etc.What is the system architecture of oracle?In this section we learn the basic term of oracle, which are commonly used inoracle.In oracle database : database is a collection of data file and programs thatmanipulate those data files.Two type of data we can able to store in database: I. User data : it is related to particular application. II. System data : It is required to manage database itself.Component of Database: 1. Database File : It consist of physical storage of data. That means data will store in hard disk. In oracle database we can make one o more database file. These file contain data, which is accessible by SQL (Structured Query language). A file can be associated with one and only one logical file (Tablespace). When we create any database it consists of one and only one physical storage or physical file and one logical file. Logical file have information about data and index. Note: By default we can able to open 32 files at a time. 2. Control File : Physical architecture of databases are controlled by control file. It is a binary file that is used to store physical information of database. Control file includes:  The database name.  Name and location of associate datafiles.  Timestamp of creation of database file.  Current log sequence number.  Checkpoint information. The control file automatically created by oracle at the time of creation of database. User can’t edit control file. Without it oracle can not functioning. Lalit Shaktawat
  3. 3. 3 It is use full for backup and recovery. 3. Redo Log file : It contain all transaction that have occurred against database. When we will do any changes in database. It is used to store all changes made in database. No activity takes place without recording in redo log file. Redo log necessary to protect data loss. Redo log is also called transaction logs. Every database required minimum of two redo file. It is used in recovery operations to restore lost and damage file. 4. Tablespace : When we create any database it create two files, One is physical file and another one is logical file. Logical file is called Tablespace. It is a logical storage unit within oracle database. It is logical because tablespace is not visible in file system. It is build a bridge between (logical and physical database) oracle database and file system, where indexes and data will store. Typically tablespace present in oracle database are:  SYSTEM : It is used to store information that will manage itself.  TEMP : Store all temporary table.  TOOLS : Store database objects that are need to supports different tool.  USER : Information about user to store.  DATA & INDEXES : Hold the information about users.  ROLLBACK : Where all undo information is stored. 5. Data block : Datablock is a small logical unit to store oracle data.One datablock represent specific number of byte on physical storage of HDD. 6. Segments : All data in Tablespace are stored in allocation of database space. It is called segment. For each table there is a table segment. For indexes, So called index segments are allocated. The segment associated with database object belongs to exactly on tablespace. - In oracle there are five type of segments :  Data Segments  Index Segment  Rollback Segment  Temporary Segment  Bootstrap Segment 7. Extents : Is a collection of contiguous datablock. One or more segments makeup a Segments. It express in byte. Lalit Shaktawat
  4. 4. 4Common Term in Oracle : 1. SGA: SGA stands for System Global Area. It is a group of shared memory areas that are dedicated to an oracle instance (The combination of all processes and SGA is called database instance). Simply we can say that this is an area where all data will retrieve, store and control. Each oracle instance will use SGA for storing information. Each oracle instance allocates its SGA and de-allocate at the time of shut down. It is use full when several user need to access same instance. It shares the instance to multiple users. So it is called Shared Global Area. 2. PGA : Program or Process Global Area is memory area (RAM) that stores data and control information for a single process.It contain user context area and store Variable….etc as well as process information.The memory in PGA is not sharable. 3. Checkpoint : Occurs when DBWR ( Database writer : write all modified datablocks to datafile) process writes all modified buffers in the SGA buffers cache to the database datafile.The above common terms, will ask by recruiters.Schema : Schema is set of objects like tables,indexes,view….etc that belongs touser account. Simply we can say that schema is collection of objects.DBA Tools :There are 7 types of DBA tools available- 1. Instance manager : It task is manage instance and session. 2. Schema manager : Manage Schema Objects. 3. Security manager : Manage Security. 4. Storage manager : Manage Storage. 5. SQL Worksheet : Enters and Execute DBA Commands, SQL Statements and PL/SQL Commands. Lalit Shaktawat
  5. 5. 5 6. Backup manager : Manage database recovery and backup environment. 7. Data manager : Exports, Imports and load data in/out of an oracle database.What is SQL?SQL : Structured query language. We said it structured query language becauseby using of this you can design schema (table) for database and stored yourdata in tabular form as well as you can get your resultant output in tabular formalso. Database manages in proper structured form.How many level of Database Structure?There are three level of database Structure: 1. External Level : The user view of database. 2. Conceptual Level : The community view of database. 3. Internal Level : The physical representation of database.Function of DBMS : 1. Data storage, retrieval and update 2. A user-accessible catalog. 3. Transaction support. 4. Concurrency control services. 5. Recovery services. 6. Authorization services. 7. Support for data communication. 8. Integrity services. 9. Services to promote data independence. 10. Utility services.If you are going to attend written test of any company, which is a primary stageof selection in an interview. Most of software Development Company will giveyou some question and include some terminology questions so pl. revert itbefore going to attend. - Relation: A relation is a table with column and rows. - Attribute: An attribute is a named column of a relation. Or you can say that name of columns is called attributes. - Domain: A domain is the set of allowable values for one or more attributes. - Tuple: A tuple is a row of a relation. Or you can say that name of row is called tuple. - Degree: The degree of a relation (table) is the number of attributes (columns) it contains. - Cardinality: The cardinality of a relation is number of tuples (rows) it contains. - Relational database: A collection of normalized relation (table). Lalit Shaktawat
  6. 6. 6We are learning Oracle so it is required to know normalization. It is alsoimportant topic that should be discussed.Normalization: Normalization is the process of putting things right, makingthem normal.There are 5 NF is considered but we can achieve our goal with 3 NF.Un-normal form (UNF): Is a table that contains one or more repeating groups.  1 NF: This is done by moving data in separate tables, where the data in each table a primary key- a unique label or identifier. This is eliminating repeating groups of data. It has only one and one value  2 NF: Second normal form, entail taking out data that’s only dependent on a part of the primary key. If there are attributes that do not depend on the entire key, that attributes should be moved to a new table.  3 NF: In this table that is 1 NF, 2 NF in which no non-primary-key attribute is transitive dependent on the primary key. Or you can make a new table that is does not depend on primary key but it is part of table.  BCNF: (Byte Code Normal Form) is a relation in which every determinant is a candidate key.  4 NF: In this table that is in BCNF and contains no trivial multi- values dependency.  5 NF: Is a table that contains no join dependency.Let’s discuss primary key, candidate key and foreign key:Candidate key: A candidate key is a combination of one or more columns, thevalues of which uniquely identify each row of a table. These columns cannotcontain null value. In simply we can say if a table contains more than oneunique field in a tale it is called candidate key. You can make it by usingunique constraint at the time of creating table.Primary Key: The primary key of a table is one of the candidate keys that yougive some special characteristics. You can have only one primary key in atable. You cannot make more than one primary key in a table and primary keycolumn cannot contain NULLs.Foreign key: foreign key is a combination of columns with values based onprimary key value from another table. A foreign key constraint, also known asa referential integrity constraint, specifies that the value of the foreign keycorresponds to actual values of the primary key in other table. You can refer toa primary key or unique key, even in the same table. You can make more thanone foreign key in the table.What are DML and DLL? Lalit Shaktawat
  7. 7. 7 DML: Data Manipulation Language, it is used to get query in database. Byusing of this you can insert, update, delete and retrieve your data fromdatabase.Commands: select, insert, update and delete.DDL: When you design a schema for any table you are using Data DefinitionLanguage.Command: createWhat is ODBC?ODBC: Open Database Connectivity. It provides a way for client program(VB, Excel, and Access) to access database. It is a standard API (ApplicationProgram Interface), Developed according to the specification of SQL accessgroup, than allows one to connect to SQL database.What is JDBC?JDBC: Java Database Connectivity. It is a set of classes and interfaces writtenin java to allow other java programs to send SQL statement to a relationaldatabase management system.The above questions are very common questions, these questions will ask byrecruiter at the time of written test and face to face interview. I will be alsotelling you more questions and answer in my coming notes. Now I am statingOracle and pl/sql tutorial chapter by chapter………Chapter 1: Critical Database Concepts.Oracle database is a collection of data in one or more files. The databasecontains physical and logical structures.The basic structure of oracle database is Table. Like: Relational tables, Object-relational tables, Index-organized tables, External tables, and Materializedview, Temporary tables as well as indexes also like: B* tree indexes, BitmapIndexes, Reverse Key indexes, Text indexes…Storing the Data: Logical structure of database must be store in somewhere indatabase. Oracle maintain a data dictionary that records metadata about eachobject-the object owner, a definition, related privileges, and so n. For objectsthat require physical storage space of their own, Oracle will allocate spacewithin a tablespace.Note: You can create a special kind of tablespace, called a bigfile table space,that can be many thousands of terabytes in size.I have previously mentioned about tablespace. Here I am going to tell you moreabout table space. Don’t bother about it nobody will ask more detail about thisbut you should know more after an experience, somebody may be ask. Lalit Shaktawat
  8. 8. 8If tablespace is designated as a temporary tablespace, the tablespace itself ispermanent; only the segments saved in the table space are temporary. Oracleuses temporary tablespaces to support sorting operations such as indexcreations and join processing. Temporary segments should not be stored in thesame tablespaces as permanent objects.Tablespace can be managed either dictionary or locally. In a dictionary-managed tablespace, space management is recorded in data dictionary. In alocally managed tablespace (the default), oracle maintains a bitmap in eachdatafile of the tablespace to track space availability.AUM (Automatic Undo Management): It is used to support your transactions;Oracle can dynamically create and manage undo segments, which helpmaintain prior images of the changed block and rows. Users who havepreviously queried the row you are changing will still see the rows as theyexisted when their queries began. Automatic Undo Management allows Oracleto manage the undo segments directly with no database administratorintervention required.Dropped Data: The Recycle bin concept introduced with Oracle10g impacts thespace requirements for your tablespaces and datafiles. By using of it, if yourtable will drop in any reason then it will be recovered. When you delete anytable a copy of your table will go to recovery area and it will recover by usingof flashback method or purge command.Guarding the data: You can able fully control the access to your data. You fanable to give grant permission of specific row and data, which will be access byother group and user. Even in oracle you can create users also.I will give you example of these in later chapters.In this chapter I want to tell you the difference between DBMS and RDBMS?DBMS is a Database management System. You can manage your data inTabular form and retrieve data from table by using query. Similarly RDBMSbut one major difference is that in RDBMS (Relational Database ManagementSystem) you can relate two tables by using primary and foreign key concepts.This is simple answer and enough for good marks.Note: At the time of interview no need to give lengthy reply to recruiter it willcreate a problem for you also. Your answer should be short and sweet and pointthe level.Whatever I discuss in this tutorial all things is important and do practice well. Lalit Shaktawat
  9. 9. 9Chapter 2: Installing Oracle database 10g and run.Installation of Oracle 10g is very simple.Here you will find three Edition of oracle like: Enterprise Edition, StandardEdition and Personal Edition.So chose any one of them. Remember if you want to recover you data afterdrop your table then chose Enterprise Edition because this feature is availableonly this edition.Remaining editions are same. Standard edition is useful for small business andPersonal Edition useful for development application and allow running yourapplication in Enterprises and Personal Edition. Personal Edition will not use inProduction Environment.So chose according to your requirement.Username and password pl. chose SYSTEM. You can also give according toyour choice.My suggestions to install oracle 10g express edition. It is good for practice.We are using OUI to install oracle software: OUI is Oracle Universal Installer.It is used to install and manage all oracle components for both the server andclient side components. You can also uninstall any oracle products from theinitial OUI screens.Just insert CD in CD drive. Just click next, next …………… reach to thefinished point.After installation your first step of learning is completed. Now enjoy yourtutorial with practice.After that how will it run? Your oracle has been stored in Local Host so youhave to start any browser like Mozilla, firefox, Google chrome, InternetExplorer any one of them.Then type local host address in address bar. type your give username and password. Then click on Login push button.Then chose SQL --- SQL Command Screen.Now you can start your practice.Note: There are 12 code rules for RDBMS. But there is no database is availablethose are fulfill all 12 rules. Only 7 to 8 rules are fulfill by Oracle databasealso. Lalit Shaktawat
  10. 10. 10Chapter 3: Planning Oracle Applications-Approaches, Risk, andStandards.Cooperative Approach: Oracle is an Object-relational database managementsystem. By using of it you can use Object oriented features.In this chapter I want to introduce you some simple oracle command. LikeWrite a command to view all tables, which is present in oracle database? Here I am giving a view of this command.For execution of any command you should type your query. Then select yourquery by using mouse or shift + arrow keys and click on Run button.TAB is a synonymous of TABLE. It has three columns TNAME, TABTYPEand CLUSTERID. TNAME: Represent Table Name. TABTYPE: Representtype of Table; like TABLE, VIEW and SYNONMOUS.Select statement used to retrieve your record from the database or table. Here Iam using TAB keyword. Remember TAB is a special keyword it is used toshow all users table. TAB is a data dictionary command. So that command isshowing all user tables.Chapter 4: Creating and Managing TableIn this chapter I want to tell you how to create table, create table withconstraints and how to manage table.First is how to create simple table? Lalit Shaktawat
  11. 11. 11Type this command in editor and click on run button.Question: What is the difference between char and varchar2 variable?Answer: When you use char type of data type to any variable. It will occupyfull memory that will be mentioned at the time of creation. If you will usevarchar2 then it will occupy only required memory. According to given data. Ifyou gave 5 characters of length to varchar2 and given data is only 2 characterslong then it will occupy only 2 byte.Question: What is the termination of SQL Command?Answer: Termination of SQL command is ; column.Mostly used data types are: Date, Char, Varchar2 and Number. For integer partyou can use Number(<Size of integer>) like: Number(3) and for floating or realtype data type you can use Number(<Size of integer>,<Size of decimal part>)like: Number(6,2).Here Number(6,2) means, Space is allocated to 4 number of digit and 2 numberof digit for decimal points.Note: Do not enclosed table and column names within double quotes.Otherwise, case will matter. This can be disastrous for your users or developer.Size of variable must be decided at time of table creation. Otherwise you willface truncate problem. Max. Number of size for char are 2000 and varchar2 are4000 characters. For date type data type no need to specify size because it willautomatically take 8 bytes.If you will not specify size in number data type then you can able to give anyquantity of number with decimal also. Lalit Shaktawat
  12. 12. 12Describe information statement: Describe statement is used to show describeinformation of Table. All column name, Size, ………. and so on. It shows allobjects of table.Insert statement: Insert statement is used to insert record in created table.There are many methods to insert record in a table.1st:Syntax:Insert into <Table name> values (<value1>,<value2> …);2nd: If you want to insert particular value to particular field then you can usebelow syntax:Insert into <Table name> (<Column name1>, <Column name2> …)values (<value1>,<value2> …); Lalit Shaktawat
  13. 13. 133rd: It is a latest method to insert record in a table. It is called multitable inserts;I will discuss it in later chapter.Note: At the time of insertion you have to remember string, character and Dateshould be inset in single quote. Like: ‘LALIT’,’A’,’22-jun-11’ etc. By using ofabove method, I inserted many records.Dropping Table Statement: It is used to drop/delete existing table.Now emp table is deleted from system.Constraints in create table: You can enforce several constrains in creatingtables. Like Primary key, foreign Key, candidate key and condition check. Aconstraint clause can constrain a single column and group of column in a table.It gets integrity of your database. You can able to use two types of constraints.As a part of column definition is called column constraint and at the end ofcreate statement known as table constraints. Lalit Shaktawat
  14. 14. 14The candidate key: I have already defined candidate key definition in abovecolumn.You can specify candidate key by using of UNIQUE constraint.Here you can see I made two unique fields (emp_cd ,Dept_cd). Thesefields/columns are uniquely defined and not null. These are candidate key.NOT NULL means Empty.Primary Key: you can declare Primary key by using of primary key constraintand Unique. Whenever, you declared any field as a unique key. It isautomatically declared as a Primary key.Question: How many fields can you able to declare as a Primary key?Answer: You can declare as per you need field as a primary key in a Table. Butit’s considered as a candidate key. Because you can have only one primary key. I am dropping table Department.II method: Lalit Shaktawat
  15. 15. 15Foreign key: Foreign key is also a Primary key for another table. But it is usinga reference of primary key of other table. That means if any table have primarykey then other table can use it as a foreign key by using of its references.Remember in foreign key only can use the value, which is already present inPrimary key value.When you create foreign key and wants to drop this table. You can’t drop thistable with drooping of table of primary key.That means if you wants to drop foreign key table, you have to drop primarykey table first.Designing Index tablespaces:Unique and primary key constraints create indexes. When you createUnique, Candidate and Primary key, it will store in default table space. Bydefault table space is USER but if you want to store your primary key andunique key in your tablespace. You can get it by using index tablespaceclause. When you specified tablespace, name of primary keys and Uniqueare stored in this table space.You can check your index by using this …………….. Lalit Shaktawat
  16. 16. 16Now I am creating new table and using tablespace of USERS.Now see the Tablespace.First I will see the STD_PK.Now see the Tablespace for TJS1See USER is the tablespace for both the table. Lalit Shaktawat
  17. 17. 17Remember: You can’t store foreign key in specified tablespace location.Then the question is: Where the foreign key index is to be stored?Let’s find out------Now for this I am creation a table TJS3 by using of primary key of TJS2.Let’s find………………..Here, you can see foreign key does not create any index. So it is not necessaryto give table space at the time of creation of table. It is not allow for foreignkey.The CHECK constraint: Many columns must have some value that arecertain range or that is satisfy certain conditions. With CHECK constraint youcan specify an expression that must always true for every row in a table.I have already doped all tables: TJS, TJS1, TJS3, and TJS2. Using of drop tablestatement.In above example you can see the result.Now I am trying to give wrong value. Let’s see what will happen? Lalit Shaktawat
  18. 18. 18When you did give wrong value it showed error. Now you are thinking what isSYSTEM.SYS_C004050? It is a name of constraint that is created bySYSTEM. It’s given by System because at the time of creation of table you didnot specified name of constraint.Here System is a USER.You can make number of users for privacy and security.Now see the constraints, which are created by SYSTEM……Oracle will show error by using of these constraints name.Naming Constraints: You can able to give name of your constraint. If youwill not to do this then system is automatically give the name of constraint. It isalso unique.Now see another example of this……………….I am creating a new table TJS1.Here TJS1_EMP_CD_PK is a name of constraint of PRIMARY KEY. I havealready inserted data in TJS1 table. See inserted rows. USERS is a tablespace,TJS1_EMP_CD_PK is stored in this tablespace. Lalit Shaktawat
  19. 19. 19Now I am trying to give duplicate value.You can see the error.Now I am creating a new check constraint and I am giving a name of thisconstraint. After giving name of the constraint, System will not give any namefor this constraint. System will create constraint as the name of, which is givenby me.Let’s see the example.I created table TJS12, with EMP_CD_CHK constraint.Let’s insert some right and wrong value.Whenever, you are inserted wrong value. Its showing error within given checkconstrain name (SYSTEM.EMP_CD_CHECK).Now see, where it SYSTEM.EMP_CD_CHECK? Lalit Shaktawat
  20. 20. 20Question: Can I give one name of constraint for two no. of fields?Answer: YES, if you want to give one name for two no. of primary key in thesame table that is possible.Create table TJSCOLLEGE (EMP_CD number(2), DEPT_NO number(2),Constraint EMP_DEPT_CD_PK Primary key (EMP_CD, DEPT_CD))I think all issue related to constraint are cleared.Dropping Table:I have already explained this statement. Now I am going to telling you alldetails about Drop table truncate table and Purge table statement.Drop table statement is very simple to use. If table is no longer used then youcan able to drop it.I want to show a view of recycle bin, which is present in Oracle 10g.Here you saw Drop object and Purge Recycle Bin. When, you will drop anyTable. Remember Table is also an Object. It will go to Dropped ObjectsRecycle Bin. From Dropped Object Recycle Bin, You can recover your table.When you remove table from dropped object recycle bin, it will go to PurgeRecycle Bin. When you will remove objects from Purge Recycle Bin, It willdelete permanently from HDD. You can’t recover your table. Lalit Shaktawat
  21. 21. 21If you decide that you are never going to restore objects from the Recycle Bin,you can purge them. Purging the Recycle Bin removes all objects and releasestheir storage space.It is also possible from command. I am using Table – TJS. You can use yours.To drop he table and remove from recycle bin at the same time. - Drop table TJS purge;If table has already been dropped, you can purge it from recycle bin. - Purge table TJS;You can purge all content of recycle bin. - Purge recycle bin;Truncate command: It is used to remove all content of table including row andcolumn data, without removing description of table.Note: Truncating can’t be rollback. If you remove all data by using of truncatecommand. You can’t recover it. If any trigger has attached with any row. Thenit will not perform its action.Altering table: Table definition can be altered in several ways. If you want tochange table definition like modify existing column, addition of column,changing column definition and dropping a column etc. 1. Addition of new column: Here, you will learn lots of important task. Practically I am creating a table TJS.Now I am trying to insert some records in this table. Lalit Shaktawat
  22. 22. 22Now I am trying to add new column Address in this table as a NOT NULLconstraint.See the above error. Command is right, then why is that happened?If table already have any record then you can’t add any column as NOT NULL.This will be done without using of NOT NULL constraint. Or you can add anycolumn with NOT NULL constraint, if and only if table is empty.1st Method:Then you can modify existing column as NOT NULL.It will not modify because it has NULL value. For this you have to give a valuein it.Now you remove the error. Let’s try this command again. Lalit Shaktawat
  23. 23. 23So noticed that : NOT NULL constraint will add or modify for empty table andwhen table have some values in a rows.Remember: It will work if all rows have some value.2nd Method: You can add NOT NULL constraint with default clause.3rd Method: If column has already in NOT NULL condition and you want toconvert into NULL. You can use alter table command with NULL clause. Itwill work whether Table is empty or not.For this I want to drop TJS table first and create a new table. By using ofDrop Table TJS;Create table TJS (EMP_CD number(2),CITY varchar2(4) NOT NULL);alter table TJS modify (CITY NULL);The rules for adding or modifying a column: 1. You can increase/decrease column characters width or digits in a number at any time. 2. You can change data type of any column. But column should be empty.Here I want to discuss two data type, LONG and CLOB. Long data type usedto store long type of character data. Long data type can able to convert LONGto CLOB.Now I am converting LONG to CLOB.Creating Read Only Table: You can create ready only table of existing tableby using of read only clause with alter table command. Lalit Shaktawat
  24. 24. 24By using of this you can prevent insert, update and delete command on thistable.First creates any table. Then insert some record in it.Then try to below command:Alter table <TABLE NAME> read only;For read and write:Alter table <TABLE NAME> read write;It works in Oracle 11g……………Creating virtual column: You can create virtual column for storing deriveddata. The value is based on other column. You can give any function withinthis column. It will generated by demand.Note: - You can’t insert any value in this column. - You don’t have to create any procedure, trigger or other mechanism to populate that column. These values are not physically stored in the table; it is generated as needed. - You can create index on virtual column. I will discuss it later. - You can partition table based on this column. I will discuss it later.To create of virtual column: You can use generated always clause.Dropping a column: Dropping of column is complicated because column datais removed. If it’s a primary key then it will drop. Sometimes you can alsomark is as unused. Unused means it will not release memory space. But aftermark any column as Unused that column will never be displayed / accessed.Here EMP_CD is a primary key and it is dropped. So from dropping of columnwill drop any type of column.Now I am using unused clause. Lalit Shaktawat
  25. 25. 25Once you mark any column as unused it will never be access. But memory willnot release. You can drop it at later.Question: Can you set unused column for more than one column at the sametime.Answer: No, You can’t do it. If you want to set unused column for more thanone column; you have to use above command for more times.See the result. I have already been dropped EMP_CD and marked unused forName.Now I am going to dropped unused columns.NOTE: If you dropped multiple columns, don’t use column keyword.alter table TJS1234 drop (EMP_CD,SAL); -You can’t drop all columns in a table. You have to keep one column in a Table.Creating a Table from a Table:You can create any table by using of any tables. - You can create any table by using of any query with select statement. - It will not work if any of columns has LONG datatype. - The constraint Primary key will not create automatically for new Table. - NOT NULL constraint will create automatically for new table. - Here: 1] Statement I created a table TJS68 with one primary key.2] Statement I created a Table TJS69 with NOT NULL constraint.3] Statement I created a Table TJS69 with Foreign Key constraint. Lalit Shaktawat
  26. 26. 264] Now I created table based on these above two table’s columns with query.5] In last Statement I created a Table using of table’s column of TJS69.Special Condition:If you want to create a table without getting any record of tables.You can use a formula 1=2, with where condition clause.Note: Every Oracle database includes two or more redo log files. Archivingyour redo log files is an effective way to protect your database from mediafailure. You cannot alter your archive logging mode using this interface.So you can create a table based on a query without generating redo log file.Avoiding the generation of these entries is accomplished by using thenologging keyword in the create table command.By using of nologging keyword, you have to take backup of created file.Because you can’t recover database, if any failure. It reduced overhead tocreate redo log file.It will improve the performance of the operations that load the data in the table. 1. Creation an index- organized table:An index-organized table its data stored according to the primary key columnvalues for the table. Indexes serve two main purposes.  To enforce uniqueness: When a Primary key or Unique constraint is created. Oracle creates an index to enforce the uniqueness of the indexed column.  To improve performance: When a query can use an index, the performance is dramatically improved.An index-organized table allows you to store its entire data in an index. Anormal index stored the indexed columns; an index organized table stores all itscolumns in an index.To create index organized table, use the organization index clause of thecreate table command.Note: For using index organized table, you have to use Primary key constraint. Lalit Shaktawat
  27. 27. 27Before giving Example of above topic I want to clear a thing, That will create aconfusion:CREATE TABLE TJS1211 MP_CD NUMBER(3),DEPT NUMBER(3), CONSTRAINT ECD_DPT_PK12 PRIMARY KEY(MP_CD,DEPT));---- I have already been mentioned that; you can haveonly one Primary key but you can create a primary keywith more than one column in a table. -------create table TJS653 (Emp_cd number(2), Dept_cdnumber(2), Dep_name varchar2(4),Emp_name varchar2(4),constraint EDDE_PK primary key (Emp_cd,Dept_cd,Dep_name,emp_name));----Here in Bold Letter, word is an index for allmentioned column--So, you can say that, you have only one index for all columns, which isspecified as primary key. You can have only one primary key. When you createorganized index, it will automatically creates unique index. For creatingorganization index, you should have primary key columns.CREATE UNIQUE INDEX EDDE_PK ON TJS653(EMP_CD,DEPT_CD, DEP_NAME, EMP_NAME);Note: Table name considered as an object name. 2. Creating an index: you can create index via the create index command. I have already been mentioned that; when you designate any Primary key or Unique column during table creation or maintenance. Oracle automatically creates a unique index to support that constraint. Create [bitmap/unique] index index on table (clumn1……column..n) [revrse]; Bitmap indexes allow you to create useful indexes on columns with very few distinct values. Reveres: The reverse keyword tells Oracle to reverse the byte of indexed value, which may improve the I/O distribution during the insert of many sequential data values. Lalit Shaktawat
  28. 28. 28 Indexing is useful when you use where clause in your query.Note: By using of foreign key, you can create a table without creating ofprimary key.CREATE TABLE TJS10211 (EMP_CD NUMBER(3),CONSTRAINTFK_EMP_CD11 FOREIGN KEY (EMP_CD)REFERENCESTJS3111(EMP_CD));------------It is called single indexing ------------------Creating a Unique index: You can create unique index by using of primarykey and unique key constraint. Third way to create unique index, you shouldcreate primary key constraint for the table first. Oracle will use existing indexas primary key index.Creating a Bitmap Index:To help tune queries that use nonselective column in their limiting conditions,you can use bitmap indexes. Bitmap indexes should only be used if the data isinfrequently updated, because they add to the cost of all data-manipulationtransactions against the table they index. This feature is not available in Oracle10G.Note: Bitmap indexes should not be used for tables involved on onlinetransaction-processing applications due to the internal mechanisms Oracle usedto maintain them. Restrict their usage to table involved in batch transaction.Every index required storage location.Create bitmap index TJS102_BMI on TJS102(EMP_CD);When to create an index: Indexes are most useful on larger tables, oncolumns that are likely to appear in where clauses either as a simple quantity,such asWhere Emp_cd = 102 and salary = 5000;Or in joins, such asWhere EMP.emp_cd = Deptt.Emp_cd;How many indexes to use on a table: You can create many indexes in a singletable, with many columns in each index. Lalit Shaktawat
  29. 29. 29Remember: if you creates indexing on multiple columns, without using uniqueindex clause that is called un-unique index. It allows inserting duplicate values.Then a question occurs: What is the use of this (Un-Unique) indexing?Indexing is useful when you get query with where clause.You can also specify tablespace to store index on this database.Now I am discussing very important topic: SequenceYou can assign unique numbers, such as Emp_CD, to column in your databaseby using a sequence; you don’t need to create a special table and code to keeptrack of the unique numbers in use. This is done by using the create sequencecommand.Here we will use .NextVal. It will provide unique number to next value. Whenyou create any sequence, which is for all the columns on other table also. So ifyou want to use it in different table; you have to use .currVal instead of.NextVal; Currvalue will take current value and insert in to next column ofanother table. But you have to use .NextVal command first before using.CurrVal.Dropping of index: drop INDEX TJS1_IN;Dropping of Sequence: drop sequence EMP_CD;Capitalization in Name and Data: Oracle makes it slightly easier toremember table and column name by ignoring whether you type in capitalletters, small letters or a mixture of two. It store tale names and column namesin its internal data dictionary in upper case. Lalit Shaktawat
  30. 30. 30Chapter 5: The basic Parts of speech in SQLSQL *Plus is powerful product of oracle that can take your instructions forOracle, check them for correctness, Submit them to Oracle, and then modify orreformat the response Oracle gives, based on orders or directions you’ve set inplace.Then the question is that; What SQL *Plus is doing and what Oracle is doing?Answer: Especially because the error message that Oracle produces are simplypassed on to you by SQL * Plus. To run SQL *Plus: Select – Run SQLCommand Line.Give User Name (system) and Password (system).SQL*Plus: Release - Production on Thu Aug 11 16:02:24 2011Copyright (c) 1982, 2005, Oracle. All rights reserved.SQL> connectEnter user-name: systemEnter password:Connected.SQL> _Now you are connected with database. You can apply all the command.Here, I want to discuss one more method to insert record in a table. You canalso insert value by making of variable. You can create variable with & sign.For Numerical value no need to enclosed variable with single quote. For stringor character you have to enclose with single quote.This command will run in SQL *Plus only.Like insert into TJS45 values (& EMP_CD, ‘&NAME’);For repeating this command; you can use / back slash sing.Select, From, Where, and Order by: These are called clause.Select used to; which column you want? From used to, Name of Table; whichhave your selected column? Where used to tell to the Oracle, what qualifiersyou would like to put on the information, it is selecting. Order By used forreturn information in sorted order.Like:Select Emp_cd, Emp_Name, Salary from TJS45 Where salary <= 5000 orderby EMP_CD; Lalit Shaktawat
  31. 31. 31If you need descending order:Select Emp_cd, Emp_Name, Salary from TJS45 Where salary <= 5000 orderby EMP_CD DESC;Note: For testing of numerical value; single quote is not required but characteror string value it required.Logical Tests against a single value:All these operator works with letters or number, and with columns or literals.Salary = 5000 Salary is equal to 5000.Salary > 5000 Salary is greater than 5000.Salary < 5000 Salary is less than 5000.Salary >= 5000 Salary is greater than or equal to 5000.Salary <= 5000 Salary is less than or equal to 5000.Salary != 5000 Salary is Not equal to 5000.Salary ^= 5000 Salary is Not equal to 5000. (^ caret sign)Salary <> 5000 Salary is Not equal to 5000.Like perform pattern matching. It is called pattern matching operator.Underscore sign ( _ ) used for exactly single character ( Position Marker ) and% (Wildcard Character ) sing used for any number of characters, IncludingZero characters.Note: Be careful when using the greater than and less than operators againstnumbers that are stored in character datatype columns. All values in varchar2and char columns will be treated as characters during comparisons. Therefore,numbers that are stored in those types of columns will be compared as if theywere character strings, not number. If column datatype is number, then 12 isgreater than 9 but in character 9 is greater than 12, because 9 is greater than ‘1’.When, you did not give value to any of column in table. Oracle automaticallystore NULL value. Null means Empty. For these types of query you can able touse IS NULL and IS NOT NULL clause with command. Lalit Shaktawat
  32. 32. 32Single Tests against a List of Values:We have already been seen, How to test single value with logical operator.What about group of values? Or list of values?Logical tests with numbers:EMP_CD IN (101,102,103) EMP_CD is in the list(101,102,103)EMP_CD NOT IN (101,102,103) EMP_CD is not in the list(101,102,103)EMP_CD BETWEEN 101 AND 106 EMP_CD is equal to 101, 106, or anything in between.EMP_CD NOT BETWEEN 101 AND 106 EMP_CD is below 101, or above 106With letters (or Characters):Section IN (‘A’,’B’,’C’) Section is in list (‘A’,’B’,’C’)Section NOT IN (‘A’,’B’,’C’) Section is not in list (‘A’,’B’,’C’)Section BETWEEN A AND D Section equal to A, D or anything in between.Section NOT BETWEEN C AND D Section is below C or above D.AND, OR: This is used for combining logic. This is logical connector.AND: Both conditions should be TRUE. OR: Get TRUE if any of condition isTRUE.Table of AND and OR. AND have heavy precedence.AND: OR:A B Result A B Result0 0 0 0 0 00 1 0 0 1 11 0 0 1 0 11 1 1 1 1 1Where, clause is also used for sub queries. Here I am providing some importantcommand which, will be asked by recruiter. So pl. to be kept in your mind.Very important question is; how do you find out second max. salary from thetable?I] NOTE: TRY TO UNDERSTAND MY QUERY CAREFULLY. Lalit Shaktawat
  33. 33. 33II] Find out Maximum Salary from TJS_SAL1.Select Max(Salary) from TJS_SAL1;III] Find out all records, which is less than Max(SALARY).Select * from TJS_SAL1 where salary NOT IN (Select MAX(SALARY) fromTJS_SAL1); OR Select EMP_NAME, SALARY from TJS_SAL1 where Salary < (Select MAX(salary) from TJS_SAL1) ;IV] Find out record of Max. Salary.Select EMP_NAME, SALARY from TJS_SAL1 where salary = (SelectMAX(salary) from TJS_SAL1) ; Select * from TJS_SAL1 where Salary in (Select MAX(SALARY) from TJS_SAL1); V] Find out second last maximum salary.Select Max(SALARY) as SALARY from TJS_SAL1 where salary < (SelectMAX(salary) from TJS_SAL1);Select EMP_NAME,Salary from TJS_SAL1 where Salary = (SelectMax(SALARY) from TJS_SAL1 where salary < (Select MAX(salary) fromTJS_SAL1));Combining Tables: You can able to combine more than one table to get allinformation.Select TJS_EMP.EMP_CD, TJS_EMP.EMP_NAME, TJS_SAL.SALARY,TJS_SAL.NET_SAL from TJS_EMP, TJS_SAL Lalit Shaktawat
  34. 34. 34 where TJS_EMP.EMP_CD = TJS_SAL.EMP_CD;You can write above query in different format; by using of alias name ofTABLE.Select TE.EMP_CD, TE.EMP_NAME, TS.SALARY, TS.NET_SAL fromTJS_EMP TE, TJS_SAL TS where TE.EMP_CD = TS.EMP_CD;Here TE and TS are alias name of used table. This technique is also calledjoining of two tables.You can also use more than two tables.SELECT TJS_SAL.EMP_NAME,TJS_SAL.salary, TJS_SAL1.EMP_NAME,TJS_SAL2.EMP_NAME from TJS_SAL,TJS_SAL1,TJS_SAL2 where TJS_SAL.salary = TJS_SAL1.SALARYand TJS_SAL.SALARY = TJS_SAL2.SALARY;Creating View: By using of this technique you can create a new table withnew name. It provides a way to hiding the logic that created a new table bycombining of two tables. It will just display the information.Syntax: Create or replace view <Name of View> as select (columns….) Where<condition>We will use create and replace; because Oracle gives this facility; If view isalready exist to the same name. Then it will create view for the same name,without dropping existing view.You can also use the select * from <Table name> where < condition> ;It hides all the logic of creation of view. You can also get query with view. Butonly column that are present in this view.Question: what is the difference between table and view?Ans.: View contains only information. It does not contain data. Table containsdata.Only materialized view contains data. It is truly table. Let’s try some command and see the result.Create or replace view TJS_VIEW as select TJS_EMP.EMP_CD,TJS_EMP.EMP_NAME, TJS_EMP_SALARY.EMP_SALARY,TJS_EMP.STATE From TJS_EMP, TJS_EMP_SALARYwhere TJS_EMP.EMP_CD = TJS_EMP_SALARY.EMP_CD;select * from TJS_VIEW; You can see the resultant output.1] How to delete record from view?delete from TJS_View where EMP_Cd = 107;DELETE FROM EMP_DEMO WHERE NAME IS NULL; Lalit Shaktawat
  35. 35. 352] How to modify existing record in the view?Create or replace view TJS_V_EMP as select * from TJS_EMP;Select * from TJS_V_EMP;update TJS_V_EMP set EMP_NAME = NEW where EMP_CD = 107;Now the chapter is END. Pl. tries more command according to yourrequirement. Don’t be hopeless in your life. Don’t think about problem. Youhave think about solution only and try to reach @ the solution.Chapter 6: FORM & REPORTIn one of my interview recruiter asked: How to create form and report?It’s very simple in oracle 10G. For this you can use application builder.First LOG IN with HR; how? You can create report and form to give great lookto your data.To create your application, you need to log in as a database user. OracleDatabase XE comes with a sample database user called HR. This user owns anumber of database tables in a sample schema that can be used to createapplications for a fictional Human Resources department. However, forsecurity reasons, this users account is locked. You need to unlock this accountbefore you can build a sample application.To unlock the sample user account:Make sure you are still logged on as the database administrator, as described inthe previous section.Click the Administration icon, and then click Database Users.Click the HR schema icon to display the user information for HR.Description of the illustration gs_hr_icon.gifUnder Manage Database User, enter the following settings:Password and Confirm Password: Enter hr for the password.Account Status: Select Unlocked.Roles: Ensure that both CONNECT and RESOURCE are enabled.Click Alter User.Now you are ready to create your first application.3 Logging in as the Sample User AccountTo log in as the sample user account:Log out from the database administrator account by clicking Logout in theupper right corner of the Database Home Page.In the window, click Login.In the Login window, enter hr for both the user name and password.Click Login.The Database Home Page appears.4 Creating a Simple Application Lalit Shaktawat
  36. 36. 36Creating an application is an easy way to view and edit your database data.You create this application based on the EMPLOYEES table, which is part ofthe HR schema.To create an application based on the EMPLOYEES table:On the Database Home Page, click the Application Builder icon.Click the Create button.Under Create Application, select Create Application and click Next.Under Create Application:Name: Enter MyApp.Accept the remaining defaults.Click Next.Next, add pages to your application.Under Add Page:For Select Page Type, select Report and Form.Description of the illustration gs_report_and_form.gifNotice that Action describes the type of page you are adding.Next to the Table Name field, click the up arrow, and thenselect EMPLOYEES from the Search Dialog window.Click Add Page.Two new pages display at the top of the page, under Create Application.Description of the illustration gs_two_new_pages.gifClick Next.On the Tabs panel, accept the default (One Level of Tabs) and click Next.On the Shared Components panel, accept the default (No) and click Next.This option enables you to import shared components from another application.Shared components are common elements that can display or be applied on anypage within an application.For Authentication Scheme, Language, and User Language Preference DerivedFrom, accept the defaults and click Next.For the theme, select Theme 2 click Next.Themes are collections of templates that you can use to define the layout andstyle of an entire application.Confirm your selections. To return to a previous wizard page, click Previous.To accept your selections, click Create. Lalit Shaktawat
  37. 37. 37After you click Create, the following message displays at the top of the page:Application created successfully.5 Running Your New ApplicationTo run your application:Click the Run Application icon.Description of the illustration gs_run_ico_sm.gifIn the log in page, enter hr for both the User Name and Password.Your application appears, showing the EMPLOYEES table.Explore your application.You can query the EMPLOYEES table, if you want. To manage theapplication, use the Developer toolbar at the bottom on the page.Description of the illustration gs_d_toolbar.gifThe Developer toolbar offers a quick way to edit the current page, create a newpage, control, or component, view session state, or toggle debugging or editlinks on and off.To exit your application and return to Application Builder, click Edit Page 1 onthe Developer toolbar.To return to the Database Home Page, select the Home breadcrumb at the topof the page.Description of the illustration gs_bread_myapp.gifCongratulations! You have just created your first application using OracleDatabase XE.Note: Pl. does it yourself. There are lots of tools available in Oracle. So try todo practice. Create a form and Report yourself.Chapter 7: Getting Text Information and Changing it.This chapter introduces String Functions, which are software tools that allowmanipulating string, letters or other characters.NOTE: If you are using PL/SQL then you can create your own function withthe create function statement.Datatype: in Oracle include NUMBER, CHAR (short of CHARCTER) ,VARCHAR2, DATE, TIMESTAMP, LONG, RAW, LONGRAW, BLOG,CLOG, and BFILE.Highlighted datatype you have already known. VARCHAR and VARCHAR2are the same. VARCHAR datatype is the synonymous of the VARCHAR2.String: A bunch of things in a line is called string. Datatype that are restrictedto pure numbers (plus a decimal and minus sign) are called NUMBER. 1. Concatenation: concatenation of tow string. The | symbols called pipe sign or vertical bar. Lalit Shaktawat
  38. 38. 38 a. SELECT LALIT||SHAKTAWAT FROM DUAL. b. SELECT CITY||STATE FROM TJS_EMP; c. SELECT CONCAT (LALIT,SHAKTAWAT) FROM DUAL; d. SELECT CONCAT (CITY,STATE) FROM DUAL; CONCAT and || is works as a same manner. DUAL: Dual is a tiny table Oracle provides with one row and one column in it. DESC DUAL; Select * from DUAL; It is using to get experiment with function with sufficient values. Select statement does not care about column. You can give date value also in it. 2. LPAD, RPAD, LTRIM, RTRIM, TRIM, LENGTH, SUBSTR, and INSTR are functions are used to cut and paste of String. a. LPAD: Left pad. Make a string a certain length by adding a certain set of characters to the left. It provides a facility to add set of character to the string for the fixed length in left hand side. b. RPAD: Right pad. It provides a facility to make a string by adding a set of character for fixed length in right hand side. c. LTRIM: Left trim. Trim means remove. It removes specified set of character to the given string from left hand side. d. RTRIM: Right trim. It removes set of character to the string from right hand side. e. TRIM: It works for the both sides. From the beginning of character and end of character. It removes specified set of character from both sides. You can simply say that it is a combination of RTRIM and LTRIM. f. LENGTH: Tells the length of characters. g. SUBSTR: Substring. It is used to clip out a piece of string. It is used to get string; String start with give number and end with specified number of character. h. INSTR: Find out the location of character in a string. Note: String should be written in single quote and column name does not enclosed with quote. Name of the function write in uppercase. [ ] is used for optional part. RPAD and LPAD: If you will not specified any set of character. It will automatically take place space by default. Syntax: RPAD (strings/column, length [,’set’] ) LPAD (strings/column, length [,’set’]) SELECT RPAD(THIS IS MY NEW CAR,20,.....) FROM DUAL; Lalit Shaktawat
  39. 39. 39 See the result. Here I have given to add four dots in statement/string atright hand side; But only two dots is added, why? Because of length. I havespecified length of character is 20. & my character length is 18. So it will addonly two characters. So for adding all set of character, I should increase thelength.This command want to add dots from right side of the string but characterlength has already more than 20. So after 20; it will not find space to add it. Soafter E. it will not display the required result.If, we will use same command; with LPAD than result will be same. So don’tbe confused. So conclusion is LPAD and RPAD is used to add set of characterto the specified string or columns. But, if length of String or column hasalready length comparison of specified length then it will display string orcolumn according to specified length. This example is showing that; How to use both function LPAD and RPAD. It is also justify right and Length of left. When, you will use character depend LPAD. String will be in on this value right justified and for RPAD, string will be in leftJustify. Note: LPAD and RPAD With the column, it will always left justify.LTRIM, RTRIM, and TRIM: These are used to remove unwanted set ofcharacter from specified string or column.LTRIM (string/column, ‘set of character’);RTRIM (string/column, ‘set of character’);TRIM (‘set of character’ from column/string); Lalit Shaktawat
  40. 40. 40 You can also use leading and trailing wit TRIM command. It works LTRIM and RTRIM respectively.SELECT NAME, TRIM(LEADING L FROM NAME) AS LEFT FROMEMP_DEMO;SELECT NAME, TRIM(TRAILING L FROM NAME) AS LEFT FROMEMP_DEMO; Lalit Shaktawat
  41. 41. 41NOTE: You can use more than one function with other function.LOWER, UPPER, and INITCAP:INITCAP: It takes all the word and convert first letter in upper case, remainingare in same condition (upper/lower).LENGTH: How many characters are in the column or string, including space,special character or anything else?SUBSTR: SUBSTR function is used (cut) to clip out piece of a string. It clipout a subsection of string, beginning at position start with specified positionand end up to specified position. If ending position is not specified then it willcontinued up to end of string.SUBSTR (string/column, start position [,count] ) Lalit Shaktawat
  42. 42. 42 You can also use negative value in SUBSTR function. It works from end of the string. It clip out string from end of the string. Note: Don’t use this with CHAR type datatype; because char have fixed length column. After string it has spaces. So value will not clip out from end of string. It determines starting position relative to end of column.INSTR: It is used for searching set of character in string/column.INSTR (String/column, set of character, [start [, occurrence]])Here: Start used for starting position of location; it will skip all character up tothat point. By default it will search from 1st position. Occurrence; A set ofcharacter may occurs more than once in a string. So if you want to search set ofcharacter at its occurrence. So you can use it. Case is measured here. So pl. tobe used right case.SELECT NAME, INSTR(NAME,A) as POSITION FROM EMP_DEMO;SELECT NAME, INSTR(NAME,A,3) as POSITION FROM EMP_DEMO; it will start searching from 3rd position.It searches a set of character in second occurrence.ASCII and CHR: It used during ad hoc queries. CHR converts numericalvalue to their ASCII character string equivalents. Simply you can say that, itconverts numerical value to character; according to its ASCII value. ASCIIconverts character to its ASCII value; but if you are trying to give string then itwill convert only first character of string. Lalit Shaktawat
  43. 43. 43Here you have seen, we found that; ASCII no. of A is 65 and a is 97.A to Z = 65 to 90; a to z = 97 to 122.To solve the problem of not getting ASCII value of all the character, If you areusing string. You can use DUMP function; to get ASCII value of all character of string. ASCII value of Space is 32.SOUNDEX: It is also a good function to search a string according to its sound.If you don’t know exact spell of searching string; then you can use thisfunction. This function works with where clause.COUNT: Count Function is used to count no. of rows in a table.REPLACE: It is used to replace searched string with specified string.REPLACE (string/column, ’search string’ [‘replacestring’])CLUSTER: Clustering is a method to store tables in the same area on thedisk, which are intimately related and often join together. For applying thismethod you have to create a table with a primary key to the both tables. After Lalit Shaktawat
  44. 44. 44this you have to create a cluster with a column. Store both primary keys to thesame on cluster. All the data to the both tables are stored into same area.Remember for this cluster column type and size should be same of primarykeys.To insert a row in any table you have to do indexing into cluster.create cluster demo_cul (col1 varchar2(12));Create table demo_cul_tab (emp_cd varchar2(12) primary key) clusterdemo_cul(emp_cd);Create table demo_cul_tab1 (emp_cd varchar2(12) primary key, Namevarchar2(10)) cluster demo_cul (emp_cd);Create index emp_cd_in on cluster demo_cul;insert into demo_cul_tab1 values (111,pp);Chapter 8: Playing the NumbersIn this chapter I want to discuss some important function, which will work formathematical calculation. It’s a part of business.NULL: null does not contain any value. It’s empty. It does not contain ZERO.To understand all the function I am going to create a table MATH./* this is used for comments */I created this table because it has sufficient value to understand math function.Addition(+), Subtraction(-), Multiplication (*), Division (/):Now let’s calculate this with empty column.See the result. You don’t get any result because; NULL does have unknownvalue. It has null value. So if you will calculate anything with NULL. It alwaysreturns null. Lalit Shaktawat
  45. 45. 45NVL: This function used for NULL value substitution. NVL (value/column,substitution)Note: If value is not null, this function is equal to value. That means if value isalready exist then existing value will not change. Only null value is substitutewith specified value.ABS: Absolute value is always positive. If number is in negative term. It willchange into positive. If number is already in positive manner then it will noteffect to its sign.SELECT ABS(-12), ABC (23) FROM DUAL;RESULT: 12 23CEIL: Ceiling function produced smallest integer (whole number) or largerthan specific value or equal to value.CEIL(2) = 2 , CEIL(1.0) = 1, CEIL(1.1) = 2 /*1.1 to 1.9 it will produce 2 */CEIL(-2) = -2, CEIL(-2.0) = -2, CEIL(-2.1) = -2 /* -2.1 to -2.9 it will produce -2 */FLOOR: Floor function produced largest integer or less than a specific value.FLOOR(2) = 2, FLOOR(1.3) = 1, FLOOR(-2) = -2, FLOOR(-2.3) = -3MOD: It returns remainder. MOD (value, divisor); you can also useREMAINDER function instead of MOD. Both are produced similar result butit uses ROUND and MOD uses FLOOR function.Note: If divisor is NEGATIVE or value is ZERO then MOD function alwaysproduces ZERO as result with real number. If value id less than divisor thenresult is specify value and if any value is divided by zero then remainder isZERO. If any number is divided by 1. It always produced zero.POWER: This function produces raise a number to a given positive number. Lalit Shaktawat
  46. 46. 46 a0 = 1 [formula]; 0.5 = square root [power ½] SQRT: Square Root ofgiven number.SQRT (64) = 8, SQRT (4) = 2ROUND and TRUNC: These are singe value function. TRUNC is used totruncate number according to given precision. Round is used to round givennumber according to given precision. By default is zero precision.If, you will not specified any precision then it will give integer.Syntax: ROUND (value, precision)Precision: If you will give precision then it will round after decimal. LikeROUND (ABOVE, 1); Round first value after decimal. ROUND (ABOVE) = ROUND (ABOVE, 0)You can also use negative value as a precision. This negative precisionfunction will round nearest and largest ZERO. See this Example:Main thing is .5, if value is equal to or greater than .5 then at the time of roundit will increase the value and for less than .5, the value will not increase.SELECT ROUND(333.33,-1), ROUND(333.33,-2), ROUND(333.33,-3) FROMDUAL;SELECT ROUND(355.33,-1), ROUND(355.33,-2), ROUND(355.33,-3) FROMDUAL;Note: TRUNC function produces same result with –ve precision. Lalit Shaktawat
  47. 47. 47TRUNC: This function used to truncate value after decimal. By default ittruncates ZERO precision.TRUNC (value/column, precision)Let’s see difference again:ROUND (55.5) = 56, ROUND (-55.5) = -56TRUNC (55.5) = 55, TRUNC (-55.5) = -55CEIL (55.5) = 56, CEIL (-55.5) = -55 /* GREATER THAN SPECIFICNUMBER */FLOOR (55.5) = 55, FLOOR (-55.5) = -56 /* LESS THAN SPECIFICNUMBER */SIGN: Sign tells you sign of value not magnitude. But ABS function producesmagnitude.SIGN (120) = 1, SIGN (-120) = -1SIGN (0) = 0, SIGN (-0) =0 /* ZERO and –ZERO is equal, without anynumber */Trigonometry Function: SIN, SINH, COS, COSH, TAN, TANH, ACOS,ATAN, ATAN2, and ASIN. Result will shows in radians (Degree multipliedby pi and divided by 180).SIN, COS, and TAN functions are standard trigonometric functions. SINH,COSH, and TANH functions are hyperbolic function. ASIN, ACOS, andATAN2 functions return the arc sine; arc cosine, arc tangent, and ATAN2return the arc tangent of two values.Aggregate function: It is also called group-value function. For AVG andCOUNT function is treated differently to NULL value. COUNT function willnot consider NULL value.AVG: It returns average of value. (SUM of argument) /Number of argument.COUNT: It returns no of valued row. It will not consider NULL values.MAX: It returns maximum value in column.MIN: It returns minimum value in column.Note: You can also combine more than two functions in single statement. Youcan place single value function inside group value function. It works.Like: AVG (ABS ( )); But If you want to place group value function insidesingle value function, then you should use GROUP BY clause.STDDEV and VARIANCE: It is used for standard deviation and variance. Lalit Shaktawat
  48. 48. 48DISTINCT in group function: Distinct versus all. It is used to show distinctvalue versus all. When it fount two or more than two value are same. It count atonce time. From this example; I thanked function work is cleared.List Function: List function (GREATEST and LEAST) is used to compare thevalue of each row of several columns.Notice here with null value. It does not calculate anything. If, you want tocalculate with NULL. You can use COALESCE.Chapter 9: Dates, Then, Now and differenceThis not an important chapter, but I want to give some Important Function,which help you not in interview but in business application.SYSDATE: it returns system date.SYSTIMESTAMP: It returns system date and time.CURRENT_DATE: It returns current system date. Lalit Shaktawat
  49. 49. 49TO_DATE: This function covert literal into internal date format. It is a correct result.MOTHS_BETWEEN: It returns number of months between two columns/dates. Remember: Column should be in date data type.This is sufficient for understanding dates in ORACLE. May somebody will askabove query; that how to find out age of EMPLOYEE. So keep it in your mind.TRANSLATE: It is used for character by character substitution. If it foundthen it will substitute according to give series.DECODE: It is used to value by value substitution.Syntax: DECODE (value/column, if, then, if, then… else) Lalit Shaktawat
  50. 50. 50 Chapter 10: Grouping things togetherIn this chapter we will try to learn group by and having clause. Before starting Iwant to tell you what is the difference between where and having clause?Ans.: Where can able to use can able to use with individual row. Having clausewill use with group value function only.It works when value returns in group. Like SUM, AVG,COUNTOrder of Execution of statement: 1. It choose rows based on where clause. 2. Group those rows together based on the group by clause. 3. Calculate the results of the group function for each group. 4. Having clause used for taking condition.Logic of having clause: In the having clause, the choice of the group function.It determines which, row in a table have duplicate value in specific column.JOINING: SQL JOIN, it is used whenever we have to select data from 2 ormore tables. To do this we have to make a relation between certain columns inthese tables.Note: If you want to insert date in a table by using of SQL *PLUS. To do thisyou have to take ‘&DOSALE’ this type of variable. Lalit Shaktawat
  51. 51. 51Now I want to tell you, there are two type of JOINING. First is inner joining,other one is outer joining. Inner joining is also called natural joining. You canalso use alias name of table and column but space is not allow here.Remember, if you are getting any calculation (AVG, SUM, and COUNT) withjoining of tables then you have to use group by clause. If you are using groupby clause; all column, which are common in joining of table should be presentin group by clause.These are the information those are matched in both the tables.You can use JOIN ……………….. ON clause instead of above query.Another Joining is outer joining, which give information whose are notmatched according to given condition. There are three type of outer joining:Left Outer Joining, Right Outer Joining, and Full Outer Joining. 1. Left outer joining: It produces information from right side table. It also shows the information those are not matched in both table and shows unmatched information form right hand side table. 2. Right outer joining: It produces information from left side table. It also shows the information those are not matched in both table and shows the unmatched information form left hand side table. 3. Full outer joining: It return all rows from both tables. Rows that are not satisfy on condition; return NULL.For left outer joining put + sign in left hand side or use LEFT JOIN … ON ,LEFT JOIN …….. ON.For left outer joining put + sign in left hand side or use LEFT JOIN … ON ,LEFT JOIN …….. ON. Lalit Shaktawat
  52. 52. 52LEFT OUTER JOIN:RIGHT OUTER JOIN:FULL OUTER JOIN:IS NULL:NATURAL JOINING: Join should be performed based on all columns thathave same name in two tables. Lalit Shaktawat
  53. 53. 53SET OPERATORS: Sometimes you need to combine information of a similartype from more than one table.1] UNION: It shows the information which is common in both the tables.Duplicate rows/data will not repeat.2] UNION ALL: It shows information/data which is common in both the field.Duplicate is repeats.3] INTERSECT: It shows the records, which is not common in both tables.4] MINUS: It shows the records, which is not in second table.i.e.:Select EMP_NO, Name from EMPUNIONSelect EMP_NO, Name from Deptt;Chapter 11: Changing data: Insert, Update, Merge, and DeleteI have already mentioned about insert command. Here I want to tell you moreabout insert command. You can use insert command with interactive manner.Insert with Select: Lalit Shaktawat