Anda di halaman 1dari 79

Tutor on Oracle Structured Query Language

Page 1 of 79

Wipro Confidential

Preface.................................................................................................................................4
Audience..........................................................................................................................4
Organization.....................................................................................................................4
Introduction..........................................................................................................................4
SQL - Structured Query Language......................................................................................4
General Information.........................................................................................................4
Types of SQL:..................................................................................................................5
Data Types in Oracle........................................................................................................5
Oracle Operators:.............................................................................................................5
SQL*PLUS......................................................................................................................6
How to open SQL * PLUS?.........................................................................................6
How to edit the last executed query?...........................................................................6
How to create a table?......................................................................................................6
How to view the structure of the table?...........................................................................6
How to view the tables present in the logged in user area?.............................................7
How to insert the values to the table?..............................................................................7
How to view the records present in the table?...............................................................10
How to select only the records that we need?................................................................11
How to copy a table?.....................................................................................................13
How to copy the structure of a table alone?..................................................................14
Wild Cards.....................................................................................................................14
Built In Functions in SQL..............................................................................................15
Types..........................................................................................................................15
1. Number Function...............................................................................................17
2. Character Functions...........................................................................................20
3. Date Functions:..................................................................................................25
4. Conversion Function..........................................................................................25
5. Group Function..................................................................................................27
6. Environmental Function....................................................................................31
7. Special Functions...............................................................................................33
How to modify a record?...............................................................................................33
How to revert the changes?............................................................................................34
How to save the transactions?........................................................................................34
How to remove a record from the table?.......................................................................34
How to remove a particular record?..............................................................................35
How to modify the table structure?...............................................................................35
How to add a new field to the existing table?............................................................35
How to change the data type of an existing field?.....................................................36
How to increase or decrease the field size?...............................................................37
How to rename a table?.................................................................................................38
How to flush off the records in the table?......................................................................39
How to remove the table structure from the DB?..........................................................40
Constraints:....................................................................................................................40
How do I add a new constrain to an existing table?..................................................47
How do I remove an existing constraint?..................................................................49
Page 2 of 79

Wipro Confidential

Is it possible to disable or enable a constraint?..........................................................50


How to enable the constraint?....................................................................................51
How to set the name to the constraints?....................................................................51
Set Operators:................................................................................................................52
1. UNION ALL:.....................................................................................................52
2. UNION:.............................................................................................................52
3. INTERSECT......................................................................................................53
4. MINUS:.............................................................................................................53
Pseudo columns in Oracle:............................................................................................53
1. ROWID:.............................................................................................................53
2. ROWNUM:........................................................................................................54
3. LEVEL:..............................................................................................................55
4. CURRVAL and NEXTVAL...............................................................................58
Joins...............................................................................................................................58
1. Equi Join:...........................................................................................................59
2. Non Equi Joins:..................................................................................................60
3. Outer Joins:........................................................................................................61
Privileges:......................................................................................................................63
1. System privileges:..............................................................................................63
2. Object privileges................................................................................................67
Data Base Objects:.........................................................................................................69
1. View:..................................................................................................................69
2. Synonyms..........................................................................................................71
3. Sequence:...........................................................................................................72
4. Index:.................................................................................................................75
5. Cluster:...............................................................................................................76

Page 3 of 79

Wipro Confidential

ORACLE SQL TUTOR

Preface
This tutor contains a description of the Structured Query Language (SQL) used to
manage information in an Oracle database. Oracle SQL is a superset of the American
National Standards Institute (ANSI) and the International Standards Organization (ISO)
SQL99 standard.

Audience
The SQL tutor is intended for beginners and intermediate users of Oracle SQL.
Intermediate users can skip the elementary initial sections.

Organization
This SQL Tutor contains a lot of examples and important notes and I would
suggest the users of this guide to try out these examples as and when they go through the
sections.

Introduction
In 1979, Relational Software, Inc. (now Oracle Corporation) introduced the first
commercially available implementation of SQL. Today, SQL is accepted as the standard
RDBMS language. Structured Query Language (SQL) is the set of statements with which
all programs and users access data in an Oracle database.

SQL - Structured Query Language

It is used to interact with the RDBMS.


It is a fourth generation language.
It is a non procedural language.

General Information
Users in the database
Tables in the user
Records in the table
Columns in the table 7.x
Columns in the table 8.x
Default DATE FORMAT

No limit
No limit
No limit
256
1000
DD-MON-YY

A TABLE (ENTITY) consists of rows(records) and columns(fields)

Page 4 of 79

Wipro Confidential

Types of SQL:
Types
DDL (Data Definition Language)
DML (Data Manipulation Language)
DQL (Data Query Language)
TCL (Transaction Control Language)
DCL (Data Control Language)

Example
CREATE, ALTER, DROP, TRUNCATE,
RENAME
INSERT, UPDATE, DELETE
SELECT
COMMIT, ROLLBACK, SAVE POINT
GRANT, REVOKE

Data Types in Oracle


Version 7.X
NUMBER NUMBER(P,S) - P-PRECISION,S -SCALE
o NUMBER(8,2) - Total number of digits 8 with 2 decimal points
CHAR - Fixed length character.
VARCHAR
VARCHAR2 - Variable length character
DATE
RAW To store raw binary data.
LONG - To store the documents.
LONG RAW - 2GB - To store pictures.
Version 8.X
LOB- Large Objects
CLOB (Character Large Objects) - To store documents. (Maximum size is 4 GB)
BLOB (Binary Large Objects) - To store images. (Maximum size is 4 GB)
BFILE - Contains a locator to a large binary file stored outside the database.
(Maximum size is 4 GB)

Oracle Operators:
Type
Arithmetic
Logical
Relational
Set
Special
Address
Concatenation

Page 5 of 79

Operators
+
*
/
AND OR
NOT
<
<=
>
>=
=
<>
!=
UNION, UNION ALL, INTERSECT, MINUS
IS, IN, LIKE, BETWEEN
&
||

^=

Wipro Confidential

SQL*PLUS

It is an environment used to communicate with the database.


CL[EAR] SCR[EEN] - To clear the screen
EXIT - To exit SQL *PLUS

How to open SQL * PLUS?


Navigation
START->
PROGRAMS->
ORACLE FOR WIN95, NT--->SQL*-PLUS->CLICK
User Name & Password
USER NAME - SCOTT
PASS WORD - TIGER
(OR)
USERNAME - SCOTT/TIGER

How to edit the last executed query?


ED is used to edit the last executed query. Type ED in the sql prompt, the last
executed query will be opened in the notepad. Edit the query, save and close the
window. Now type / in the sql prompt to execute the modified query.

How to create a table?


Syntax:
>CREATE TABLE <TABLENAME> (COLNAME1 DATATYPE (SIZE),
COLNAME2 DATATYPE (SIZE),
.......... ............,
.......... ............);
It is a DDL command.
Example:
> CREATE TABLE DUMP1 (NO NUMBER (3), NA VARCHAR2 (20), DOB DATE);
>Table Created.

How to view the structure of the table?


Syntax:
>DESC[RIBE] <TABLE NAME>
It is a SQL plus command.
Example:
SQL>DESC DUMP1
Name
Null?
----------------- -----------Page 6 of 79

Type
------------Wipro Confidential

NO
NA
DOB

NUMBER(3)
VARCHAR2(20)
DATE

How to view the tables present in the logged in user area?


Example:
SQL>SELECT * FROM TAB;

How to insert the values to the table?


INSERT
Its a DML command.
Used to create a new row or record.
Types of Insert
Direct Insert
Specific Insert
Macros.
Direct Insert:
To create a new record we must give the values to all fields and we cant change
the order of the fields.
Syntax
INSERT INTO <tname> VALUES(v1,v2....);

Example
>INSERT INTO DUMP1 VALUES(1,'OCEAN','05-FEB-03');
>1 Row Created.

Note 1
If the fields data type is Char, Varchar2 or Date then we should specify the values
with in quotes.

Note 2
What if we change the order of the values say
>INSERT INTO DUMP1 VALUES('OCEAN',2,'05-FEB-03');
>Error: invalid number.

Note 3
What if we miss some values say
>INSERT INTO DUMP1 VALUES(2,'OCEAN');
>Error : not enough values

Note 4

Page 7 of 79

Wipro Confidential

What if we give extra values say


>INSERT INTO DUMP1 VALUES(2,'OCEAN','05-FEB-03',20);
>Error: too many values.

Note 5
What if we dont have a value for the DOB field?
We have to use the NULL Keyword.
How to put the Null value to a Field?
>INSERT INTO DUMP1 VALUES(2,'MADHU',NULL);
>1 Row Created.

Specific Insert
We can change the order of the fields.
We can also specify the columns for which we want to insert data.and the
remaining fields will be filled by the NULL value automatically.

Syntax
>INSERT INTO <tname>(fn1,..) VALUES(v1,...);

Example
>INSERT INTO DUMP1(NO,NA) VALUES(3,'SIVA');
>1 Row Created.
In this case the DOB field automatically filled with NULL value.
Note
The order of the selected fields must match exactly with the order of the values
provided and its data type.
o Example
INSERT INTO DUMP1(NO,NA) VALUES('HA',4);
*
Error: invalid number

o More values:
INSERT INTO DUMP1(NO,NA) VALUES(4,'DEMO',20);
*
Error : too many values
o Not enough values
INSERT INTO DUMP1(NO,NA) VALUES(4);
Error : not enough values.
Macros:
This is used to get input from the user. Address operator is used to accomplish it.
Types
1. Direct Macros
Page 8 of 79

Wipro Confidential

2. Specific Macros
Address Operator (&)
Used to get the value from the user and substitute it in the query.
1. Direct Macros:
We must give the values for all fields without changing the Order.
Syntax:
>INSERT INTO <tname> VALUES(&var1,...);
>Enter the value for var1 : val1
Output
old : INSERT INTO <tname> VALUES(&var1,...);
new : INSERT INTO <tname> VALUES(val1,...);
1 Row Created.
Example:
INSERT INTO DUMP1 VALUES(&V1,&V2,&V3);
Enter the value for v1 : 4
Enter the value for v2 : 'MATHEW'
Enter the value for v3 : '10-DEC-71'
old : INSERT INTO DUMP1 VALUES(&V1,&V2,&V3);
new : INSERT INTO DUMP1 VALUES(4,'MATHEW','10-DEC-71');
1 Row Created.
NOTE: To run the last executed query type / in the prompt.
SQL> /
Enter the value for v1 : 5
Enter the value for v2 : 'BADHU'
Enter the value for v3 : '10-DEC-91'
old : INSERT INTO DUMP1 VALUES(&V1,&V2,&V3);
new : INSERT INTO DUMP1 VALUES(5,'BADHU','10-DEC-81');
1 Row Created.
By this way we can insert n number of records easily. You can notice that
when we enter values for date and varchar fields (v3 and v2) we enter the
values within single quote each time but this can be avoided if we give the
single quote in the insert statement itself as follows.
INSERT INTO DUMP1 VALUES(&V1,'&V2','&V3');
SQL>/
Enter the value for v1 : 6
Enter the value for v2 : RAVI
Enter the value for v3 : 10-DEC-81
old : INSERT INTO DUMP1 VALUES(6,'RAVI','10-DEC-81');
Page 9 of 79

Wipro Confidential

1 Row Created.
2. Specific Macros
We can select the fields for which we are going to insert values and the
other fields will be inserted with NULL value automatically (If the omitted
field is not a NOTNULL field).
Syntax:
INSERT INTO <tname>(fn1,...) VALUES(&v1,..);
Enter the value for V1 : val1
old : INSERT INTO <tname>(fn1,...) VALUES(&v1,..);
new : INSERT INTO <tname>(fn1,...) VALUES(val1,..);
1 Row Created.
Example
>INSERT INTO DUMP1(NO,NA) VALUES(&V1,'&V2');
Enter the value for v1 : 6
Enter the value for v2 : RAVI
>1 Row Created.

How to view the records present in the table?


SELECT:
Its a DQL statement which is a part of DML statement.
Used to select the value from the object.
Syntax:
SELECT { * / fn1,... } FROM <tname> [WHERE condition];
N Rows Selected.
Example
SELECT * FROM DUMP1;
SELECT NA,NO,DOB FROM DUMP1;
SELECT DOB FROM DUMP1;
Column Alias
We can use a column alias to label the preceding expression in the select list,
so that the column is displayed with a new heading. The alias effectively renames
the select list item for the duration of the query.
Syntax:
SELECT fieldname aliasname,... FROM <tname>;
Or
SELECT fieldname "aliasname",... FROM <tname>...;
Or
SELECT fieldname AS aliasname ,... FROM <tname>...;
Examples
Page 10 of 79

Wipro Confidential

>SELECT NO "STUDENT_NUMBER",NA "STUDENT_NAME" FROM


DUMP1;
>SELECT NO AS STUDENT_NUMBER,NA AS STUDENT_NAME FROM
DUMP1;
>SELECT NO STUDENT_NUMBER,NA STUDENT_NAME FROM DUMP1;
>SELECT NO student_number FROM DUMP1;
>SELECT NO AS student_number FROM DUMP1;
>SELECT NO "student_number" FROM DUMP1;
Note:
The alias can be used in the ORDER BY clause, but not other clauses in
the query.

How to select only the records that we need?


SELECT * FROM DUMP1;
This query will return all the records in the table. What if we want to retrieve only
records which belong to Employee Number 5? We need to add a WHERE clause to the
query to retrieve records accordingly.
WHERE Clause:
Used to fetch the required records alone from the database.
Syntax:
WHERE fieldname OPERATOR value
Note:
If the fields data type is Char, Varchar2, Date we have to specify the value
with in the '' (single quote).
Example:
1) Records with NO = 5
SELECT * FROM DUMP1 WHERE NO = 5;
2) Records with NA = RAVI
SELECT * FROM DUMP1 WHERE NA = 'Ravi';
No Rows Selected.
Note:
Data stored in database is case sensitive. If you dont give the values in
proper case then the values will not be fetched.
SELECT * FROM DUMP1 WHERE NA = 'RAVI';
3)
DESC EMP
Name
Page 11 of 79

Null?

Type
Wipro Confidential

------------------------------EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO

-------NOT NULL

-----NUMBER(4)
VARCHAR2(10)
VARCHAR2(9)
NUMBER(4)
DATE
NUMBER(7,2)
NUMBER(7,2)
NUMBER(2)

SELECT * FROM EMP;


List all employees working in DEPTNO 20.
SELECT * FROM EMP WHERE DEPTNO = 20;
List all employees working as a MANAGER.
SELECT * FROM EMP WHERE JOB = 'MANAGER';
List all employees working in department number 10 and as a
MANAGER.
SELECT * FROM EMP WHERE DEPTNO = 10 AND JOB =
'MANAGER';
Note:
Logical Operators:

Page 12 of 79

Condition

Operation

Example

NOT

Returns TRUE if the


following
condition is FALSE.
Returns
FALSE if it is TRUE. If it is
UNKNOWN, it remains
UNKNOWN.

SELECT *
FROM employees
WHERE NOT (job_id IS
NULL);
SELECT *
FROM employees
WHERE NOT
(salary BETWEEN 1000
AND 2000);

AND

Returns TRUE if both


component conditions are
TRUE. Returns FALSE if
either
is FALSE. Otherwise
returns
UNKNOWN.

SELECT *
FROM employees
WHERE job_id =
PU_CLERK
AND department_id = 30;

OR

Returns TRUE if either

SELECT *
Wipro Confidential

component condition is
TRUE.
Returns FALSE if both are
FALSE. Otherwise returns
UNKNOWN.

FROM employees
WHERE job_id =
PU_CLERK
OR department_id = 10;

List all employees working in department number 10,20 and his salary is
less than his commission.
SELECT * FROM EMP WHERE DEPTNO = 10 OR DEPTNO=20 AND
SAL < COMM;
List all employees who are not getting any commission.
SELECT * FROM EMP WHERE COMM = NULL;
No Rows Selected.
The above query will return No Rows Selected even if the value for
commission is null. This is because we cannot use equal-to operator to
check for null values. We need to use IS which is a special relational
operator to check for null values.
Correct Query
SELECT * FROM EMP WHERE COMM IS NULL;
List all employees who are getting commission.
SELECT * FROM EMP WHERE COMM IS NOT NULL;
List all employees in department number 10,20,30 and whose job is either
CLERK or MANAGER..
SELECT * FROM EMP WHERE (DEPTNO = 10 OR DEPTNO = 20 OR
DEPTNO = 30) AND (JOB = 'CLERK' OR JOB = 'MANAGER');
We can simplify the above query by using IN operator.
Syntax:
Fieldname IN(v1,...)
SELECT * FROM EMP WHERE DEPTNO IN (10,20,30) AND
JOB IN ('MANAGER','CLERK');
List all employees who are getting Salary greater than 2000 and less than
3000
SELECT * FROM EMP WHERE SAL>2000 and SAL<3000;
(OR)
SELECT * FROM EMP WHERE SAL BETWEEN 2001 AND 2999;

How to copy a table?


Syntax:
Page 13 of 79

Wipro Confidential

CREATE TABLE <tname> AS query;


Table created
Example:
CREATE TABLE MUNI AS SELECT * FROM EMP;
Table Created.
SELECT * FROM MUNI;
14 rows selected
This way we can get the exact backup of a table and its data.

How to copy the structure of a table alone?


We can accomplish this by just giving a condition that will return 0 records as
below.
Example:
CREATE TABLE MUNI1 AS SELECT * FROM EMP WHERE 1 = 2;
Table Created.
SELECT * FROM MUNI1;
NO Rows selected.

Wild Cards
In DOS:
DIR
Select all Dir / Files in current directory.
Dir *.txt
Select all .txt extension file from the current directory.
Dir p*.txt
Select the all .txt files starting with letter P.
Dir *p.txt
Select the all .txt files ending with letter P.
Dir ?p*.txt
Select the all .txt files with second letter as P.
Dir *p*.txt
Select the all .txt files containing letter P.
*
?
Page 14 of 79

Represents any number of characters.


Represents single Character.
Wipro Confidential

These characters are called Wild Card Characters (WCC).


In ORACLE:
%
_

Represents any number of characters.


Represents single Character.

Examples:
List all employees whose name starts with A.
SELECT * FROM EMP WHERE ENAME = 'A%';
No Rows Selected.
The above query will return No Rows Selected even if the there are
employees whose name starts with A. This is because we cannot use
equal-to operator when we are using wild card characters. We need to use
LIKE which is a special relational operator.
Correct Query
SELECT * FROM EMP WHERE ENAME LIKE 'A%';
List all employees whose name ends with N.
SELECT * FROM EMP WHERE ENAME LIKE '%N';
List all employees whose name has A as the second letter.
SELECT * FROM EMP WHERE ENAME LIKE '_A%';
List all employees whose name contains letter A.
SELECT * FROM EMP WHERE ENAME LIKE '%A%';
Exercise:
List all employees whose name contains letter A only once. (Eg. If there is
a employee called ADAMS then it should not be listed).
Answer:
SELECT * FROM EMP WHERE ENAME LIKE '%A%' AND ENAME
NOT LIKE '%A%A%';

Built In Functions in SQL


Types
1. Number Function
2. Character Function
3. Date Function
4. Conversion Function
5. Group Function
6. Environmental Function.
Page 15 of 79

Wipro Confidential

1. Number Function
abs

trunc

sign sin

cosh atan

ceil

mod

ln

cos

tanh

floor

sqrt

log

tan

asin

round power exp

sinh acos

2. Char Function
2 Types
A) Character function returning character value.
B) Character function returning numeric value.
1. Character function returning character value.
chr

ltrim initcap

soundex

concat rtrim substr


lower

lpad

replace

upper

rpad

translate

2. Character function returning numeric value.


ascii
length
instr
3. Date Function
sysdate
add_months
Page 16 of 79

Wipro Confidential

next_day
last_day
months_between
4. Conversion Function
to_char
to_number
to_date
5. Group Function
count
sum
avg
min
max
stddev
variance
6. Environmental Function
user
uid
userenv

least
greatest
nvl

7. Special Function
decode
vsize
Selecting from the DUAL Table
DUAL is a table automatically created by Oracle along with the data dictionary.
DUAL is in the schema of the user SYS, but is accessible by the name DUAL to
all users. It has one column, DUMMY, defined to be VARCHAR2(1), and
contains one row with a value X. Selecting from the DUAL table is useful for
computing a constant expression with the SELECT statement. Because DUAL has
only one row, the constant is returned only once. Alternatively, you can select a
constant, pseudo column, or expression from any table, but the value will be
returned as many times as there are rows in the table.

1.

Number Function
abs(x)
ABS returns the absolute value of n.

Page 17 of 79

Wipro Confidential

SELECT ABS(10.2) FROM DUAL;


10.2
SELECT ABS(-10.2) FROM DUAL;
10.2
SELECT ABS(-10.2) FROM EMP;
Note:
The above query will return 10.2 n times where n is the number of records in
the EMP table.
ceil(x)
CEIL returns smallest integer greater than or equal to n.
SELECT CEIL(10.00000000000001) FROM DUAL;
11
floor(x)
FLOOR returns largest integer equal to or less than n.
SELECT FLOOR(10.99999999999) FROM DUAL;
10
round(number,integer)
ROUND returns number rounded to integer places right of the decimal point. If
integer is omitted, number is rounded to 0 places. Integer can be negative to round
off digits left of the decimal point. Integer must be an integer.
SELECT ROUND(10.5) FROM DUAL;
11
SELECT ROUND(10.4) FROM DUAL;
10
SELECT ROUND(15.193,1) "Round" FROM DUAL;
Round
---------15.2
SELECT ROUND(15.193,-1) "Round" FROM DUAL;
Round
---------20
trunc(n,m)
Page 18 of 79

Wipro Confidential

TRUNC returns n truncated to m decimal places. If m is omitted, n is truncated to


0 places. m can be negative to truncate (make zero) m digits left of the decimal
point.
SELECT TRUNC(10.566) FROM DUAL;
10
SELECT TRUNC(10.4356789,2) FROM DUAL;
10.43
SELECT TRUNC(15.79,-1) "Truncate" FROM DUAL;
Truncate
---------10
mod(m,n)
MOD returns the remainder of m divided by n. Returns m if n is 0.
SELECT MOD(10,4) FROM DUAL;
2
SELECT MOD(3,9) FROM DUAL;
3
power(x,y)
POWER returns m raised to the nth power. The base m and the exponent n can be
anynumbers, but if m is negative, n must be an integer.
SELECT POWER(2,3) FROM DUAL;
8
sign(x)
Number Type
Positive Number
Negative Number
Zero

Return Value
1
-1
0

SELECT SIGN(10) FROM DUAL;


1
SELECT SIGN(-10) FROM DUAL;
-1
SELECT SIGN(0) FROM DUAL;
0
Page 19 of 79

Wipro Confidential

exp(n)
EXP returns e raised to the nth power, where e = 2.71828183 ...
SELECT EXP(0) FROM DUAL;
1
ln(n)
LN returns the natural logarithm of n, where n is greater than 0.
SELECT LN(10) FROM DUAL;
2.30258509
log(m,n)
LOG returns the logarithm, base m, of n. The base m can be any positive number
other than 0 or 1 and n can be any positive number.
SELECT LOG(10,1000) FROM DUAL;
3

2.

Character Functions
I. Character function returning character value.
chr('number')
Chr returns the character value for the ASCII number entered.
SELECT CHR('65') FROM DUAL;
A
SELECT CHR('97') FROM DUAL;
a
SELECT CHR('3') FROM DUAL;
"
SELECT CHR('39') FROM DUAL;
'
concat(String1,String2)
This is used to concatenate strings.
SELECT CONCAT('Wipro','Technologies') FROM DUAL;
WiproTechnologies
SELECT CONCAT(ENAME,JOB) FROM EMP;
Concatenation Operator ( || )

Page 20 of 79

Wipro Confidential

This is also used to concatenate strings.


SELECT ENAME || JOB FROM EMP;
SELECT ENAME || ' ' || JOB FROM EMP;
SELECT ENAME || ' IS A ' || JOB FROM EMP;
SELECT CONCAT(ENAME || ' IS A ' ,JOB) FROM EMP;
Exercise:
Dont use the Concatenation Operator || In the above query and get the
same output.
Answer:
SELECT CONCAT(CONCAT(ENAME,' IS A ' ),JOB) FROM EMP;
lower(string)
This returns the lower case of the string.
SELECT LOWER('RAVINDRAN') FROM DUAL;
ravindran
upper(string)
This returns the upper case of the string.
SELECT UPPER('ravindran') FROM DUAL;
RAVINDRAN
initcap(String)
This returns the string with first letter of the words as capital ones.
SELECT INITCAP('THIS IS MY DEMO TO STUDENTS') FROM
DUAL;
This Is My Demo To Students
ltrim(String)
This is used to remove spaces in the left side of the string.
SELECT ' WIPRO' FROM DUAL;
WIPRO
SELECT LTRIM(' WIPRO ') FROM DUAL;
WIPRO
rtrim(String)
This is used to remove spaces in the right side of the string.
SELECT 'WIPRO ' FROM DUAL;
Page 21 of 79

Wipro Confidential

WIPRO
SELECT RTRIM('WIPRO
WIPRO

') FROM DUAL;

lpad(char1,n,char2)
This is used for reporting purpose to format the values.
LPAD returns char1, left-padded to length n with the sequence of
characters in char2; char2 defaults to a single blank. If char1 is longer than
n, this function returns the portion of char1 that fits in n. Both char1 and
char2 can be any of the datatypes CHAR, VARCHAR2, NCHAR,
NVARCHAR2, CLOB, or NCLOB. The string returned is of VARCHAR2
datatype and is in the same character set as char1. The argument n is the
total length of the return value as it is displayed on your terminal screen.
In most character sets, this is also the number of characters in the return
value. However, in some multibyte character sets, the display length of a
character string can differ from the number of characters in the string.
SELECT LPAD('ABCDE',10,'*') FROM DUAL;
*****ABCDE
SELECT LPAD(Page 1,15,*.) "LPAD example"
FROM DUAL;
LPAD example
--------------*.*.*.*.*Page 1
rpad(char1,n,char2)
RPAD returns char1, right-padded to length n with char2, replicated as
many times as necessary; char2 defaults to a single blank. If char1 is
longer than n, this function returns the portion of char1 that fits in n. Both
char1 and char2 can be any of the data types CHAR, VARCHAR2,
NCHAR, NVARCHAR2, CLOB, or NCLOB. The string returned is of
VARCHAR2 data type and is in the same character set as char1. The
argument n is the total length of the return value as it is displayed on your
terminal screen. In most character sets, this is also the number of
characters in the return value. However, in some multi byte character sets,
the display length of a character string can differ from the number of
characters in the string.
SELECT RPAD('ABCDE',10,'*') FROM DUAL;
ABCDE*****
Exercise:
***ABCDE***
Answer:
Page 22 of 79

Wipro Confidential

select rpad(lpad('ABCDE',8,'*'),11,*) from dual;


substr(String,start[,length])
Used to get a part of a string.
SELECT SUBSTR('THIS IS DEMO',1,4) FROM DUAL;
THIS
SELECT SUBSTR('THIS IS DEMO',6) FROM DUAL;
IS DEMO
SELECT SUBSTR('THIS IS DEMO',6,2) FROM DUAL;
IS
replace(char, Search_string, Replacement_string)
REPLACE returns char with every occurrence of search string replaced
with replacement string. If replacement string is omitted or null, all
occurrences of search string are removed. If search string is null, char is
returned.
Search string and replacement string, as well as char, can be any of the
data type CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or
NCLOB. The string returned is of VARCHAR2 data type and is in the
same character set as char.
The following example replaces occurrences of "J" with "BL":
SELECT REPLACE (JACK and JUE,J,BL) "Changes"
FROM DUAL;
Changes
-------------BLACK and BLUE
SELECT REPLACE ('THIS IS DEMO','S','*') FROM DUAL;
THI* I* DEMO
translate(String,Search Char , replace char)
SELECT TRANSLATE('THIS IS DEMO','S','*') FROM DUAL;
THI* I* DEMO
SELECT TRANSLATE('THIS IS DEMO','SI','*%') FROM DUAL;
TH%* %* FRMO
soundex()

Page 23 of 79

Wipro Confidential

SOUNDEX returns a character string containing the phonetic


representation of char. This function lets you compare words that are
spelled differently, but sound alike in English.
SELECT * FROM EMP WHERE SOUNDEX(ENAME) =
SOUNDEX('SMITHY');
SELECT * FROM EMP WHERE SOUNDEX(ENAME) =
SOUNDEX('CLERK');
II. Chacter function returning numeric value:
ascii()
This returns the ASCII value of the character.
SELECT ASCII('A') FROM DUAL;
65
SELECT ASCII('a') FROM DUAL;
97
length()
This function returns the length of the given string
SELECT LENGTH('ABCDE') FROM DUAL;
5
instr(String,Search String,Start[,Occurance])
This function returns the position of the search string in the searched
string.
SELECT INSTR('THIS IS DEMO','IS') FROM DUAL;
3
In the below case the search starts from the 4th character of the source
string.
SELECT INSTR('THIS IS DEMO','IS',4) FROM DUAL;
6
In the below case the search starts from the 1st character of the source
string but the 2nd occurrence of IS is returned.
SELECT INSTR('THIS IS DEMO','IS',1,2) FROM DUAL;
6
SELECT INSTR('THIS IS DEMO IS','IS',1,3) FROM DUAL;
14
Exercise:
Page 24 of 79

Wipro Confidential

Without using the occurrence parameter find the second


occurrence of IS in the string 'THIS IS DEMO
Answer:
SELECT INSTR('THIS IS DEMO',IS,INSTR('THIS IS DEMO','IS')+1)
FROM DUAL;

3.

Date Functions:
Sysdate:
This function returns the current system date.
SELECT SYSDATE FROM DUAL;
23-JUL-03
last_day(date)
This function returns the last date of that month.
SELECT LAST_DAY(SYSDATE) FROM DUAL;
31-JUL-03
add_months(date,number)
This function adds the number of months specified to the given date.
SELECT ADD_MONTHS(SYSDATE,3) FROM DUAL;
10-FEB-06
next_day(Date,DayOfTheWeek)
This function returns the date of the first weekday named by DayOfTheWeek
that is later than the date Date.
SELECT NEXT_DAY(SYSDATE,'FRIDAY') FROM DUAL;
months_between(date1, date2)
MONTHS_BETWEEN returns number of months between dates date1 and date2.
If date1 is later than date2, result is positive; if earlier, negative. If date1 and date2
are either the same days of the month or both last days of months, the result is
always an integer. Otherwise Oracle calculates the fractional portion of the result
based on a 31-day month and considers the difference in time components date1
and date2.
SELECT MONTHS_BETWEEN(SYSDATE,'23-JAN-03') FROM DUAL;

4.

Conversion Function

To_Char()
It is a conversion function used to convert the date into the desired format.
Syntax:
Page 25 of 79
Wipro Confidential

TO_CHAR(DATE,'Format')
Format:
DD-MON-YY
DD
D
Day
DDTH
DDSP
MM
MONTH
MMSP
YYY
YYYY
HH:MI:SS
Example:
SELECT TO_CHAR(SYSDATE,'DD-MON-YY') FROM DUAL;
10-NOV-05
SELECT TO_CHAR(SYSDATE,'DD-MONTH-YY') FROM DUAL;
10-NOVEMBER -05
SELECT TO_CHAR(SYSDATE,'DD-MONTH-YYYY') FROM DUAL;
10-NOVEMBER -2005
SELECT TO_CHAR(SYSDATE,'DD') FROM DUAL;
10
SELECT TO_CHAR(SYSDATE,'D') FROM DUAL;
5
SELECT TO_CHAR(SYSDATE,'DAY') FROM DUAL;
THURSDAY
SELECT TO_CHAR(SYSDATE,'DDSP-MONTH-YYYY') FROM
DUAL;
TEN-NOVEMBER -2005
SELECT TO_CHAR(SYSDATE,'HH:MI:SS') FROM DUAL;
02:48:59
SELECT TO_CHAR(SYSDATE,'MM') FROM DUAL;
11
SELECT TO_CHAR( HIREDATE,'MONTH') FROM EMP;
Page 26 of 79

Wipro Confidential

Exercise:
List all employees hired in the month of april.
Answer:
SELECT * from emp where
trim(TO_CHAR( HIREDATE,'MONTH')) = 'APRIL'
(OR)
SELECT * from emp where TO_CHAR( HIREDATE,'MM')=4

5.

Group Function
count()
COUNT returns the number of rows in the query.
Example:
SELECT COUNT (EMPNO) FROM EMP;
14
SELECT COUNT (COMM) FROM EMP;
4
Note:
As shown above COUNT () does not take into account NULL values.
SELECT COUNT (*) FROM EMP;
14
sum()
This function returns the summation for that group.
SELECT SUM (SAL) FROM EMP;
29025
avg()
This function returns the average for that group.
SELECT AVG (SAL) FROM EMP;
min()
This function returns the minimum value in that group.
SELECT MIN (SAL) FROM EMP;
800
max()
This function returns the maximum value in that group.
SELECT MAX (SAL) FROM EMP;
5000

stddev()
This function returns the Standard Deviation.
SELECT STDDEV (SAL) FROM EMP;
Page 27 of 79

Wipro Confidential

variance()
This function returns the variance value.
SELECT VARIANCE(SAL) FROM EMP;
SELECT SQRT(VARIANCE(SAL)) FROM EMP;

Group by caluse:
This clause is used to show repeated values only once.
Syntax:
GROUP BY <fieldname>
SELECT { fn1,gf(fn),.. } FROM <tname> [WHERE clause]
[GROUP BY clause[HAVING clause]] [ORDER BY clause];
SELECT DEPTNO FROM EMP GROUP BY DEPTNO;
Note:
The column in the group by clause is ordered by ascending automatically.
SELECT COUNT(*) FROM EMP GROUP BY DEPTNO;
SELECT COUNT(*),DEPTNO FROM EMP GROUP BY DEPTNO;
SELECT SUM(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;
SELECT MIN(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;
SELECT JOB FROM EMP;
14 Rows Selected.
SELECT JOB FROM EMP GROUP BY JOB;
5 Rows Selected.
Exercise:
Group the employees by their nature of job and display Job, Sum (Sal),
Avg (Sal), Min (Sal)
Answer:
SELECT JOB, SUM (SAL), AVG (SAL), MIN(SAL) FROM EMP
GROUP BY JOB;
Exercise:
Page 28 of 79

Wipro Confidential

Find the total salary paid to the employees of each department.


Answer:
SELECT SUM(SAL),DEPTNO FROM EMP GROUP BY DEPTNO;
Wrong ways of writing the query:
SELECT SUM(SAL),DEPTNO FROM EMP;
*
Error : not a single-group group function.
SELECT SUM(SAL),DEPTNO FROM EMP GROUP BY JOB;
Error: not a Group by Expression.
Exercise:
Fetch the employee details for the employee who is getting the maximum
salary.
Answer:
SELECT * FROM EMP WHERE SAL = MAX(SAL);
*
Error: Group Functions Not Allowed Here.
Note:
We cant use group functions in the WHERE clause. Hence
Step 1:
SELECT MAX (SAL) FROM EMP;
5000
Step 2:
SELECT * FROM EMP WHERE SAL = 5000;
To get the desired result we need to execute 2 different queries as
shown above. We can merge the two queries as shown below.
SELECT * FROM EMP WHERE SAL = (SELECT MAX(SAL)
FROM EMP);
Exercise:
Fetch the employee details for the employee who is getting the maximum
salary.
Answer:
SELECT * FROM EMP WHERE SAL = (SELECT MIN(SAL) FROM
EMP);
Exercise:
Fetch the second maximum salary.
Answer:
Step 1:
SELECT MAX (SAL) FROM EMP;
5000
Page 29 of 79

Wipro Confidential

Step 2:
SELECT MAX (SAL) FROM EMP WHERE SAL < 5000;
3000
Final Query:
SELECT MAX(SAL) FROM EMP WHERE SAL < (SELECT
MAX(SAL) FROM EMP);
3000
Exercise:
Fetch the employee details for the employee who is getting the second
minimum salary.
Answer:
SELECT * FROM EMP WHERE SAL=(SELECT MIN(SAL) FROM
EMP WHERE SAL > (SELECT MIN(SAL) FROM EMP));
950
Exercise:
Fetch the employee details for the employees having the longest name.
Answer:
SELECT * FROM EMP WHERE LENGTH(ENAME) = (SELECT
MAX(LENGTH(ENAME)) FROM EMP);
Exercise:
Fetch the employee details for the employees having the second longest
name.
Answer:
SELECT * FROM EMP WHERE LENGTH(ENAME)=(SELECT
MAX(LENGTH(ENAME)) FROM EMP WHERE LENGTH(ENAME) <
(SELECT MAX(LENGTH(ENAME)) FROM EMP));
Exercise:
Fetch the employee details for the employees having the second shortest
name.
Answer:
SELECT * FROM EMP WHERE LENGTH(ENAME)=(SELECT
MIN(LENGTH(ENAME)) FROM EMP WHERE LENGTH(ENAME) >
(SELECT MIN(LENGTH(ENAME)) FROM EMP));
Exercise:
Fetch the third minimum salary paid to the employees.
Answer:
SELECT MIN(SAL) FROM EMP WHERE SAL > (SELECT MIN(SAL)
FROM EMP WHERE SAL>(SELECT MIN(SAL) FROM EMP))
Page 30 of 79

Wipro Confidential

Note:
Maximum number of sub queries in a query is 255.
Using Where clause and Group By clause in a query
Example:
Fetch the total amount of salary paid to the employees in department 10
SELECT SUM(SAL),DEPTNO FROM EMP WHERE DEPTNO = 10
GROUP BY DEPTNO;
List the department number and total salary paid to the employees of that
department only if the total salary paid to that department is greater than
9000.
SELECT SUM(SAL),DEPTNO FROM EMP WHERE SUM(SAL) > 9000
GROUP BY DEPTNO
*
ERROR at line 1:
ORA-00934: group function is not allowed here
Note:
We cannot use group functions in the where clause of the query and hence
we have to use having clause as shown below.
Having Clause:
Syntax:
SELECT fn,gf(fn),... FROM <tname> [WHERE clause]
[GROUP BY clause[HAVING clause]] [ORDER BY clause];
SELECT DEPTNO,SUM(SAL) FROM EMP GROUP BY DEPTNO
HAVING SUM(SAL) > 9000;
Exercise
List the total salary paid to employees based on their designation (i.e.
Job) only if the total salary is less than 5500.
Answer
SELECT SUM(SAL),JOB FROM EMP GROUP BY JOB HAVING
Sum(sal) < 5500;
Exercise
Select the department number which is having least number of employees.
Hint
Select the department number whose count (*) is the minimum.
Answer
SELECT DEPTNO,COUNT(*) FROM EMP GROUP BY DEPTNO
HAVING COUNT(*)=(SELECT MIN(COUNT(*)) FROM EMP GROUP
BY DEPTNO)

Page 31 of 79

Wipro Confidential

6.

Environmental Function
User
This gives the logged in user name.
SELECT USER FROM DUAL;
scott
uid
This returns the User ID of the logged in user.
SELECT UID FROM DUAL;
20
userenv:
This retuns the Environment details of the user area.
SELECT USERENV('LANG') FROM DUAL;
US
SELECT USERENV('LANGUAGE') FROM DUAL;
USERENV('LANGUAGE')
---------------------------------------------------AMERICAN_AMERICA.UTF8
SELECT USERENV('SESSIONID') FROM DUAL;
USERENV('SESSIONID')
-------------------177495
least(v1,v2,v3...)
This returns the least value in the list.
SELECT LEAST(10,2,100,1,20) FROM DUAL;
1
greatest(v1,v2,...)
This returns the greatest value in the list.
SELECT GREATEST(10,2,100,1,20) FROM DUAL;
100
nvl(field,TreateValue)
This function is used to represent null value in the way we desire.
SELECT COMM FROM EMP;
If you execute the above query you can see some blanks in commission field, these
blanks are nulls in the data base.

Page 32 of 79

Wipro Confidential

SELECT NVL(COMM,0) FROM EMP;


If you execute the above query you can notice that nulls are replaced by zeros.
SELECT COUNT(COMM) FROM EMP;
4
SELECT COMM,NVL(COMM,2) FROM EMP;
Exercise:
Add the commission with the salary and display the net salary of
the employees.
Answer:
SELECT ENAME,SAL,COMM,SAL+COMM FROM EMP;
Execute the above query and you will be surprised to see that
where ever the commission is null the resultant addition will also
be null. To overcome this problem we need to use NVL as shown
below.
SELECT SAL,COMM,SAL+COMM,SAL+NVL(COMM,0)
FROM EMP;

7.

Special Functions
decode
This is similar to Like if-else-if in programming languages.
Syntax:
DECODE(fieldname,V1,treatvalue,V2,treatvalue,...,DEFAULT)
Example:
SELECT DECODE ( DEPTNO ,10,'ACCOUNTING' ,20, 'RESEARCH',
'DEMO') , DEPTNO FROM EMP;
vsize
This returns the size of the field.
Syntax:
VSIZE(fieldname)
Example:
SELECT VSIZE(HIREDATE) FROM EMP;
DD-MON-YY
7

How to modify a record?


UPDATE:
Update is a DML command. It is used to modify the existing records.
Syntax:
UPDATE <tname> SET fieldname1=value1,.... [WHERE clause];
Page 33 of 79
Wipro Confidential

N Rows Updated.
Note:
If we are not specifying any condition in the where clause of the update query
then all the records in the table are updated.
UPDATE EMP SET COMM = 100;
14 Rows Updated
SELECT * FROM EMP;
All the records will have commission as 100 now.
Update a specific record:
UPDATE EMP SET COMM = 100 WHERE EMPNO = 7839;
1 Row Updated.
Update values in 2 or more fields in a record
UPDATE EMP SET COMM = 100,SAL = SAL + 100 WHERE EMPNO = 7839;

How to revert the changes?


ROLLBACK:
Its a TCL command which is a part of DCL. It is used to revert back the changes
made.
Syntax:
ROLLBACK;
Rollback Completed.

How to save the transactions?


COMMIT
Its a TCL command, part of DCL which is used to save the changes made.
Syntax:
COMMIT;
Commit Completed.

How to remove a record from the table?


DELETE
Its a DML command which is used to remove the existing records.
Syntax:
DELETE [FROM] <tname> [WHERE clause];
N Rows Deleted.
Note:
If we miss the WHERE clause, All records will be deleted.
Page 34 of 79

Wipro Confidential

Example:
DELETE EMP;
14 Rows Deleted.
SELECT * FROM EMP;
No Rows Selected.
ROLLBACK;
SELECT * FROM EMP;
14 Rows Selected.

How to remove a particular record?


DELETE FROM EMP WHERE EMPNO = 7934;
1 Row Deleted.

How to modify the table structure?


ALTER TABLE:
Its a DDL command. Used to
1. Add the New Fields
2. Modify the Existing Field Size, Data type
3. Add / Modify / Drop / Enable/ Disable
Constraints
4. Remove a Field from the Table(8.x)

How to add a new field to the existing table?


Syntax:
ALTER TABLE <tname> ADD(fn DATATYPE(size),...);
Example:
Create a dummy table to experiment as follows.
CREATE TABLE DEMO_EX(NO NUMBER(3),NA VARCHAR2(20));
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)
Example:
ALTER TABLE DEMO_EX ADD(DOB DATE);
Table Altered.
Note:
The newly added field will be at the end of the structure.
Page 35 of 79

Wipro Confidential

DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)
DOB
DATE
If the table has some records already the newly added field will have NULL
values for those records.

How to change the data type of an existing field?


Syntax:
ALTER TABLE <tname> MODIFY(efn DATATYPE(size),...);
Table Altered.
Note:
We can change the data type of a field only if the field is not having any data.
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)
DOB
DATE
SELECT * FROM DEMO_EX;
No Rows Selected.
ALTER TABLE DEMO_EX MODIFY(NO VARCHAR2(3));
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
VARCHAR2(3)
NA
VARCHAR2(20)
DOB
DATE
Note:
We cant change the data type of a field if it is already having some data.
SELECT * FROM EMP;
14 Rows Selected.
ALTER TABLE EMP MODIFY (ENAME NUMBER(30))
*
ERROR at line 1:
Page 36 of 79
Wipro Confidential

ORA-01439: column to be modified must be empty to change data type

How to increase or decrease the field size?


Syntax:
ALTER TABLE <tname> MODIFY(efn DATATYPE(size),...);
Table Altered.
Note:
We cant change the size of a field if it is already having some data.
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
VARCHAR2(3)
NA
VARCHAR2(20)
DOB
DATE
ALTER TABLE DEMO_EX MODIFY(NO VARCHAR2(5));
ALTER TABLE category MODIFY(CATEGORY_NAME VARCHAR2(30));
Table Altered.
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
VARCHAR2(5)
NA
VARCHAR2(20)
DOB
DATE
To Decrease:
ALTER TABLE DEMO_EX MODIFY (NO VARCHAR2 (2));
Table Altered.
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
VARCHAR2 (2)
NA
VARCHAR2 (20)
DOB
DATE
Note:
If the field is already having some data we can increase the size of the field but
we cant decrease the fields size.
Page 37 of 79

Wipro Confidential

SELECT * FROM EMP;


14 Rows Selected.
DESC EMP
ALTER TABLE EMP MODIFY (EMPNO NUMBER (5));
Table Alerted.
If we try to decrease the size of the field which is already having some data then
we get the following error message.
Error: Column to modify must be empty to decrease the scale or precision.
How to view all objects in our user area?
SELECT * FROM TAB;
This shows all objects in Our User Area.
TAB:
This is a synonym.
DUAL:
This is a table and its an invisible object.
SELECT * FROM TAB;
You will not be able to see DUAL table when you execute the above
statement because it is an invisible object.
DESC DUAL
Name
-----------------DUMMY

Null?
-----------

Type
----------VARCHAR2(1)

SELECT * FROM DUAL;


D
X

How to rename a table?


RENAME:
This is a DDL command used to change the name of a table.
Syntax:
RENAME <old> TO <new>;
Table Renamed.
Page 38 of 79

Wipro Confidential

Example:
DESC DEMO_EX
RENAME DEMO_EX TO DEMO_EX1;
Table Renamed.
Now let us try to access DEMO_EX.
DESC DEMO_EX
Error : Object Demo_Ex does not exists
DESC DEMO_EX1

How to flush off the records in the table?


TRUNCATE:
This is a DDL command used to delete all the records in the table.
DELETE
TRUNCATE
DML
DDL
We must commit to complete the deletion.
It is auto committed.
We have the option to rollback before
We cant rollback.
committing the changes.
Syntax:
TRUNCATE TABLE <tname>;
Table Truncated.
Example:
SELECT * FROM EMP;
DELETE EMP;
14 Rows Deleted.
SELECT * FROM EMP;
No Rows Selected.
ROLLBACK;
SELECT * FROM EMP;
14 Rows Selected
TRUNCATE TABLE EMP;
Table Truncated.
SELECT * FROM EMP;
No Rows Selected.
ROLLBACK;
SELECT * FROM EMP;
Page 39 of 79

Wipro Confidential

No Rows Selected.

How to remove the table structure from the DB?


DROP:
This is a DDL command used to remove the table structure from the DB.
Syntax:
DROP TABLE <table name> [CASCADE CONSTRAINTS];
Table Dropped.
Example:
DESC EMP
DROP TABLE EMP;
DESC EMP
Error: Object EMP does not exists

Constraints:
This is a way to restrict data that goes into a table.
2 Types
1. Column Level Constraints
2. Table Level Constraints.
Column Level Constraints
Types:
1. NOT NULL
2. CHECK
3. UNIQUE
4. PRIMARY KEY
5. REFERENCES
NULL:
It is a keyword used to represent the field in a record which does not have any
value. In a storage space perspective Null does not occupy any space as such.
Note:
In oracle all the table fields default constraint is NULL.
NOT NULL:
If a field has a not null constraint specified then it cannot hold null values.
DROP TABLE DEMO_EX;
Page 40 of 79

Wipro Confidential

CREATE TABLE DEMO_EX (NO NUMBER (3) NOT NULL, NA VARCHAR2


(20));
Note:
Column level constraints are specified after the column definition.
Column definition: fieldname DATATYPE(SIZE)
DESC DEMO_EX
Name
Null?
Type
---------------- -----------------------NO
NOT NULL NUMBER(3)
NA
VARCHAR2(20)
INSERT INTO DEMO_EX VALUES (1,'OCEAN');
INSERT INTO DEMO_EX (NO) VALUES (2);
INSERT INTO DEMO_EX (NA) VALUES ('DEMO');
Error: cannot insert null into "scott"."Demo_ex"."no"
SELECT * FROM DEMO_EX;
INSERT INTO DEMO_EX (NO) VALUES (2);
SELECT * FROM DEMO_EX;
Note:
Not Null fields can accept the duplicate values.
CHECK:
This constrain is used to check for some condition before accepting values to that
field.
Example:
CREATE TABLE DEMO_EX(NO NUMBER(3),NA VARCHAR2(20));
The NO column in the above table can have values from 0 to 999. But if we
want this column to allow values from 0 to 100 alone then we need to add a
CHECK constrain as shown below.
DROP TABLE DEMO_EX;
CREATE TABLE DEMO_EX(NO NUMBER(3) CHECK(NO < 101),NA
VARCHAR2(20));
Page 41 of 79

Wipro Confidential

DESC DEMO_EX
Name
-----------NO
NA

Null?
Type
-------- -----------NUNBER (3)
VARCHAR2 (20)

INSERT INTO DEMO_EX VALUES (1,'OCEAN');


INSERT INTO DEMO_EX (NO) VALUES (2);
INSERT INTO DEMO_EX (NA) VALUES ('MARS');
INSERT INTO DEMO_EX (NO) VALUES (2);
INSERT INTO DEMO_EX (NO) VALUES (101);
Error: Check Constraint(Scott.Name) Violated.
Note:
A column with check constrain alone will accept Null values and duplicate
records.
UNIQUE:
This constrain is used to avoid duplicate values to a column.
DROP TABLE DEMO_EX;
CREATE TABLE DEMO_EX(NO NUMBER(3) UNIQUE,NA
VARCHAR2(20));
DESC DEMO_EX
Name
Null? Type
------------------------------- -------- ---NO
NUMBER (3)
NA
VARCHAR2 (20)
INSERT INTO DEMO_EX VALUES (1,'DEMO');
INSERT INTO DEMO_EX (NO) VALUES (2);
INSERT INTO DEMO_EX (NA) VALUES ('OCEAN');
INSERT INTO DEMO_EX (NO) VALUES (2);
Error: Unique Constraint (Scott.Name) Violated.
Note:
Page 42 of 79

Wipro Confidential

A column with Unique constrain alone allows Null values.


PRIMARY KEY:
The primary key is an attribute or a set of attributes that uniquely identify a
specific instance of an entity. Every entity in the data model must have a primary
key whose values uniquely identify instances of the entity.
To qualify as a primary key for an entity, an attribute must have the following
properties:
* It must have a non-null value for each instance of the entity.
* The value must be unique for each instance of an entity.
* The values must not change or become null during the life of each entity
instance.
NOT NULL + UNIQUE
Example:
DROP TABLE DEMO_EX;
CREATE TABLE DEMO_EX (NO NUMBER (3) PRIMARY KEY, NA
VARCHAR2 (20));
DESC DEMO_EX
Name
Nul?
Type
---------------- -------------------NO
NOT NULL NUMBER (3)
NA
VARCHAR2 (20)
INSERT INTO DEMO_EX VALUES (1,'OCEAN');
INSERT INTO DEMO_EX (NO) VALUES (2);
INSERT INTO DEMO_EX (NA) VALUES ('DEMO');
Error: Cannot Insert Null into "Scott"."DEMO_EX"."NO"
INSERT INTO DEMO_EX (NO) VALUES (2);
Error: Unique Constraint (Scott.Name) Violated.
References:
This always refers to the Primary key values. A table that holds a reference to a
primary key column is called Child Table and the referred table is called Master
table.
DROP TABLE DEMO_EX1;

Page 43 of 79

Wipro Confidential

CREATE TABLE DEMO_EX1(NO NUMBER(3) REFERENCES


DEMO_EX(NO), ADDR VARCHAR2(20));
Note 1:
Once the master table and child table are created, we cant drop the master table.
Master Table :
Demo_Ex
Has PK
Child Table :
Demo_Ex1
Refers PK
Example:
DROP TABLE DEMO_EX;
Error: unique / primary keys in table referenced by foreign keys
Note 3:
The column which has reference to the primary key column can have duplicate
entries.
SELECT * FROM DEMO_EX;
INSERT INTO DEMO_EX1 VALUES (1,'A');
INSERT INTO DEMO_EX1 VALUES (2,'B');
INSERT INTO DEMO_EX1 VALUES (2,'C');
INSERT INTO DEMO_EX1 VALUES (1,'D');
INSERT INTO DEMO_EX1 VALUES (3,'C');
Error: Integrity Constraint (Scott.Name) Violated. Parent key not found
Note 4:
If the Master record, have Child Records referring to it then we cant delete or
update the Master record.
SELECT * FROM DEMO_EX;
SELECT * FROM DEMO_EX1;
DELETE FROM DEMO_EX WHERE NO = 1;
Error: Integrity Constraint (Scott.Name) Violated. Child Record Found.
UPDATE DEMO_EX SET NO = 10 WHERE NO = 1;
Error: Integrity Constraint (Scott.Name) Violated. Child Record Found.
Table Level Constraints:
The Work is same, the way of declare is different.
Page 44 of 79

Wipro Confidential

Classifications
CHECK
UNIQUE
PRIMARY KEY
FOREIGN KEY
CHECK:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM (
NO NUMBER(3),
NA VARCHAR2(20),
CHECK(NO < 101)
);
Table Level Constraint:
The functionality is the same as that of column level constrain but the way we
define them is different.
Column Level Constraint:
CREATE TABLE EX_DEM1(
NO NUMBER (3) CHECK (NO<101),
NA VARCHAR2 (20)
);
INSERT INTO EX_DEM VALUES (1,'OCEAN');
INSERT INTO EX_DEM (NO) VALUES (2);
INSERT INTO EX_DEM (NA) VALUES ('DEMO');
INSERT INTO EX_DEM (No) VALUES (101);
Error: Check Constraint (Scott.Name) Violated.
Table Level Constraint:
Unique:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM (
NO NUMBER(3),
NA VARCHAR2(20),
UNIQUE(NO)
);
Primary Key:
DROP TABLE EX_DEM;
Page 45 of 79

Wipro Confidential

CREATE TABLE EX_DEM (


NO NUMBER (3),
NA VARCHAR2 (20),
PRIMARY KEY (NO)
);
Foreign Key:
DROP TABLE EX_DEM1;
CREATE TABLE EX_DEM1 (
NO NUMBER (3),
NA VARCHAR2 (20),
FOREIGN KEY (NO) REFERENCES EX_DEM (NO)
);
Default:
This is used to set the default value to a field.
CREATE TABLE EX_DEM(NO NUMBER(3),NA VARCHAR2(20) DEFAULT
'OCEAN');
Note:
If we dont give a value to NA the default value specified will be inserted
to that Field.
Example:
INSERT INTO EX_DEM VALUES(1,'MADHU');
INSERT INTO EX_DEM(NO) VALUES(2);
SELECT * FROM EX_DEM;
On Delete Cascade:
On using On Delete Cascade, if the master record deleted, the associated
child record is also deleted automatically from the child table. Let us see an
example to understand it better.
Example:
CREATE TABLE EX_DEM(NO NUMBER(3) PRIMARY KEY, NA
VARCHAR2(20));
CREATE TABLE EX_DEM1(NO NUMBER(3)
REFERENCES EX_DEM(NO) ON DELETE CASCADE,ADDR
VARCHAR2(20));
Page 46 of 79

Wipro Confidential

INSERT INTO EX_DEM VALUES(1,'OCEAN');


INSERT INTO EX_DEM VALUES(2,'SSS');
INSERT INTO EX_DEM1 VALUES(1,'TRICHY');
INSERT INTO EX_DEM1 VALUES(2,'TRICHY');
INSERT INTO EX_DEM1 VALUES(2,'SALEM');
INSERT INTO EX_DEM1 VALUES(2,'MADURAI');
COMMIT;
SELECT * FROM EX_DEM;
2 Row Selected.
SELECT * FROM EX_DEM1;
4 Rows Selected.
DELETE EX_DEM WHERE NO = 2;
1 Row Deleted.
SELECT * FROM EX_DEM;
1 Row Selected
SELECT * FROM EX_DEM1;
1 Row Selected.
Now we see that only one row is present in EX_DEM1 this is because when we
deleted the record with NO=2 from EX_DEM which is the master table the 3
records referring to this record from the child table EX_DEM1 also gets deleted.

How do I add a new constrain to an existing table?


Let us understand this through the below example
Step 1: Create a table without any constraint specified.
CREATE TABLE EX_DEM(NO NUMBER(3),NA VARCHAR2(20));
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)
Step 2:
Add NOT NULL constraint to NO field.
ALTER TABLE:
Syntax:
ALTER TABLE <tname> MODIFY(fn NOT NULL);
Page 47 of 79

Wipro Confidential

Usage:
ALTER TABLE EX_DEM MODIFY(NO NOT NULL);
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NOT NULL NUMBER(3)
NA
VARCHAR2(20)

Add UNIQUE constraint to NO field.


DROP TABLE EX_DEM;
CREATE TABLE EX_DEM(NO NUMBER(3),NA VARCHAR2(20));
Usage:
ALTER TABLE EX_DEM ADD UNIQUE(NO);
Add CHECK constraint to NO field.
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM(NO NUMBER(3),NA VARCHAR2(20));
Usage:
ALTER TABLE EX_DEM ADD CHECK(NO < 101);
Add PRIMARY KEY constraint to NO field.
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM(NO NUMBER(3),NA VARCHAR2(20));
ALTER TABLE EX_DEM ADD PRIMARY KEY(NO);
Add FOREIGN KEY constraint to NO field.
DROP TABLE EX_DEM1;
CREATE TABLE EX_DEM1(NO NUMBER(3),ADDR VARCHAR2(20));
Usage:
ALTER TABLE EX_DEM1 ADD FOREIGN KEY(NO) REFERENCES
EX_DEM(NO);
Page 48 of 79

Wipro Confidential

Note 1:
Since table EX_DEM1 is referring to EX_DEM we will not be able to drop
EX_DEM.
Example:
DROP TABLE EX_DEM;
Error : unique/primary keys in table referenced by foreign keys
Note 2:
We can add or modify the constraint to an existing table field as long as the field
has no values in it or if the field has already some values those values must satisfy
the new constraint that we are trying to add or modify.

How do I remove an existing constraint?


Syntax:
ALTER TABLE <tname> DROP CONSTRAINT <cname>;
cname: Name of the Constraint.
Note:
In oracle we dont specify the constraint name; oracle automatically
creates a constraint name and associates it with the constraint.
USER_CONSTRAINTS:
This is a view which has the details about the constraints.
sql> DESC USER_CONSTRAINTS
Name
Null?
-------------------------------------OWNER
NOT NULL
CONSTRAINT_NAME
NOT NULL
CONSTRAINT_TYPE
TABLE_NAME
NOT NULL
SEARCH_CONDITION
R_OWNER
R_CONSTRAINT_NAME
DELETE_RULE
STATUS
DEFERRABLE
DEFERRED
VALIDATED
GENERATED
BAD
LAST_CHANGE
Page 49 of 79

Type
---VARCHAR2(30)
VARCHAR2(30)
VARCHAR2(1)
VARCHAR2(30)
LONG
VARCHAR2(30)
VARCHAR2(30)
VARCHAR2(9)
VARCHAR2(8)
VARCHAR2(14)
VARCHAR2(9)
VARCHAR2(13)
VARCHAR2(14)
VARCHAR2(3)
DATE
Wipro Confidential

SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME
FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
CONSTRAINT_TYPE
MEANING
P
Primary Key
R
References
C
Not null & Check
U
Unique.
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,TABLE_NAME
FROM USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM1';
Example:
DROP TABLE EX_DEM1;
DROP TABLE EX_DEM;
Create a table with NOT NULL constraint to NO field.
CREATE TABLE EX_DEM(NO NUMBER(3) NOT NULL,NA
VARCHAR2(20));
Find the name of the constraint
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE FROM
USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NOT NULL NUMBER(3)
NA
VARCHAR2(20)
Remove the constraint
ALTER TABLE EX_DEM DROP CONSTRAINT SYS_C00740;
Table Altered.
DESC EX_DEM
Name
Null? Type
------------------------------- -------- ---NO
NUMBER(3)
NA
VARCHAR2(20)

Is it possible to disable or enable a constraint?


Yes, it is possible to do so.
Syntax:
ALTER TABLE <tname> ENABLE / DISABLE CONSTRAINT <cname>;
Table Altered.
Note:
If we create a table and set the constraint to the table fields, all the
constraints are ENABLED by default.
Page 50 of 79
Wipro Confidential

Example:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM(NO NUMBER(3) NOT NULL,NA VARCHAR2(20)
UNIQUE);
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS FROM
USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
INSERT INTO EX_DEM(NA) VALUES('DEMO');
Error: Cannot Insert Null into "Scott"."Ex_Dem"."No"
INSERT INTO EX_DEM VALUES(1,'OCEAN');
1 Row Created.
INSERT INTO EX_DEM VALUES(1,'OCEAN');
Error : Unique Constraint(Scott.Sys_C00742) Violated.
ALTER TABLE EX_DEM DISABLE CONSTRAINTS SYS_C00742;
Table Altered.
SELECT CONSTRAINT_NAME,CONSTRAINT_TYPE,STATUS FROM
USER_CONSTRAINTS WHERE TABLE_NAME = 'EX_DEM';
Since we have disabled the unique constraint now we can insert duplicate values..
INSERT INTO EX_DEM VALUES(1,'OCEAN');
1 Row Created.

How to enable the constraint?


Syntax:
ALTER TABLE <tname> ENABLE CONSTRAINTS <cname>;
Note:
A disabled constraint can only be enabled if the field contains data that
satisfies the constraint that we are trying to enable.

How to set the name to the constraints?


Example:
DROP TABLE EX_DEM;
CREATE TABLE EX_DEM(NO NUMBER(3) CONSTRAINT
EX_DEM_NO_UNIQUE UNIQUE, NA VARCHAR2(20));
Page 51 of 79

Wipro Confidential

INSERT INTO EX_DEM VALUES(1,'OCEAN');


INSERT INTO EX_DEM VALUES(1,'DEMO');
Error : Unique Constraint(Scott. EX_DEM_NO_UNIQUE) Violated

Set Operators:
The four set operators union, union all, intersect and minus allow to serially
combine more than one select statement. Although more than one select statement
will then be present, only one result set is then returned.
If the select statements vary in their numbers of returned columns, Oracle reportS
an ORA-01789: query block has incorrect number of result columns.
For the demonstration of set operators, the following test tables are created:
CREATE TABLE U1(NO NUMBER(3));
CREATE TABLE U2(NO NUMBER(3));
INSERT INTO U1 VALUES(1);
INSERT INTO U1 VALUES(4);
INSERT INTO U1 VALUES(2);
INSERT INTO U2 VALUES(3);
INSERT INTO U2 VALUES(4);
INSERT INTO U2 VALUES(5);
COMMIT;
SELECT * FROM U1;
SELECT * FROM U2;

1. UNION ALL:
Union all selects all rows from all select statements:
Example:
SELECT * FROM U1
UNION ALL
SELECT * FROM U2;
1
4
2
3
4
5

Page 52 of 79

Wipro Confidential

2. UNION:
Union is very similar to union all, however, it dismisses duplicate rows
found across different select statements:
Note :
The selected values automatically displayed in ascending order.
Example:
SELECT * FROM U1 UNION SELECT * FROM U2;
1
2
3
4
5

3. INTERSECT
Intersect only returns the rows that are found in all select statements:
Example:
SELECT * FROM U1 INTERSECT SELECT * FROM U2;
4

4. MINUS:
Minus returns all rows from the first select statements except those who
are duplicated in a following select statement:
Example:
SELECT * FROM U1 MINUS SELECT * FROM U2;
1
2
SELECT * FROM U2 MINUS SELECT * FROM U1;
3
5

Pseudo columns in Oracle:


A pseudo column behaves like a table column, but is not actually stored in the
table. You can select from pseudo columns, but you cannot insert, update, or
delete their values. This section describes these pseudo columns:

1. ROWID:
For each row in the database, the ROWID pseudo column returns a rows
address. Usually, a rowid value uniquely identifies a row in the database.
However, rows in different tables that are stored together in the same
cluster can have the same rowid. Values of the ROWID pseudo column
have the data type ROWID or UROWID.
Important uses of ROWID:
a. They are the fastest way to access a single row.
Page 53 of 79

Wipro Confidential

b. They can show you how a tables rows are stored.


c. They are unique identifiers for rows in a table.
You should not use ROWID as a tables primary key. If you delete and
reinsert a row with the Import and Export utilities, for example, its rowid
may change. If you delete a row, Oracle may reassign its rowid to a new
row inserted later.
Although you can use the ROWID pseudo column in the SELECT and
WHERE clause of a query, these pseudo column values are not actually
stored in the database. You cannot insert, update, or delete a value of the
ROWID pseudo column.
Example:
This statement selects the address of all rows that contain data for
employees in department 20:
SELECT ROWID, last_name FROM employees WHERE
department_id = 20;

2. ROWNUM:
For each row returned by a query, the ROWNUM pseudo column returns a
number indicating the order in which Oracle selects the row from a table
or set of joined rows. The first row selected has a ROWNUM of 1, the
second has 2, and so on.
You can use ROWNUM to limit the number of rows returned by a query,
as in this example
Example:
SELECT * FROM employees WHERE ROWNUM < 10;
If an ORDER BY clause follows ROWNUM in the same query, the rows
will be reordered by the ORDER BY clause. The results can vary
depending on the way the rows are accessed. For example, if the ORDER
BY clause causes Oracle to use an index to access the data, Oracle may
retrieve the rows in a different order than without the index. Therefore, the
following statement will not have the same effect as the preceding
example:
Example:
SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY
last_name;
If you embed the ORDER BY clause in a sub query and place the
ROWNUM condition in the top-level query, you can force the ROWNUM
condition to be applied after the ordering of the rows. For example, the
following query returns the 10 smallest employee numbers. This is
sometimes referred to as a "top-N query":
Example:
Page 54 of 79
Wipro Confidential

SELECT * FROM (SELECT * FROM employees ORDER BY


employee_id) WHERE ROWNUM < 11;
In the preceding example, the ROWNUM values are those of the top-level
SELECT statement, so they are generated after the rows have already been
ordered by employee_id in the sub query.
Conditions testing for ROWNUM values greater than a positive integer
are always false, hence only =, <, <= operators when used with
ROWNUM will return records. For example, this query returns no rows:
Example:
SELECT * FROM employees WHERE ROWNUM > 1;
The first row fetched is assigned a ROWNUM of 1 and makes the
condition false. The second row to be fetched is now the first row and is
also assigned a ROWNUM of 1 and makes the condition false. All rows
subsequently fail to satisfy the condition, so no rows are returned.
You can also use ROWNUM to assign unique values to each row of a
table, as in this example.
Example:
UPDATE my_table SET column1 = ROWNUM;

3. LEVEL:
For each row returned by a hierarchical query, the LEVEL pseudo column
returns 1 for a root row, 2 for a child of a root, and so on.
A root row is the highest row within an inverted tree.
A child row is any non root row.
A parent row is any row that has children.
A leaf row is any row without children.
Figure below shows the nodes of an inverted tree with their LEVEL
values.

Page 55 of 79

Wipro Confidential

To define a hierarchical relationship in a query, you must use the START


WITH and CONNECT BY clauses.
Let us understand the usage of level through the following example.
Example: (Using Hierarchical Queries)
Let us create a table that contains primary key as well as foreign
in the same table. (Sort of recursive relationship)
DROP TABLE DEMO_EX1;
DROP TABLE DEMO_EX;
CREATE TABLE DEMO_EX(ENO NUMBER(3) PRIMARY KEY, JOB
VARCHAR2(20),MNO NUMBER(3) REFERENCES
DEMO_EX(ENO));
Recap:
Primary Key: NOT NULL + UNIQUE
Foreign Key: Always refers the primary key values.
INSERT INTO DEMO_EX VALUES(1,'MD',NULL);
INSERT INTO DEMO_EX VALUES(1,'MD',NULL);
Error : Unique Constraint (Scott.Name) Violated.
INSERT INTO DEMO_Ex(JOB) VALUES('GM');
Error : Cannot Insert null into "Scott"."Demo_Ex"."Eno"
INSERT INTO DEMO_EX VALUES(2,'GM',1);
INSERT INTO DEMO_EX VALUES(3,'CLERK',7);
Error : Integrity Constrain(Scott.name) Violated. Parent Key NotFound
Page 56 of 79

Wipro Confidential

INSERT INTO DEMO_EX VALUES(3,'SALESMAN',2);


INSERT INTO DEMO_EX VALUES(4,'ACCOUNTMAN',2);
INSERT INTO DEMO_EX VALUES(5,'SALESMAN',3);
INSERT INTO DEMO_EX VALUES(6,'CLERK',4);
COMMIT;
SELECT * FROM DEMO_EX;
Hierarchical Queries:
If a table contains hierarchical data, you can select rows in a hierarchical
order using the hierarchical query clause:
a. START WITH specifies the root row(s) of the hierarchy.
b. CONNECT BY specifies the relationship between parent rows and
child rows of the hierarchy. Some part of the connect_by_condition
must use the PRIOR operator to refer to the parent row.
c. PRIOR evaluates the connect_by_condition for the parent row of the
current row in a hierarchical query.
Syntax:
CONNECT BY PRIOR pkFIELD = fkFIELD
START WITH Clause: Used to tell the starting point in the tree view.
START WITH condition
condition: Should select the Root Information.
Select Syntax:
SELECT LEVEL,... FROM <tname>
CONNECT BY PRIOR condition
START WITH condition;
SELECT LEVEL,ENO,JOB,MNO FROM DEMO_EX
CONNECT BY PRIOR ENO = MNO
START WITH JOB = 'MD' ORDER BY LEVEL;

Page 57 of 79

Wipro Confidential

Tree View:
SELECT LPAD(LEVEL,LEVEL,' '),ENO,JOB,MNO FROM DEMO_EX
CONNECT BY PRIOR ENO = MNO
START WITH JOB = 'MD';

SELECT LPAD(LEVEL,LEVEL,' '),ENO,JOB,MNO FROM DEMO_EX


CONNECT BY PRIOR ENO = MNO
START WITH JOB = 'MD' ORDER BY LEVEL;

4. CURRVAL and NEXTVAL


A sequence is a schema object that can generate unique sequential values.
These values are often used for primary and unique keys. You can refer to
sequence values in SQL statements with these pseudo columns:
CURRVAL: The CURRVAL pseudo column returns the current value of a
sequence.
NEXTVAL: The NEXTVAL pseudo column increments the sequence and
returns the next value
You must qualify CURRVAL and NEXTVAL with the name of the
sequence:
sequence.CURRVAL
sequence.NEXTVAL

Joins:
Joins are used to select fields from many tables using a single select statement.
3 Types
1. Equi Join
2. Non Equi Join
3. Outer Join
Cartesian product:
Page 58 of 79

Wipro Confidential

A{1,2,3}
B{a,b}
A * B = 1a,1b,,2a,2b,3a,3b
Steps to write a query with join:
Identify the fields that you need to view from different tables and add
those field names in the SELECT clause of the query.
Add all table names to the FROM clause of the query.
Identify the common fields between the tables and add them to the join
condition.
Join Condition:
Table1.Fieldname OPERATOR Table2.FieldName
Note:
If there are N number of tables in the FROM clause of the query there should be
N-1 join conditions.

1. Equi Join:
Syntax:
Table1.Fieldname = Table2.FieldName
Example:
SELECT * FROM DEPT;
4 Rows Selected.
SELECT * FROM EMP;
14 Rows Selected.
List the Ename and Dname column values.
SELECT ENAME,DNAME FROM EMP,DEPT;
56 Rows Selected.
The above query will return a Cartesian product of the two tables and
hence we get 56 (14 * 4 =56) rows selected. This happens because there is
no join condition mentioned in the above query.
To Avoid: (Mention a join condition)
SELECT ENAME,DNAME FROM EMP,DEPT WHERE EMP.DEPTNO
= DEPT.DEPTNO;
List Ename,Job,Loc,Dname column values.
SELECT ENAME,JOB,LOC,DNAME FROM EMP,DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO;
Page 59 of 79

Wipro Confidential

Select the employee name and his department who gets a salary greater
than 2000.
SELECT ENAME,DNAME FROM EMP WHERE SAL > 2000;
*
Error: Invalid Column Name
SELECT ENAME, DNAME FROM EMP, DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO AND SAL > 2000;
List Ename, Dname, DeptNo column values.
SELECT ENAME, DNAME, DEPTNO FROM EMP, DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO;
Error : Column Ambiguously defined
The above query is throwing an error because the column DEPTNO
mentioned in the select clause is present in both EMP and DEPT table.
Hence we should mention the TABLE.FIELD_NAME to avoid confusion.
SELECT ENAME, DNAME, EMP.DEPTNO FROM EMP, DEPT
WHERE
EMP.DEPTNO = DEPT.DEPTNO;
SELECT ENAME, DNAME, DEPT.DEPTNO FROM EMP, DEPT
WHERE
EMP.DEPTNO = DEPT.DEPTNO;
Select Ename, Deptno, and Dname of the employee getting maximum
salary.
SELECT ENAME, DNAME FROM EMP, DEPT WHERE
EMP.DEPTNO = DEPT.DEPTNO AND
SAL = (SELECT MAX (SAL) FROM EMP);
Select all employees belonging to the department having maximum
number of employees.
Step 1:
SELECT DEPTNO FROM EMP GROUP BY DEPTNO;
Step 2:
SELECT COUNT (*), DEPTNO FROM EMP GROUP BY DEPTNO;
Step 3:
SELECT DEPTNO FROM EMP GROUP BY DEPTNO
HAVING COUNT (*) = (SELECT MAX (COUNT (*)) FROM EMP
GROUP BY DEPTNO);
Step 4:
Page 60 of 79

Wipro Confidential

SELECT * FROM EMP WHERE DEPTNO = (SELECT DEPTNO


FROM EMP
GROUP BY DEPTNO HAVING COUNT (*) = (SELECT MAX
(COUNT(*))
FROM EMP GROUP BY DEPTNO));
13

2. Non Equi Joins:


Syntax:
Table1.Fieldname <> Table2.FieldName
Example:
SELECT * FROM DEPT;
SELECT * FROM EMP;
Select the department name in which King is not working.
SELECT ENAME,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO != DEPT.DEPTNO
AND ENAME = 'KING';
Operator: !=, ^=, <>

3. Outer Joins:
A "normal" join finds values of two tables that are in a relation to each
other. In most cases, this relation is equality (=), but it can also be all sorts
of operations that either return true or false. The important thing is that a
"normal" join only returns rows of both tables of which the compared
columns return true. Of course, a row whose column-value is not found in
the other table's joined column is not returned at all. However, sometimes,
there is a requirement to show these rows as well.
Example:
SELECT * FROM DEPT;

SELECT * FROM EMP;

Page 61 of 79

Wipro Confidential

Select Each Employee Working Deptname with Not have a employee In


the Department.
Types:
Left Outer Join
Right Outer Join

(+) =
= (+)

Select employees name his department number and his department name.
Normal Equi Join:
SELECT ENAME,DEPT.DEPTNO,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO;

14 Rows Selected.
Left Outer Join:
SELECT ENAME,DEPT.DEPTNO,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO(+) = DEPT.DEPTNO;

Page 62 of 79

Wipro Confidential

15 Rows Selected.
Table1.Field(+) = Table2.Field
This condition selects the matching records plus the additional records in
Table2 which does not have a matching record in Table1.
Right Outer Join:
SELECT ENAME,DEPT.DEPTNO,DNAME FROM EMP,DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO(+);

14 Rows Selected.
In this case we get only 14 records because the EMP table is the child
table and DEPT table is the master table and hence it cannot contain an
employee belonging to a totally new department which is not there in the
department table.
Select all the departments which do not have any employees working in
it.
The result for the above requirement can be obtained in 2 ways
Using Join:
SELECT DEPT.DEPTNO,DNAME,LOC FROM EMP,DEPT
Page 63 of 79

Wipro Confidential

WHERE EMP.DEPTNO(+) = DEPT.DEPTNO AND ENAME IS NULL;

Using Join:
SELECT * FROM DEPT WHERE DEPTNO NOT IN (SELECT
DEPTNO FROM EMP GROUP BY DEPTNO);

Privileges:
A privilege is a right to execute an SQL statement or to access another user's object. In
Oracle, there are two types of privileges: system privileges and object privileges. A
privileges can be assigned to a user or a privilege The set of privileges is fixed, that is,
there is no SQL statement like create privilege xyz.

1. System privileges:
There are quite a few system priviliges: in Oracle 9.2, we count 157 of them,
and 10g has even 173. Those can be displayed with
Select name from system_privilege_map
Executing this statement, we find privileges like create session, drop user,
alter database. System privileges can be audited. Arguably, the most important
system privileges are:
a. create session (A user cannot login without this privilege. If he tries, he
gets an ORA-01045).
b. create table
c. create view
d. create procedure
e. sysdba
f. sysoper
This is basically used for DB related activities live user creation, object
creation etc.
Note:
When we install the Oracle, it automatically creates 5 Users
User
Password
1
Sys
Change_On_Install
2
System
Manager
The above 2 are DBA users
3
Scott
tiger
4
Demo
Demo
5
DBSNMP
DBSNMP
The above 3 are Ordinary Users.
DBA:
Users have System Privileges.
Page 64 of 79
Wipro Confidential

Ordinary User:
Do the operations within their area.
Examples of DBA operations:
User Creation
User Alteration
Grant the Permission
Drop the user.
Note: We must login into the DBA user Area.
Example: System / Manager
How to find your user name in the SQL Prompt?
SHOW USER
Its a SQL * Plus Editor Command.
How to Create a User?
CREATE USER:
Its a DDL command.
Syntax:
CREATE USER <uname> IDENTIFIED BY <pwd>;
User Created.
or
Insufficient Privileges
Example:
Log in as Scott:
CREATE USER MUNI IDENTIFIED BY MUNI;
Insufficient Privileges
Log in as System:
CREATE USER MUNI IDENTIFIED BY MUNI;
User Created.
Now that we have created a user let us try to log in. We will get an error
message as shown below.
error : user MUNI lacks CREATE SESSION privileges : logon denied
This is because the user that we just created is not having the privilege to
connect with the data base.
How to give the permission to the user to connect with the DB?
Page 65 of 79

Wipro Confidential

Grant:
Its a DCL command, which is used to give the permission
Syntax:
GRANT <permission> TO <username>;
Grant Succeeded.(DBA)
or
Insufficient Previleges(Ordinary User)
Permission:
CONNECT
RESOURCE
DBA

Connect With DB
DUAL, User_Constraints,...
Treat like a another DBA

Example:
Scott:
GRANT CONNECT,RESOURCE TO MUNI;
Error : Insufficient Previleges
System:
GRANT CONNECT,RESOURCE TO MUNI;
Grant Succeeded.
Note:
Now the user will be able to connect with the database.
How to change the User Password?
ALTER USER:
Its a DDL command which is used to change the password.
Syntax:
ALTER USER <uname> IDENTIFIED BY <pwd>;
User Altered.
Note:
The Password can be changed by current user or by the DBA.
Example:
Scott:
ALTER USER MUNI IDENTIFIED BY MUNI1;
Error : Insufficient Previleges
System:
ALTER USER MUNI IDENTIFIED BY MUNI2;
Page 66 of 79

Wipro Confidential

User Altered.
Muni:
ALTER USER MUNI IDENTIFIED BY MUNI3;
User Altered.
How to drop the user from the DB?
DROP USER:
Its a DDL command which is used to remove the user from DB.
Syntax:
DROP USER <uname> [CASCADE];
User Dropped.
or
Insufficient Privileges.
Example:
Scott:
DROP USER MUNI;
Error : Insufficient Previleges.
System:
DROP USER MUNI;
User Dropped.
CASCADE:
If the user we are dropping has some objects in his area then he cannot be
dropped unless his objects are dropped first. To accomplish this we use
Cascade key word. On using this the objects are dropped first and the user
is dropped next.

2. Object privileges
Object privileges can be assigned to the following types of objects:
1. Tables
Select, insert, update, delete, alter, debug, flashback, on commit
refresh, query rewrite, references, all
2. Views
Select, insert, update, delete, under, references, flashback, debug
3. Sequence
alter, select
4. Packages, Procedures, Functions (Java classes, sources...)
execute, debug

Page 67 of 79

Wipro Confidential

For a user to be able to access an object in another user's schema, he needs the
according object privilege. Object privileges can be displayed using
all_tab_privs_made or user_tab_privs_made.
This is basically used to enable communication between users.
Grant:
Its a DCL command used to give the permission to the user to access
objects.
Syntax:
GRANT <permission> ON <object> TO <user>;
Grant Succeeded.
Permission
SELECT
INSERT
UPDATE
DELETE
ALL
Object:
Tables, procedures, views etc.
Example:
Scott:
GRANT SELECT ON EMP TO MUNI;
Grant Succeeded.
MUNI:
SELECT * FROM TAB;
No Rows Selected.
SELECT * FROM EMP;
Error : table or view does not exists
SELECT * FROM SCOTT.EMP;
14 Rows Selected.
SELECT * FROM SCOTT.DEPT;
Error: table or view does not exists
Note:
Suppose if user "MUNI" performs other than the select operation he will
get the "Insufficient Privilege" error because scott has granted only select
privilege to MUNI on EMP table
Page 68 of 79

Wipro Confidential

Example:
MUNI:
DELETE FROM SCOTT.EMP;
Error: Insufficient Privileges
How to revoke the granted permission?
REVOKE:
Its a DCL command.
Syntax:
REVOKE <permission> ON <object> FROM <user>;
Revoke Succeeded.
Example:
Scott:
REVOKE SELECT ON EMP FROM MUNI;
Revoke Succeeded.
From now on user MUNI cannot access Scott.Emp.
Muni:
SELECT * FROM SCOTT.EMP;
Error: table or view does not exists
How to grant more than one permission to a user?
GRANT SELECT, DELETE ON EMP TO MUNI;
Grant Succeeded.

Data Base Objects:


These are used to store and retrieve the data in different ways.
Types:
1. View
2. Synonym
3. Sequence
4. Index
5. Cluster

1. View:
It is a logical representation of the Table (Object). Table is a physical
representation of data. View does not occupy memory; it is just used to store
the query. A view when called always executes the query associated to fetch
the results.
We can create a view for a Table, View or Synonym.
Page 69 of 79

Wipro Confidential

Syntax:
CREATE [OR REPLACE] VIEW <vname>[(fn1,fn2,..)] AS query;
View Created.

OR REPLACE:
If a view is already having the given "vname" then old query in that view
is replaced by the current query.
Example:
CREATE OR REPLACE VIEW VV1 AS SELECT * FROM EMP;
View Created.
SELECT * FROM VV1;
14 Rows Selected.
Note:
If a View is created from single table with all fields included then we can
manipulate the data using that view.
Manipulation:
Manipulation in this context means Inserting, Deleting and Updating the
data.
INSERT INTO VV1 (EMPNO, DEPTNO) VALUES (1, 20);
1 Row Created.
SELECT * FROM VV1;
15 Rows Selected.
SELECT * FROM EMP;
15 Rows Selected.
Note:
The new values must satisfy the constraints in on that table.
UPDATE VV1 SET ENAME='DEMO' WHERE EMPNO = 1;
1 Row Updated.
SELECT * FROM VV1;
SELECT * FROM EMP;
DELETE FROM VV1 WHERE EMPNO = 1;
SELECT * FROM VV1;
SELECT * FROM EMP;
COMMIT;
Page 70 of 79

Wipro Confidential

Note:
If we are creating a view which has columns from more than one table in
that case we cant modify the data using the view.
Example:
CREATE OR REPLACE VIEW VV1 AS SELECT ENAME, DNAME
FROM EMP, DEPT
WHERE EMP.DEPTNO = DEPT.DEPTNO;
View Created.
SELECT * FROM VV1;
14 Rows Selected.
INSERT INTO VV1 (ENAME) VALUES ('DEMO');
Error: cannot modify the multiple table join view.
How to change the field names in the view?
Example:
CREATE OR REPLACE VIEW VV1 AS SELECT * FROM EMP;
SELECT * FROM VV1;
Now the column names are the same as that of EMP table. In order to give
different name the columns we need to create a view as follows.
CREATE OR REPLACE VIEW VV1(ENO,ENA,DNO) AS SELECT
EMPNO,ENAME,DEPTNO FROM EMP;
SELECT * FROM VV1;

2. Synonyms
A synonym is an alias for one of the following objects:
a. table
b. object table
c. view
d. object view
e. sequence
f. stored procedure
g. stored function
h. package
i. materialized view
j. java class
k. used defined object object type
l. another synonym

Page 71 of 79

Wipro Confidential

The object does not need to exist at the time of its creation. Synonyms can't be
used in a drop and truncate statements. If this is tried, it results in a ORA00942: table or view does not exist
Syntax:
create synonym <synonym-name> for <object-name>;
create public synonym <synonym-name> for <object-name>;
Public synonyms:
A public synonym (create public synonym) is owned by public rather than the
one who has created it. Therefore, a public synonym is valid for each schema.
Example:
SQL> create table test_ (a number);
Table created.
SQL> create synonym t for test_;
Synonym created.
SQL> insert into t values(4);
1 row created.
SQL> insert into t values(5);
1 row created.
SQL> update t set a =40 where a =4;
1 row updated.
SQL> delete from t where a = 5;
1 row deleted.
SQL> truncate table t;
truncate table t
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> drop table t;
drop table t
*
ERROR at line 1:
ORA-00942: table or view does not exist

Page 72 of 79

Wipro Confidential

3. Sequence:
It is used to generate unique numbers in a sequential manner. It is a database
object. As we have seen earlier NEXTVAL and CURRVAL are the pseudo
columns which are used to access the value from the sequence
Syntax:
CREATE SEQUENCE <sname>
[INCREMENT BY
NUMBER
START WITH
NUMBER
MINVALUE
NUMBER]
MAXVALUE
NUMBER
[CACHE /*NOCACHE NUMBER
CYCLE /*NOCYCLE;]
Sequence Created
Example:
CREATE SEQUENCE SEQ1
INCREMENT BY1
START WITH
1
MINVALUE
1
MAXVALUE
5;
Sequence Created
SELECT * FROM TAB;
This will not display the sequence objects.
CREATE TABLE U1 (NO NUMBER (3));
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
3
4
5
Page 73 of 79

Wipro Confidential

INSERT INTO U1 VALUES(SEQ1.NEXTVAL);


Error : sequence SEQ1.NEXTVAL exceeds MAXVALUE and cannot be
instantiated
How to Increase the Sequence Max Value?
ALTER SEQUENCE:
Syntax:
ALTER SEQUENCE <sname> MAXVALUE NUMBER;
Sequence Altered.
Example:
ALTER SEQUENCE SEQ1 MAXVALUE 10;
SELECT * FROM U1;
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
INSERT INTO U1 VALUES(SEQ1.NEXTVAL);
SELECT * FROM U1;
How to Remove the Sequence from the DB?
Syntax:
DROP SEQUENCE <sname>;
Sequence Dropped.
Example:
DROP SEQUENCE SEQ1;
What is a cyclic sequence?
Once the MAXVALUE specified for the sequence is reached when we try to
access the NEXTVAL we get an error but if we make the sequence cyclic then
on reaching the max value the sequence starts from the initial value again.
How to Make a Sequence as Cyclic?
Example:
CREATE SEQUENCE SEQ1
INCREMENT BY1
START WITH
1
MINVALUE
1
MAXVALUE
3
CACHE
2
CYCLE;
Page 74 of 79

Wipro Confidential

/
Sequence Created.
TRUNCATE TABLE U1;
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
3
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
INSERT INTO U1 VALUES (SEQ1.NEXTVAL);
SELECT * FROM U1;
1
2
3
1
2
3
Note:
The Start with value must be greater than the Min value.
Example:
DROP SEQUENCE SEQ1;
CREATE SEQUENCE SEQ1
INCREMENT BY1
START WITH
0
MINVALUE
2
MAXVALUE
5;
Error : Start with Cannot Less than Minvalue
How to know the current value of the sequence?
SELECT SEQ1.CURRVAL FROM DUAL;

Page 75 of 79

Wipro Confidential

4. Index:
Index is used to make the selection of records faster. An index is a schema
object that contains an entry for each value that appears in the indexed
column(s) of the table or cluster and provides direct, fast access to rows.
Type1:
CREATE INDEX <iname> ON <tname>(fn1,..);
Type2:
CREATE UNIQUE INDEX <iname> ON <tname>(fn1,..);
Type3:
CREATE INDEX <iname> ON CLUSTER <cname>;
Example:
CREATE INDEX II1 ON EMP(ENAME);
Index Created.
SELECT * FROM EMP;
SELECT * FROM EMP WHERE DEPTNO = 10;
The II1 index is not used in the above queries.
SELECT * FROM EMP WHERE ENAME LIKE 'A%';
The II1 index will be used in the above query and this will make the record
selection in faster.
Note:
We cant create more than one index on a field.
Example:
CREATE INDEX II2 ON EMP(ENAME);
Error: such column list already indexed
How to Drop the Index?
DROP INDEX <iname>;
Index Dropped.
Example:
DROP INDEX II1;
Unique Index:
CREATE UNIQUE INDEX II1 ON EMP(ENAME);
Index Created.
Note:
Page 76 of 79

Wipro Confidential

Specify UNIQUE to indicate that the value of the column (or columns) upon
which the index is based must be unique.
It work like the Unique Constraint once an unique index is created on a
column you cannot insert duplicates.
INSERT INTO EMP(EMPNO,ENAME,DEPTNO) VALUES(1,'KING',20);
Error : Unique Constraint (Scott.II1) Violated.
Note : (OCP)
If a table field contains Primary Key / Unique Constraint we cant create an
Index to those fields because automatically an index will be created on the
primary key / Unique field.
Example:
CREATE TABLE U1(NO NUMBER(3) PRIMARY KEY,NA
VARCHAR2(20) UNIQUE);
CREATE INDEX II2 ON U1 (NO);
Error: such column list already indexed
CREATE INDEX II2 ON U1 (NA);
Error: such column list already indexed

5. Cluster:
A cluster is a schema object that contains data from one or more tables, all of
which have one or more columns in common. Oracle stores together all the
rows (from all the tables) that share the same cluster key.
For information on existing clusters, query the USER_CLUSTERS,
ALL_CLUSTERS, and DBA_CLUSTERS data dictionary views.
Clusters are groups of one or more tables that are physically stored together
because they share common columns and usually are used together. Because
related rows are physically stored together, disk access time improves.
Steps to Create a Cluster:
1. Create a cluster.
2. Create the table and add the table fields to the cluster.
3. Create an index for the cluster.
4. Add records to the Cluster tables.
Example:
If we are not going to use cluster then we would be performing the following
operations.
CREATE TABLE STUD_PER (RNO NUMBER (3), NA VARCHAR2 (20));
Table Created.
Page 77 of 79
Wipro Confidential

CREATE TABLE STUD_MARK (RNO NUMBER (3), SEM VARCHAR2


(10);
Table Created.
CREATE TABLE STUD_TC (RNO NUMBER (3), DOL DATE);
Table Created.
CREATE INDEX II1 ON STUD_PER (RNO);
CREATE INDEX II2 ON STUD_MARK (RNO);
CREATE INDEX II3 ON STUD_TC (RNO);
In the above three tables RNO column is the same and we are creating
separate indexes on the above 3 tables for RNO. This is an ideal case where
we can go for a cluster.
1. Create a Cluster:
Syntax:
CREATE CLUSTER <cname> (fieldname DATATYPE(size),....);
Cluster Created.
Example:
CREATE CLUSTER CU1 (NO NUMBER (3));
Cluster Created.
2. Create the table and add the table fields to the cluster.
Syntax:
CREATE TABLE <tname>(tfn DATATYPE(size),...)CLUSTRER clname
(tfn,..);
Table Created.
Example:
CREATE TABLE STUD_PER (RNO NUMBER (3), NA VARCHAR2
(20)) CLUSTER CU1 (RNO);
Table Created.
CREATE TABLE STUD_MARK (RNO NUMBER (3), M1 NUMBER
(3)) CLUSTER CU1 (RNO);
Table Created.
Note:
With out creating a Cluster Index we cannot insert data into the tables
associated with the cluster.
Example:
Page 78 of 79

Wipro Confidential

INSERT INTO STUD_PER VALUES(1,'MUNI');


Error: Cluster tables cannot be used before cluster index is built
3. Create an index for the cluster.
Syntax:
CREATE INDEX <iname> ON CLUSTER <cluname>;
Index Created.
Example:
CREATE INDEX IC1 ON CLUSTER CU1;
Index Created.
Note:
All tables attached to this cluster will use the index created on the cluster.
4. Add records to the tables.
Example:
INSERT INTO STUD_PER VALUES(1,'MUNI');
1 Row Created.
INSERT INTO STUD_MARK VALUES (1, 80);
1 Row Created.
SELECT * FROM STUD_PER;
SELECT * FROM STUD_MARK;

Page 79 of 79

Wipro Confidential

Anda mungkin juga menyukai