This action might not be possible to undo. Are you sure you want to continue?
Oracle and PL/SQL tutorial Objective: I am preparing this tutorial because I found if you know basics of Oracle/SQL/PL-SQL then you can have a chance to enter in IT Company or other Industries as a Database Admin. And there is lots of Scope in IT for database handler. Now a days there are lots of database is available. Most Popular 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 have knowledge about data. In my notes I will discuss some important interview questions. So pl. keeps all the 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 may be 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 APPLE Database: Database is an organized collection of data. Its content can easily retrieve, 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 or software. It designed for specific purpose for creation, update, and retrieval of organized data from database. It store in computer hard disk. In DBMS collection of data is stored in file. It is called database. It is used to control creation of data, maintain and retrieval of data. DBMS Approach: it is a shared collection of logically related data, designed to meet the information needs of an organization. So database approach will renew. 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.
- 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 the difference between DBMS and RDBMS (Oracle). I will give the answer for the same in later. What is Oracle? Oracle is RDBMS (Relational Database Management System). Relational Database, data stores in a form of Row and Column in Table. A table is category of data like employee and column have information about data like Emp_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 in oracle. In oracle database : database is a collection of data file and programs that manipulate 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.
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.
Common 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 to user account. Simply we can say that schema is collection of objects. DBA Tools : There are 7 types of DBA tools available1. 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.
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 because by using of this you can design schema (table) for database and stored your data in tabular form as well as you can get your resultant output in tabular form also. 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 stage of selection in an interview. Most of software Development Company will give you some question and include some terminology questions so pl. revert it before 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).
We are learning Oracle so it is required to know normalization. It is also important topic that should be discussed. Normalization: Normalization is the process of putting things right, making them 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 multivalues 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, the values of which uniquely identify each row of a table. These columns cannot contain null value. In simply we can say if a table contains more than one unique field in a tale it is called candidate key. You can make it by using unique constraint at the time of creating table. Primary Key: The primary key of a table is one of the candidate keys that you give some special characteristics. You can have only one primary key in a table. You cannot make more than one primary key in a table and primary key column cannot contain NULLs. Foreign key: foreign key is a combination of columns with values based on primary key value from another table. A foreign key constraint, also known as a referential integrity constraint, specifies that the value of the foreign key corresponds to actual values of the primary key in other table. You can refer to a primary key or unique key, even in the same table. You can make more than one foreign key in the table. What are DML and DLL?
DML: Data Manipulation Language, it is used to get query in database. By using of this you can insert, update, delete and retrieve your data from database. Commands: select, insert, update and delete. DDL: When you design a schema for any table you are using Data Definition Language. Command: create What 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 (Application Program Interface), Developed according to the specification of SQL access group, than allows one to connect to SQL database. What is JDBC? JDBC: Java Database Connectivity. It is a set of classes and interfaces written in java to allow other java programs to send SQL statement to a relational database management system. The above questions are very common questions, these questions will ask by recruiter at the time of written test and face to face interview. I will be also telling you more questions and answer in my coming notes. Now I am stating Oracle 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 database contains physical and logical structures. The basic structure of oracle database is Table. Like: Relational tables, Objectrelational tables, Index-organized tables, External tables, and Materialized view, Temporary tables as well as indexes also like: B* tree indexes, Bitmap Indexes, Reverse Key indexes, Text indexes… Storing the Data: Logical structure of database must be store in somewhere in database. Oracle maintain a data dictionary that records metadata about each object-the object owner, a definition, related privileges, and so n. For objects that require physical storage space of their own, Oracle will allocate space within 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 more about table space. Don’t bother about it nobody will ask more detail about this but you should know more after an experience, somebody may be ask.
If tablespace is designated as a temporary tablespace, the tablespace itself is permanent; only the segments saved in the table space are temporary. Oracle uses temporary tablespaces to support sorting operations such as index creations and join processing. Temporary segments should not be stored in the same tablespaces as permanent objects. Tablespace can be managed either dictionary or locally. In a dictionarymanaged tablespace, space management is recorded in data dictionary. In a locally managed tablespace (the default), oracle maintains a bitmap in each datafile 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 help maintain prior images of the changed block and rows. Users who have previously queried the row you are changing will still see the rows as they existed when their queries began. Automatic Undo Management allows Oracle to manage the undo segments directly with no database administrator intervention required. Dropped Data: The Recycle bin concept introduced with Oracle10g impacts the space requirements for your tablespaces and datafiles. By using of it, if your table will drop in any reason then it will be recovered. When you delete any table a copy of your table will go to recovery area and it will recover by using of flashback method or purge command. Guarding the data: You can able fully control the access to your data. You fan able to give grant permission of specific row and data, which will be access by other 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 in Tabular form and retrieve data from table by using query. Similarly RDBMS but one major difference is that in RDBMS (Relational Database Management System) 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 will create a problem for you also. Your answer should be short and sweet and point the level. Whatever I discuss in this tutorial all things is important and do practice well.
Chapter 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, Standard Edition and Personal Edition. So chose any one of them. Remember if you want to recover you data after drop your table then chose Enterprise Edition because this feature is available only this edition. Remaining editions are same. Standard edition is useful for small business and Personal Edition useful for development application and allow running your application in Enterprises and Personal Edition. Personal Edition will not use in Production Environment. So chose according to your requirement. Username and password pl. chose SYSTEM. You can also give according to your 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 and client side components. You can also uninstall any oracle products from the initial OUI screens. Just insert CD in CD drive. Just click next, next …………… reach to the finished point. After installation your first step of learning is completed. Now enjoy your tutorial with practice. After that how will it run? Your oracle has been stored in Local Host so you have to start any browser like Mozilla, firefox, Google chrome, Internet Explorer any one of them. Then type local host address in address bar. http://127.0.0.1:8080/apex/f?p=4550:11:3259225634834205::NO::: Then 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 available those are fulfill all 12 rules. Only 7 to 8 rules are fulfill by Oracle database also.
Chapter 3: Planning Oracle Applications-Approaches, Risk, and Standards. Cooperative Approach: Oracle is an Object-relational database management system. By using of it you can use Object oriented features. In this chapter I want to introduce you some simple oracle command. Like Write 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 your query by using mouse or shift + arrow keys and click on Run button. TAB is a synonymous of TABLE. It has three columns TNAME, TABTYPE and CLUSTERID. TNAME: Represent Table Name. TABTYPE: Represent type of Table; like TABLE, VIEW and SYNONMOUS.
Select statement used to retrieve your record from the database or table. Here I am using TAB keyword. Remember TAB is a special keyword it is used to show all users table. TAB is a data dictionary command. So that command is showing all user tables. Chapter 4: Creating and Managing Table In this chapter I want to tell you how to create table, create table with constraints and how to manage table. First is how to create simple table?
Type 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 occupy full memory that will be mentioned at the time of creation. If you will use varchar2 then it will occupy only required memory. According to given data. If you gave 5 characters of length to varchar2 and given data is only 2 characters long 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 part you can use Number(<Size of integer>) like: Number(3) and for floating or real type 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 number of 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 will face truncate problem. Max. Number of size for char are 2000 and varchar2 are 4000 characters. For date type data type no need to specify size because it will automatically take 8 bytes. If you will not specify size in number data type then you can able to give any quantity of number with decimal also.
Describe information statement: Describe statement is used to show describe information of Table. All column name, Size, ………. and so on. It shows all objects 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 use below syntax: Insert into <Table name> (<Column name1>, <Column name2> …) values (<value1>,<value2> …);
3rd: 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 Date should be inset in single quote. Like: ‘LALIT’,’A’,’22-jun-11’ etc. By using of above 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 creating tables. Like Primary key, foreign Key, candidate key and condition check. A constraint 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 of create statement known as table constraints.
The candidate key: I have already defined candidate key definition in above column. You can specify candidate key by using of UNIQUE constraint.
Here you can see I made two unique fields (emp_cd ,Dept_cd). These fields/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 constraint and Unique. Whenever, you declared any field as a unique key. It is automatically 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. But it’s considered as a candidate key. Because you can have only one primary key.
I am dropping table Department.
Foreign key: Foreign key is also a Primary key for another table. But it is using a reference of primary key of other table. That means if any table have primary key 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 in Primary key value.
When you create foreign key and wants to drop this table. You can’t drop this table with drooping of table of primary key. That means if you wants to drop foreign key table, you have to drop primary key table first. Designing Index tablespaces: Unique and primary key constraints create indexes. When you create Unique, Candidate and Primary key, it will store in default table space. By default table space is USER but if you want to store your primary key and unique key in your tablespace. You can get it by using index tablespace clause. When you specified tablespace, name of primary keys and Unique are stored in this table space.
You can check your index by using this ……………..
Now 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 TJS1
See USER is the tablespace for both the table.
Remember: 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.
Here, you can see foreign key does not create any index. So it is not necessary to give table space at the time of creation of table. It is not allow for foreign key. The CHECK constraint: Many columns must have some value that are certain range or that is satisfy certain conditions. With CHECK constraint you can 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 table statement.
In above example you can see the result. Now I am trying to give wrong value. Let’s see what will happen?
When you did give wrong value it showed error. Now you are thinking what is SYSTEM.SYS_C004050? It is a name of constraint that is created by SYSTEM. It’s given by System because at the time of creation of table you did not 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 you will not to do this then system is automatically give the name of constraint. It is also 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 have already inserted data in TJS1 table. See inserted rows. USERS is a tablespace, TJS1_EMP_CD_PK is stored in this tablespace.
Now 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 this constraint. After giving name of the constraint, System will not give any name for this constraint. System will create constraint as the name of, which is given by 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 check constrain name (SYSTEM.EMP_CD_CHECK). Now see, where it SYSTEM.EMP_CD_CHECK?
Question: 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 the same 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 all details about Drop table truncate table and Purge table statement. Drop table statement is very simple to use. If table is no longer used then you can 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 any Table. Remember Table is also an Object. It will go to Dropped Objects Recycle Bin. From Dropped Object Recycle Bin, You can recover your table. When you remove table from dropped object recycle bin, it will go to Purge Recycle Bin. When you will remove objects from Purge Recycle Bin, It will delete permanently from HDD. You can’t recover your table.
If 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 releases their 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 and column data, without removing description of table. Note: Truncating can’t be rollback. If you remove all data by using of truncate command. You can’t recover it. If any trigger has attached with any row. Then it will not perform its action. Altering table: Table definition can be altered in several ways. If you want to change 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.
Now I am trying to add new column Address in this table as a NOT NULL constraint.
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 any column 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 value in it.
Now you remove the error. Let’s try this command again.
So noticed that : NOT NULL constraint will add or modify for empty table and when 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 to convert into NULL. You can use alter table command with NULL clause. It will work whether Table is empty or not. For this I want to drop TJS table first and create a new table. By using of Drop 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 used to store long type of character data. Long data type can able to convert LONG to CLOB.
Now I am converting LONG to CLOB.
Creating Read Only Table: You can create ready only table of existing table by using of read only clause with alter table command.
By using of this you can prevent insert, update and delete command on this table. 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 derived data. The value is based on other column. You can give any function within this 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 data is removed. If it’s a primary key then it will drop. Sometimes you can also mark is as unused. Unused means it will not release memory space. But after mark 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 column will drop any type of column. Now I am using unused clause.
Once you mark any column as unused it will never be access. But memory will not release. You can drop it at later. Question: Can you set unused column for more than one column at the same time. Answer: No, You can’t do it. If you want to set unused column for more than one column; you have to use above command for more times.
See the result. I have already been dropped EMP_CD and marked unused for Name. 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.
4] 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. Archiving your redo log files is an effective way to protect your database from media failure. 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 the nologging 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 to create 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 column values 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. A normal index stored the indexed columns; an index organized table stores all its columns in an index. To create index organized table, use the organization index clause of the create table command. Note: For using index organized table, you have to use Primary key constraint.
Before giving Example of above topic I want to clear a thing, That will create a confusion: 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 have only one Primary key but you can create a primary key with more than one column in a table. ------create table TJS653 (Emp_cd number(2), Dept_cd number(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 all mentioned column-So, you can say that, you have only one index for all columns, which is specified as primary key. You can have only one primary key. When you create organized index, it will automatically creates unique index. For creating organization 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.
Indexing is useful when you use where clause in your query. Note: By using of foreign key, you can create a table without creating of primary key. CREATE TABLE TJS10211 (EMP_CD NUMBER(3),CONSTRAINT FK_EMP_CD11 FOREIGN KEY (EMP_CD)REFERENCES TJS3111(EMP_CD)); ------------It is called single indexing -----------------Creating a Unique index: You can create unique index by using of primary key and unique key constraint. Third way to create unique index, you should create primary key constraint for the table first. Oracle will use existing index as 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 is infrequently updated, because they add to the cost of all data-manipulation transactions against the table they index. This feature is not available in Oracle 10G. Note: Bitmap indexes should not be used for tables involved on online transaction-processing applications due to the internal mechanisms Oracle used to 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, on columns that are likely to appear in where clauses either as a simple quantity, such as Where Emp_cd = 102 and salary = 5000; Or in joins, such as Where EMP.emp_cd = Deptt.Emp_cd; How many indexes to use on a table: You can create many indexes in a single table, with many columns in each index.
Remember: if you creates indexing on multiple columns, without using unique index 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: Sequence You can assign unique numbers, such as Emp_CD, to column in your database by using a sequence; you don’t need to create a special table and code to keep track of the unique numbers in use. This is done by using the create sequence command. Here we will use .NextVal. It will provide unique number to next value. When you create any sequence, which is for all the columns on other table also. So if you 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 of another 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 to remember table and column name by ignoring whether you type in capital letters, small letters or a mixture of two. It store tale names and column names in its internal data dictionary in upper case.
Chapter 5: The basic Parts of speech in SQL SQL *Plus is powerful product of oracle that can take your instructions for Oracle, check them for correctness, Submit them to Oracle, and then modify or reformat the response Oracle gives, based on orders or directions you’ve set in place. 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 simply passed on to you by SQL * Plus. To run SQL *Plus: Select – Run SQL Command Line. Give User Name (system) and Password (system).
SQL*Plus: Release 10.2.0.1.0 - Production on Thu Aug 11 16:02:24 2011 Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> connect Enter user-name: system Enter 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 can also insert value by making of variable. You can create variable with & sign. For Numerical value no need to enclosed variable with single quote. For string or 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; which have your selected column? Where used to tell to the Oracle, what qualifiers you would like to put on the information, it is selecting. Order By used for return information in sorted order. Like: Select Emp_cd, Emp_Name, Salary from TJS45 Where salary <= 5000 order by EMP_CD;
If you need descending order: Select Emp_cd, Emp_Name, Salary from TJS45 Where salary <= 5000 order by EMP_CD DESC; Note: For testing of numerical value; single quote is not required but character or 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, Including Zero characters. Note: Be careful when using the greater than and less than operators against numbers that are stored in character datatype columns. All values in varchar2 and char columns will be treated as characters during comparisons. Therefore, numbers that are stored in those types of columns will be compared as if they were character strings, not number. If column datatype is number, then 12 is greater 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 automatically store NULL value. Null means Empty. For these types of query you can able to use IS NULL and IS NOT NULL clause with command.
Single 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 106 With 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 is TRUE. Table of AND and OR. AND have heavy precedence. AND: A B 0 0 0 1 1 0 1 1 OR: Result 0 0 0 1 A 0 0 1 1 B 0 1 0 1 Result 0 1 1 1
Where, clause is also used for sub queries. Here I am providing some important command 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 the table? I] NOTE: TRY TO UNDERSTAND MY QUERY CAREFULLY.
II] 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) from TJS_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 = (Select MAX(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 < (Select MAX(salary) from TJS_SAL1);
Select EMP_NAME,Salary from TJS_SAL1 where Salary = (Select Max(SALARY) from TJS_SAL1 where salary < (Select MAX(salary) from TJS_SAL1));
Combining Tables: You can able to combine more than one table to get all information. Select TJS_EMP.EMP_CD, TJS_EMP.EMP_NAME, TJS_SAL.SALARY, TJS_SAL.NET_SAL from TJS_EMP, TJS_SAL
where TJS_EMP.EMP_CD = TJS_SAL.EMP_CD; You can write above query in different format; by using of alias name of TABLE. Select TE.EMP_CD, TE.EMP_NAME, TS.SALARY, TS.NET_SAL from TJS_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 called joining 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.SALARY and TJS_SAL.SALARY = TJS_SAL2.SALARY; Creating View: By using of this technique you can create a new table with new name. It provides a way to hiding the logic that created a new table by combining 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 is already 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. But only 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 contains data. 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_SALARY where 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;
2] 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 your requirement. Don’t be hopeless in your life. Don’t think about problem. You have think about solution only and try to reach @ the solution. Chapter 6: FORM & REPORT In 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 look to your data. To create your application, you need to log in as a database user. Oracle Database XE comes with a sample database user called HR. This user owns a number of database tables in a sample schema that can be used to create applications for a fictional Human Resources department. However, for security reasons, this user's account is locked. You need to unlock this account before 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 in the 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.gif Under 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 Account To log in as the sample user account: Log out from the database administrator account by clicking Logout in the upper 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
Creating 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 of the 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.gif Notice that Action describes the type of page you are adding. Next to the Table Name field, click the up arrow, and then select 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.gif Click 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 any page within an application. For Authentication Scheme, Language, and User Language Preference Derived From, 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 and style of an entire application. Confirm your selections. To return to a previous wizard page, click Previous. To accept your selections, click Create.
After you click Create, the following message displays at the top of the page: Application created successfully. 5 Running Your New Application To run your application: Click the Run Application icon.
Description of the illustration gs_run_ico_sm.gif In 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 the application, use the Developer toolbar at the bottom on the page. Description of the illustration gs_d_toolbar.gif The Developer toolbar offers a quick way to edit the current page, create a new page, control, or component, view session state, or toggle debugging or edit links on and off. To exit your application and return to Application Builder, click Edit Page 1 on the Developer toolbar. To return to the Database Home Page, select the Home breadcrumb at the top of the page. Description of the illustration gs_bread_myapp.gif Congratulations! You have just created your first application using Oracle Database XE. Note: Pl. does it yourself. There are lots of tools available in Oracle. So try to do 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 allow manipulating string, letters or other characters. NOTE: If you are using PL/SQL then you can create your own function with the 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 VARCHAR2 are the same. VARCHAR datatype is the synonymous of the VARCHAR2. String: A bunch of things in a line is called string. Datatype that are restricted to 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.
a. b. c. d.
SELECT LALIT||SHAKTAWAT FROM DUAL. SELECT CITY||STATE FROM TJS_EMP; SELECT CONCAT (LALIT,SHAKTAWAT) FROM DUAL; 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;
See the result. Here I have given to add four dots in statement/string at right hand side; But only two dots is added, why? Because of length. I have specified length of character is 20. & my character length is 18. So it will add only two characters. So for adding all set of character, I should increase the length.
This command want to add dots from right side of the string but character length has already more than 20. So after 20; it will not find space to add it. So after E. it will not display the required result. If, we will use same command; with LPAD than result will be same. So don’t be confused. So conclusion is LPAD and RPAD is used to add set of character to the specified string or columns. But, if length of String or column has already length comparison of specified length then it will display string or column 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 left Justify. Note: LPAD and RPAD With the column, it will always left justify. LTRIM, RTRIM, and TRIM: These are used to remove unwanted set of character from specified string or column. LTRIM (string/column, ‘set of character’); RTRIM (string/column, ‘set of character’); TRIM (‘set of character’ from column/string);
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 FROM EMP_DEMO;
SELECT NAME, TRIM(TRAILING 'L' FROM NAME) AS LEFT FROM EMP_DEMO;
NOTE: 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, remaining are 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 clip out a subsection of string, beginning at position start with specified position and end up to specified position. If ending position is not specified then it will continued up to end of string. SUBSTR (string/column, start position [,count] )
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 to that point. By default it will search from 1st position. Occurrence; A set of character may occurs more than once in a string. So if you want to search set of character at its occurrence. So you can use it. Case is measured here. So pl. to be 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 numerical value to their ASCII character string equivalents. Simply you can say that, it converts numerical value to character; according to its ASCII value. ASCII converts character to its ASCII value; but if you are trying to give string then it will convert only first character of string.
Here 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 are using 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 this function. 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’ [‘replace string’])
CLUSTER: Clustering is a method to store tables in the same area on the disk, which are intimately related and often join together. For applying this method you have to create a table with a primary key to the both tables. After
this you have to create a cluster with a column. Store both primary keys to the same 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 primary keys. 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) cluster demo_cul(emp_cd); Create table demo_cul_tab1 (emp_cd varchar2(12) primary key, Name varchar2(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 Numbers In this chapter I want to discuss some important function, which will work for mathematical 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 unknown value. It has null value. So if you will calculate anything with NULL. It always returns null.
NVL: 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 is already exist then existing value will not change. Only null value is substitute with specified value. ABS: Absolute value is always positive. If number is in negative term. It will change into positive. If number is already in positive manner then it will not effect to its sign. SELECT ABS(-12), ABC (23) FROM DUAL; RESULT: 12 23 CEIL: Ceiling function produced smallest integer (whole number) or larger than 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) = -3 MOD: It returns remainder. MOD (value, divisor); you can also use REMAINDER function instead of MOD. Both are produced similar result but it uses ROUND and MOD uses FLOOR function.
Note: If divisor is NEGATIVE or value is ZERO then MOD function always produces ZERO as result with real number. If value id less than divisor then result is specify value and if any value is divided by zero then remainder is ZERO. If any number is divided by 1. It always produced zero.
POWER: This function produces raise a number to a given positive number.
a0 = 1 [formula]; 0.5 = square root [power ½]
SQRT: Square Root of given number. SQRT (64) = 8, SQRT (4) = 2 ROUND and TRUNC: These are singe value function. TRUNC is used to truncate number according to given precision. Round is used to round given number 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. Like ROUND (ABOVE, 1); Round first value after decimal. ROUND (ABOVE) = ROUND (ABOVE, 0) You can also use negative value as a precision. This negative precision function 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 round it 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) FROM DUAL;
SELECT ROUND(355.33,-1), ROUND(355.33,-2), ROUND(355.33,-3) FROM DUAL;
Note: TRUNC function produces same result with –ve precision.
TRUNC: This function used to truncate value after decimal. By default it truncates ZERO precision. TRUNC (value/column, precision)
Let’s see difference again: ROUND (55.5) = 56, ROUND (-55.5) = -56 TRUNC (55.5) = 55, TRUNC (-55.5) = -55 CEIL (55.5) = 56, CEIL (-55.5) = -55 /* GREATER THAN SPECIFIC NUMBER */ FLOOR (55.5) = 55, FLOOR (-55.5) = -56 /* LESS THAN SPECIFIC NUMBER */ SIGN: Sign tells you sign of value not magnitude. But ABS function produces magnitude. SIGN (120) = 1, SIGN (-120) = -1 SIGN (0) = 0, SIGN (-0) =0 /* ZERO and –ZERO is equal, without any number */ Trigonometry Function: SIN, SINH, COS, COSH, TAN, TANH, ACOS, ATAN, ATAN2, and ASIN. Result will shows in radians (Degree multiplied by pi and divided by 180). SIN, COS, and TAN functions are standard trigonometric functions. SINH, COSH, and TANH functions are hyperbolic function. ASIN, ACOS, and ATAN2 functions return the arc sine; arc cosine, arc tangent, and ATAN2 return the arc tangent of two values. Aggregate function: It is also called group-value function. For AVG and COUNT function is treated differently to NULL value. COUNT function will not 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. You can place single value function inside group value function. It works. Like: AVG (ABS ( )); But If you want to place group value function inside single value function, then you should use GROUP BY clause. STDDEV and VARIANCE: It is used for standard deviation and variance.
DISTINCT in group function: Distinct versus all. It is used to show distinct value versus all. When it fount two or more than two value are same. It count at once time.
From this example; I thanked function work is cleared.
List Function: List function (GREATEST and LEAST) is used to compare the value of each row of several columns.
Notice here with null value. It does not calculate anything. If, you want to calculate with NULL. You can use COALESCE.
Chapter 9: Dates, Then, Now and difference This 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.
TO_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 ask above 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 found then 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)
Chapter 10: Grouping things together In this chapter we will try to learn group by and having clause. Before starting I want 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 clause will use with group value function only. It works when value returns in group. Like SUM, AVG,COUNT
Order 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 or more tables. To do this we have to make a relation between certain columns in these tables. Note: If you want to insert date in a table by using of SQL *PLUS. To do this you have to take ‘&DOSALE’ this type of variable.
Now 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 can also use alias name of table and column but space is not allow here. Remember, if you are getting any calculation (AVG, SUM, and COUNT) with joining of tables then you have to use group by clause. If you are using group by clause; all column, which are common in joining of table should be present in 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 not matched 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.
LEFT OUTER JOIN:
RIGHT OUTER JOIN:
FULL OUTER JOIN:
NATURAL JOINING: Join should be performed based on all columns that have same name in two tables.
SET OPERATORS: Sometimes you need to combine information of a similar type 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 EMP UNION Select EMP_NO, Name from Deptt; Chapter 11: Changing data: Insert, Update, Merge, and Delete I have already mentioned about insert command. Here I want to tell you more about insert command. You can use insert command with interactive manner. Insert with Select:
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.