0% found this document useful (0 votes)
6 views

Oracle Study

This document provides a comprehensive overview of Oracle SQL, including its purpose, structure, and various components such as DDL, DML, and TCL. It covers key concepts like data types, table creation, data manipulation, and querying techniques, making it suitable for beginners. Additionally, it addresses advanced topics like joins, subqueries, and PL/SQL basics.

Uploaded by

ashok1202
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Oracle Study

This document provides a comprehensive overview of Oracle SQL, including its purpose, structure, and various components such as DDL, DML, and TCL. It covers key concepts like data types, table creation, data manipulation, and querying techniques, making it suitable for beginners. Additionally, it addresses advanced topics like joins, subqueries, and PL/SQL basics.

Uploaded by

ashok1202
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 88

Oracle Material

Table of Contents

1 INTRODUCTION 3
1.1 Purpose 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) 21
2.2.6 DELETE (DML) 21
2.2.7 TRUNCATE (DDL) 22
2.2.8 DROP (DDL) 22
2.2.9 USING DDL 23
2.2.10 USING TCL 24
2.2.11 USING DCL 26
2.3 Synonym 27
2.4 Dblink 28
2.5 How to take Backup table data? 28
2.6 Aliases 29
2.7 Functions 30
2.7.1 SINGLE ROW FUNCTIONS 30
2.7.2 GROUP BY AND HAVING 55
2.8 Set Operators 57
2.8.1 UNION 57
2.8.2 UNION ALL 58
2.8.3 INTERSECT 58
2.8.4 MINUS 58
2.9 Constraints 58
2.9.1 NOT NULL 59
2.9.2 CHECK 60
2.9.3 UNIQUE 60
2.9.4 PRIMARY KEY 61
2.9.5 FOREIGN KEY 62

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

Detailed SQL DocumentAutomation of Candidate Extract and Load

Page 2 of 88
1 INTRODUCTION

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

2 ORACLE

2.1 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

Page 3 of 88
DRL -- select

TCL -- commit, rollback, save point

DCL -- grant, revoke

Oracle Data types:

Max Size:
Data types Description
Oracle 11g

Variable length character string


having maximum length size
4000 bytes
VARCHAR2(size) bytes.
minimum is 1
You must specify size. we can
use to store string values

The precision p can


NUMBER(p,s) Number having precision p and range from 1 to 38.
scale s. Which we can use to
store number values The scale s can range
from -84 to 127.

Valid date range. We can use to


DATE
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 88
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’,’MM-DD-


YYYY’));

To insert a new record again you have to type entire insert

Page 5 of 88
command, if there are lot of records this will be difficult.

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);

Page 6 of 88
Ex:

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 NAME address

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

1 sham hyd

2 mohan mpl

Page 7 of 88
SQL> select no, name, address from student;

NO NAME address

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

1 sham hyd

2 mohan mpl

SQL> select no, name from student;

NO NAME

--- -------

1 Sham

2 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
 Comparison operators

Page 8 of 88
 Logical operators
 Arithmetic operators -- highest precedence
+, -, *, /

 Comparison operators
 =, !=, >, <, >=, <=, <>
 between, not between
 in, not in
 null, not null
 like
 Logical operators
 And
 Or -- lowest precedence
 Not
a) USING =, >, <, >=, <=, !=, <>

Ex:

SQL> select * from student where DOJ = To_date (’01-23-2010’,’MM-


DD-YYYY’);

NO NAME MARKS

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

2 Saketh 200

2 Naren 400

SQL> select * from student where no < 2;

NO NAME MARKS

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

Page 9 of 88
1 Sudha 100

1 Jagan 300

SQL> select * from student where no > 2;

NO NAME MARKS

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

3 Ramesh

4 Madhu

5 Visu

6 Rattu

SQL> select * from student where no <= 2;

NO NAME MARKS

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

1 Sudha 100

2 Saketh 200

1 Jagan 300

2 Naren 400

SQL> select * from student where no >= 2;

NO NAME MARKS

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

2 Saketh 200

2 Naren 400

Page 10 of 88
3 Ramesh

4 Madhu

5 Visu

6 Rattu

SQL> select * from student where no != 2;

NO NAME MARKS

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

1 Sudha 100

1 Jagan 300

3 Ramesh

4 Madhu

SQL> select * from student where no <> 2;

NO NAME MARKS

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

1 Sudha 100

1 Jagan 300

3 Ramesh

4 Madhu

5 Visu

6 Rattu

b) USING AND

Page 11 of 88
This will gives the output when all the conditions become true.

Syntax:

Select * from <table_name> where <condition1> and <condition2>


and... <conditionn>;

Ex:

SQL> select * from student where no = 2 and marks >= 200;

NO NAME MARKS

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

2 Saketh 200

2 Naren 400

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... <conditionn>;

Ex:

SQL> select * from student where no = 2 or marks >= 200;

NO NAME MARKS

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

2 Saketh 200

1 Jagan 300

d) USING BETWEEN

Page 12 of 88
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 MARKS

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

2 Saketh 200

1 Jagan 300

2 Naren 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;

NO NAME MARKS

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

Page 13 of 88
1 Sudha 100

f) USING IN

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 MARKS

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

1 Sudha 100

2 Saketh 200

1 Jagan 300

2 Naren 400

3 Ramesh

g) USING NOT IN

This will gives the output based on the column which values are not in
the list of values specified.

Syntax:

Select * from <table_name> where <col> not in (value1, value2,


value3 … valuen);

Page 14 of 88
Ex:

SQL> select * from student where no not in (1, 2, 3);

NO NAME MARKS

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

4 Madhu

5 Visu

6 Rattu

h) USING NULL

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 MARKS

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

3 Ramesh

4 Madhu

5 Visu

6 Rattu

Page 15 of 88
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 MARKS

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

1 Sudha 100

2 Saketh 200

1 Jagan 300

2 Naren 400

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:

i) This will give the rows whose marks are 100.

SQL> select * from student where marks like 100;

NO NAME MARKS

Page 16 of 88
--- ------- ---------

1 Sudha 100

ii) This will give the rows whose name start with ‘S’.

SQL> select * from student where name like 'S%';

NO NAME MARKS

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

1 Sudha 100

2 Saketh 200

iii) This will give the rows whose name ends with ‘h’.

SQL> select * from student where name like '%h';

NO NAME MARKS

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

2 Saketh 200

3 Ramesh

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

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

2 Saketh 200

1 Jagan 300

Page 17 of 88
2 Naren 400

3 Ramesh

4 Madhu

6 Rattu

V) This will give the rows whose name’s third letter start with ‘d’.

SQL> select * from student where name like '__d%';

NO NAME MARKS

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

1 Sudha 100

4 Madhu

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 MARKS

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

2 Saketh 200

6 Rattu

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

SQL> select * from student where name like '%a%a%';

NO NAME MARKS

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

Page 18 of 88
1 Jagan 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 MARKS

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

1 Sudha 100

1 Jagan 300

2 Saketh 200

2 Naren 400

3 Ramesh

4 Madhu

SQL> select * from student order by no desc;

NO NAME MARKS

Page 19 of 88
--- ------- ---------

4 Madhu

3 Ramesh

2 Saketh 200

2 Naren 400

1 Sudha 100

1 Jagan 300

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

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.

Page 20 of 88
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:

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.

Page 21 of 88
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:

Alter table <table_name> drop column < col_name >;

Ex:

SQL> Alter table student drop column sdob;

c) INCREASING OR DECREASING PRECISION OF A COLUMN

Page 22 of 88
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:

SQL> Rename student to stud;

2.2.10 USING TCL

USING COMMIT

This will be used to save the work.

Page 23 of 88
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;

Or

Rollback or rollback work;

* While process is going on, if suddenly power goes then oracle will
rollback the transaction.

Page 24 of 88
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.

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;

Page 25 of 88
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; -- you can revoke


individual privilege

SQL> revoke select, insert on student from abc; -- you can revoke set
of privileges

SQL> revoke all on student from abc; -- you can revoke all privileges

2.3 Synonym
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
 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.

Page 26 of 88
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 *


from <old_table_name>;

Ex:

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

Page 27 of 88
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;

2.6 Aliases
COLUMN ALIASES

Syntax:

Select <orginal_col> <alias_name> from <table_name>;

Ex:

SQL> select no sno from student;

Page 28 of 88
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

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

Page 29 of 88
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) MOD(1,5) MOD(NULL,NULL) MOD(0,0) MOD(-7,4)

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

3 1 0 -3

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)

Ex:

SQL> select * from student; -- here for 3rd row marks value is null

NO NAME MARKS

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

1 a 100

2 b 200

3 c

SQL> select no, name, nvl(marks,300) from student;

Page 30 of 88
NO NAME NVL(MARKS,300)

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

1 a 100

2 b 200

3 c 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

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) :

Page 31 of 88
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
 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.

Page 32 of 88
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;

UPPER

-----------

COMPUTER

c) LOWER

This will convert the string into lowercase.

Syntax: lower (string)

Ex:

SQL> select lower('COMPUTER') from dual;

LOWER

-----------

Page 33 of 88
computer

d) LENGTH

This will give length of the string.

Syntax: length (string)

Ex:

SQL> select length('computer') from dual;

LENGTH

-----------

e) RPAD

This will allows you to pad the right side of a column with any set of
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.

Page 34 of 88
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:

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.

Page 35 of 88
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;

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(

Page 36 of 88
-----

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

------

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.

Page 37 of 88
Syntax: replace (string, old_chars [, new_chars])

Ex:

SQL> select replace('india','in','xy'), replace(‘india’,’in’) from dual;

REPLACE REPLACE

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

Xydia dia

m) CONCAT

This will be used to combine two strings only.

Syntax: concat (string1, string2)

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

Page 38 of 88
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')

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

97 97

o) CHR

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

-----

p) SUBSTR

This will be used to extract substrings.

Syntax: substr (string, start_chr_count [, no_of_chars])

Page 39 of 88
Ex:

SQL> select substr('computer',2), substr('computer',2,5),


substr('computer',3,7) from dual;

SUBSTR( SUBST SUBSTR

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

omputer omput mputer

q) INSTR

This will allows you for searching through a string for set of characters.

Syntax: instr (string, search_str [, start_chr_count [, occurrence] ])

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

Page 40 of 88
tests.

Syntax: decode (value, if1, then1, if2, then2, ……. else);

Ex:

SQL> select sal, decode(sal,500,'Low',5000,'High','Medium') from


emp;

SAL DECODE

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

500 Low

2500 Medium

2000 Medium

3500 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.

Page 41 of 88
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

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

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.

Page 42 of 88
2.7.1.1.3 DATE FUNCTIONS

Oracle default date format is DD-MON-YY.

 Sysdate
 Current_date
 Current_timestamp
 Systimestamp
 Localtimestamp
 Dbtimezone
 Sessiontimezone
 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

-----------

Page 43 of 88
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

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

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;

Page 44 of 88
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.

Syntax: to_char (date, format)

DATE FORMATS

D -- No of days in week

DD -- No of days in month

DDD -- No of days in year

MM -- No of month

MON -- Three letter abbreviation of month

MONTH -- Fully spelled out month

RM -- Roman numeral month

DY -- Three letter abbreviated day

DAY -- Fully spelled out day

Y -- Last one digit of the year

YY -- Last two digits of the year

YYY -- Last three digits of the year

Page 45 of 88
YYYY -- Full four digit year

SYYYY -- Signed year

I -- One digit year from ISO standard

IY -- Two digit year from ISO standard

IYY -- Three digit year from ISO standard

IYYY -- Four digit year from ISO standard

Y, YYY -- Year with comma

YEAR -- Fully spelled out year

CC -- Century

Q -- No of quarters

W -- No of weeks in month

WW -- No of weeks in year

IW -- No of weeks in year from ISO standard

HH -- Hours

MI -- Minutes

SS -- Seconds

FF -- Fractional seconds

AM or PM -- Displays AM or PM depending upon time of day

A.M or P.M -- Displays A.M or P.M depending upon time of day

AD or BC -- Displays AD or BC depending upon the date

A.D or B.C -- Displays AD or BC depending upon the date

Page 46 of 88
FM -- Prefix to month or day, suppresses padding of
month or day

TH -- Suffix to a number

SP -- suffix to a number to be spelled out

SPTH -- Suffix combination of TH and SP to be both spelled out

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)

Page 47 of 88
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

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

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

Page 48 of 88
 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)

Ex:

SQL> select months_between(to_date('11-aug-1990','dd-mon-yyyy'),


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','DD-MON-
YYYY'))

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

SQL> select months_between(to_date('11-jan-1990','dd-mon-


yyyy'), to_date('11-aug-1990','dd-mon-yyyy')) from dual;

MONTHS_BETWEEN(TO_DATE('11-JAN-1990','DD-MON-YYYY'),TO_DATE('11-AUG-1990','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;

Page 49 of 88
NEXT_DAY(

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

31-DEC-06

-- If the day parameter is null then it will display nothing.

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('11-


mar-90','dd-mon-yy'),to_date('11-apr-90','dd-mon-yy')) from dual;

GREATEST(

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

Page 50 of 88
11-APR-90

p) LEAST

This will give the least date.

Syntax: least (date1, date2, date3 … daten)

Ex:

SQL> select least(to_date('11-jan-90','dd-mon-yy'),to_date('11-mar-


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'),

Page 51 of 88
trunc(to_date('11-mar-06','dd-mon-yy'),'year') from dual;

TRUNC(TO_ TRUNC(TO_

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

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 01-JAN-04

2.7.1.2 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 ename sal r

100 A 5000 1

200 B 5000 1

300 C 4000 3

d) DENSE_RANK

Page 52 of 88
This will give the sequential ranking.

The DENSE_RANK function works acts like the RANK function except
that it assigns consecutive ranks:

EX:

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

Empno ename sal r

100 A 5000 1

200 B 5000 1

300 C 4000 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 8750

20 10875

30 9400

Page 53 of 88
SQL> select deptno,job,sum(sal) from emp group by deptno,job;

DEPTNO JOB SUM(SAL)

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

10 CLERK 1300

10 MANAGER 2450

10 PRESIDENT 5000

20 ANALYST 6000

20 CLERK 1900

20 MANAGER 2975

30 CLERK 950

30 MANAGER 2850

30 SALESMAN 5600

HAVING

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;

EMPNO NAME ADDRESS COUNT

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

Page 54 of 88
200 SHAM HYD 3

300 MOHAN BANG 2

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


having sum(sal) > 3000 order by job;

DEPTNO JOB TSAL

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

20 ANALYST 6000

10 PRESIDENT 5000

30 SALESMAN 5600

ORDER OF EXECUTION

 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.

Page 55 of 88
Ex:

SQL> select * from student1

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.

Page 56 of 88
Domain integrity constraints

 Not null
 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 -- along with the column definition


 TABLE LEVEL -- after the table definition
 Alter level -- 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));

Page 57 of 88
2.9.2 CHECK

This is used to insert the values based on specified condition.

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

Page 58 of 88
SQL> create table student(no number(2) unique, name varchar(10),
marks number(3));

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), marks number(3));

Page 59 of 88
TABLE LEVEL

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), Primary 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 foreign
key(deptno) references dept(deptno));

ALTER LEVEL

SQL> alter table emp add foreign key(deptno) references


dept(deptno);

Page 60 of 88
SQL> alter table emp add constraint fk foreign key(deptno)
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 foreign
key(deptno) references dept(deptno) on delete cascade);

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)

Page 61 of 88
references dept(deptno) on delete cascade;

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 62 of 88
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), dname varchar(10), constraint pk primary key(empno),
constraint fk foreign key(deptno,dname) references
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);

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
 Outer join

Page 63 of 88
 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 mkt hyd

20 fin bang

30 hr bombay

SQL> select * from emp;

EMPNO ENAME JOB MGR DEPTNO

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

111 saketh analyst 444 10

222 sudha clerk 333 20

333 jagan manager 111 10

444 madhu engineer 222 40

Page 64 of 88
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 saketh analyst mkt hyd

333 jagan manager mkt hyd

222 sudha clerk fin bang

USING CLAUSE

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


using(deptno);

EMPNO ENAME JOB DNAME LOC

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

111 saketh analyst mkt hyd

333 jagan manager mkt hyd

222 sudha clerk fin bang

ON CLAUSE

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

Page 65 of 88
on(e.deptno=d.deptno);

EMPNO ENAME JOB DNAME LOC

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

111 saketh analyst mkt hyd

333 jagan manager mkt hyd

222 sudha clerk fin bang

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 sudha clerk mkt hyd

444 madhu engineer mkt hyd

444 madhu engineer fin bang

444 madhu engineer hr bombay

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


e2 where e1.mgr=e2.empno;

Page 66 of 88
EMPNO ENAME JOB DEPTNO

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

111 jagan analyst 10

222 madhu clerk 40

333 sudha manager 20

444 saketh engineer 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 saketh analyst mkt hyd

333 jagan manager mkt hyd

222 sudha clerk fin 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 67 of 88
111 saketh analyst mkt hyd

222 sudha clerk mkt hyd

333 jagan manager mkt hyd

444 madhu engineer mkt hyd

111 saketh analyst fin bang

222 sudha clerk fin bang

333 jagan manager fin bang

444 madhu engineer fin bang

111 saketh analyst hr bombay

222 sudha clerk hr bombay

333 jagan manager hr bombay

444 madhu engineer hr 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


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

Or

Page 68 of 88
SQL> select empno,ename,job,dname,loc from emp e,dept d where

e.deptno=d.deptno(+);

EMPNO ENAME JOB DNAME LOC

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

111 saketh analyst mkt hyd

333 jagan manager mkt hyd

222 sudha clerk fin bang

444 madhu engineer

2.10.6.2 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

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

111 saketh analyst mkt hyd

333 jagan manager mkt hyd

Page 69 of 88
222 sudha clerk fin bang

hr 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 jagan manager mkt hyd

111 saketh analyst mkt hyd

222 sudha clerk fin bang

444 madhu engineer

Page 70 of 88
hr bombay

2.10.7 INNER JOIN

This will display all the records that have matched.

Ex:

SQL> select empno,ename,job,dname,loc from emp inner join dept


using(deptno);

EMPNO ENAME JOB DNAME LOC

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

111 saketh analyst mkt hyd

333 jagan manager mkt hyd

222 sudha clerk fin 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;

SAL CASE

Page 71 of 88
----- --------

500 low

2500 medium

2000 medium

3500 medium

3000 medium

5000 high

4000 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

You can use merge command to perform insert and update in a single
command.

Ex: Merge into student1 s1

Page 72 of 88
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) Values (s2.no, s2.name,


s2.marks);

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

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

7788 SCOTT ANALYST 7566 19-APR-87 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

Page 73 of 88
7902 FORD ANALYST 7566 03-DEC-81 3000 20

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 JONES MANAGER 7839 02-APR-81 2975 20

7788 SCOTT ANALYST 7566 19-APR-87 3000 20

7839 KING PRESIDENT 17-NOV-81 5000 10

7902 FORD ANALYST 7566 03-DEC-81 3000 20

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
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

Page 74 of 88
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
 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?

Page 75 of 88
 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);
ENAME SAL RANK
---------- ---------- ----------
SMITH 800 1
JAMES 950 2
ADAMS 1100 3
WARD 1250 4

Page 76 of 88
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

A view has a logical existence. It A materialized view has a physical


does not contain data. existence.

We cannot perform DML operation We can perform DML operation on


on complex view. materialized view.

When we do select * from view it When we do select * from


will fetch the data from base table. materialized view it will fetch the
data from materialized view.

Page 77 of 88
In view we cannot schedule to In materialized view we can
refresh. 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
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);

Page 78 of 88
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);

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);

Page 79 of 88
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.

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.

Page 80 of 88
 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

Rowid is an oracle internal id that Row-num is a row number


is allocated every time a new returned by a select statement.
record is inserted in a table. This
ID is unique and cannot be
changed by the user.

Rowid is permanent. Row-num is temporary.

Rowid is a globally unique The row-num pseudocoloumn


identifier for a row in a database. returns a number indicating the
It is created at the time the row order in which oracle selects the
is inserted into the table, and row from a table or set of joined

Page 81 of 88
destroyed when it is removed rows.
from a table.

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 But having clause we need to use


mandatory. it with the group by.

Where clause applies to the Where as having clause is used to


individual rows. test some condition on the group
rather than on individual rows.

Where clause is used to restrict But having clause is used to


rows. restrict groups.

Restrict normal query by where Restrict group by function by


having

In where clause every record is In having clause it is with


filtered based on where. aggregate records (group by
functions).

2.17.3 SUB QUERY & CO_RELATED SUB QUERY

Sub-query Co-related sub-query

A sub-query is executed once for Where as co-related sub-query is


the parent Query executed once for each row of the
parent query.

Example: Example:

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

Page 82 of 88
2.17.4 STORE PROCEDURE & FUNCTION

Stored Procedure Functions

Stored procedure may or may not Function should return at least one
return values. output parameter. Can return more
than one parameter using OUT
argument.

Stored procedure can be used to Function can be used to


solve the business logic. calculations

Stored procedure is a pre-compiled But function is not a pre-compiled


statement. statement.

Stored procedure accepts more Whereas function does not accept


than one argument. arguments.

Stored procedures are mainly used Functions are mainly used to


to process the tasks. compute values

Cannot be invoked from SQL Can be invoked form SQL


statements. E.g. SELECT statements e.g. SELECT

Can affect the state of database Cannot affect the state of database.
using commit.

Stored as a pseudo-code in Parsed and compiled at runtime.


database i.e. compiled form.

2.17.5 Trigger & Procedure

Triggers Stored Procedures

In trigger no need to execute Where as in procedure we need to


manually. Triggers will be fired execute manually.
automatically.

Triggers that run implicitly when an


INSERT, UPDATE, or DELETE
statement is issued against the
associated table.

Page 83 of 88
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,

b In Number,

c Out Number) IS

BEGIN

c=a+b;

DBMS_OUTPUT.PUT_LINE(c);

END;

Page 84 of 88
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

 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

Page 85 of 88
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 ON EMP

DECLARE

BEGIN

Delete from X;

Commit;

END;

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
by empno);

3. Below query transpose columns into rows.

Name No Add1 Add2

Abc 100 Hyd bang

Xyz 200 Mysore pune

Select name, no, add1 from A

UNION

Page 86 of 88
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 )

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);

Page 87 of 88
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

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 88 of 88

You might also like