Oracle Material

Table of Contents

1 INTRODUCTION
1.1 Purpose

3
3

2 ORACLE

3

2.1 What is Oracle? 3 2.2 SQL is divided into the following 3 2.2.1 CREATE (DDL)...................................................................................................................... 4 2.2.2 INSERT (DML)....................................................................................................................... 5 2.2.3 Commit (TCL)......................................................................................................................... 7 2.2.4 SELECT (DRL)....................................................................................................................... 7 2.2.5 UPDATE (DML).................................................................................................................... 20 2.2.6 DELETE (DML).................................................................................................................... 21 2.2.7 TRUNCATE (DDL)............................................................................................................... 21 2.2.8 DROP (DDL)........................................................................................................................ 22 2.2.9 USING DDL.......................................................................................................................... 22 2.2.10 USING TCL........................................................................................................................ 24 2.2.11 USING DCL........................................................................................................................ 25 2.3 Synonym 26 2.4 Dblink 27 2.5 How to take Backup table data? 27 2.6 Aliases 29 2.7 Functions 29 2.7.1 SINGLE ROW FUNCTIONS...........................................................................................30 2.7.2 GROUP BY AND HAVING.................................................................................................. 54 2.8 Set Operators 56 2.8.1 UNION.................................................................................................................................. 56 2.8.2 UNION ALL.......................................................................................................................... 57 2.8.3 INTERSECT......................................................................................................................... 57 2.8.4 MINUS.................................................................................................................................. 57 2.9 Constraints 57 2.9.1 NOT NULL............................................................................................................................ 58 2.9.2 CHECK................................................................................................................................. 58 2.9.3 UNIQUE............................................................................................................................... 59 2.9.4 PRIMARY KEY..................................................................................................................... 60 2.9.5 FOREIGN KEY..................................................................................................................... 61 2.9.6 COMPOSITE KEYS............................................................................................................. 63

Page 1 of 90

2.10 Joins 64 2.10.1 EQUI JOIN......................................................................................................................... 66 2.10.2 NON-EQUI JOIN................................................................................................................ 67 2.10.3 SELF JOIN......................................................................................................................... 67 2.10.4 NATURAL JOIN.................................................................................................................. 68 2.10.5 CROSS JOIN..................................................................................................................... 68 2.10.6 OUTER JOIN...................................................................................................................... 69 2.10.7 INNER JOIN....................................................................................................................... 72 2.11 Case OR Decode () 72 2.11.1 CASE.................................................................................................................................. 72 2.11.2 Decode ()............................................................................................................................ 73 2.12 Merge Statement 73 2.13 Sub Queries, Co-Related Queries and EXISTS clause 74 2.13.1 SUB QUERIES................................................................................................................... 74 2.13.2 CORRELATED SUBQUERIES..........................................................................................75 2.13.3 EXISTS............................................................................................................................... 76 2.14 Views, Inline Views and Materialized Views 76 2.14.1 VIEWS................................................................................................................................ 76 2.14.2 INLINE VIEW ..................................................................................................................... 77 2.14.3 MATERILIZED VIEW ......................................................................................................... 78 2.15 Indexes 79 2.15.1 UNIQUE INDEX.................................................................................................................. 80 2.15.2 NON-UNIQUE INDEX........................................................................................................ 80 2.15.3 BTREE INDEX or ASCENDING INDEX.............................................................................80 2.15.4 BITMAP INDEX.................................................................................................................. 80 2.15.5 COMPOSITE INDEX.......................................................................................................... 81 2.16 Query Tuning approach 81 2.17 Differences 82 2.17.1 ROWID & ROW_NUM........................................................................................................ 82 2.17.2 WHERE & HAVING............................................................................................................ 83 2.17.3 SUB QUERY & CO_RELATED SUB QUERY....................................................................83 2.17.4 STORE PROCEDURE & FUNCTION................................................................................84 2.17.5 Trigger & Procedure........................................................................................................... 85 2.18 PL/SQL Basics 85 2.18.1 Store Procedure................................................................................................................. 85 2.18.2 Triggers:............................................................................................................................. 86 2.19 IMPORTANT QUERIES 87

Detailed SQL DocumentAutomation of Candidate Extract and Load Process

Page 2 of 90

1 1.1

INTRODUCTION Purpose The purpose of this document is to provide the detailed information about Oracle-SQL based on Real-Time for beginners.

2 2.1

ORACLE What is Oracle?

Oracle is a Database which is developed by Oracle Corporation. Organizations can store data on various media and in different formats, such as a hard-copy document in a filing cabinet or data stored in electronic spreadsheets or in databases. A database is an organized collection of information. To manage databases, you need database management systems (DBMS). A DBMS is a program that stores, retrieves, and modifies data in the database on request. There are four main types of databases: hierarchical, network, relational, and more recently object relational (ORDBMS). Oracle divided into 2 parts 1. SQL (Structure Query Language) 2. PL/SQL (Procedure Language for SQL)

2.2

SQL is divided into the following  Data Definition Language (DDL)  Data Manipulation Language (DML)  Data Retrieval Language (DRL)  Transaction Control Language (TCL)  Data Control Language (DCL)

DDL -- create, alter, drop, truncate, rename DML -- insert, update, delete DRL -- select

Page 3 of 90

TCL -- commit, rollback, save point DCL -- grant, revoke Oracle Data types: Data types Description Variable length character string having maximum length size bytes. You must specify size. we can use to store string values Max Size: Oracle 11g

VARCHAR2(size)

4000 bytes minimum is 1

NUMBER(p,s)

Number having precision p and scale s. Which we can use to store number values

The precision p can range from 1 to 38. The scale s can range from -84 to 127.

DATE

Valid date range. We can use to store date values

Database: Its collection of schemas or users Schema/User: Its collection of Objects like tables, Views etc.. Table: Table is the basic element in a database or object in database to store the data in the form of rows and columns.

2.2.1 CREATE (DDL) Create table <table_name> (col1 datatype1, col2 datatype2 …coln datatypen);

Page 4 of 90

Ex: SQL> create table student (no number (2), name varchar2 (10), Address varchar2 (50));

2.2.2 INSERT (DML) This will be used to insert the records into table. We have two methods to insert. By value method By address method a) USING VALUE METHOD Syntax: Insert into <table_name> values (value1, value2, value3 …. Valuen); Ex: SQL> insert into student values (1, ’sham’, ‘hyd’); SQL> insert into student values (2, ’mohan’,’bang’); EMP NO NAME DOJ

SQL> Insert into EMP values (100, ’Sham’, To_date (’01-23-2010’,’MMDD-YYYY’)); To insert a new record again you have to type entire insert command, if there are lot of records this will be difficult.
Page 5 of 90

This will be avoided by using address method. b) USING ADDRESS METHOD Syntax: Insert into <table_name> values (&col1, &col2, &col3 …. &coln); This will prompt you for the values but for every insert you have to use forward slash. Ex: SQL> insert into student values (&no, '&name', ‘&address’); Enter value for no: 1 Enter value for name: Jagan Enter value for address: mpl SQL> / Enter value for no: 2 Enter value for name: Naren Enter value for address: Chennai c) INSERTING DATA INTO SPECIFIED COLUMNS USING VALUE METHOD

Syntax: Insert into <table_name>(col1, col2, col3 … Coln) values (value1, value2, value3 …. Valuen); Ex:
Page 6 of 90

SQL> insert into student (no, name) values (3, ’Ramesh’); SQL> insert into student (no, name) values (4, ’Madhu’); d) INSERTING NULL DATA INTO SPECIFIED COLUMNS SQL> insert into student values (1, ’sham’, NULL); Here null is not a value you can’t use it for comparison. 2.2.3 Commit (TCL) To save transaction permanently in the database we need to issue commit. Every DML should follow TCL. SQL> commit; 2.2.4 SELECT (DRL) Syntax: Select * from <table_name>; -- here * indicates all columns Or Select col1, col2 … coln from <table_name>; Ex: SQL> select * from student; NO --1 2 NAME -----sham mohan address -------hyd mpl

Page 7 of 90

SQL> select no, name, address from student; NO NAME address -------hyd mpl

--- -----1 2 sham mohan

SQL> select no, name from student; NO NAME

--- ------1 2 Sham mohan

CONDITIONAL SELECTIONS AND OPERATORS We have two clauses used in this  Where  Order by USING WHERE We can retrieve or select specific data or rows with where clause.

Syntax: Select * from <table_name> where <condition>; The following are the different types of operators used in where clause.  Arithmetic operators
Page 8 of 90

 Comparison operators  Logical operators  Arithmetic operators +, -, *, /  Comparison operators  =, !=, >, <, >=, <=, <>  between, not between  in, not in  null, not null  like  Logical operators  And  Or  Not a) USING =, >, <, >=, <=, !=, <> Ex: SQL> select * from student where DOJ = To_date (’01-232010’,’MM-DD-YYYY’); NO NAME --- ------2 2 Saketh Naren MARKS --------200 400 -- lowest precedence -- highest precedence

SQL> select * from student where no < 2; NO NAME MARKS

Page 9 of 90

--- ------1 1 Sudha Jagan

---------100 300

SQL> select * from student where no > 2; NO NAME --- ------3 4 5 6 Ramesh Madhu Visu Rattu MARKS ----------

SQL> select * from student where no <= 2; NO NAME --- ------1 2 1 2 Sudha Saketh Jagan Naren MARKS ---------100 200 300 400

SQL> select * from student where no >= 2; NO NAME --- ------2 Saketh MARKS --------200
Page 10 of 90

2 3 4 5 6

Naren Ramesh Madhu Visu Rattu

400

SQL> select * from student where no != 2; NO NAME --- ------1 1 3 4 Sudha Jagan Ramesh Madhu MARKS ---------100 300

SQL> select * from student where no <> 2; NO NAME --- ------1 1 3 4 5 6 Sudha Jagan Ramesh Madhu Visu Rattu
Page 11 of 90

MARKS ---------100 300

b) USING AND This will gives the output when all the conditions become true. Syntax: Select * from <table_name> where <condition1> and <condition2> and... Ex: SQL> select * from student where no = 2 and marks >= 200; NO NAME --- ------2 2 c) USING OR This will gives the output when either of the conditions becomes true. Syntax: Select * from <table_name> where <condition1> or <condition2> or... Ex: SQL> select * from student where no = 2 or marks >= 200; NO NAME --- ------2 Saketh MARKS --------200 <conditionn>; Saketh Naren MARKS -------200 400 <conditionn>;

Page 12 of 90

1

Jagan

300

d) USING BETWEEN This will gives the output based on the column and its lower bound, upper bound. Syntax: Select * from <table_name> where <col> between <lower bound> and <upper bound>; Ex: SQL> select * from student where marks between 200 and 400; NO NAME --- ------2 1 2 Saketh Jagan Naren MARKS --------200 300 400

e) USING NOT BETWEEN This will gives the output based on the column which values are not in its lower bound, upper bound. Syntax: Select * from <table_name> where <col> not between <lower bound> and <upper bound>; Ex: SQL> select * from student where marks not between 200 and 400;

Page 13 of 90

NO NAME --- ------1 f) USING IN Sudha

MARKS --------100

This will gives the output based on the column and its list of values specified. Syntax: Select * from <table_name> where <col> in (value1, value2, value3 … valuen); Ex: SQL> select * from student where no in (1, 2, 3); NO NAME --- ------1 2 1 2 3 g) USING NOT IN This will gives the output based on the column which values are not in the list of values specified. Syntax:
Page 14 of 90

MARKS --------100 200 300 400

Sudha Saketh Jagan Naren Ramesh

Select * from <table_name> where <col> not in (value1, value2, value3 … valuen); Ex: SQL> select * from student where no not in (1, 2, 3);

NO NAME --- ------4 5 6 h) USING NULL Madhu Visu Rattu

MARKS ---------

This will gives the output based on the null values in the specified column. Syntax: Select * from <table_name> where <col> is null; Ex: SQL> select * from student where marks is null; NO NAME --- ------3 4 Ramesh Madhu MARKS ---------

Page 15 of 90

5 6

Visu Rattu

i) USING NOT NULL This will gives the output based on the not null values in the specified column. Syntax: Select * from <table_name> where <col> is not null; Ex: SQL> select * from student where marks is not null; NO NAME --- ------1 2 1 2 j) USING LIKE This will be used to search through the rows of database column based on the pattern you specify. Syntax: Select * from <table_name> where <col> like <pattern>; Ex: Sudha Saketh Jagan Naren MARKS --------100 200 300 400

Page 16 of 90

i) This will give the rows whose marks are 100. SQL> select * from student where marks like 100; NO NAME --- ------1 Sudha MARKS --------100

ii) This will give the rows whose name start with ‘S’. SQL> select * from student where name like 'S%'; NO NAME --- ------1 2 Sudha Saketh MARKS --------100 200

iii) This will give the rows whose name ends with ‘h’. SQL> select * from student where name like '%h';

NO NAME --- ------2 3 Saketh Ramesh

MARKS --------200

iV) This will give the rows whose name’s second letter start with ‘a’. SQL> select * from student where name like '_a%'; NO NAME MARKS
Page 17 of 90

--- ------2 1 2 3 4 6 Saketh Jagan Naren Ramesh Madhu Rattu

-------200 300 400

V) This will give the rows whose name’s third letter start with ‘d’. SQL> select * from student where name like '__d%'; NO NAME --- ------1 4 Sudha Madhu MARKS --------100

Vi) This will give the rows whose name’s second letter start with ‘t’ from ending. SQL> select * from student where name like '%_t%'; NO NAME --- ------2 6 Saketh Rattu MARKS --------200

Viii) This will give the rows whose name cotains 2 a’s.

Page 18 of 90

SQL> select * from student where name like '%a%a%'; NO NAME --- ------1 Jagan MARKS ---------300

* You have to specify the patterns in like using underscore ( _ ). USING ORDER BY This will be used to ordering the columns data (ascending or descending). Syntax: Select * from <table_name> order by <col> desc; By default oracle will use ascending order. If you want output in descending order you have to use desc keyword after the column. Ex: SQL> select * from student order by no; NO NAME --- ------1 1 2 2 3 Sudha Jagan Saketh Naren Ramesh MARKS --------100 300 200 400

Page 19 of 90

4

Madhu

SQL> select * from student order by no desc; NO NAME --- ------4 Madhu 3 Ramesh 2 Saketh 2 Naren 1 Sudha 1 Jagan 200 400 100 300 MARKS ---------

2.2.5 UPDATE (DML) USING UPDATE This can be used to modify the table data. Syntax: Update <table_name> set <col1> = value1, <col2> = value2 where <condition>; Ex: SQL> update student set marks = 500; If you are not specifying any condition this will update entire table. Update specific data in a table using Where clause

Page 20 of 90

SQL> update student set marks = 500 where no = 2; SQL> update student set marks = 500, name = 'Venu' where no = 1; 2.2.6 DELETE (DML) This can be used to delete the table data temporarily. Need to issue commit since Delete is DML We can use Delete, to delete specific rows or data. We can use where clause with delete statement. Syntax: Delete <table_name> where <condition>; Ex: SQL> delete student; If you are not specifying any condition this will delete entire table. SQL> Delete student where no = 2; 2.2.7 TRUNCATE (DDL) This can be used to delete the entire table data permanently. No need commit since truncate is DDL We can’t use truncate to delete specific rows or data. We can’t use where clause with truncate statement. Syntax: Truncate table <table_name>; Ex:

Page 21 of 90

SQL> Truncate table student; 2.2.8 DROP (DDL) This will be used to drop the database objects; Drop will delete data as well structure. No need commit since drop is DDL Syntax: Drop table <table_name>; Ex: SQL> Drop table student;

2.2.9 USING DDL USING ALTER This can be used to add or remove columns and to modify the precision of the data type. a) ADDING COLUMN Syntax: Alter table <table_name> add <col data type>; Ex: SQL> Alter table student add sdob date; b) REMOVING COLUMN Syntax:

Page 22 of 90

Alter table <table_name> drop column < col_name >; Ex: SQL> Alter table student drop column sdob; c) INCREASING OR DECREASING PRECISION OF A COLUMN Syntax: Alter table <table_name> modify <col data type>; Ex: SQL> Alter table student modify marks number (5); * To decrease precision the column should be empty.

e) RENAMING COLUMN Syntax: Alter table <table_name> rename column <old_col_name> to <new_col_name>; Ex: SQL> Alter table student rename column marks to smarks; USING RENAME This will be used to rename the database object; Syntax: Rename <old_table_name> to <new_table_name>; Ex:

Page 23 of 90

SQL> Rename student to stud; 2.2.10 USING TCL USING COMMIT This will be used to save the work. Commit is of two types.  Implicit  Explicit

a) IMPLICIT This will be issued by oracle internally  When any DDL operation is performed. b) EXPLICIT This will be issued by the user. Syntax: Commit or commit work; * Whenever you committed then the transaction was completed. USING ROLLBACK This will undo the operation. This will be applied in two methods.  Up to previous commit  Up to previous rollback Syntax: Roll or roll work;

Page 24 of 90

Or Rollback or rollback work; * While process is going on, if suddenly power goes then oracle will rollback the transaction. USING SAVEPOINT You can use savepoints to rollback portions of your current set of transactions. Syntax: Savepoint <savepoint_name>; 2.2.11 USING DCL DCL commands are used to granting and revoking the permissions on objects. To access tables from one schema to another schema. USING GRANT This is used to grant the privileges to other users. Syntax: Grant <privileges> on <object_name> to <user_name> [with grant option]; Ex: SQL> grant select on student to abc; -- you can give individual privilege SQL> grant select, insert on student to abc; -- you can give set of privileges SQL> grant all on student to abc; -- you can give all privileges The abc user has to use dot method to access the object.
Page 25 of 90

SQL> select * from scott.student; The abc user can not grant permission on student table to other users. To get this type of option use the following. SQL> grant all on student to abc with grant option; Now abc user also grants permissions on student table. USING REVOKE This is used to revoke the privileges from the users to which you granted the privileges. Syntax: Revoke <privileges> on <object_name> from <user_name>; Ex: SQL> revoke select on student form abc; individual privilege SQL> revoke select, insert on student from abc; set of privileges SQL> revoke all on student from abc; -- you can revoke all privileges 2.3 Synonym -- you can revoke -- you can revoke

A synonym is a similar named object, which is used as an alias for a table, view or sequence. To access a tables or views or sequence from one schema to another schema without specifying table prefix schema name (scott.emp). TYPES  Private

Page 26 of 90

 Public Private synonym is available to the particular user who creates. Public synonym is created by DBA which is available to all the users. ADVANTAGES  Hide the name and owner of the object. CREATE AND DROP SQL> create synonym emp for scott.emp; SQL> create public synonym emp for scott.emp; Login to abc schema then try SQL> select * from emp SQL> drop synonym emp; 2.4 Dblink

To access a tables or views or sequence from one database to another database. Syntax: CREATE DATABASE LINK CAASEDW CONNECT TO ITO_ASA IDENTIFIED BY exact123 USING ' CAASEDW ’ SQL> select * from emp@ CAASEDW 2.5 How to take Backup table data?

CREATE WITH SELECT (Take Backup table data) We can create a table using existing table [along with data] Called it as Back up tables. Syntax: Create table <new_table_name> [col1, col2, col3 ... coln] as select *

Page 27 of 90

from Ex:

<old_table_name>;

SQL> create table student1 as select * from student; Creating table with your own column names. SQL> create table student2 (sno, sname, smarks) as select * from student; Creating table with specified columns. SQL> create table student3 as select no, name from student; Creating table without table data. SQL> create table student2 (sno, sname, smarks) as select * from student where 1 = 2; In the above where clause give any condition which does not satisfy. INSERT WITH SELECT Using this we can insert existing table data to another table in a single trip. But the table structure should be same. Syntax: Insert into <table1> select * from <table2>; Ex: SQL> insert into student1 select * from student; Inserting data into specified columns SQL> insert into student1 (no, name) select no, name from student;

Page 28 of 90

2.6

Aliases

COLUMN ALIASES Syntax: Select <orginal_col> <alias_name> from <table_name>; Ex: SQL> select no sno from student; Or SQL> select no as sno from student; TABLE ALIASES If you are using table aliases you can use dot method to the columns. Syntax: Select <alias_name>.<col1>, <alias_name>.<col2> … <alias_name>.<coln> from <table_name> <alias_name>; Ex: SQL> select s.no, s.name from student s; 2.7 Functions

SQL functions are built into Oracle Database and are available for use in various appropriate SQL statements. Functions can be categorized as follows.  Single row functions  Group functions

Page 29 of 90

2.7.1 SINGLE

ROW

FUNCTIONS

Single row functions can be categorized into five. These will be applied for each row and produces individual output for each row.  Numeric functions  String functions  Date functions  Miscellaneous functions  Conversion functions 2.7.1.1.1 Numeric Functions

Numeric functions accept numeric input and return numeric values MOD: This will give the remainder. Syntax: mod (value, divisor) Ex: SQL> select mod(7,4), mod(1,5), mod(null, null), mod(0,0), mod(-7,4) from dual;
MOD(7,4) -----------3 MOD(1,5) MOD(NULL,NULL) MOD(0,0) MOD(-7,4) ----------- ------------0 -3

---------- --------------------1

DUAL is Dummy table it does not have data or structure.

NVL: This will substitutes the specified value in the place of null values. Syntax: nvl (null_col, replacement_value)

Page 30 of 90

Ex: SQL> select * from student; -- here for 3rd row marks value is null NO NAME --- ------1 2 3 a b c MARKS --------100 200

SQL> select no, name, nvl(marks,300) from student;
NO --1 2 3 NAME ------a b c NVL(MARKS,300) --------------------100 200 300

ROUND: This will rounds numbers to a given number of digits of precision. Syntax: round (value, precision) Ex: SQL>
select round(123.2345), round(123.2345,2), round(123.2354,2) from dual;

ROUND(123.2345) ROUND(123.2345,0) ROUND(123.2345,2) ROUND(123.2354,2) --------------------123 ------------------------ ----------------------- ----------------------123 123.23 123.24

Page 31 of 90

GREATEST: This will give the greatest number. Syntax: greatest (value1, value2, value3 … valuen) Ex: SQL> select greatest(1, 2, 3), greatest(-1, -2, -3) from dual;
GREATEST(1,2,3) GREATEST(-1,-2,-3) -------------------- ----------------------3 -1

TRUNC (number) : The TRUNC (number) function returns n truncated to m decimal places. SELECT TRUNC(15.79,1) "Truncate" FROM DUAL; Truncate ---------15.7 2.7.1.1.2 String Functions

Character functions that return character values return values of the same datatype as the input argument.  Initcap  Upper  Lower  Length  Rpad  Lpad  Ltrim  Rtrim  Trim

Page 32 of 90

 Translate  Replace  Soundex  Concat ( ‘ || ‘ Concatenation operator)  Ascii  Chr  Substr  Instr  Decode  Greatest  Least  Coalesce a) INITCAP This will capitalize the initial letter of the string. Syntax: initcap (string) Ex: SQL> select initcap('computer') from dual; INITCAP ----------Computer b) UPPER This will convert the string into uppercase. Syntax: upper (string) Ex: SQL> select upper('computer') from dual;
Page 33 of 90

UPPER ----------COMPUTER c) LOWER This will convert the string into lowercase. Syntax: lower (string) Ex: SQL> select lower('COMPUTER') from dual; LOWER ----------computer d) LENGTH This will give length of the string. Syntax: length (string) Ex: SQL> select length('computer') from dual; LENGTH ----------8 e) RPAD This will allows you to pad the right side of a column with any set of
Page 34 of 90

characters. Syntax: rpad (string, length [, padding_char]) Ex: SQL> select rpad('computer',15,'*'), rpad('computer',15,'*#') from dual;
RPAD('COMPUTER' RPAD('COMPUTER' ---------------------- ---------------------computer******* computer*#*#*#*

-- Default padding character was blank space. f) LPAD This will allows you to pad the left side of a column with any set of characters. Syntax: lpad (string, length [, padding_char]) Ex: SQL> select lpad('computer',15,'*'), lpad('computer',15,'*#') from dual;
LPAD('COMPUTER' LPAD('COMPUTER' --------------------*******computer --------------------*#*#*#*computer

-- Default padding character was blank space. g) LTRIM This will trim off unwanted characters from the left end of string. Syntax: ltrim (string [,unwanted_chars]) Ex:
Page 35 of 90

SQL> select ltrim('computer','co'), ltrim('computer','com') from dual;
LTRIM( LTRIM -------- --------mputer puter

SQL> select ltrim('computer','puter'), ltrim('computer','omputer') from dual;

LTRIM('C LTRIM('C ---------computer ---------computer

-- If you haven’t specify any unwanted characters it will display entire string. h) RTRIM This will trim off unwanted characters from the right end of string. Syntax: rtrim (string [, unwanted_chars]) Ex: SQL> select rtrim('computer','er'), rtrim('computer','ter') from dual; RTRIM( RTRIM -------- --------comput compu

SQL> select rtrim('computer','comput’), rtrim('computer','compute') from dual;

Page 36 of 90

RTRIM('C RTRIM('C ---------computer ---------computer

-- If you haven’t specify any unwanted characters it will display entire string.

i) TRIM This will trim off unwanted characters from the both sides of string. Syntax: trim (unwanted_chars from string) Ex: SQL> select trim( 'i' from 'indiani') from dual; TRIM( ----ndian SQL> select trim( leading'i' from 'indiani') from dual; -- this will work as LTRIM TRIM(L -----ndiani SQL> select trim( trailing'i' from 'indiani') from dual; -- this will work as RTRIM TRIM(T
Page 37 of 90

-----Indian j) TRANSLATE This will replace the set of characters, character by character. Syntax: translate (string, old_chars, new_chars) Ex: SQL> select translate('india','in','xy') from dual; TRANS -------xydxa k) REPLACE This will replace the set of characters, string by string. Syntax: replace (string, old_chars [, new_chars]) Ex: SQL> select replace('india','in','xy'), replace(‘india’,’in’) from dual; REPLACE REPLACE

----------- ----------Xydia m) CONCAT This will be used to combine two strings only. Syntax: concat (string1, string2)
Page 38 of 90

dia

Ex: SQL> select concat('computer',' operator') As Name from dual; Name ------------------------computer operator If you want to combine more than two strings you have to use concatenation Operator(||). SQL> select 'how' || ' are' || ' you' from dual; 'HOW'||'ARE --------------how are you n) ASCII This will return the decimal representation in the database character set of the first character of the string. Syntax: ascii (string) Ex: SQL> select ascii('a'), ascii('apple') from dual; ASCII('A') ASCII('APPLE') ------------ ------------------

Page 39 of 90

97 o) CHR

97

This will return the character having the binary equivalent to the string in either the database character set or the national character set. Syntax: chr (number) Ex: SQL> select chr(97) from dual; CHR ----a p) SUBSTR This will be used to extract substrings. Syntax: substr (string, start_chr_count [, no_of_chars]) Ex: SQL> select substr('computer',2), substr('computer',2,5), substr('computer',3,7) from dual; SUBSTR( SUBST SUBSTR ---------- ------omputer omput q) INSTR This will allows you for searching through a string for set of characters. Syntax: instr (string, search_str [, start_chr_count [, occurrence] ]) -------mputer

Page 40 of 90

Ex: SQL> select instr('information','o',4,1), instr('information','o',4,2) from dual;
INSTR('INFORMATION','O',4,1) INSTR('INFORMATION','O',4,2) ------------------------------------ ------------------------------------4 10

 If you are not specifying start_chr_count and occurrence then it will start search from the beginning and finds first occurrence only.  If both parameters start_chr_count and occurrence are null, it will display nothing. r) DECODE Decode will act as value by value substitution. For every value of field, it will checks for a match in a series of if/then tests. Syntax: decode (value, if1, then1, if2, then2, ……. else); Ex: SQL> select sal, decode(sal,500,'Low',5000,'High','Medium') from emp; SAL ----500 DECODE --------Low

Page 41 of 90

2500 2000 3500

Medium Medium Medium

SQL> select decode(1,1,3), decode(1,2,3,4,4,6) from dual;

DECODE(1,1,3) DECODE(1,2,3,4,4,6) ----------------- -----------------------3 6

 If the number of parameters are odd and different then decode will display nothing.  If the number of parameters are even and different then decode will display last value.  If all the parameters are null then decode will display nothing.  If all the parameters are zeros then decode will display zero. s) GREATEST This will give the greatest string. Syntax: greatest (strng1, string2, string3 … stringn) Ex: SQL> select greatest('a', 'b', 'c'), greatest('satish','srinu','saketh') from dual; GREAT GREAT ------- -------

Page 42 of 90

c

srinu

 If all the parameters are nulls then it will display nothing.  If any of the parameters is null it will display nothing. t) LEAST This will give the least string. Syntax: greatest (strng1, string2, string3 … stringn) Ex: SQL> select least('a', 'b', 'c'), least('satish','srinu','saketh') from dual; LEAST LEAST ------- ------a saketh

 If all the parameters are nulls then it will display nothing.  If any of the parameters is null it will display nothing.

2.7.1.1.3

DATE FUNCTIONS

Oracle default date format is DD-MON-YY.  Sysdate  Current_date  Current_timestamp  Systimestamp  Localtimestamp  Dbtimezone  Sessiontimezone

Page 43 of 90

 To_char  To_date  Add_months  Months_between  Next_day  Last_day  Extract  Greatest  Least  Round  Trunc  New_time  Coalesce a) SYSDATE This will give the current date and time. Ex: SQL> select sysdate from dual; SYSDATE ----------24-DEC-06 b) CURRENT_DATE This will returns the current date in the session’s timezone. Ex: SQL> select current_date from dual; CURRENT_DATE

Page 44 of 90

-----------------24-DEC-06 c) CURRENT_TIMESTAMP This will returns the current timestamp with the active time zone information. Ex: SQL> select current_timestamp from dual;
CURRENT_TIMESTAMP --------------------------------------------------------------------------24-DEC-06 03.42.41.383369 AM +05:30

d) SYSTIMESTAMP This will returns the system date, including fractional seconds and time zone of the database. Ex: SQL> select systimestamp from dual;
SYSTIMESTAMP --------------------------------------------------------------------------24-DEC-06 03.49.31.830099 AM +05:30

h) TO_CHAR This will be used to extract various date formats. The available date formats as follows.

Page 45 of 90

Syntax: to_char (date, format)

DATE FORMATS D DD DDD MM MON MONTH RM DY DAY Y YY YYY YYYY SYYYY I IY IYY IYYY ------------------No of days in week No of days in month No of days in year No of month Three letter abbreviation of month Fully spelled out month Roman numeral month Three letter abbreviated day Fully spelled out day Last one digit of the year Last two digits of the year Last three digits of the year Full four digit year Signed year One digit year from ISO standard Two digit year from ISO standard Three digit year from ISO standard Four digit year from ISO standard
Page 46 of 90

Y, YYY YEAR CC Q W WW IW HH MI SS FF AM or PM

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

Year with comma Fully spelled out year Century No of quarters No of weeks in month No of weeks in year No of weeks in year from ISO standard Hours Minutes Seconds Fractional seconds Displays AM or PM depending upon time of day Displays A.M or P.M depending upon time of day Displays AD or BC depending upon the date Displays AD or BC depending upon the date Prefix to month or day, suppresses padding of

A.M or P.M -AD or BC --

A.D or B.C -FM month or day TH SP SPTH out -----

Suffix to a number suffix to a number to be spelled out Suffix combination of TH and SP to be both spelled

Page 47 of 90

THSP

--

same as SPTH

SQL> select to_char(sysdate,'dd month year') from dual; TO_CHAR(SYSDATE,'DDMONTHYEAR') ------------------------------------------------------24 december two thousand six SQL> select to_char(sysdate,'dd fmmonth year') from dual; TO_CHAR(SYSDATE,'DD FMMONTH YEAR') ------------------------------------------------------24 december two thousand six SQL> select to_char(sysdate,'ddth DDTH') from dual; TO_CHAR(S -----------24th 24TH i) TO_DATE This will be used to convert the string into date format. Syntax: to_date (date) Ex: SQL> select to_char(to_date('24/dec/2006','dd/mon/yyyy'), 'dd * month * day') from dual;

TO_CHAR(TO_DATE('24/DEC/20 --------------------------

Page 48 of 90

24 * december * Sunday -- If you are not using to_char oracle will display output in default date format. j) ADD_MONTHS This will add the specified months to the given date. Syntax: add_months (date, no_of_months) Ex: SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), 5) from dual; ADD_MONTHS ---------------11-JUN-90 SQL> select add_months(to_date('11-jan-1990','dd-mon-yyyy'), -5) from dual; ADD_MONTH --------------11-AUG-89  If no_of_months is zero then it will display the same date.  If no_of_months is null then it will display nothing. k) MONTHS_BETWEEN This will give difference of months between two dates. Syntax: months_between (date1, date2)

Page 49 of 90

Ex: SQL> select months_between(to_date('11-aug-1990','dd-monyyyy'), to_date('11-jan-1990','dd-mon-yyyy')) from dual;
MONTHS_BETWEEN(TO_DATE('11-AUG-1990','DD-MON-YYYY'),TO_DATE('11-JAN-1990','DDMON-YYYY')) ----------------------------------------------------------------------------------------------7

SQL> select months_between(to_date('11-jan-1990','dd-monyyyy'), to_date('11-aug-1990','dd-mon-yyyy')) from dual;

MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG1990','DD-MON-YYYY')) -------------------------------------------------------------------------------------------------7

l) NEXT_DAY This will produce next day of the given day from the specified date. Syntax: next_day (date, day) Ex: SQL> select next_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual; NEXT_DAY( ------------31-DEC-06 -- If the day parameter is null then it will display nothing.
Page 50 of 90

m) LAST_DAY This will produce last day of the given date. Syntax: last_day (date) Ex: SQL> select last_day(to_date('24-dec-2006','dd-mon-yyyy'),'sun') from dual; LAST_DAY( ------------31-DEC-06 o) GREATEST This will give the greatest date. Syntax: greatest (date1, date2, date3 … daten) Ex: SQL> select greatest(to_date('11-jan-90','dd-mon-yy'),to_date('11mar-90','dd-mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

GREATEST( ------------11-APR-90 p) LEAST This will give the least date.

Page 51 of 90

Syntax: least (date1, date2, date3 … daten) Ex: SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11mar-90','dd-mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual; LEAST( ------------11-JAN-90 r) TRUNC Trunc will chops off the date to which it was equal to or less than the given date. Syntax: trunc (date, (day | month | year))  If the second parameter was year then it always returns the first day of the current year.  If the second parameter was month then it always returns the first day of the current month.  If the second parameter was day then it always returns the previous sunday.  If the second parameter was null then it returns nothing.  If the you are not specifying the second parameter then trunk will resets the time to the begining of the current day. Ex: SQL> select trunc(to_date('24-dec-04','dd-mon-yy'),'year'), trunc(to_date('11-mar-06','dd-mon-yy'),'year') from dual;

TRUNC(TO_ TRUNC(TO_

Page 52 of 90

------------- -------------01-JAN-04 01-JAN-06

SQL> select trunc(to_date('11-jan-04','dd-mon-yy'),'month'), trunc(to_date('18-jan-04','dd-mon-yy'),'month') from dual; TRUNC(TO_ TRUNC(TO_ ------------- ------------01-JAN-04 2.7.1.2 01-JAN-04

MISCELLANEOUS FUNCTIONS

a) RANK This will give the non-sequential ranking. Ex: Select empno, ename, sal, r from (select empno, ename, sal, rank () over (order by sal desc) r from EMP); Empno 100 200 300 d) DENSE_RANK This will give the sequential ranking. The DENSE_RANK function works acts like the RANK function except that it assigns consecutive ranks: EX:
Page 53 of 90

ename A B C

sal 5000 5000 4000

r 1 1 3

Select empno, ename, Sal, from (select empno, ename, sal, dense_rank () over (order by sal desc) r from emp);

Empno 100 200 300

ename A B C

sal 5000 5000 4000

r 1 1 2

2.7.2 GROUP BY AND HAVING GROUP BY Using group by, we can create groups of related information. Columns used in select must be used with group by, otherwise it was not a group by expression. Ex: SQL> select deptno, sum(sal) from emp group by deptno; DEPTNO SUM(SAL)

---------- ---------10 20 30 8750 10875 9400

SQL> select deptno,job,sum(sal) from emp group by deptno,job; DEPTNO JOB ---------- --------SUM(SAL) ----------

Page 54 of 90

10 10 10 20 20 20 30 30 30 HAVING

CLERK MANAGER PRESIDENT ANALYST CLERK MANAGER CLERK MANAGER SALESMAN

1300 2450 5000 6000 1900 2975 950 2850 5600

This will work as where clause which can

be used only with group by

because of absence of where clause in group by. On top of the Group by if we want to filter the groups then we use having clause. Ex: SQL> Select empno, name,address,count (*) from EMP group by empno, name,address having count (*)>1;
NAME ADDRESS ---------HYD BANG COUNT -----3 2

EMPNO

---------- --------200 300 SHAM MOHAN

SQL> select deptno,job,sum(sal) tsal from emp group by deptno,job

Page 55 of 90

having sum(sal) > 3000 order by job;

DEPTNO

JOB

TSAL ----------

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

20 10 30 ORDER OF EXECUTION

ANALYST PRESIDENT SALESMAN

6000 5000 5600

 Group the rows together based on group by clause.  Calculate the group functions for each group.  Choose and eliminate the groups based on the having clause.  Order the groups based on the specified column.

2.8

Set Operators

To Combine two queries we need set operators. TYPES  Union  Union all  Intersect  Minus 2.8.1 UNION This will combine the records of multiple tables having the same structure. Ex: SQL> select * from student1

Page 56 of 90

Union select * from student2; 2.8.2 UNION ALL This will combine the records of multiple tables having the same structure but including duplicates. Ex: SQL> select * from student1 union all select * from student2; 2.8.3 INTERSECT This will give the common records of multiple tables having the same structure. Ex: SQL> select * from student1 intersect select * from student2; 2.8.4 MINUS This will give the records of a table whose records are not in other tables having the same structure. Ex: SQL> select * from student1 minus select * from student2; 2.9 Constraints

Constraints required maintaining consistence data in a database. Constraints are categorized as follows.

Domain integrity constraints  Not null
Page 57 of 90

 Check Entity integrity constraints  Unique  Primary key Referential integrity constraints  Foreign key Constraints are always attached to a column not a table. We can add constraints in three ways.  Column level  TABLE LEVEL  Alter level -- along with the column definition -- after the table definition -- using alter command

While adding constraints you need not specify the name but the type only, oracle will internally name the constraint. If you want to give a name to the constraint, you have to use the constraint clause. 2.9.1 NOT NULL This is used to avoid null values. We can add this constraint in column level only. Ex: SQL> create table student(no number(2) not null, name varchar(10), marks number(3));

SQL> create table student(no number(2) constraint nn not null, name varchar(10), marks number(3)); 2.9.2 CHECK This is used to insert the values based on specified condition.
Page 58 of 90

We can add this constraint in all three levels. Ex: COLUMN LEVEL SQL> create table student(no number(2) , name varchar(10), marks number(3) check (marks > 300));

SQL> create table student(no number(2) , name varchar(10), marks number(3) constraint ch check(marks > 300));

TABLE LEVEL SQL> create table student(no number(2) , name varchar(10), marks number(3), check (marks > 300));

SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint ch check(marks > 300));

ALTER LEVEL SQL> alter table student add check(marks>300); SQL> alter table student add constraint ch check(marks>300); 2.9.3 UNIQUE This is used to avoid duplicates but it allow nulls. We can add this constraint in all three levels. Ex:

COLUMN LEVEL SQL> create table student(no number(2) unique, name varchar(10), marks number(3));
Page 59 of 90

SQL> create table student(no number(2) constraint un unique, name varchar(10), marks number(3));

TABLE LEVEL SQL> create table student(no number(2) , name varchar(10), marks number(3), unique(no));

SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint un unique(no));

ALTER LEVEL SQL> alter table student add unique(no); SQL> alter table student add constraint un unique(no); 2.9.4 PRIMARY KEY  This is used to avoid duplicates and nulls. This will work as combination of unique and not null.  Primary key always attached to the parent table.  Primary key will create Unique index by default.  We can add this constraint in all three levels. Ex: COLUMN LEVEL SQL> create table student(no number(2) primary key, name varchar(10), marks number(3));

SQL> create table student(no number(2) constraint pk primary key, name varchar(10), TABLE LEVEL marks number(3));

Page 60 of 90

SQL> create table student(no number(2) , name varchar(10), marks number(3), primary key(no));

SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint pk primary key(no));

ALTER LEVEL SQL> alter table student add primary key(no); SQL> alter table student add constraint pk primary key(no); 2.9.5 FOREIGN KEY  This is used to reference the parent table primary key column which allows duplicates.  Foreign key always attached to the child table.  We can add this constraint in table and alter levels only. Ex: TABLE LEVEL SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), rimary key(empno), foreign key(deptno) references dept(deptno)); SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), constraint pk primary key(empno), constraint fk dept(deptno)); foreign key(deptno) references

ALTER LEVEL SQL> alter table emp add foreign key(deptno) references dept(deptno); SQL> alter table emp add constraint fk foreign key(deptno)
Page 61 of 90

references dept(deptno); Once the primary key and foreign key relationship has been created then you can not remove any parent record if the dependent childs exists. USING ON DELTE CASCADE By using this clause you can remove the parent record even it childs exists. Because when ever you remove parent record oracle automatically removes all its dependent records from child table, if this clause is present while creating foreign key constraint. Ex: TABLE LEVEL SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), primary key(empno), foreign key(deptno) references dept(deptno) on delete cascade);

SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), constraint pk primary key(empno), constraint fk dept(deptno) on delete cascade); foreign key(deptno) references

ALTER LEVEL SQL> alter table emp add foreign key(deptno) references dept(deptno) on delete cascade;

SQL> alter table emp add constraint fk foreign key(deptno) references dept(deptno) on delete cascade;
Page 62 of 90

2.9.6 COMPOSITE KEYS A composite key can be defined on a combination of columns. Composite key can be defined in table and alter levels only. Ex: UNIQUE (TABLE LEVEL) SQL> create table student(no number(2) , name varchar(10), marks number(3), unique(no,name));

SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint un unique(no,name));

UNIQUE (ALTER LEVEL) SQL> alter table student add unique(no,name); SQL> alter table student add constraint un unique(no,name); PRIMARY KEY (TABLE LEVEL) SQL> create table student(no number(2) , name varchar(10), marks number(3), primary key(no,name));

SQL> create table student(no number(2) , name varchar(10), marks number(3), constraint pk primary key(no,name));

PRIMARY KEY (ALTER LEVEL) SQL> alter table student add primary key(no,anme); SQL> alter table student add constraint pk primary key(no,name); FOREIGN KEY (TABLE LEVEL)

Page 63 of 90

SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), dname varchar(10), primary key(empno), foreign key(deptno,dname) references dept(deptno,dname));

SQL> create table emp(empno number(2), ename varchar(10), deptno number(2), dept(deptno,dname)); FOREIGN KEY (ALTER LEVEL) SQL> alter table emp add foreign key(deptno,dname) references dept(deptno,dname); SQL> alter table emp add constraint fk foreign key(deptno,dname) references dept(deptno,dname); dname varchar(10), constraint pk primary key(deptno,dname) references key(empno), constraint fk foreign

2.10 Joins

• • •

The purpose of a join is to combine the data across tables. A join is actually performed by the where clause which combines the specified rows of tables. If a join involves in more than two tables then oracle joins first two tables based on the joins condition and then compares the result with the next table and so on.

TYPES  Equi join  Non-equi join  Self join  Natural join  Cross join

Page 64 of 90

 Outer join    Left outer Right outer Full outer

 Inner join  Using clause  On clause

Assume that we have the following tables. SQL> select * from dept; DEPTNO DNAME LOC

------ ---------- ---------10 20 30 mkt fin hr hyd bang bombay

SQL> select * from emp;

EMPNO

ENAME

JOB

MGR

DEPTNO

---------- ---------- ---------- ---------- ---------111 222 333 saketh sudha jagan analyst clerk manager 444 333 111 10 20 10

Page 65 of 90

444

madhu

engineer

222

40

2.10.1 EQUI JOIN A join which contains an ‘=’ operator in the joins condition. Ex: SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno; EMPNO ENAME JOB DNAME LOC

---------- ---------- ---------- ---------- ---------111 333 222 USING CLAUSE SQL> select empno,ename,job ,dname,loc from emp e join dept d using(deptno); saketh jagan sudha analyst mkt hyd hyd bang

manager mkt clerk fin

EMPNO

ENAME

JOB

DNAME

LOC

---------- ---------- ---------- ---------- ---------111 333 222 ON CLAUSE
Page 66 of 90

saketh jagan sudha

analyst

mkt

hyd hyd bang

manager mkt clerk fin

SQL>

select empno,ename,job,dname,loc from emp e join dept d

on(e.deptno=d.deptno); EMPNO ENAME JOB DNAME LOC

---------- ---------- ---------- ---------- ---------111 333 222 saketh jagan sudha analyst mkt hyd hyd bang

manager mkt clerk fin

2.10.2 NON-EQUI JOIN A join which contains an operator other than ‘=’ in the joins condition. Ex: SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno > d.deptno; EMPNO ENAME JOB DNAME LOC

---------- ---------- ---------- ---------- ---------222 444 444 444 2.10.3 SELF JOIN Joining the table itself is called self join. Ex: SQL> select e1.empno,e2.ename,e1.job,e2.deptno from emp e1,emp sudha madhu madhu madhu clerk engineer engineer engineer mkt mkt fin hr hyd hyd bang bombay

Page 67 of 90

e2 where

e1.mgr=e2.empno; EMPNO ENAME JOB DEPTNO

---------- ---------- ---------- ---------111 222 333 444 jagan madhu sudha saketh analyst clerk manager engineer 10 40 20 10

2.10.4 NATURAL JOIN Natural join compares all the common columns. Ex: SQL> select empno,ename,job,dname,loc from emp natural join dept; EMPNO ENAME JOB DNAME LOC

---------- ---------- ---------- ---------- ---------111 333 222 saketh jagan sudha analyst manager clerk mkt mkt fin hyd hyd bang

2.10.5 CROSS JOIN This will gives the cross product. Ex: SQL> select empno,ename,job,dname,loc from emp cross join dept; EMPNO ENAME JOB DNAME LOC

Page 68 of 90

---------- ---------- ---------- ---------- ---------111 222 333 444 111 222 333 444 111 222 333 444 saketh sudha jagan madhu saketh sudha jagan madhu saketh sudha jagan madhu analyst clerk manager engineer analyst clerk manager engineer analyst clerk manager engineer mkt mkt mkt mkt fin fin fin fin hr hr hr hr hyd hyd hyd hyd bang bang bang bang bombay bombay bombay bombay

2.10.6 OUTER JOIN Outer join gives the non-matching records along with matching records from both the tables. Its divided into Left, Right and Full outer join 2.10.6.1 LEFT OUTER JOIN

This will display the all matching records from both the tables and also non matching records from opposite side outer join symbol table. Ex: SQL> select empno,ename,job,dname,loc from emp e left outer join

Page 69 of 90

dept d

on(e.deptno=d.deptno); Or

SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno=d.deptno(+); EMPNO ENAME JOB DNAME LOC

---------- ---------- ---------- ---------- ---------111 333 222 444 2.10.6.2 saketh jagan sudha madhu analyst manager clerk engineer mkt mkt fin hyd hyd bang

RIGHT OUTER JOIN

This will display the all matching records and the records which are in right hand side table those that are not in left hand side table. Ex: SQL> select empno,ename,job,dname,loc from emp e right outer join dept d on(e.deptno=d.deptno); Or SQL> select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) = d.deptno; EMPNO ENAME JOB DNAME LOC

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

Page 70 of 90

111 333 222

saketh jagan sudha

analyst manager clerk

mkt mkt fin hr

hyd hyd bang bombay

2.10.6.3

FULL OUTER JOIN

This will display the all matching records and the non-matching records from both tables.Union between Left and Right outer joins nothing but Full Outer join. Ex: SQL> select empno,ename,job,dname,loc from emp e right outer join dept d on(e.deptno=d.deptno) UNION select empno,ename,job,dname,loc from emp e,dept d where e.deptno(+) = d.deptno; OR SQL> select empno,ename,job,dname,loc from emp e full outer join dept d on(e.deptno=d.deptno);

EMPNO

ENAME

JOB

DNAME

LOC

---------- ---------- ---------- ---------- ---------333 111 jagan saketh manager analyst mkt mkt hyd hyd

Page 71 of 90

222 444

sudha madhu

clerk engineer

fin

bang

hr 2.10.7 INNER JOIN This will display all the records that have matched. Ex:

bombay

SQL> select empno,ename,job,dname,loc from emp inner join dept using(deptno); EMPNO ENAME JOB DNAME LOC

---------- ---------- ---------- ---------- ---------111 333 222 saketh jagan sudha analyst manager clerk mkt mkt fin hyd hyd bang

2.11 Case OR Decode ()

2.11.1 CASE
Case is similar to decode but easier to understand while going through coding Ex: SQL> Select sal, Case sal When 500 then ‘low’ When 5000 then ‘high’ Else ‘medium’ End case From emp;

Page 72 of 90

SAL ----500 2500 2000 3500 3000 5000 4000

CASE -------low medium medium medium medium high medium

2.11.2 Decode ()

SQL> Select sal, Decode( sal ,500 , ‘low’, 5000, ‘high’, ‘medium’) as sal From emp;

SQL>Select NAME, NO, Decode( address ,’’HYD , ‘Hyderabad’ ‘BANG,‘Bangulure’,address) as Address From emp;

2.12 Merge Statement

Page 73 of 90

You can use merge command to perform insert and update in a single command. Ex: Merge into student1 s1 Using (select * from student2) s2 On (s1.no=s2.no) When matched then Update set marks = s2.marks When not matched then Insert (s1.no, s1.name, s1.marks) s2.marks); Values (s2.no, s2.name,

2.13 Sub Queries, Co-Related Queries and EXISTS clause 2.13.1 SUB QUERIES If we write select statement in where clause that we called it as sub queries or inner queries. TYPES  Single row subqueries  Multi row subqueries  Correlated subqueries

2.13.1.1

SINGLE ROW SUBQUERIES

In single row subquery, it will return one value. Ex: SQL> select * from emp where sal > (select sal from emp where empno = 7566);
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO

Page 74 of 90

---------- ---------- --------- ---------- ------------ ------- ---------- ---------7788 7839 7902 SCOTT KING FORD ANALYST PRESIDENT ANALYST 7566 7566 19-APR-87 3000 20 10 20

17-NOV-81 5000 03-DEC-81 3000

2.13.1.2

MULTI ROW SUBQUERIES

In multi row subquery, it will return more than one value. In such cases we should include operators like any, all, in or not in between the comparision operator and the subquery. Ex: SQL> select * from emp where sal > any (select sal from emp where sal between 2500 and 4000);

EMPNO

ENAME

JOB

MGR

HIREDATE

SAL

COMM

DEPTNO

---------- ---------- --------- ---------- ----------7566 7788 7839 7902 JONES SCOTT KING FORD MANAGER ANALYST PRESIDENT ANALYST 7839 02-APR-81 7566 19-APR-87

-------- ---------- ---------2975 3000 5000 3000 20 20 10 20

17-NOV-81 7566 03-DEC-81

2.13.2 CORRELATED SUBQUERIES

A subquery is evaluated once for the entire parent statement where as a correlated subquery is evaluated once for every row processed by the

Page 75 of 90

parent statement. Ex: Find all employees who earn more than the average salary in their

department. SQL> SELECT last-named, salary, department_id FROM employees A WHERE salary > (SELECT AVG (salary) FROM employees B WHERE B.department_id =A.department_id Group by B.department_id) 2.13.3 EXISTS

The EXISTS operator tests for existence of rows in the results set of the subquery. SQL> Select dname from dept where exists (select 1 from EMP where dept.deptno= emp.deptno);

2.14 Views, Inline Views and Materialized Views

2.14.1 VIEWS

A view is a database object that is a logical representation of a table. It is delivered from a table but has no storage of its own. View will fetch the date from base table.It will run the Base query. A view takes the output of the query and treats it as a table TYPES  Simple view
Page 76 of 90

 Complex view Simple view can be created from one table where as complex view can be created from multiple tables. We can do DML on Simple view but not on Complex views. WHY VIEWS?  Provides additional level of security by restricting access to a predetermined set of rows and/or columns of a table. Ex: SQL> Create view dept_v as select *from dept; SQL> Create view dept_v as select deptno, sum(sal) t_sal from emp group by deptno; SQL> Select * from dept_v ; DROPPING VIEWS SQL> drop view dept_v; 2.14.2 INLINE VIEW If we write a select statement in from clause that is nothing but inline view. Ex: Get dept wise max sal along with empname and emp no. SQL> Select a.empname, a.empno, b.sal, b.deptno From EMP a, (Select max (sal) sal, deptno from EMP group by deptno) b Where a.sal=b.sal and a.deptno=b.deptno

SQL> Select ename, sal, rownum rank from (select *from emp order by sal);
Page 77 of 90

ENAME SMITH JAMES ADAMS WARD

SAL 800 950 1100 1250

RANK 1 2 3 4

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

2.14.3 MATERILIZED VIEW In DWH materialized views are very essential because in reporting side if we do aggregate calculations as per the business requirement report performance would be de graded. So to improve report performance rather than doing report calculations and joins at reporting side if we put same logic in the MV then we can directly select the data from MV without any joins and aggregations. We can also schedule MV (Materialize View).

Syntax: CREATE MATERIALIZED HWMD_MTH_ALL_METRICS_CURR_MV REFRESH COMPLETE START WITH sysdate NEXT TRUNC(SYSDATE+1)+ 4/24 WITH PRIMARY KEY AS Select * from HWMD_MTH_ALL_METRICS_CURR_VW; Another Method to refresh MV: DBMS_MVIEW.REFRESH('MV_COMPLEX', 'C'); Or we can use Informatica mapping to refresh Materialized views.

What is the difference between view and materialized view? View Materialized view
Page 78 of 90

A view has a logical existence. It does not contain data. We cannot perform DML operation on complex view. When we do select * from view it will fetch the data from base table. In view we cannot schedule to refresh.

A materialized view has a physical existence. We can perform DML operation on materialized view. When we do select * from materialized view it will fetch the data from materialized view. In materialized view we can schedule to refresh. We can keep aggregated data into materialized view. Materialized view mostly used for reporting purpose.

2.15 Indexes We can create indexes explicitly to speed up SQL statement execution on a table. The index points directly to the location of the rows containing the value. WHY INDEXES? Indexes are most useful on larger tables, on columns that are likely to appear in where clauses as simple equality. TYPES  Unique index  Non-unique index  Btree index  Bitmap index  Composite index  Function-based index  Cluster index

Page 79 of 90

2.15.1 UNIQUE INDEX Unique indexes guarantee that no two rows of a table have duplicate values in the columns that define the index. Unique index is automatically created when primary key or unique constraint is created. Ex: SQL> create unique index stud_ind on student(sno); 2.15.2 NON-UNIQUE INDEX Non-Unique indexes do not impose the above restriction on the column values. Ex: SQL> create index stud_ind on student(sno); 2.15.3 BTREE INDEX or ASCENDING INDEX The default type of index used in an oracle database is the btree index. A btree index is designed to provide both rapid access to individual rows and quick access to groups of rows within a range. The btree index does this by performing a succession of value comparisons. Each comparison eliminates many of the rows. Ex: SQL> create index stud_ind on student(sno); 2.15.4 BITMAP INDEX This can be used for low cardinality columns: that is columns in which the number of distinct values is snall when compared to the number of the rows in the table. Ex: SQL> create bitmap index stud_ind on student(sex);
Page 80 of 90

2.15.5 COMPOSITE INDEX A composite index also called a concatenated index is an index created on multiple columns of a table. Columns in a composite index can appear in any order and need not be adjacent columns of the table. Ex: SQL> create bitmap index stud_ind on student(sno, sname); 2.16 Query Tuning approach What is your tuning approach if SQL query taking long time? Or how do u tune SQL query? If query taking long time then we need to run the query in Explain Plan it will give us execution plan of the query like whether the query is using the relevant indexes on the joining columns or not . If joining columns doesn’t have index then it will do the full table scan if it is full table scan the cost will be more then we have to create the indexes on the joining columns and will run the query it should give better performance . And also needs to analyze the tables if analyzation happened long back. It may causes performance. The ANALYZE statement can be used to gather statistics for a specific table, index or cluster using ANALYZE TABLE employees COMPUTE STATISTICS; If still has performance issue then will use HINTS, hint is nothing but a clue. We can use hints in select statement like Use Hint to force using index SELECT /*+INDEX (TABLE_NAME INDEX_NAME) */ COL1,COL2 FROM TABLE_NAME

ALL_ROWS One of the hints that 'invokes' the Cost based optimizer ALL_ROWS is usually used for batch processing or data warehousing systems.

Page 81 of 90

Select /*+ ALL_ROWS */

FIRST_ROWS One of the hints that 'invokes' the Cost based optimizer FIRST_ROWS is usually used for OLTP systems.

(/*+ FIRST_ROWS */)

CHOOSE One of the hints that 'invokes' the Cost based optimizer This hint lets the server choose (between ALL_ROWS and FIRST_ROWS, based on statistics gathered. HASH Hashes one table (full scan) and creates a hash index for that table. Then hashes other table and uses hash index to find corresponding records. Therefore not suitable for < or > join conditions.

/*+ use_hash */ Select ( /*+ hash */ ) empno from

Hints are most useful to optimize the query performance. Why Hints Required? It is a perfect valid question to ask why hints should be used. Oracle comes with an optimizer that promises to optimize a query's execution plan. When this optimizer is really doing a good job, no hints should be required at all. Sometimes, however, the characteristics of the data in the database are changing rapidly, so that the optimizer (or more accuratly, its statistics) are out of date. In this case, a hint could help. You should first get the explain plan of your SQL and determine what changes can be done to make the code operate without using hints if possible. 2.17 Differences

2.17.1 ROWID & ROW_NUM

Rowid

Row-num

Page 82 of 90

Rowid is an oracle internal id that is allocated every time a new record is inserted in a table. This ID is unique and cannot be changed by the user. Rowid is permanent. Rowid is a globally unique identifier for a row in a database. It is created at the time the row is inserted into the table, and destroyed when it is removed from a table.

Row-num is a row number returned by a select statement.

Row-num is temporary. The row-num pseudocoloumn returns a number indicating the order in which oracle selects the row from a table or set of joined rows.

2.17.2 WHERE & HAVING Where clause Having clause

Both where and having clause can be used to filter the data. Where as in where clause it is not mandatory. Where clause applies to the individual rows. Where clause is used to restrict rows. Restrict normal query by where In where clause every record is filtered based on where. But having clause we need to use it with the group by. Where as having clause is used to test some condition on the group rather than on individual rows. But having clause is used to restrict groups. Restrict group by function by having In having clause it is with aggregate records (group by functions).

2.17.3 SUB QUERY & CO_RELATED SUB QUERY Sub-query A sub-query is executed once for the parent Query Co-related sub-query Where as co-related sub-query is executed once for each row of the

Page 83 of 90

parent query. Example: Select * from emp where deptno in (select deptno from dept); Example: Select a.* from emp e where sal >= (select avg(sal) from emp a where a.deptno=e.deptno group by a.deptno);

2.17.4 STORE PROCEDURE & FUNCTION Stored Procedure Stored procedure may or may not return values. Functions Function should return at least one output parameter. Can return more than one parameter using OUT argument. Function can be used to calculations But function is not a pre-compiled statement. Whereas function does not accept arguments. Functions are mainly used to compute values Can be invoked form SQL statements e.g. SELECT Cannot affect the state of database. Parsed and compiled at runtime.

Stored procedure can be used to solve the business logic. Stored procedure is a pre-compiled statement. Stored procedure accepts more than one argument. Stored procedures are mainly used to process the tasks. Cannot be invoked from SQL statements. E.g. SELECT Can affect the state of database using commit. Stored as a pseudo-code in database i.e. compiled form.

Page 84 of 90

2.17.5 Trigger & Procedure Triggers In trigger no need to execute manually. Triggers will be fired automatically. Triggers that run implicitly when an INSERT, UPDATE, or DELETE statement is issued against the associated table. Stored Procedures Where as in procedure we need to execute manually.

2.18 PL/SQL Basics 2.18.1 Store Procedure A stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database in compiled form so that it can be shared by a number of programs. Pprerequisites: Before creating a procedure, the user SYS must run a SQL script commonly called DBMSSTDX.SQL. The exact name and location of this script depend on your operating system. To create a procedure in your own schema, you must have the CREATE PROCEDURE system privilege. To create a procedure in another user's schema, you must have the CREATE ANY PROCEDURE system privilege. To replace a procedure in another schema, you must have the ALTER ANY PROCEDURE system privilege. SQL> CREATE OR REPLACE PROCEDURE delete_emp(empid_in IN NUMBER) IS BEGIN DELETE FROM emp WHERE empno = empid_in; Commit; END;

SQL>CREATE OR REPLACE PROCEDURE add_sp(a In NUMBER,

Page 85 of 90

b In Number, c Out Number) IS BEGIN c=a+b; DBMS_OUTPUT.PUT_LINE(c); END;

Packages: Packages provide a method of encapsulating related procedures, functions, and associated cursors and variables together as a unit in the database. package that contains several procedures and functions that process related to same transactions. A package is a group of related procedures and functions, together with the cursors and variables they use, Packages provide a method of encapsulating related procedures, functions, and associated cursors and variables together as a unit in the database.

2.18.2 Triggers: Oracle lets you define procedures called triggers that run implicitly when an INSERT, UPDATE, or DELETE statement is issued against the associated table Triggers are similar to stored procedures. A trigger stored in the database can include SQL and PL/SQL Types of Triggers This section describes the different types of triggers:
• •

Row Triggers and Statement Triggers BEFORE and AFTER Triggers

Page 86 of 90

• •

INSTEAD OF Triggers Triggers on System Events and User Events

Row Triggers A row trigger is fired each time the table is affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement. If a triggering statement affects no rows, a row trigger is not run. A statement trigger is fired once on behalf of the triggering statement, regardless of the number of rows in the table that the triggering statement affects, even if no rows are affected. For example, if a DELETE statement deletes several rows from a table, a statement-level DELETE trigger is fired only once. BEFORE and AFTER Triggers When defining a trigger, you can specify the trigger timing--whether the trigger action is to be run before or after the triggering statement. BEFORE and AFTER apply to both statement and row triggers. BEFORE and AFTER triggers fired by DML statements can be defined only on tables, not on views. CREATE OR REPLACE TRIGGER EMP_AUR

AFTER INSERT DECLARE BEGIN Delete from X; Commit; END;

ON EMP

2.19 IMPORTANT QUERIES 1. Get duplicate rows from the table: Select empno, count (*) from EMP group by empno having count (*)>1; 2. Remove duplicates in the table: Delete from EMP where rowid not in (select max (rowid) from EMP group

Page 87 of 90

by empno); 3. Below query transpose columns into rows. Name Abc Xyz No 100 200 Add1 Hyd Mysore Add2 bang pune

Select name, no, add1 from A UNION Select name, no, add2 from A; 4. Below query transpose rows into columns. select emp_id, max(decode(row_id,0,address))as address1, max(decode(row_id,1,address)) as address2, max(decode(row_id,2,address)) as address3 from (select emp_id,address,mod(rownum,3) row_id from temp order by emp_id ) group by emp_id Other query: select emp_id, max(decode(rank_id,1,address)) as add1, max(decode(rank_id,2,address)) as add2, max(decode(rank_id,3,address))as add3 from (select emp_id,address,rank() over (partition by emp_id order by emp_id,address )rank_id from temp )
Page 88 of 90

group by emp_id 5. Rank query: Select empno, ename, sal, r from (select empno, ename, sal, rank () over (order by sal desc) r from EMP); 6. Dense rank query: The DENSE_RANK function works acts like the RANK function except that it assigns consecutive ranks: Select empno, ename, Sal, from (select empno, ename, sal, dense_rank () over (order by sal desc) r from emp); 7. Top 5 salaries by using rank: Select empno, ename, sal,r from (select empno,ename,sal,dense_rank() over (order by sal desc) r from emp) where r<=5; Or Select * from (select * from EMP order by sal desc) where rownum<=5; 8. 2 nd highest Sal: Select empno, ename, sal, r from (select empno, ename, sal, dense_rank () over (order by sal desc) r from EMP) where r=2; 9. Top sal: Select * from EMP where sal= (select max (sal) from EMP); 10. How to display alternative rows in a table?

SQL> select *from emp where (rowid, 0) in (select rowid,mod(rownum,2) from emp); 11. Hierarchical queries

Starting at the root, walk from the top down, and eliminate employee Higgins in the result, but process the child rows. SELECT department_id, employee_id, last_name, job_id, salary FROM employees
Page 89 of 90

WHERE last_name! = ’Higgins’ START WITH manager_id IS NULL CONNECT BY PRIOR employee_id = menagerie;

You Have Successfully Completed Basic Oracle Training. ****** Best Of Luck******

Page 90 of 90

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.