SlideShare a Scribd company logo
1 of 344
Copyright  CSC India, 2001. All rights reserved.
SQL
By Venkat
Mail:pichelavenkat@gmail.com
1-2 Copyright  CSC India, 2001. All rights reserved.
SQL Training Agenda
•Introduction to Oracle
•Working with SQL Languages
-- Operators
-- Functions
-- Integrity Constraints
-- Joins
-- Sub queries
-- Schema Objects
Copyright  CSC India, 2001. All rights reserved.
Introduction to Oracle
1-4 Copyright  CSC India, 2001. All rights reserved.
Introduction to Oracle
• What is Oracle
• Overview of RDBMS
• Normalization
1-5 Copyright  CSC India, 2001. All rights reserved.
Relational Database Concept
Dr. E.F. Codd proposed the relational model for
database systems in 1970.
It is the basis for the relational database
management system.
The relational model consists of the following:
– Collection of objects or relations
– Set of operators to act on the relations
– Data integrity for accuracy and consistency
1-6 Copyright  CSC India, 2001. All rights reserved.
Definition of a Relational Database
A relational database is a collection of relations or
two-dimensional tables.
Table Name:
EMPLOYEES
Table Name:
DEPARTMENTS
Oracle Server
1-7 Copyright  CSC India, 2001. All rights reserved.
Model of
system
in client’s
mind
Model of
System in
Clients mind
Entity model of Client’s model
Table model of entity model
Tables on disk
Data Models
1-8 Copyright  CSC India, 2001. All rights reserved.
Entity Relationship Model
Create an entity relationship diagram from
business specifications
• Assign one or more employees to a department
• Some departments do not yet have assigned employees
1-9 Copyright  CSC India, 2001. All rights reserved.
Entity Relationship Modeling Conventions
Entity
• Soft box
• Singular, unique name
• Uppercase
• Synonym in parentheses
Attribute
• Singular name
• Lowercase
• Mandatory marked with “*”
• Optional marked with “o”
Primary marked with “#”
Secondary marked with “(#)”
assigned to
composed of
1-10 Copyright  CSC India, 2001. All rights reserved.
Relating Multiple Tables
• Each row of data in a table is uniquely identified by a primary key (PK).
• You can logically relate data from multiple tables using foreign keys (FK).
Table Name: EMPLOYEES Table Name: DEPARTMENTS
Primary key Foreign key Primary key
1-11 Copyright  CSC India, 2001. All rights reserved.
Communicating with a RDBMS Using SQL
SQL statement
is entered.
Statement is sent to
Oracle Server.
Data is displayed.
1-12 Copyright  CSC India, 2001. All rights reserved.
Relational Database Management System
User tables Data
dictionary
1-13 Copyright  CSC India, 2001. All rights reserved.
SQL Languages
Statement Language
SELECT Data retrieval language
INSERT
UPDATE Data manipulation language (DML)
DELETE
MERGE
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK Transaction control language (TCL)
SAVEPOINT
GRANT
REVOKE Data control language (DCL)
1-14 Copyright  CSC India, 2001. All rights reserved.
SQL Used to
• Querying data
• Inserting, updating, and deleting rows in a table
• Creating, altering, and dropping objects
• Controlling access to the database and its objects
• Guaranteeing database consistency and integrity
1-15 Copyright  CSC India, 2001. All rights reserved.
Tables Used in this Training
EMP  Stores details of all Employees
DEPT Stores details of all Departments
SALGRADE Stores details of salaries for various grades
1-16 Copyright  CSC India, 2001. All rights reserved.
1-17 Copyright  CSC India, 2001. All rights reserved.
1-18 Copyright  CSC India, 2001. All rights reserved.
1-19 Copyright  CSC India, 2001. All rights reserved.
Normalization
Normalization is the process of efficiently
organizing the data in the database
Goals:
•Eliminate redundant data(storing the same
data in more than on table)
•Ensure data dependencies (only storing
related data in a table)
1-20 Copyright  CSC India, 2001. All rights reserved.
Normalization
Types of Normal Forms(Rules):
•First normal form(1NF)
Eliminate duplicative columns from the same table
Create separate tables for each group of related data and
identify each row with a unique column or set of
columns(primary key)
1-21 Copyright  CSC India, 2001. All rights reserved.
Normalization
•Second normal form(2NF)
Meet all the requirements of the first normal form.
Remove subsets of data that apply to multiple rows of a
table and place them in a separate tables.
 Create relationships between these tables by using
foreign keys.
1-22 Copyright  CSC India, 2001. All rights reserved.
Normalization
•Third normal form(3NF)
Meet all the requirements of the second normal form.
Remove columns that are not dependent on the primary key
Copyright  CSC India, 2001. All rights reserved.
Writing Basic SQL Statements
1-24 Copyright  CSC India, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able to
do the following :
• List the capabilities of SQL SELECT statements
• Execute a basic SELECT statement
• Differentiate between SQL statements and iSQL*
Plus commands.
1-25 Copyright  CSC India, 2001. All rights reserved.
Basic SELECT Statement
Syntax :
SELECT * | { [DISTINCT] column | expression
[alias],…}
FROM table;
SELECT identifies what columns
FROM identifies which table
1-26 Copyright  CSC India, 2001. All rights reserved.
Writing SQL Statements
• SQL statements are not case sensitive
• SQL statements can be on one or more lines
• Keywords cannot be abbreviated or split across
lines
• Clauses are usually placed on separate lines
• Indents are used to enhance readability
1-27 Copyright  CSC India, 2001. All rights reserved.
Arithmetic Expressions
Operator Precedence : * / + -
• Multiplication and division take priority over
addition and subtraction
• Operators of the same priority are evaluated from
left to right
• Parentheses are used to force prioritized
evaluation and to clarify statements
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
1-28 Copyright  CSC India, 2001. All rights reserved.
Using Arithmetic Examples
SELECT Ename, Sal, Sal +500 FROM Emp;
1-29 Copyright  CSC India, 2001. All rights reserved.
Operator Precedence :
SELECT Ename, Sal, 12*Sal +500
FROM Emp;
1-30 Copyright  CSC India, 2001. All rights reserved.
Using Parentheses :
SELECT Ename, Sal, 12*(Sal +500 )
FROM Emp;
1-31 Copyright  CSC India, 2001. All rights reserved.
Defining a NULL value
Syntax: NVL(expr1,expr2)
• A null is a value that is unavailable, unassigned, unknown, or inapplicable.
• A null is not the same as zero or a blank space.
SQL> Select Empno, Ename,Sal,Comm,Sal+Comm "Total Salary“
from Emp where deptno =30;
SQL> Select Empno, Ename, Sal, Comm, Sal+ Nvl (Comm,0)
"Total Salary“ from Emp where deptno =30;
SQL> Select Empno, Ename ,Sal,
Nvl (To_char (Comm),'Not Applicable') commission
from Emp where Deptno =30;
Note: Arithmetic expressions containing a null value evaluate to null
1-32 Copyright  CSC India, 2001. All rights reserved.
1-33 Copyright  CSC India, 2001. All rights reserved.
Defining a Column Alias
A column alias :
• Renames a column heading
• Is useful with calculations
• Immediately follows the column name
• An optional AS keyword can be used
• Requires double quotations if it contains spaces or
special characters
Ex:
SELECT Ename Employee name, 12*Sal AS “Annual
Salary”
FROM Emp;
1-34 Copyright  CSC India, 2001. All rights reserved.
Defining a Column Alias
1-35 Copyright  CSC India, 2001. All rights reserved.
Concatenation Operator
• Concatenates columns or character strings to other
columns
• Operator is two vertical bars ( || )
• Creates a resultant column that is a character
expression
Example :
1-36 Copyright  CSC India, 2001. All rights reserved.
Literal Character Strings
 A character, a number, or a date included in the
SELECT list
 Date and character literal values must be enclosed
within single quotation marks
 Each character string is output once for each row
returned
 Literal strings included in the query are treated as a
column in the SELECT list.
Ex:
1-37 Copyright  CSC India, 2001. All rights reserved.
Eliminating Duplicate Rows
The default display is all rows, including duplicate rows
To eliminate duplicate rows, use the DISTINCT keyword
Note : The duplicate row are just not displayed but they
remain in the database
1-38 Copyright  CSC India, 2001. All rights reserved.
Interacting with Oracle Server
We can interact with Oracle Server by two environments
SQL*Plus :
- Character based
- Provides a line editor for modifying SQL statements
iSQL*Plus :
- GUI based
- Provides online editing for modifying SQL statements
- Accessed from browser
Copyright  CSC India, 2001. All rights reserved.
Restricting and Sorting Data
1-40 Copyright  CSC India, 2001. All rights reserved.
Objective
After completing this lesson, you should be able to
do :
• Limit the rows retrieved by a query
• Sort the rows retrieved by a query
1-41 Copyright  CSC India, 2001. All rights reserved.
Limiting the Rows Selected
Use the WHERE clause
SELECT * | { [DISTINCT] column/expression [alias],…
}
FROM table
[ WHERE conditions(s) ];
The WHERE clause follows the FROM clause.
The condition is composed of column names,
expressions, constants and a comparison operator
Ex :
SELECT Empno, Ename, Job
FROM Emp
WHERE Deptno=10;
1-42 Copyright  CSC India, 2001. All rights reserved.
Character Strings and Dates
Are enclosed in single quotation marks
Character values are case sensitive
Date values are format sensitive
The default date format is DD-MON-RR
Ex:
1-43 Copyright  CSC India, 2001. All rights reserved.
Comparison Operators
They are used in the WHERE clause in the following
Format.
Syntax :
….. WHERE Expr operator value
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> , != , ^= Not Equal to
1-44 Copyright  CSC India, 2001. All rights reserved.
Other Comparison Operators
Use the LIKE condition to perform wildcard
searches of valid search string values
- % denotes zero or many characters
- _ denotes one character (underscore)
Operator Meaning
BETWEEN..AND… Between two values (inclusive)
IN(Set) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
1-45 Copyright  CSC India, 2001. All rights reserved.
Examples on using Comparison Operators
SQL> SELECT * from Emp Where deptno IN (10,20);
SQL> SELECT Empno,Ename,Job,Sal FROM Emp WHERE Job
IN('MANAGER','CLERK');
SQL> SELECT * from Emp Where Ename LIKE ‘S%’;
SQL> SELECT * from Emp Where Hiredate LIKE ‘%JAN%’;
SQL> SELECT * from Emp Where Ename LIKE '_____'
SQL> SELECT * from Emp Where Ename LIKE ‘S_I_H’
SQL> SELECT * from Emp Where Comm IS NULL;
SQL> SELECT * from Emp Where NOT deptno=10;
SQL> SELECT * from Emp Where EXISTS (select deptno from dept);
1-46 Copyright  CSC India, 2001. All rights reserved.
Examples on using Comparison Operators
1-47 Copyright  CSC India, 2001. All rights reserved.
Examples on using Comparison Operators
1-48 Copyright  CSC India, 2001. All rights reserved.
Logical Operators
Operator Meaning
AND Returns TRUE if both component
conditions are true
OR Returns TRUE if either component
condition is true
NOT Returns TRUE if the following
condition is false
•Combines the result of two component conditions to
produce a single result
• With these operators we can use several conditions in one
WHERE clause.
1-49 Copyright  CSC India, 2001. All rights reserved.
Using the AND Operators
AND requires both conditions to be true
SELECT Empno, Ename, Job, Sal
FROM Emp
WHERE Sal >=2000 AND Job LIKE '%MAN%';
AND TRUE FALSE NULL
TRUE TRUE FALSE NULL
FALSE FALSE FALSE FALSE
NULL NULL FALSE NULL
1-50 Copyright  CSC India, 2001. All rights reserved.
Using the OR operator
OR requires either condition to be true
SELECT Empno, Ename, Job, Sal
FROM Emp
WHERE Sal >=2000 OR Job LIKE '%MAN%';
OR TRUE FALSE NULL
TRUE TRUE TRUE TRUE
FALSE TRUE FALSE NULL
NULL TRUE NULL NULL
1-51 Copyright  CSC India, 2001. All rights reserved.
Examples
1-52 Copyright  CSC India, 2001. All rights reserved.
Using the NOT Operator
To negate the result we use the NOT Operator
SELECT Ename, Job, Sal
FROM Emp
WHERE Job NOT IN('MANAGER','CLERK');
1-53 Copyright  CSC India, 2001. All rights reserved.
Rules of Precedence
Order Evaluated Operator
1 Arithmetic operators
2 Concatenation operator
3 Comparison conditions
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 NOT logical condition
7 AND logical condition
8 OR logical condition
Override rules of precedence by using parentheses.
The same precedence operators work from left to right.
1-54 Copyright  CSC India, 2001. All rights reserved.
ORDER BY Clause
Sort rows with the ORDER BY clause
- ASC : Ascending order, default
- DESC : Descending order
Syntax :
SELECT expr,column(s) FROM table
[WHERE condition(s)]
[ORDER BY {column, expr} [ASC|DESC] ] ;
Default Ordering of Data
 Numeric values lowest values first 1 - 999
 Date values earliest value first 1-jan-92 before 1-jan-95
 Character values alphabetical order a first and z last
 Null values last
1-55 Copyright  CSC India, 2001. All rights reserved.
Sorting Examples
SELECT Ename, Job, Deptno, Hire_date
FROM Emp
ORDER BY Hire_date ;
SELECT Ename, Job, Deptno, Hire_date
FROM Emp
ORDER BY Hire_date DESC ;
 Sort order can be specified by position value also
SELECT Ename, Job, Deptno, Hire_date
FROM Emp
ORDER BY 3 DESC ;
1-56 Copyright  CSC India, 2001. All rights reserved.
Some more sorting methods
Sorting by Column Alias
SELECT Empno, Ename, Sal*12 annual_sal
FROM Emp
ORDER BY annual_sal ;
Sorting by Multiple Columns
- we can use multiple columns in the ORDER BY
clause
- The order of ORDER BY list is the order of sort
SELECT Ename , Deptno, Sal
FROM Emp
ORDER BY Deptno, Sal DESC;
1-57 Copyright  CSC India, 2001. All rights reserved.
Examples
1-58 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to :
Use the WHERE clause to restrict rows of output
- use the comparison conditions
- use the BETWEEN..AND.. , IN , LIKE , and NULL
conditions
- Apply the logical AND, OR, and NOT operators
Use the ORDER BY clause to sort rows of output
Copyright  CSC India, 2001. All rights reserved.
Functions
1-60 Copyright  CSC India, 2001. All rights reserved.
Objectives
• After completing this lesson, you should be able
to do the following :
• Describe various types of functions available in
SQL
• Use character, number and date functions in
SELECT statements
• Describe the use of conversion functions
1-61 Copyright  CSC India, 2001. All rights reserved.
SQL Functions
Function
Function
performs action
arg1
arg2
arg n
Result value
Input
Output
1-62 Copyright  CSC India, 2001. All rights reserved.
Two types of SQL Functions
Single row functions : Operate on single rows only and
return one result per row .
Different Types of Single row functions :
Character Number Date Conversion General
Multiple row functions: Manipulates groups of rows to
give one result per group of rows. Also called as
group functions
Functions
Single-row
functions
Multiple-row
functions
1-63 Copyright  CSC India, 2001. All rights reserved.
Single Row Functions
Single row functions :
• Manipulate data items
• Accept arguments and return one value
• Act on each row returned
• Return one result per row
• May modify the data type
• Can be nested
• Accept arguments which can be a column or an
expression function_name [ (arg1, arg2, …) ]
• Can be used in SELECT, WHERE, and ORDER
BY clauses
1-64 Copyright  CSC India, 2001. All rights reserved.
Character Functions
Character Functions
Case-manipulation
functions
Character-manipulation
functions
LOWER
UPPER
INITCAP
CONCAT
SUBSTR
LENGTH
INSTR
LPAD | RPAD
TRIM
REPLACE
1-65 Copyright  CSC India, 2001. All rights reserved.
Case Manipulation Functions
These functions convert case for character strings.
- LOWER : converts character strings to lowercase
- UPPER : converts character strings to uppercase
- INITCAP: converts the first letter of each word to
uppercase and remaining letters to lowercase
Example :
SELECT LOWER('SQL Course') , INITCAP('SQL
Course') From Dual
These functions are useful for String comparisons in
WHERE clause
Example
I. SELECT * FROM Emp WHERE Ename =
UPPER('scott');
1-66 Copyright  CSC India, 2001. All rights reserved.
Character-Manipulation Functions
These functions manipulate character strings :
• CONCAT : Joins values together
• SUBSTR : Extracts a string of determined length
• LENGTH : Shows the length of a string as a numeric value
• INSTR : Finds numeric position of a named character
• LPAD : Pads the character value right-justified
• RPAD : Pads the character value left-justified
• TRIM : Trims heading or trailing characters( or both)
from a character string
1-67 Copyright  CSC India, 2001. All rights reserved.
Examples
Query Output
Select CONCAT('Hello', 'World') HelloWorld
SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld'), 10
INSTR('HelloWorld', 'W'), 6
LPAD('Hello',10, '*'), *****Hello
RPAD('Hello',10, '*'), Hello*****
TRIM('H' FROM 'HelloWorld') elloWorld
FROM dual;
1-68 Copyright  CSC India, 2001. All rights reserved.
Character Functions:
Character Functions Returning Character Values
(CHR,LOWER,UPPER,LTRIM,RTRIM,INITCAP,REPLACE,
SUBSTRING,INSTRING)
CHR returns the character having the binary equivalent to n
SELECT CHR(67)||CHR(65)||CHR(84) "Dog" FROM DUAL;
Dog
---
CAT
LOWER returns char, with all letters lowercase
SELECT LOWER('MR. SCOTT MCMILLAN') "Lowercase" FROM DUAL;
UPPER returns char, with all letters uppercase.
SELECT UPPER('Large') "Uppercase" FROM DUAL;
Character-Manipulation Functions
1-69 Copyright  CSC India, 2001. All rights reserved.
LTRIM removes characters from the left of char, with all the leftmost characters that
appear in set removed
SELECT LTRIM ( 'xyxXxyLAST WORD ','xy‘ ) "LTRIM example" FROM DUAL;
Result: XxyLAST WORD
RTRIM returns char, with all the rightmost characters that appear in set removed
SELECT RTRIM ('BROWNINGyxXxy‘ ,'xy') "RTRIM example" FROM DUAL;
Result: BROWNINGyxX
INITCAP returns char, with the first letter of each word in uppercase, all other letters in
lowercase
SELECT INITCAP('the soap') "Capitals" FROM DUAL;
Result: The Soap
REPLACE returns char with every occurrence of search string replaced with
replacement string.
SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL;
Result : BLACK and BLUE
Character-Manipulation Functions
1-70 Copyright  CSC India, 2001. All rights reserved.
SUBSTR return a portion of string, beginning at character position, substring length
characters long.
SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL;
Result: CDEF
Character Functions Returning Number Values:
ASCII returns the decimal representation in the database character set of the first
character of char.
SELECT ASCII('Q') FROM DUAL;
Result: 81
INSTR function returns an integer indicating the position of the character in string that
is the first character of this occurrence.
SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL;
Result: 14
LENGTH function return the length of char
SELECT LENGTH('CANDIDE') "Length in characters" FROM DUAL;
Result:7
Character-Manipulation Functions
1-71 Copyright  CSC India, 2001. All rights reserved.
Number Functions
Numeric functions accept numeric input and
return numeric values
(ABS,CEIL,FLOOR, MOD,POWER,,ROUND,TRUNC)
--ABS returns the absolute value of n.
SQL> SELECT ABS(-15) "Absolute" FROM DUAL;
Absolute
----------
15
--CEIL returns smallest integer greater than or equal to n
SELECT CEIL(15.7) "Ceiling" FROM DUAL;
Ceiling
----------
16
1-72 Copyright  CSC India, 2001. All rights reserved.
Number Functions
FLOOR returns largest integer equal to or less than n.
SELECT FLOOR(15.7) "Floor" FROM DUAL;
Floor
----------
15
MOD returns the remainder of m divided by n. Returns m if n is 0.
SELECT MOD(11,4) "Modulus" FROM DUAL;
Modulus
----------
3
POWER returns m raised to the nth power
SELECT POWER(3,2) "Raised" FROM DUAL;
Raised
----------
9
1-73 Copyright  CSC India, 2001. All rights reserved.
Number Functions
ROUND returns number rounded to integer places right of the decimal point
SELECT ROUND(15.193,1) "Round" FROM DUAL;
Round
----------
15.2
The TRUNC (number) function returns n truncated to m decimal places.
SELECT TRUNC(15.79,1) "Truncate" FROM DUAL;
Truncate
----------
15.7
> SELECT ROUND(45.92,1),ROUND(45.92,0),ROUND(45.92,-1),
TRUNC(45.92,1), TRUNC(45.92,0), TRUNC(45.92,-1),
MOD(45 , 7 ), MOD(45,9)
FROM DUAL;
> O/p : 45.9 46 50 45.9 45 40 3 0
1-74 Copyright  CSC India, 2001. All rights reserved.
Date Functions
Function Description
MONTHS_BETWEEN(date1,
date2)
Number of months between two
dates
ADD_MONTHS(date, n) Add calendar months to date
NEXT_DAY(date, ‘char’) Next day of the date specified
LAST_DAY(date) Last day of the month
ROUND(date [, ‘fmt’] ) Round date
TRUNC(date [,’fmt’]) Truncate date
Datetime functions operate on values of the DATE datatype.
All datetime functions return a datetime or interval value of
DATE datatype, except the MONTHS_BETWEEN function,
which returns a number.
1-75 Copyright  CSC India, 2001. All rights reserved.
Using Date Functions
SELECT
MONTHS_BETWEEN(’01-sep-95’ , ’11-jan-94’)
ADD_MONTHS(’11-JAN-94’ , 6)
NEXT_DAY(’01-SEP-95’ , ‘FRIDAY’)
LAST_DAY(’01-FEB-95’)
ROUND(SYSDATE , ‘MONTH’)
ROUND(SYSDATE , ‘YEAR’)
TRUNC(SYSDATE, ‘MONTH’)
TRUNC(SYSDATE, ‘YEAR’)
SYSDATE
FROM DUAL;
19.67741941
1-JUL-94
08-SEP-95
28-FEB-95
01-AUG-95
01-JAN-96
01-JUL-95
01-JAN-95
25-JUL-95
Output
1-76 Copyright  CSC India, 2001. All rights reserved.
Date Functions Examples
1-77 Copyright  CSC India, 2001. All rights reserved.
Date Functions Examples
1-78 Copyright  CSC India, 2001. All rights reserved.
Conversion Functions
Data type
conversion
Implicit data type
conversion
Explicit data type
conversion
1-79 Copyright  CSC India, 2001. All rights reserved.
Implicit Data Type Conversion
If a different data type value comes for an expected data
type value then Oracle server automatically converts the
former to the later data type and uses it
This can happen in assignments or expression evaluations
The implicit conversion of string to number data type
happens only when it is compatible
Example :
SELECT Ename, Job, Sal
FROM Emp
WHEREdeptno= '10'; ;
Although implicit data type conversion is available, it is
recommended to do explicit data type conversion to
ensure reliability.
1-80 Copyright  CSC India, 2001. All rights reserved.
Explicit Data Type Conversion
Date or Number to Varchar2 string
TO_CHAR(number/date , [fmt] )
Character to number
TO_NUMBER(char , [fmt] )
Character to Date
TO_DATE( char, [fmt] )
5000
$5,000
1-81 Copyright  CSC India, 2001. All rights reserved.
Explicit Conversion functions
T0_CHAR Converts number and date values in to
variable character format
Sql> Select TO_CHAR (sysdate, ’dd/month/yyyy’ )
Today from dual;
Result: 09/december /2008
Sql> Select TO_CHAR (258560,'$9,99,999') from Dual;
Result: $2,58,560
1-82 Copyright  CSC India, 2001. All rights reserved.
Explicit Conversion functions
TO_DATE –> Converts variable date formats into default
date formats
Select TO_CHAR (TO_DATE('18-APR-06','DD-MON-YY'),
'dd/month/yyyy') Today from dual;
Result: 18/april /2006
Select TO_CHAR (TO_DATE('18-APR-2006',
'DD-MON-YYYY'),'dd/month/yyyy') Today from dual;
Result: 18/april /2006
1-83 Copyright  CSC India, 2001. All rights reserved.
Explicit Conversion functions
TO_NUMBER –>Converts Character datatype containing a
number in the format to a value of NUMBER datatype
Select TO_NUMBER('$5,46,350',’L9,99,999')from dual
Result: 546350
Format
Select TO_NUMBER('$2,555.760', 'L9,999.999')from dual
Result: 2555.76
1-84 Copyright  CSC India, 2001. All rights reserved.
1-85 Copyright  CSC India, 2001. All rights reserved.
Elements of the Date Format
Model
Format Model Description
YYYY Full year in numbers
YEAR Year spelled out
MM Two-digit value for month
MONTH Full name of the month
MON Three-letter abbreviation of the month
DY Three-letter abbreviation of day of the
week
DAY Full name of the day of the week
DD Numeric day of the month
1-86 Copyright  CSC India, 2001. All rights reserved.
Elements of the Date Format
Model
Format Model Description
HH or HH12 or HH24 Hour of day, or hour(1-12), or hour(0-23)
MI Minute (0-59)
SS Second (0-59)
SSSSS Seconds past midnight ( 0-86399 )
AM or PM Meridian indicator
A.M. or P.M. Meridian indicator with periods
1-87 Copyright  CSC India, 2001. All rights reserved.
RR Date Format
Example :
SELECT ename, hiredate FROM emp
WHERE hiredate < TO_DATE(’01-JAN-60’ ,‘DD-MON-
RR’);
If the specified two-digit year is
0-49 50-99
If two
digits of
the
current
year are :
0-49 The return date is in
current century
The return date is in
century before current
one
50-99 The return date is in the
century after current one
The return date is in
current century
1-88 Copyright  CSC India, 2001. All rights reserved.
RR Date Format
If the specified two-digit year is
0-49 50-99
If two
digits of
the
current
year are :
0-49 The return date is in
current century
The return date is in
century before current
one
50-99 The return date is in the
century after current one
The return date is in
current century
Current Year Given Date Interpreted( RR) Interpreted (YY)
1994 27-OCT-95 1995 1995
1994 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017
1-89 Copyright  CSC India, 2001. All rights reserved.
YY Date Format
Command is Run in 2009
Command is Run in 1999
1-90 Copyright  CSC India, 2001. All rights reserved.
RR Date Format
Command is Run in 2009
Command is Run in 1999
1-91 Copyright  CSC India, 2001. All rights reserved.
Nesting Functions
• Single – row functions can be nested to any level
• Nested Functions are evaluated from deepest level to
the least deep level
Ex :
SELECT TO_CHAR (TO_DATE('18-APR-06’),
'dd/month/yyyy') Today from dual;
Result : 18/april /2006
1-92 Copyright  CSC India, 2001. All rights reserved.
General Functions
These functions work with any data type and pertain
to using nulls.
NVL( expr1, expr2)
NVL2(expr1, expr2, expr3)
NULLIF(expr1, expr2)
COALESCE(expr1, expr2,…..,exprn)
Note : The NVL2, NULLIF, COALESCE functions are
introduced in Oracle 9i
1-93 Copyright  CSC India, 2001. All rights reserved.
NVL Function
• Converts a null to an actual value
• Data types must match
• Useful for expressions having null values as with this,
null values converts to a meaningful value
Syntax :
NVL (expr1, expr2 )
If expr1 is null then expr2 is returned else expr1 is
returned
Example :
SELECT NVL(10,20) FROM DUAL;
SELECT NVL(null,20) FROM DUAL;
1-94 Copyright  CSC India, 2001. All rights reserved.
Using NVL2 function
NVL2 Function
NVL2(expr1, expr2, expr3)
If expr1 is not null then expr2 is returned else expr3
is returned
Example :
Output
SELECT NVL2(10,20,30) FROM DUAL ; 20
SELECT NVL2(NULL,20,30) FROM DUAL ; 30
1-95 Copyright  CSC India, 2001. All rights reserved.
Using NULLIF function
NULLIF function
NULLIF(expr1, expr2)
If expr1 and expr2 are equal then null else expr1 is
returned
Example :
SELECT NULLIF(4*3 , 3*2), NULLIF( 2*3, 3*2)
FROM DUAL;
O/p : 12 -
Null is there but it will not appear
1-96 Copyright  CSC India, 2001. All rights reserved.
Using the COALESCE Function
The advantage of the COALESCE function over the NVL
function is that this function can take multiple
alternate values.
COALESCE(expr1, expr2, expr3….,exprn)
This checks sequentially from expr1 to exprn and
returns first non-null value
Example :
SELECT COALESCE(NULL,NULL,NULL,2,NULL,10,20)
FROM DUAL;
1-97 Copyright  CSC India, 2001. All rights reserved.
DECODE Function
Facilitates conditional inquiries by doing
the work of a CASE or IF-THEN-ELSE
statement
DECODE (col /expression, search1, result1
[, search2, result2,...,]
[, default])
1-98 Copyright  CSC India, 2001. All rights reserved.
Using the DECODE Function
SQL> SELECT job, sal,
DECODE(job, 'ANALYST', SAL*1.1,
'CLERK', SAL*1.15,
'MANAGER', SAL*1.20,
SAL)
REVISED_SALARY
FROM Emp;
JOB SAL REVISED_SALARY
--------- --------- --------------
PRESIDENT 5000 5000
MANAGER 2850 3420
MANAGER 2450 2940
...
14 rows selected.
1-99 Copyright  CSC India, 2001. All rights reserved.
Decode:
1-100 Copyright  CSC India, 2001. All rights reserved.
Conditional Expressions
To Provide the use of IF-THEN-ELSE logic within a SQL
statement, use :
- CASE expression
- DECODE function
CASE expression
CASE expr WHEN comparison_expr1 THEN
return_expr1
[WHEN comparison_expr2 THEN return_expr2
ELSE else_expr ]
END
DECODE function
DECODE(col/expr, search1, result1
[, search2, result2,…] [, default] )
1-101 Copyright  CSC India, 2001. All rights reserved.
Examples
SELECT CASE ‘a’ WHEN ‘b’ THEN ‘hello b’
WHEN ‘a’ THEN ‘hello a’
ELSE ‘hello somebody’
END hello
FROM DUAL;
SELECT DECODE('A','B','HELLO B','A','HELLO A',
'HELLO X') HELLO
FROM DUAL
1-102 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to :
• Perform calculations on data using functions
• Modify individual data items using functions
• Manipulate output for groups of rows using
functions
• Alter date formats for display using functions
• Convert column data types using functions
• User NVL functions
• Use IF-THEN-ELSE logic
Copyright  CSC India, 2001. All rights reserved.
Group Functions
1-104 Copyright  CSC India, 2001. All rights reserved.
Objective
After completing this lesson, you should be able to
do the following :
• Identify the available group functions
• Describe the use of group functions
• Group data using the GROUP BY clause
• Include or exclude grouped rows by using the
HAVING clause
1-105 Copyright  CSC India, 2001. All rights reserved.
Group Functions
Group Functions operate on sets of rows to give one
result per group
Syntax :
SELECT [column, ] group_function(column), ….
FROM table
[WHERE condition]
[GROUP BY column]
[HAVING group_condition]
[ORDER BY column] ;
• All group functions ignore null values. To substitute a
value for null values use NVL functions
• The Oracle server implicitly sorts the result set in
ascending order when using a GROUP BY clause.
1-106 Copyright  CSC India, 2001. All rights reserved.
Types of Group Functions
Function Description
AVG([DISTINCT|ALL] n) Average value of n
COUNT(
{ *| [DISTINCT|ALL] expr } )
Number of rows where expr
evaluates to not null.
For *, including duplicates and
rows with nulls also
MAX( [DISTINCT|ALL] expr ) Maximum value of expr
MIN( [DISTINCT|ALL] expr) Minimum value of expr
STDDEV( [DISTINCT|ALL] x) Standard deviation of n
SUM ( [DISTINCT|ALL] n) Sum values of n
VARIANCE( [DISTINCT|ALL]x) Variance of n
1-107 Copyright  CSC India, 2001. All rights reserved.
Group functions Examples:
Sql> select count(*),count (distinct(comm)) ,count(comm)
from Emp;
Sql> select max(sal) max_sal, min(sal) min_sal, avg(sal) avg_sal,
sum(sal) sum_sal FROM Emp;
1-108 Copyright  CSC India, 2001. All rights reserved.
Using the Group Functions
The AVG and SUM are used with numeric data.
The MIN and MAX functions used with any data type
The COUNT returns the number of rows with non null
values.
Use DISTINCT clause not to consider duplicate values
Group functions do not consider null values. To consider
user NVL functions.
Example :
Select sum(sal), avg(comm), avg(nvl(comm,0)),
min(hiredate), max(hiredate), count(*) strength
FROM Emp;
1-109 Copyright  CSC India, 2001. All rights reserved.
Group functions Examples:
Select deptno
,max(sal) max_sal
,min(sal) min_sal
,avg(sal) avg_sal
,sum(sal) sum_sal
from Emp group by deptno;
1-110 Copyright  CSC India, 2001. All rights reserved.
Creating Groups of Data
 Use GROUP BY clause to divide the table information into small
groups
 Use group functions to get summary information for each group
 All individual columns other than group functions must be specified in
the GROUP BY clause list, when using GROUP BY
 Any column other than selected column can also be placed in
GROUP BY clause
 By default rows are sorted by ascending order of the column included
in the GROUP BY list.
Example :
SELECT deptno, AVG(Sal)
FROM Emp
GROUP BY deptno;
1-111 Copyright  CSC India, 2001. All rights reserved.
Excluding Group Results
To restrict groups we have to use HAVING clause
- Rows are grouped
- The group function is applied
- Groups matching the HAVING Clause are displayed.
Example :
SELECT Deptno, MAX(sal)
FROM Emp
GROUP BY Deptno
HAVING MAX(sal) > 3000;
1-112 Copyright  CSC India, 2001. All rights reserved.
Group functions Examples:
Select deptno, count(deptno)
From Emp
Group by deptno
Having count(*)>3;
1-113 Copyright  CSC India, 2001. All rights reserved.
Group functions Examples:
Sql> select deptno, count(deptno)
From Emp
Where deptno in(20,30)
Group by deptno
Having count(*)>3
Order by 1;
1-114 Copyright  CSC India, 2001. All rights reserved.
Nesting of Group Functions
Group functions can be nested to a depth of two.
Example :
SELECT MAX(AVG(salary))
FROM Emp
GROUP BY Deptno ;
1-115 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to :
• Use the group functions COUNT, MAX, MIN, AVG
• Write queries that use the GROUP BY clause
• Write queries that use the HAVING clause
Copyright  CSC India, 2001. All rights reserved.
Formatting Output Using
SQL*Plus
1-117 Copyright  CSC India, 2001. All rights reserved.
Objective
After completing this lesson, you should be able to do :
• Produce queries that require a substitution variables
• Customize the iSQL*Plus environment
• Produce more readable output
• Create and execute script files
1-118 Copyright  CSC India, 2001. All rights reserved.
Substitution Variables
Some times, there is a need of user interaction to
create interactive reports
This can be achieved with the substitution variables
Use substitution variables to :
- To temporarily store values
~ Single ampersand (&)
~ Double ampersand (&&)
~ DEFINE command
- Pass variable values between SQL statement
- Dynamically after headers and footers
1-119 Copyright  CSC India, 2001. All rights reserved.
Using the & substitution variable
Use a variable prefixed with an ampersand (&) to prompt
the user for a value
Example :
SELECT Empno ,Ename , Sal
FROM Emp
WHERE Deptno= &dno;
Use single quotation marks for date and character
values
Example :
SELECT Empno ,Ename , Sal
FROM Emp
WHERE Job= '&job_name';
1-120 Copyright  CSC India, 2001. All rights reserved.
Defining Substitution Variables
The DEFINE command predefines variables
A defined variable is available for the current
session only
It remains defined until
- it cleared using UNDEFINE command Or
- Exit iSQL*Plus or SQL*Plus environment
Command Description
DEFINE variable = value Creates a user variable with the
CHAR data and assigns a value to it
DEFINE variable Displays the variable, its value, and
its data type
DEFINE Displays all user variables with their
values and data types
1-121 Copyright  CSC India, 2001. All rights reserved.
Using the DEFINE Command
Create the substitution variable using the DEFINE
command
Use a variable prefixed with an ampersand (&) to substitute
the value in the SQL statement.
To change the value UNDEFINE the variable and recreate it.
 DEFINE employee_num = 1
 SELECT ‘hello world’ FROM DUAL
WHERE &enum = &employee_num ;
Here, enum variable is undefined and hence asks the user
for input. Depending on the value and already defined
employee_num value comparison is done and result is
displayed
UNDEFINE employee_num
1-122 Copyright  CSC India, 2001. All rights reserved.
Use the && Substitution variable
Use the double ampersand (&&) if you want to reuse
the variable without prompting the user each time.
Example :
SELECT ‘welcome to ‘ || ‘&& name’ , ‘Hello ‘
||’&name’
FROM DUAL ;
The value supplied is stored to that variable using
DEFINE command internally. Hence its value
persists for this session.
For any change in the value use UNDEFINE command
1-123 Copyright  CSC India, 2001. All rights reserved.
Using the VERIFY Command
Use the VERIFY command to toggle the display of
the substitution variable, before and after
iSQL*Plus replaces substitution variable with
values.
First set verify command using
SET VERIFY ON
This will show the text of command before and after
it replaces the substitution variables with values
1-124 Copyright  CSC India, 2001. All rights reserved.
Customizing the iSQL*Plus
Environment
Use SET commands to control current session
SET system_variable value
Verify what you have set by using the SHOW
command
- SET ECHO ON
- SHOW ECHO
O/p : echo ON
Use SHOW ALL to see all SET variable values
All format commands remain in effect until the end
of iSQL*Plus session or the settings are
overwritten or cleared
If alias is present for a column, then reference the
alias name, not the column name.
1-125 Copyright  CSC India, 2001. All rights reserved.
SET Command Variables
Examples :
SET HEADING OFF
SET FEEDBACK 4
SET Variable and Values Description
ARRAY [SIZE] { 20 | n } Sets the database data fetch size
FEED[BACK]
{6|n|OFF|ON}
Displays the number of records returned
by a query when the query selects at least
n records
HEA[DING] {OFF|ON} Determines whether column headings are
displayed in reports
LONG {80 | n} Sets maximum width for displaying
LONG values
1-126 Copyright  CSC India, 2001. All rights reserved.
iSQL*Plus Format Commands
Command Description
COL[UMN][column option] Controls column formats
TTI[TLE] [text | OFF | ON ] Specifies a header to appear at the top
of each page of the report
BTI[TLE] [text | OFF | ON] Specifies a footer to appear at the
bottom of each page of the report
BRE[AK][ON
report_element]
Suppresses duplicate values and
divides rows of data into sections by
using line breaks
1-127 Copyright  CSC India, 2001. All rights reserved.
The COLUMN Command
Controls display of a column :
COL[UMN] [{column | alias} [OPTION] ]
The various Column options are :
- CLE[AR] clears any column formats
- HEA[DING] text sets the column heading
- FOR[MAT] format changes the display of the column
using a format model
- NOPRINT | PRINT not to display / display
- NUL[L] text specifies text to be displayed for nulls
Example :
 COLUMN mgr NULL “no mgr”
 SELECT * from emp;
1-128 Copyright  CSC India, 2001. All rights reserved.
Using the Format Options
Break : To suppress duplicates
- BREAK ON job
TTITLE : To Display headers
- TTITLE ‘Salary/Report’
BTITLE : To display footers
- BTITLE ‘Confidential’
CLEAR : To clear the settings
- CLEAR COLUMN
- CLEAR BREAK
1-129 Copyright  CSC India, 2001. All rights reserved.
Sample Report
 SET FEEDBACK OFF
 TTITLE ‘Employee | Report’
 BTITLE ‘Confidential’
 BREAK ON job
 COLUMN job HEADING ‘Job|Category’
 COLUMN sal HEADING sal FORMAT $99,999.99
 SELECT job, ename, sal
FROM emp ;
 CLEAR columns
 CLEAR break
1-130 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to :
 Use iSQL*Plus substitution variables to store values
temporarily
 Use SET commands to control the current
iSQL*Plus environment
 Use the COLUMN command to control the display of
a column
 Use the BREAK command to suppress duplicates
and divide rows into sections
 Use the TTITLE and BTITLE commands to display
headers and footers.
Copyright  CSC India, 2001. All rights reserved.
Manipulating Data
1-132 Copyright  CSC India, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able to do :
• Describe each DML statement
• Insert rows into a table
• Update rows in a table
• Delete rows from a table
• Merge rows in a table
• Control transactions
1-133 Copyright  CSC India, 2001. All rights reserved.
Data Manipulation Language
It is core part of SQL.
A DML statement is executed when you :
- Add new rows to a table
- Modify existing rows in a table
- Remove existing rows from a table
A transaction consists of a collection of DML
statements that form a logical unit of work.
They are useful for the maintenance of Integrity of
database
1-134 Copyright  CSC India, 2001. All rights reserved.
The INSERT Statement Syntax
Add new rows to a table by using the INSERT
statement
INSERT INTO table [ (column [, column…]) ]
VALUES (value [, value … ] ) ;
Example :
 INSERT INTO dept
VALUES ( 10, ’Sales’,’vizag’);
Substitution variables can also be used
 INSERT INTO departments
VALUES ( 10, ’Sales’, ‘&location’ );
1-135 Copyright  CSC India, 2001. All rights reserved.
INSERT Statement Examples
• Syntax:
– Insert into <table_name> values (val1,val2,val3……);
SQL> INSERT into Emp values (1,’Allen’,5000,’20-jun-06’,10);
• Inserting data into the specified columns
• Syntax:
– Insert into <table_name>(col1,col2,col3) values (val1,val2,val3);
SQL> IINSERT into Emp (empno,ename,deptno) values (2,’Miller’,20);
• Inserting data by using Substitution variables
• Insert into <table_name> values (&val1,&val2,&val3….);
SQL> INSERT into Emp values (&empno, ’&ename’ , &deptno);
Note: Character and Date values should enclose within single quotes.
1-136 Copyright  CSC India, 2001. All rights reserved.
Copying Row from Another Table
Write INSERT statement with a sub query
INSERT INTO copy_emp(id, name, salary,comm)
SELECT empno, ename, sal, comm
FROM emp WHERE job_id LIKE ‘%MAN%’ ;
• Do not use the VALUES clause
• Match the number of columns and their data
types in the INSERT clause to those in the sub
query
1-137 Copyright  CSC India, 2001. All rights reserved.
Changing Data using UPDATE statement
Modify existing rows with the UPDATE statement
UPDATE table
SET column = value [, column = value, … ]
[WHERE condition ] ;
• Update more than one row at a time, if required
• If WHERE clause is omitted, then all rows are are
modified
• Subqueries can also be used for values
Example :
UPDATE Emp
SET sal = 10000
WHERE deptno = 10 ;
1-138 Copyright  CSC India, 2001. All rights reserved.
Removing rows using DELETE
statement
Syntax:
DELETE [FROM] table
[WHERE condition] ;
If WHERE clause is omitted then all rows in table
are deleted
Example :
DELETE FROM dept
WHERE dname = ‘SALES’ ;
1-139 Copyright  CSC India, 2001. All rights reserved.
Using WHERE Clause in DML Statements
– To Restrict the rows affected by the Select, Insert, Update and
Delete Statements
– Should appear after ‘FROM’ clause
– Where clause is Optional
• Select with Where clause
SQL> SELECT * from Emp WHERE Empno=10;
SQL> SELECT * from Emp WHERE Ename=‘Miller’;
SQL> SELECT * from Emp WHERE Hire_date=’20-jun-06’;
SQL> SELECT * from Emp WHERE Empno=&Empno;
1-140 Copyright  CSC India, 2001. All rights reserved.
Using WHERE Clause in DML Statements
• Update with Where clause
SQL> UPDATE Emp SET sal=30000 WHERE deptno=20;
SQL> UPDATE Emp SET sal=&sal WHERE
Empno=&Empno;
• Delete with Where clause
SQL> DELETE from Emp WHERE deptno=20;
SQL> DELETE from Emp WHERE Ename=‘Allen’;
1-141 Copyright  CSC India, 2001. All rights reserved.
Using a Sub query in an INSERT Statement
Use a sub query in place of the table name in the INTO
clause of the INSERT statement.
The select list must have the same number of columns as
the column list of the VALUES clause.
Ex :
INSERT INTO ( SELECT dname, deptno FROM dept)
VALUES (’ODS’,100) ;
1-142 Copyright  CSC India, 2001. All rights reserved.
Explicit Default Feature
Oracle9i allows to use Default Keyword not only in
DDL statements but also in DML statements too.
DEFAULT can be used as a column value where its
default value is desired
Example :
 INSERT INTO emp(empno ,ename ,sal , deptno)
VALUES (416,’Srikanth’,5000,DEFAULT);
 UPDATE emp
SET sal=DEFAULT
where deptno=10;
1-143 Copyright  CSC India, 2001. All rights reserved.
Merge Statement
• Facilitates the user to conditionally update or insert
values into database table
• Does an Update if the row exists; else inserts a new row
into database table
Syntax:
MERGE INTO table_name table_alias
USING (table|view|sub_query) alias ON (join condition)
WHEN MATCHED THEN
UPDATE SET
col1=col_val1, col2=col_val2 …
WHEN NOT MATCHED THEN
INSERT (column_list)
VALUES (column_values);
1-144 Copyright  CSC India, 2001. All rights reserved.
Merge Statement
merge into emp_copy c
using emp e
on( c.empno= e.empno)
when matched then
update set c.ename = e.ename, c.job = e.job,
c.mgr=e.mgr, c.hiredate = e.hiredate, c.sal=e.sal,
c.comm= e.comm ,c.deptno = e.deptno
when not matched then
insert values (e.empno, e.ename, e.job, e.mgr,
e.hiredate , e.sal, e.comm , e.deptno);
1-145 Copyright  CSC India, 2001. All rights reserved.
Database Transactions
• Begin when the first executable SQL
statement is executed
• End with one of the following events:
– COMMIT or ROLLBACK is issued
– DDL or DCL statement executes
(automatic commit)
– User exits
– System crashes
1-146 Copyright  CSC India, 2001. All rights reserved.
Transaction Control Statements
Statement Description
COMMIT Ends the current transaction by making all
pending data changes permanent
SAVEPOINT name Marks a savepoint within the current
transaction
ROLLBACK Ends the current transaction by discarding
all pending data changes
ROLLBACK TO
SAVEPOINT name
Rolls back the current transaction to the
specified savepoint, thereby discarding
any changes and or savepoints created
after the specified savepoint .
1-147 Copyright  CSC India, 2001. All rights reserved.
DELETE
Controlling Transactions
Transaction
Savepoint A
ROLLBACK to Savepoint B
DELETE
Savepoint B
COMMIT
INSERT
UPDATE
ROLLBACK to Savepoint A
INSERT
UPDATE
INSERT
ROLLBACK
INSERT
1-148 Copyright  CSC India, 2001. All rights reserved.
Transaction Control Language (TCL)
– COMMIT
• Used to make the Transactions permanently in the database
SQL> COMMIT;
– ROLLBACK
• Erase the Transactions to the latest committed statement
SQL> ROLLBACK ;
SQL> ROLLBACK to <Savepoint>;
– SAVEPOINT
• Used to mark the transaction in to suitable parts
SQL> SAVEPOINT A;
SQL> ROLLBACK to A;
1-149 Copyright  CSC India, 2001. All rights reserved.
100 SMITH 20000
101 ALLEN 25000 Commit
102 JAMES 20000
103 MILLER 30000 Savepoint A
105 BLAKE 35000
106 JONES 20000 Savepoint B
107 CLARK 25000
108 KING 40000
SQL> ROLLBACK;
SQL> ROLLBACK to A;
1-150 Copyright  CSC India, 2001. All rights reserved.
Implicit Transaction Processing
• An automatic commit occurs under the
following circumstances:
– DDL statement is issued
- Normal exit from SQL*Plus, without
explicitly issuing COMMIT or
ROLLBACK
• An automatic Rollback occurs under an
abnormal termination of SQL*Plus or a
system failure.
1-151 Copyright  CSC India, 2001. All rights reserved.
State of the Data Before
COMMIT or ROLLBACK
• The previous state of the data can be
recovered.
• The current user can review the results of
the DML operations by using the SELECT
statement.
• Other users cannot view the results of the
DML statements by the current user.
• The affected rows are locked; other users
cannot change the data within the affected
rows.
1-152 Copyright  CSC India, 2001. All rights reserved.
State of the Data After COMMIT
• Data changes are made permanent in the
database.
• The previous state of the data is
permanently lost.
• All users can view the results.
• Locks on the affected rows are released;
those rows are available for other users to
manipulate.
• All savepoints are erased.
1-153 Copyright  CSC India, 2001. All rights reserved.
State of the Data After ROLLBACK
Discard all pending changes by using the
ROLLBACK statement.
• Data changes are undone.
• Previous state of the data is restored.
• Locks on the affected rows are released.
SQL> DELETE FROM employee;
14 rows deleted.
SQL> ROLLBACK;
Rollback complete.
1-154 Copyright  CSC India, 2001. All rights reserved.
Rolling Back Changes
to a Marker
• Create a marker in a current transaction
by using the SAVEPOINT statement.
• Roll back to that marker by using the
ROLLBACK TO SAVEPOINT statement.
SQL> UPDATE...
SQL> SAVEPOINT update_done;
Savepoint created.
SQL> INSERT...
SQL> ROLLBACK TO update_done;
Rollback complete.
1-155 Copyright  CSC India, 2001. All rights reserved.
Read Consistency
• Read consistency guarantees a
consistent view of the data at all times.
• Changes made by one user do not
conflict with changes made by another
user.
• Read consistency ensures that on the
same data:
– Readers do not wait for writers
– Writers do not wait for readers
1-156 Copyright  CSC India, 2001. All rights reserved.
Implementation of Read
Consistency
UPDATE emp
SET sal = 2000
WHERE ename =
'SCOTT';
Data
blocks
Rollback
segments
changed
and
unchanged
data
before
change
“old” data
User A
User B
Read
consistent
image
SELECT *
FROM emp;
1-157 Copyright  CSC India, 2001. All rights reserved.
Data Control Language (DCL)
– Used control the data among the multiple users
– GRANT
• To grant the privileges on specific object to
the specific users
– REVOKE
• To Revoke the privileges on specific
object from the specific users
To Grant all privileges on table Emp to User
SMITH
SCOTT> Grant all on Emp to SMITH;
1-158 Copyright  CSC India, 2001. All rights reserved.
To Update the Granted table
SMITH> Update Scott.Emp set sal=35000 where Empno=7566;
To Update the Granted table
SMITH> Delete from Scott.emp where Ename=‘MILLER’;
To Grant a Table to multiple Users with all privileges
SCOTT> GRANT all on Emp to SMITH , JONES;
To Grant a table with specified privileges
SCOTT> Grant select, insert on Emp to SMITH ;
To Revoke all Privileges from specified User
SCOTT> Revoke all on emp from SMITH ;
1-159 Copyright  CSC India, 2001. All rights reserved.
-To Revoke specified Privileges from specified Users
SCOTT> Revoke update, delete on emp from SMITH , JONES;
-To Grant all privileges to All users
SCOTT > Grant all on Emp to PUBLIC;
-To Revoke all privileges to All users
SCOTT> Revoke all on Emp from PUBLIC;
1-160 Copyright  CSC India, 2001. All rights reserved.
Summary
Description
Adds a new row to the table
Modifies existing rows in the table
Removes existing rows from the table
Makes all pending changes permanent
Allows a rollback to the savepoint marker
Discards all pending data changes
Statement
INSERT
UPDATE
DELETE
COMMIT
SAVEPOINT
ROLLBACK
Copyright  CSC India, 2001. All rights reserved.
Creating and Managing Tables
1-162 Copyright  CSC India, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able to :
• Describe the main database objects
• Create tables
• Describe the data types that can be used when
specifying column definition
• Alter table definitions
• Drop, rename, and truncate tables
1-163 Copyright  CSC India, 2001. All rights reserved.
Database Objects
Object Description
Table Basic unit of storage; composed of rows and
columns
View Logically represents subsets of data from one
or more tables
Sequence Generates primary key values
Index Improves the performance of some queries
Synonym Alternative name for an object
1-164 Copyright  CSC India, 2001. All rights reserved.
Naming Rules
 Table names and column names :
 Must begin with a letter
 Must be 1-30 characters long
 Must contain only A-Z, a-z, 0-9, _ , $ , and #
 Must not duplicate the name of another object
owned by the same user
 Must not be an Oracle server reserved word
 Use descriptive names for tables and other
database objects
 Table names are case insensitive (not case
sensitive)
1-165 Copyright  CSC India, 2001. All rights reserved.
The CREATE TABLE Statement
A user must have :
- CREATE TABLE privilege
- A storage area
Syntax :
CREATE TABLE [schema . ]table
(column datatype [DEFAULT expr] [,….]) ;
Specify
- Table name
- Column name, column data type, and column size
- Specify a default value for a column during an
insert.
1-166 Copyright  CSC India, 2001. All rights reserved.
Data Types
Data Type Description
VARCAHR2(size) Variable length character data
CHAR(size) Fixed-length character data
NUMBER(p,s) Variable length numeric data
DATE Date and Time values
LONG Variable length character data up to 2 GB
CLOB Character data up to 4 GB
RAW & LONG RAW Raw binary data
ROWID A 64 base number system representing
unique address of a row in its table
1-167 Copyright  CSC India, 2001. All rights reserved.
Examples
Create the table
CREATE TABLE dept
( dept_id NUMBER(2)
, deptname varchar2(14)
, location varchar2(13)
);
Referencing Tables
- If the table is in your schema only then
SELECT * FROM employees;
- If you want to use other user’s tables then You
should use the
owner’s name as a prefix
SELECT * FROM user_b.employees;
1-168 Copyright  CSC India, 2001. All rights reserved.
Tables in the Oracle Database
User Tables :
- Are a collection of tables created and maintained by
the user
- Contain user information
Data Dictionary
- Is a collection of tables created and maintained by
Oracle Server
- Contain database information
Querying the Data Dictionary Views
- USER_TABLES : gives tables owned by the user
- USER_OBJECTS : gives distinct object types owned by user
- USER_CATALOG : gives tables,views,synonyms and
sequences owned by the user
1-169 Copyright  CSC India, 2001. All rights reserved.
Creating a Table by Using a Subquery
Syntax
Create a table and insert rows by combining the
CREATE TABLE statement and the select query
with AS keyword
CREATE TABLE table [ ( column, column, …) ]
AS subquery ;
Match the number of specified columns to the
number of sub query columns
Example :
CREATE TABLE dept80AS
SELECT empno, ename, sal*12 annsal,hiredate
FROM emp WHERE deptno = 80 ;
1-170 Copyright  CSC India, 2001. All rights reserved.
Create Table Examples:
Syntax:
Create Table <Table_name> ( <col_name1> <data_type> (size),
<col_name2> <data_type> (size),
<col_name3> …..);
SQL> Create Table EMP (Empno Number (6)
, Ename Varchar2(20)
,Sal Number (10, 2)
, Hire_date Date
, Deptno Number(4));
SQL> Desc EMP
Name Null? Type
----------------------------------------- -------- --------------
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
SAL NUMBER(10,2)
HIRE_DATE DATE
DEPTNO NUMBER(4)
1-171 Copyright  CSC India, 2001. All rights reserved.
The ALTER TABLE Statement
Use the ALTER TABLE statement to :
• Add a new column
• Modify an existing column and define a default value
for the new column
- ALTER TABLE table_name
ADD | MODIFY (column datatype [DEFAULT expr]
[,column datatype]…) ;
Drop a column
- ALTER TABLE table_name
DROP (column) ;
1-172 Copyright  CSC India, 2001. All rights reserved.
Adding a column
ALTER TABLE dept80
ADD (job_id varcahr2(9) );
Modifying a column
- we can change data type, size and default value
ALTER TABLE dept80
MODIFY (last_name varchar2(30) );
Dropping a column
ALTER TABLE dept80
DROP COLUMN job_id ;
Examples
1-173 Copyright  CSC India, 2001. All rights reserved.
ALTER Table Examples
– Used to alter the structure of the schema objects.
– Use ‘ADD’ keyword to add one or more columns to the table.
– Use ‘MODIFY’ keyword to increase or decrease the size of columns.
To add a new column
Syntax:
• Alter table <table_name> Add <col_name> <data_type>(size);
SQL>Alter table Emp ADD comm number(7,2);
To modify Existing Column
SQL> Alter table Emp MODIFY Ename varchar2(30);
To Drop a Column
Syntax
• Alter table <Table_name> DROP Column <Column_name>;
SQL> Alter table Emp Drop Column Comm;
SQL> Alter table emp set unused(comm);
SQL> Alter table emp set unused(EMPNO,ENAME);
SQL> Alter table emp drop unused columns;
1-174 Copyright  CSC India, 2001. All rights reserved.
The SET UNUSED Option
• Use the SET UNUSED option to mark one or more
columns as unused. They are logically removed and
can’t be viewed or used .
• They can be dropped when the demand on system
resources is lower
• This is a fast process than using DROP clause
- ALTER TABLE tablename SET UNUSED (column ) ;
Example :
- ALTER TABLE dept SET UNUSED (loc) ;
1-175 Copyright  CSC India, 2001. All rights reserved.
The SET UNUSED Option
View the unused columns in
USER_UNUSED_COL_TABS
Use DROP UNUSED COLUMNS option to remove the
columns that are marked as unused
- ALTER TABLE table DROP UNUSED COLUMNS ;
Example :
- ALTER TABLE dept DROP UNUSED COLUMNS;
1-176 Copyright  CSC India, 2001. All rights reserved.
Dropping, Renaming, Truncating a Table
Dropping
- All data , structure in the table and indexes are
dropped
- Syntax : DROP TABLE table ;
Renaming
- We can change the name of a table, view, sequence
- Syntax : RENAME oldname TO newname ;
Truncating
- Removes all rows from a table
- Releases storage space used by that table
- Syntax :TRUNCATE TABLE table ;
Note : You can’t rollback these operations
1-177 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to use DDL
statements to create, alter, drop and rename tables
CREATE TABLE - Creates a table
ALTER TABLE - Modifies table structures
DROP TABLE - Removes the rows and table structure
RENAME - Changes the name of the table, view,
sequence, or synonym
TRUNCATE - Removes all rows from table and
releases storage space
1-178 Copyright  CSC India, 2001. All rights reserved.
Copyright  CSC India, 2001. All rights reserved.
SET Operators
1-180 Copyright  CSC India, 2001. All rights reserved.
The SET Operators
The SET Operators combine the results of two or more
component queries into one result. Queries containing
SET operators are called compound queries.
Operator Returns
UNION All distinct rows selected by either query
UNION ALL All rows selected by either query,including
duplicates
INTERSECT All distinct rows selected by both queries
MINUS All distinct rows that are selected by the first
SELECT statement and not selected in the second
SELECT statement.
1-181 Copyright  CSC India, 2001. All rights reserved.
The UNION Operator
The UNION operator returns all rows selected by either
query from multiple tables after eliminating
duplications
Guidelines
- UNION operates over all of the columns being
selected
- NULL values are not ignored during duplicate
checking
- By default, the output is sorted in ascending order
of the first column of the SELECT clause
1-182 Copyright  CSC India, 2001. All rights reserved.
Using the UNION Operator
Example
SQL> SELECT Deptno From Emp
UNION
SELECT Deptno From Dept;
The UNION operator eliminates any duplicate
records. If there are records that occur both in the
EMP and the DEPT tables and are identical, the
records will be displayed only once.
To overcome this we have to use UNION ALL
Operator
1-183 Copyright  CSC India, 2001. All rights reserved.
The UNION ALL Operator
The UNION ALL Operator returns all rows from multiple
queries
Guidelines :
- Unlike UNION,duplicate rows are not eliminated
- The output is not sorted by default.
- The DISTINCT keyword cannot be used
- apart from these, all the guidelines of UNION ALL
and UNION are the same.
Example :
- SELECT Deptno FROM Emp
UNION ALL
SELECT Deptno FROM Dept;
1-184 Copyright  CSC India, 2001. All rights reserved.
The INTERSECT Operator
The INTERSECT Operator returns all rows common to
multiple queries from multiple tables
Guidelines :
- INTERSECT result is same on reversing the order
- INTERSECT does not ignore NULL values
Example :
SELECT Deptno FROM Emp
INTERSECT
SELECT Deptno FROM Dept;
1-185 Copyright  CSC India, 2001. All rights reserved.
The MINUS Operator
• The MINUS Operator returns rows returned by first
query that are not present in the second query
• - The result is not same by reversing the order
Example :
SELECT Deptno FROM Dept
MINUS
SELECT Deptno FROM Emp;
1-186 Copyright  CSC India, 2001. All rights reserved.
SET Operator Guidelines
• The expressions in the SELECT lists must match
in number and data type
• Parentheses can be used to alter the sequence of
execution
The ORDER BY clause :
- can appear only at the very end of the statement
- will accept the column name, aliases from the
first SELECT statement, or the positional
notation
• SET operators can be used in subqueries
1-187 Copyright  CSC India, 2001. All rights reserved.
The Oracle Server and SET Operators
Duplicate rows are automatically eliminated excepted in
UNION ALL
Column names from the first query appear in the result
The output is sorted in ascending order by default
except in UNION ALL Operator.
If component queries select character data, the data
type of the return values are determined as follows :
- If both queries select values of data type CHAR, the
returned values have the data type CHAR.
- If either or both of the queries select values of data
type VARCHAR2 the returned values have data type
VARCHAR2.
1-188 Copyright  CSC India, 2001. All rights reserved.
1-189 Copyright  CSC India, 2001. All rights reserved.
1-190 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you should have learned how to :
- Use UNION to return all distinct rows
- Use UNION ALL to return all rows, including duplicates
- Use INTERSECT to return all rows shared by both queries
- Use MINUS to return all distinct rows selected by the first
query but not by the second
- Use ORDER BY only at the very end of the statement
Copyright  CSC India, 2001. All rights reserved.
Including Constraints
1-192 Copyright  CSC India, 2001. All rights reserved.
Objective
After completing this lesson, you should be able to
do :
• Describe constraints
• Create and maintain constraints
1-193 Copyright  CSC India, 2001. All rights reserved.
What are constraints ?
Constraints are the Business Rules which can be enforced to prevent
invalid data
The following constraint types are valid :
NOT NULL : The column can’t contain a null value
UNIQUE : Specifies column(s) whose values must
be unique for all rows in the table. Null
values are allowed
PRIMARY KEY: Uniquely identifies each row of the table
FOREIGN KEY: Establishes and enforces a foreign key
relationship between the column and a
column of referenced table
CHECK : Specifies a condition that must be true
1-194 Copyright  CSC India, 2001. All rights reserved.
Constraint Guidelines
• Name a constraint or the Oracle Server will
generate a name by using the SYS_Cn format.
• Create a constraint:
– At the same time as the table is created
– After the table has been created
• Define a constraint at the column or table level.
• View a constraint in the data dictionary view
User_Constraints
1-195 Copyright  CSC India, 2001. All rights reserved.
Defining Constraints
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint][,...]);
CREATE TABLE emp(
empno NUMBER(4),
ename VARCHAR2(10),
...
deptno NUMBER(7,2) NOT NULL,
CONSTRAINT emp_empno_pk
PRIMARY KEY (EMPNO));
1-196 Copyright  CSC India, 2001. All rights reserved.
Defining Constraints
• Column constraint level
• Table constraint level
column [CONSTRAINT constraint_name] constraint_type,
column,...
[CONSTRAINT constraint_name] constraint_type
(column, ...),
1-197 Copyright  CSC India, 2001. All rights reserved.
The NOT NULL Constraint
Ensures that null values are not permitted
for the column
EMP
EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
NOT NULL constraint
(no row can contain
a null value for
this column)
Absence of NOT NULL
constraint
(any row can contain
null for this column)
NOT NULL constraint
1-198 Copyright  CSC India, 2001. All rights reserved.
The NOT NULL Constraint
Defined at the column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL);
1-199 Copyright  CSC India, 2001. All rights reserved.
The UNIQUE Key Constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
UNIQUE key constraint
50 SALES DETROIT
60 BOSTON
Insert into Not allowed
(DNAME-SALES
already exists)
Allowed
1-200 Copyright  CSC India, 2001. All rights reserved.
The UNIQUE Key Constraint
– Maintains the Uniqueness in the values for the
columns on which it is defined.
– Allows the NULL values.
SQL> CREATE TABLE dept(
2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE(dname));
1-201 Copyright  CSC India, 2001. All rights reserved.
PRIMARY KEY
– Combination of UNIQUE and NOT NULL
– No two rows can have the same values
– No single row can have the NULL value
– Table can have only one primary key column
1-202 Copyright  CSC India, 2001. All rights reserved.
The PRIMARY KEY Constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
PRIMARY KEY
Insert into
20 MARKETING DALLAS
FINANCE NEW YORK
Not allowed
(DEPTNO-20 already
exists)
Not allowed
(DEPTNO is null)
1-203 Copyright  CSC India, 2001. All rights reserved.
The PRIMARY KEY Constraint
Defined at either the table level or the column
level
SQL> CREATE TABLE dept(
2 deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13),
5 CONSTRAINT dept_dname_uk UNIQUE (dname),
6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));
1-204 Copyright  CSC India, 2001. All rights reserved.
FOREIGN KEY
– Used to establish Master Detail relationship
between the tables.
– requires values in one table to match values in
another table.
– The table which contains primary key is called
Master table.
– The table which contains foreign key is called
Detail table.
– Before defining the foreign key in the Detail
table primary key should be defined in the
Master table.
1-205 Copyright  CSC India, 2001. All rights reserved.
The FOREIGN KEY Constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
PRIMARY
KEY
EMP
EMPNO ENAME JOB ... COMM DEPTNO
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
...
FOREIGN
KEY
7571 FORD MANAGER ... 200 9
7571 FORD MANAGER ... 200 20
Insert into
Not allowed
(DEPTNO 9
does not exist
in the DEPT
table)
Allowed
1-206 Copyright  CSC India, 2001. All rights reserved.
The FOREIGN KEY Constraint
Defined at either the table level or the
column level
SQL> CREATE TABLE emp(
2 empno NUMBER(4),
3 ename VARCHAR2(10) NOT NULL,
4 job VARCHAR2(9),
5 mgr NUMBER(4),
6 hiredate DATE,
7 sal NUMBER(7,2),
8 comm NUMBER(7,2),
9 deptno NUMBER(7,2) NOT NULL,
10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno)
11 REFERENCES dept (deptno));
1-207 Copyright  CSC India, 2001. All rights reserved.
FOREIGN KEY Constraint
Keywords
• FOREIGN KEY
Defines the column in the child table at
the table constraint level
• REFERENCES
Identifies the table and column in the parent
table
• ON DELETE CASCADE
Allows deletion in the parent table and deletion
of the dependent rows in the child table
1-208 Copyright  CSC India, 2001. All rights reserved.
The CHECK Constraint
• Defines a condition that each row must satisfy
–To satisfy the constraint, each row in the
table must make the condition either TRUE
or unknown (due to a null).
Expressions that are not allowed:
– References to CURRVAL, NEXTVAL and
ROWNUM pseudo columns
– Calls to SYSDATE, UID, USER, and USERENV
functions
– Queries that refer to other values in other rows
..., deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
CHECK (DEPTNO BETWEEN 10 AND 99),...
1-209 Copyright  CSC India, 2001. All rights reserved.
Adding a Constraint
• Add or drop, but not modify a constraint
• Enable or disable constraints
• Add a NOT NULL constraint by using
the MODIFY clause
ALTER TABLE table
ADD [CONSTRAINT constraint] type (column);
1-210 Copyright  CSC India, 2001. All rights reserved.
Adding a Constraint
Add a FOREIGN KEY constraint to the
EMP table indicating that a manager must
already exist as a valid employee in the
EMP table.
SQL> ALTER TABLE emp
2 ADD CONSTRAINT emp_mgr_fk
3 FOREIGN KEY(mgr) REFERENCES emp(empno);
Table altered.
1-211 Copyright  CSC India, 2001. All rights reserved.
Dropping a Constraint
• Remove the manager constraint from
the EMP table.
SQL> ALTER TABLE emp
2 DROP CONSTRAINT emp_mgr_fk;
Table altered.
• Remove the PRIMARY KEY constraint
on the DEPT table and drop the
associated FOREIGN KEY constraint on
the EMP.DEPTNO column.
SQL> ALTER TABLE dept
2 DROP PRIMARY KEY CASCADE;
Table altered.
1-212 Copyright  CSC India, 2001. All rights reserved.
Disabling Constraints
• Execute the DISABLE clause of the
ALTER TABLE statement to deactivate
an integrity constraint.
• Apply the CASCADE option to disable
dependent integrity constraints.
SQL> ALTER TABLE emp
2 DISABLE CONSTRAINT emp_empno_pk CASCADE;
Table altered.
1-213 Copyright  CSC India, 2001. All rights reserved.
Enabling Constraints
• Activate an integrity constraint currently
disabled in the table definition by using
the ENABLE clause.
• A UNIQUE or PRIMARY KEY index is
automatically created if you enable a
UNIQUE key or PRIMARY KEY
constraint.
SQL> ALTER TABLE emp
2 ENABLE CONSTRAINT emp_empno_pk;
Table altered.
1-214 Copyright  CSC India, 2001. All rights reserved.
Cascading Constraints
The CASCADE CONSTRAINTS clause is used along
with the DROP COLUMN clause
The CASCADE CONSTRAINTS clause drops all
referential integrity constraints that refer to the
primary and unique keys defined on the dropped
columns.
The CASCADE CONSTRAINTS clause also drops all
multicolumn constraints defined on the dropped
columns
ALTER TABLE test1
DROP (pk) CASCADE CONSTRAINTS ;
1-215 Copyright  CSC India, 2001. All rights reserved.
Viewing Constraints
• Query the USER_CONSTRAINTS table to view all
constraint definitions and names
• View the columns associated with the constraint
names in the USER_CONS_COLUMNS view.
Example :
SELECT constraint_name, constraint_type,
search_condition
FROM USER_CONSTRAINTS
WHERE table_name = ‘EMP’ ;
Copyright  CSC India, 2001. All rights reserved.
Displaying Data
from Multiple Tables
1-217 Copyright  CSC India, 2001. All rights reserved.
EMPNO DEPTNO LOC
----- ------- --------
7839 10 NEW YORK
7698 30 CHICAGO
7782 10 NEW YORK
7566 20 DALLAS
7654 30 CHICAGO
7499 30 CHICAGO
...
14 rows selected.
Obtaining Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO
------ ----- ... ------
7839 KING ... 10
7698 BLAKE ... 30
...
7934 MILLER ... 10
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
1-218 Copyright  CSC India, 2001. All rights reserved.
What Is a Join?
Use a join to query data from more than one
table.
• Write the join condition in the WHERE clause.
• Prefix the column name with the table name
when the same column name appears in more
than one table.
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
1-219 Copyright  CSC India, 2001. All rights reserved.
Types of Joins
Oracle proprietary Joins SQL:1999 Compliant Joins
Cartesian product Cross joins
Equijoin Natural joins
Non-equijoin Using Clause
Outer join Full or two sided outer joins
Self join Arbitrary join conditions for
outer joins
1-220 Copyright  CSC India, 2001. All rights reserved.
Cartesian Product
• A Cartesian product is formed when:
– A join condition is omitted
– A join condition is invalid
– All rows in the first table are joined to all
rows in the second table
• To avoid a Cartesian product, always include a
valid join condition in a WHERE clause.
Example :
SELECT Ename, Dname
FROM Emp, Dept;
1-221 Copyright  CSC India, 2001. All rights reserved.
Generating a Cartesian Product
ENAME DNAME
------ ----------
KING ACCOUNTING
BLAKE ACCOUNTING
...
KING RESEARCH
BLAKE RESEARCH
...
56 rows selected.
EMP (14 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO
------ ----- ... ------
7839 KING ... 10
7698 BLAKE ... 30
...
7934 MILLER ... 10
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
“Cartesian
product:
14*4=56 rows”
1-222 Copyright  CSC India, 2001. All rights reserved.
Joining Tables
• Use a join to query data from more than one table
SELECT table1.column, table2.column
FROM table1,table2
WHERE table1.column1 = table2.column2 ;
• Write the join condition in the WHERE clause
• Prefix the column name with the table name when
the same column name appears in more than one
table
• Joining n tables need a minimum of n-1 join
conditions
1-223 Copyright  CSC India, 2001. All rights reserved.
Types of Joins
Equijoin Non-equijoin Outer join Self join
1-224 Copyright  CSC India, 2001. All rights reserved.
What Is an Equijoin?
EMP DEPT
EMPNO ENAME DEPTNO
------ ------- -------
7839 KING 10
7698 BLAKE 30
7782 CLARK 10
7566 JONES 20
7654 MARTIN 30
7499 ALLEN 30
7844 TURNER 30
7900 JAMES 30
7521 WARD 30
7902 FORD 20
7369 SMITH 20
...
14 rows selected.
DEPTNO DNAME LOC
------- ---------- --------
10 ACCOUNTING NEW YORK
30 SALES CHICAGO
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
30 SALES CHICAGO
30 SALES CHICAGO
30 SALES CHICAGO
30 SALES CHICAGO
20 RESEARCH DALLAS
20 RESEARCH DALLAS
...
14 rows selected.
Foreign key Primary key
1-225 Copyright  CSC India, 2001. All rights reserved.
Retrieving Records
with Equijoins
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
EMPNO ENAME DEPTNO DEPTNO LOC
----- ------ ------ ------ ---------
7839 KING 10 10 NEW YORK
7698 BLAKE 30 30 CHICAGO
7782 CLARK 10 10 NEW YORK
7566 JONES 20 20 DALLAS
...
14 rows selected.
1-226 Copyright  CSC India, 2001. All rights reserved.
Qualifying Ambiguous
Column Names
• Use table prefixes to qualify column
names that are in multiple tables.
• Improve performance by using table
prefixes.
• Distinguish columns that have identical
names but reside in different tables by
using column aliases.
1-227 Copyright  CSC India, 2001. All rights reserved.
Using Table Aliases
Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno =dept.deptno;
SQL> SELECT e.empno, e.ename, e.deptno,
2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno =d.deptno;
1-228 Copyright  CSC India, 2001. All rights reserved.
Joining More Than Two Tables
NAME CUSTID
----------- ------
JOCKSPORTS 100
TKB SPORT SHOP 101
VOLLYRITE 102
JUST TENNIS 103
K+T SPORTS 105
SHAPE UP 106
WOMENS SPORTS 107
... ...
9 rows selected.
CUSTOMER
CUSTID ORDID
------- -------
101 610
102 611
104 612
106 601
102 602
106 604
106 605
...
21 rows selected.
ORD
ORDID ITEMID
------ -------
610 3
611 1
612 1
601 1
602 1
...
64 rows selected.
ITEM
1-229 Copyright  CSC India, 2001. All rights reserved.
Non-Equijoins
EMP SALGRADE
“salary in the EMP
table is between
low salary and high
salary in the SALGRADE
table”
EMPNO ENAME SAL
------ ------- ------
7839 KING 5000
7698 BLAKE 2850
7782 CLARK 2450
7566 JONES 2975
7654 MARTIN 1250
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
...
14 rows selected.
GRADE LOSAL HISAL
----- ----- ------
1 700 1200
2 1201 1400
3 1401 2000
4 2001 3000
5 3001 9999
1-230 Copyright  CSC India, 2001. All rights reserved.
Retrieving Records
with Non-Equijoins
ENAME SAL GRADE
---------- --------- ---------
JAMES 950 1
SMITH 800 1
ADAMS 1100 1
...
14 rows selected.
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;
1-231 Copyright  CSC India, 2001. All rights reserved.
Outer Joins
EMP DEPT
No employee in the
OPERATIONS department
ENAME DEPTNO
----- ------
KING 10
BLAKE 30
CLARK 10
JONES 20
...
DEPTNO DNAME
------ ----------
10 ACCOUNTING
30 SALES
10 ACCOUNTING
20 RESEARCH
...
40 OPERATIONS
1-232 Copyright  CSC India, 2001. All rights reserved.
Outer Joins
• You use an outer join to also see rows
that do not usually meet the join
condition.
• Outer join operator is the plus sign (+).
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column;
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column = table2.column(+);
1-233 Copyright  CSC India, 2001. All rights reserved.
Joining a Table to Itself
WORKER.ENAME||'WORKSFOR'||MANAG
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
SQL> SELECT worker.ename||' works for '||manager.ename
2 FROM emp worker, emp manager
3 WHERE worker.mgr = manager.empno;
1-234 Copyright  CSC India, 2001. All rights reserved.
Summary
Equijoin Non-equijoin Outer join Self join
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column1 = table2.column2;
1-235 Copyright  CSC India, 2001. All rights reserved.
Oracle 9i feature
Oracle 9i introduced new features in compliance with
SQL:1999 ANSI standard
Syntax :
SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name) ] |
[JOIN table2
ON (table1.column_name = table2.column_name) ] |
[LEFT | RIGHT | FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name) ] ;
1-236 Copyright  CSC India, 2001. All rights reserved.
Cross Join
Forms a Cartesian Product whenever Join condition
is not specified
SELECT Ename , Dname
FROM Emp
CROSS JOIN dept ;
1-237 Copyright  CSC India, 2001. All rights reserved.
Natural Joins
• Equivalent to Equi Join
• Joins with all the common columns present in the
tables
• The column names as well as the data types should
match
E.g.:
SELECT Empno , Ename , Dname
FROM Emp
NATURAL JOIN
Dept;
1-238 Copyright  CSC India, 2001. All rights reserved.
USING clause
No matter how many common columns are available in
the tables, NATURAL JOIN will join with all the
common columns
Use USING clause to join with specified columns
Example :
SELECT Empno , Ename ,Mgr ,Deptno , Dname
FROM Emp
JOIN Dept
USING ( Deptno , Mgr);
1-239 Copyright  CSC India, 2001. All rights reserved.
ON clause
• Explicit join condition can be specified by using ON
clause
• Additional conditions as well as sub-queries can be
used along with ON clause
Example :
SELECT e.empno , e.name, d.deptno , d.dname
FROM Emp e
JOIN
Dept d
ON (e.deptno = d.deptno)
AND d.dname =‘SALES’ ;
1-240 Copyright  CSC India, 2001. All rights reserved.
Left Outer Join
SELECT e.ename,e.sal,d.deptno,d.dname
FROM Emp e
LEFT OUTER JOIN
Dept d
ON (e.deptno = d.deptno) ;
1-241 Copyright  CSC India, 2001. All rights reserved.
Right Outer Join
SELECT e.ename,e.sal,d.deptno,d.dname
FROM Emp e
RIGHT OUTER JOIN
Dept d
ON (e.deptno = d.deptno) ;
1-242 Copyright  CSC India, 2001. All rights reserved.
FULL Outer Join
SELECT e.ename, e.sal,d.deptno,d.dname
FROM Emp e
FULL OUTER JOIN
Dept d
ON (e.deptno = d.deptno ) ;
1-243 Copyright  CSC India, 2001. All rights reserved.
Practice Overview
• Joining tables using an equijoin
• Performing outer and self joins
• Adding conditions
1-244 Copyright  CSC India, 2001. All rights reserved.
Summary
In this lesson, you have learned :
• Extracting data from multiple tables using joins
• Oracle 8i proprietary joins
• SQL:1999 ANSI standard joins ( oracle 9i feature)
Copyright  CSC India, 2001. All rights reserved.
Subqueries
1-246 Copyright  CSC India, 2001. All rights reserved.
Objectives
After completing this lesson, you should be able to do
the following :
• Describe the types of problem that subqueries can
solve
• Define subqueries
• List the types of subqueries
• Write single-row and multiple-row subqueries
• Multiple column subqueries
• Scalar subqueries
• Correlated subqueries
• Use of EXISTS and NOT EXISTS operator
1-247 Copyright  CSC India, 2001. All rights reserved.
Using a Subquery
to Solve a Problem
“Who has a salary greater than Jones’?”
“Which employees have a salary greater
than Jones’ salary?”
Main Query
?
“What is Jones’ salary?”
?
Subquery
1-248 Copyright  CSC India, 2001. All rights reserved.
Subqueries
• Sub queries are useful when a query is based on unknown
values.
• The subquery (inner query) executes once before the main
query.
• The result of the subquery is used by the main query (outer
query).
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
1-249 Copyright  CSC India, 2001. All rights reserved.
2975
SQL> SELECT ename
2 FROM emp
3 WHERE sal >
4 (SELECT sal
5 FROM emp
6 WHERE empno=7566);
Using a Subquery
ENAME
----------
KING
FORD
SCOTT
1-250 Copyright  CSC India, 2001. All rights reserved.
Guidelines for Using Subqueries
• Enclose subqueries in parentheses
• Place subqueries on the right side of the comparison
condition
• The ORDER BY clause in the sub query is not needed
unless we are performing Top-N analysis.
• Use single-row operators with single-row subqueries and
use multiple-row operators with multiple-row subqueries.
• For single-row subqueries, use single-row comparison
operators like =, < , <= , > , >=, <> Or !=
• For multiple-row subqueries use multiple-row operators
like IN , ANY , ALL
1-251 Copyright  CSC India, 2001. All rights reserved.
Types of Subqueries
• Single-row subquery
Main query
Subquery
returns
CLERK
• Multiple-row subquery
CLERK
MANAGER
Main query
Subquery
returns
• Multiple-column subquery
CLERK 7900
MANAGER 7698
Main query
Subquery
returns
1-252 Copyright  CSC India, 2001. All rights reserved.
Single-Row Subqueries
• Return only one row
• Use single-row comparison operators
Operator
=
>
>=
<
<=
<>
Meaning
Equal to
Greater than
Greater than or equal to
Less than
Less than or equal to
Not equal to
1-253 Copyright  CSC India, 2001. All rights reserved.
Executing Single-Row Subqueries
CLERK
1100
ENAME JOB
---------- ---------
MILLER CLERK
SQL> SELECT ename, job
2 FROM emp
3 WHERE job =
4 (SELECT job
5 FROM emp
6 WHERE empno = 7369)
7 AND sal >
8 (SELECT sal
9 FROM emp
10 WHERE empno = 7876);
1-254 Copyright  CSC India, 2001. All rights reserved.
Using Group Functions
in a Subquery
800
ENAME JOB SAL
---------- --------- ---------
SMITH CLERK 800
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);
1-255 Copyright  CSC India, 2001. All rights reserved.
HAVING Clause with Subqueries
• The Oracle Server executes subqueries
first.
• The Oracle Server returns results into
the HAVING clause of the main query.
800
SQL> SELECT deptno, MIN(sal)
2 FROM emp
3 GROUP BY deptno
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM emp
7 WHERE deptno = 20);
1-256 Copyright  CSC India, 2001. All rights reserved.
What Is Wrong
with This Statement?
ERROR:
ORA-01427: single-row subquery returns more than
one row
no rows selected
SQL> SELECT empno, ename
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp
6 GROUP BY deptno);
1-257 Copyright  CSC India, 2001. All rights reserved.
Multiple-Row Subqueries
• Return more than one row
• Use multiple-row comparison operators
Operator
IN
ANY
ALL
Meaning
Equal to any member in the list
Compare value to each value returned by
the subquery
Compare value to every value returned by
the subquery
1-258 Copyright  CSC India, 2001. All rights reserved.
Using ALL Operator
in Multiple-Row Subqueries
2916.6667
2175
1566.6667
EMPNO ENAME JOB SAL
--------- ---------- ---------------
7839 KING PRESIDENT 5000
7566 JONES MANAGER 2975
7902 FORD ANALYST 3000
7788 SCOTT ANALYST 3000
SQL> SELECT empno, ename, job
2 FROM emp
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);
1-259 Copyright  CSC India, 2001. All rights reserved.
Using ALL Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job
2 FROM emp
3 WHERE sal > ANY
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);
EMPNO ENAME JOB SAL
---------- ---------- --------- ----------
7839 KING PRESIDENT 5000
7902 FORD ANALYST 3000
7788 SCOTT ANALYST 3000
7566 JONES MANAGER 2975
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7499 ALLEN SALESMAN 1600
Copyright  CSC India, 2001. All rights reserved.
Multiple-Column Subqueries
1-261 Copyright  CSC India, 2001. All rights reserved.
Multiple-Column Subqueries
Main query
MANAGER 10
Subquery
SALESMAN 30
MANAGER 10
CLERK 20
Main query
compares
MANAGER 10
Values from a multiple-row and
multiple-column subquery
SALESMAN 30
MANAGER 10
CLERK 20
to
1-262 Copyright  CSC India, 2001. All rights reserved.
Using Multiple-Column
Subqueries
Display the order number, product number, and
quantity of any item in which the product
number and quantity match both the product
number and quantity of an item in order 605.
SQL> SELECT ordid, prodid, qty
2 FROM item
3 WHERE (prodid, qty) IN
4 (SELECT prodid, qty
5 FROM item
6 WHERE ordid = 605)
7 AND ordid <> 605;
1-264 Copyright  CSC India, 2001. All rights reserved.
Using a Subquery
in the FROM Clause
ENAME SAL DEPTNO SALAVG
---------- --------- --------- ----------
KING 5000 10 2916.6667
JONES 2975 20 2175
SCOTT 3000 20 2175
...
6 rows selected.
SQL> SELECT a.ename, a.sal, a.deptno, b.salavg
2 FROM emp a, (SELECT deptno, avg(sal) salavg
3 FROM emp
4 GROUP BY deptno) b
5 WHERE a.deptno = b.deptno
6 AND a.sal > b.salavg;
1-265 Copyright  CSC India, 2001. All rights reserved.
Sub query’s examples;
SQL> Select Ename,sal from emp
where sal=(select max(sal) from emp);
SQL> Select Ename,deptno,sal from emp
where (deptno,sal) in(select deptno,max(sal) from emp
group by deptno);
SQL> Create table emp1 as select * from emp;
SQL> Create table emp2 as select * from emp where 1=2;
SQL> Insert into emp2(select * from emp);
SQL> Insert into emp2(empno,ename) (select empno,ename from emp);
SQL> Update emp set sal=4000 where deptno=(select deptno from dept
where dname=‘SALES’);
1-266 Copyright  CSC India, 2001. All rights reserved.
• To find the employees getting maximum salary of any dept.
Sql> Select ename, deptno,sal from emp WHERE sal> ANY (select
max(sal) from emp group by deptno);
• To find the employees getting maximum salary of every dept.
Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select
max(sal) from emp group by deptno);
Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select
max(sal) from emp where deptno in(20,30) group by deptno);
• To select Duplicate rows present in the table
SQL> Select count(rowid), empno from emp
group by empno
having count(rowid)>1;
SQL> select * from emp
where rowid not in (select min(rowid) from emp group by empno);
1-267 Copyright  CSC India, 2001. All rights reserved.
Updating with
Multiple-Column Subquery
Update employee 7698’s job and department
to match that of employee 7499.
SQL> UPDATE emp
2 SET (job, deptno) =
3 (SELECT job, deptno
4 FROM emp
5 WHERE empno = 7499)
6 WHERE empno = 7698;
1 row updated.
1-268 Copyright  CSC India, 2001. All rights reserved.
Updating Rows Based
on Another Table
Use subqueries in UPDATE statements to
update rows in a table based on values
from another table.
SQL> UPDATE employee
2 SET deptno = (SELECT deptno
3 FROM emp
4 WHERE empno = 7788)
5 WHERE job = (SELECT job
6 FROM emp
7 WHERE empno = 7788);
2 rows updated.
1-269 Copyright  CSC India, 2001. All rights reserved.
Deleting Rows Based
on Another Table
Use subqueries in DELETE statements to
remove rows from a table based on values
from another table.
SQL> DELETE FROM employee
2 WHERE deptno =
3 (SELECT deptno
4 FROM dept
5 WHERE dname ='SALES');
6 rows deleted.
1-270 Copyright  CSC India, 2001. All rights reserved.
Correlated Subqueries
• A query is a Correlated Sub query when it references a
column from a table referred to in the parent statement
• They are executed once for every row of the outer query
• They are used for row-by-row processing
Example :
SELECT ename, sal, deptno FROM emp e
WHERE sal > (SELECT avg(sal) FROM emp d
WHERE e.deptno = d.deptno ) ;
1-271 Copyright  CSC India, 2001. All rights reserved.
Correlated UPDATE
To update rows in one table based on rows from another
table
Syntax :
UPDATE table1 alias1
SET column = ( SELECT expression FROM table2
alias2
WHERE alias1.column = alias2.column ) ;
Example :
UPDATE emp e SET deptname = (select dname
FROM dept d WHERE e.deptno = d.deptno);
Similarly Correlated Delete can be used
1-272 Copyright  CSC India, 2001. All rights reserved.
Correlated query Example;
• To find employee details who are getting salary greater than
avg salary of their own department
SQL> Select ename,sal,deptno from emp e
where sal>(select avg(sal) from emp m
where m.deptno =e.deptno);
• To find N th max sal
SQL> select * from emp x where &no=(select count (distinct sal)
from Emp y where y.sal>=x.sal);
• To find N th least sal
SQL> select * from emp x where &no=(select count (distinct sal)
from Emp y where y.sal<=x.sal)
1-273 Copyright  CSC India, 2001. All rights reserved.
EXISTS Operator
• Tests for existence of rows in the results set of the sub
query
• Returns TRUE if sub query returns at least one row else
FALSE is returned
• IN operator can replace EXISTS operator
• NOT EXISTS operator is opposite of EXISTS operator
Example :
SELECT empno, ename FROM emp e WHERE empno IN
(SELECT mgr FROM emp ) ;
SELECT empno, ename FROM emp e WHERE EXISTS
( SELECT 1 FROM emp WHERE mgr = e.empno );
Copyright  CSC India, 2001. All rights reserved.
Schema Objects
1-275 Copyright  CSC India, 2001. All rights reserved.
Schema Objects
Description
Basic unit of storage; composed of rows
and columns
Logically represents subsets of data from
one or more tables
Generates primary key values
Improves the performance of some queries
Alternative name for an object
Object
Table
View
Sequence
Index
Synonym
1-276 Copyright  CSC India, 2001. All rights reserved.
TABLE
• In a RDBMS, the data is logically perceived as
tables.
– Tables are logical data structures that we
assume hold the data that the database
intends to represent.
– Tables are not physical structures.
– Each table has a unique name.
– In general, when tables are defined, the
number of columns remain fixed for the
duration of the table, however, the number of
rows present in the table is bound to vary
– Tables are required to have at least one
column.
Copyright  CSC India, 2001. All rights reserved.
Creating Views
1-278 Copyright  CSC India, 2001. All rights reserved.
Views
Objectives
 Describe a view
 Create, alter the definition of, and drop a view
 Retrieve data through a view
 Insert, update, and delete data through a view
 Create and use an inline view
 Perform “Top-N” analysis
In this part you learn how to
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt
SQL.ppt

More Related Content

Similar to SQL.ppt

Les01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL StatementsLes01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL Statementssiavosh kaviani
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusChhom Karath
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...rehaniltifat
 
SQL Queries
SQL QueriesSQL Queries
SQL QueriesNilt1234
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query LanguageRohit Bisht
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfstudy material
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginnerssuzzanj1990
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句renguzi
 
Less08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptxLess08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptxMurtazaMughal13
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQLrehaniltifat
 
Manage schema object.ppt
Manage schema object.pptManage schema object.ppt
Manage schema object.pptAhmadUsman79
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxEliasPetros
 

Similar to SQL.ppt (20)

Les01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL StatementsLes01[1]Writing Basic SQL Statements
Les01[1]Writing Basic SQL Statements
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
Introduction to SQL, SQL*Plus
Introduction to SQL, SQL*PlusIntroduction to SQL, SQL*Plus
Introduction to SQL, SQL*Plus
 
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
03 Writing Control Structures, Writing with Compatible Data Types Using Expli...
 
sql-commands.pdf
sql-commands.pdfsql-commands.pdf
sql-commands.pdf
 
Sql commands
Sql commandsSql commands
Sql commands
 
Sql commands
Sql commandsSql commands
Sql commands
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
SQL Queries
SQL QueriesSQL Queries
SQL Queries
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query Language
 
Introduction to SQL..pdf
Introduction to SQL..pdfIntroduction to SQL..pdf
Introduction to SQL..pdf
 
chapter-14-sql-commands.pdf
chapter-14-sql-commands.pdfchapter-14-sql-commands.pdf
chapter-14-sql-commands.pdf
 
122 sql for-beginners
122 sql for-beginners122 sql for-beginners
122 sql for-beginners
 
Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句Lesson01 学会使用基本的SQL语句
Lesson01 学会使用基本的SQL语句
 
Less08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptxLess08_Schema Advanced Databases and Management.pptx
Less08_Schema Advanced Databases and Management.pptx
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Manage schema object.ppt
Manage schema object.pptManage schema object.ppt
Manage schema object.ppt
 
Intro
IntroIntro
Intro
 
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptxMy lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
My lablkxjlkxjcvlxkcjvlxckjvlxck ppt.pptx
 

Recently uploaded

Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTopCSSGallery
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdfMuhammad Subhan
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfSrushith Repakula
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxMasterG
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireExakis Nelite
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
How to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in PakistanHow to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in Pakistandanishmna97
 

Recently uploaded (20)

Top 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development CompaniesTop 10 CodeIgniter Development Companies
Top 10 CodeIgniter Development Companies
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptxCyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
Cyber Insurance - RalphGilot - Embry-Riddle Aeronautical University.pptx
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
How to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in PakistanHow to Check GPS Location with a Live Tracker in Pakistan
How to Check GPS Location with a Live Tracker in Pakistan
 

SQL.ppt

  • 1. Copyright  CSC India, 2001. All rights reserved. SQL By Venkat Mail:pichelavenkat@gmail.com
  • 2. 1-2 Copyright  CSC India, 2001. All rights reserved. SQL Training Agenda •Introduction to Oracle •Working with SQL Languages -- Operators -- Functions -- Integrity Constraints -- Joins -- Sub queries -- Schema Objects
  • 3. Copyright  CSC India, 2001. All rights reserved. Introduction to Oracle
  • 4. 1-4 Copyright  CSC India, 2001. All rights reserved. Introduction to Oracle • What is Oracle • Overview of RDBMS • Normalization
  • 5. 1-5 Copyright  CSC India, 2001. All rights reserved. Relational Database Concept Dr. E.F. Codd proposed the relational model for database systems in 1970. It is the basis for the relational database management system. The relational model consists of the following: – Collection of objects or relations – Set of operators to act on the relations – Data integrity for accuracy and consistency
  • 6. 1-6 Copyright  CSC India, 2001. All rights reserved. Definition of a Relational Database A relational database is a collection of relations or two-dimensional tables. Table Name: EMPLOYEES Table Name: DEPARTMENTS Oracle Server
  • 7. 1-7 Copyright  CSC India, 2001. All rights reserved. Model of system in client’s mind Model of System in Clients mind Entity model of Client’s model Table model of entity model Tables on disk Data Models
  • 8. 1-8 Copyright  CSC India, 2001. All rights reserved. Entity Relationship Model Create an entity relationship diagram from business specifications • Assign one or more employees to a department • Some departments do not yet have assigned employees
  • 9. 1-9 Copyright  CSC India, 2001. All rights reserved. Entity Relationship Modeling Conventions Entity • Soft box • Singular, unique name • Uppercase • Synonym in parentheses Attribute • Singular name • Lowercase • Mandatory marked with “*” • Optional marked with “o” Primary marked with “#” Secondary marked with “(#)” assigned to composed of
  • 10. 1-10 Copyright  CSC India, 2001. All rights reserved. Relating Multiple Tables • Each row of data in a table is uniquely identified by a primary key (PK). • You can logically relate data from multiple tables using foreign keys (FK). Table Name: EMPLOYEES Table Name: DEPARTMENTS Primary key Foreign key Primary key
  • 11. 1-11 Copyright  CSC India, 2001. All rights reserved. Communicating with a RDBMS Using SQL SQL statement is entered. Statement is sent to Oracle Server. Data is displayed.
  • 12. 1-12 Copyright  CSC India, 2001. All rights reserved. Relational Database Management System User tables Data dictionary
  • 13. 1-13 Copyright  CSC India, 2001. All rights reserved. SQL Languages Statement Language SELECT Data retrieval language INSERT UPDATE Data manipulation language (DML) DELETE MERGE CREATE ALTER DROP Data definition language (DDL) RENAME TRUNCATE COMMIT ROLLBACK Transaction control language (TCL) SAVEPOINT GRANT REVOKE Data control language (DCL)
  • 14. 1-14 Copyright  CSC India, 2001. All rights reserved. SQL Used to • Querying data • Inserting, updating, and deleting rows in a table • Creating, altering, and dropping objects • Controlling access to the database and its objects • Guaranteeing database consistency and integrity
  • 15. 1-15 Copyright  CSC India, 2001. All rights reserved. Tables Used in this Training EMP  Stores details of all Employees DEPT Stores details of all Departments SALGRADE Stores details of salaries for various grades
  • 16. 1-16 Copyright  CSC India, 2001. All rights reserved.
  • 17. 1-17 Copyright  CSC India, 2001. All rights reserved.
  • 18. 1-18 Copyright  CSC India, 2001. All rights reserved.
  • 19. 1-19 Copyright  CSC India, 2001. All rights reserved. Normalization Normalization is the process of efficiently organizing the data in the database Goals: •Eliminate redundant data(storing the same data in more than on table) •Ensure data dependencies (only storing related data in a table)
  • 20. 1-20 Copyright  CSC India, 2001. All rights reserved. Normalization Types of Normal Forms(Rules): •First normal form(1NF) Eliminate duplicative columns from the same table Create separate tables for each group of related data and identify each row with a unique column or set of columns(primary key)
  • 21. 1-21 Copyright  CSC India, 2001. All rights reserved. Normalization •Second normal form(2NF) Meet all the requirements of the first normal form. Remove subsets of data that apply to multiple rows of a table and place them in a separate tables.  Create relationships between these tables by using foreign keys.
  • 22. 1-22 Copyright  CSC India, 2001. All rights reserved. Normalization •Third normal form(3NF) Meet all the requirements of the second normal form. Remove columns that are not dependent on the primary key
  • 23. Copyright  CSC India, 2001. All rights reserved. Writing Basic SQL Statements
  • 24. 1-24 Copyright  CSC India, 2001. All rights reserved. Objectives After completing this lesson, you should be able to do the following : • List the capabilities of SQL SELECT statements • Execute a basic SELECT statement • Differentiate between SQL statements and iSQL* Plus commands.
  • 25. 1-25 Copyright  CSC India, 2001. All rights reserved. Basic SELECT Statement Syntax : SELECT * | { [DISTINCT] column | expression [alias],…} FROM table; SELECT identifies what columns FROM identifies which table
  • 26. 1-26 Copyright  CSC India, 2001. All rights reserved. Writing SQL Statements • SQL statements are not case sensitive • SQL statements can be on one or more lines • Keywords cannot be abbreviated or split across lines • Clauses are usually placed on separate lines • Indents are used to enhance readability
  • 27. 1-27 Copyright  CSC India, 2001. All rights reserved. Arithmetic Expressions Operator Precedence : * / + - • Multiplication and division take priority over addition and subtraction • Operators of the same priority are evaluated from left to right • Parentheses are used to force prioritized evaluation and to clarify statements Operator Description + Add - Subtract * Multiply / Divide
  • 28. 1-28 Copyright  CSC India, 2001. All rights reserved. Using Arithmetic Examples SELECT Ename, Sal, Sal +500 FROM Emp;
  • 29. 1-29 Copyright  CSC India, 2001. All rights reserved. Operator Precedence : SELECT Ename, Sal, 12*Sal +500 FROM Emp;
  • 30. 1-30 Copyright  CSC India, 2001. All rights reserved. Using Parentheses : SELECT Ename, Sal, 12*(Sal +500 ) FROM Emp;
  • 31. 1-31 Copyright  CSC India, 2001. All rights reserved. Defining a NULL value Syntax: NVL(expr1,expr2) • A null is a value that is unavailable, unassigned, unknown, or inapplicable. • A null is not the same as zero or a blank space. SQL> Select Empno, Ename,Sal,Comm,Sal+Comm "Total Salary“ from Emp where deptno =30; SQL> Select Empno, Ename, Sal, Comm, Sal+ Nvl (Comm,0) "Total Salary“ from Emp where deptno =30; SQL> Select Empno, Ename ,Sal, Nvl (To_char (Comm),'Not Applicable') commission from Emp where Deptno =30; Note: Arithmetic expressions containing a null value evaluate to null
  • 32. 1-32 Copyright  CSC India, 2001. All rights reserved.
  • 33. 1-33 Copyright  CSC India, 2001. All rights reserved. Defining a Column Alias A column alias : • Renames a column heading • Is useful with calculations • Immediately follows the column name • An optional AS keyword can be used • Requires double quotations if it contains spaces or special characters Ex: SELECT Ename Employee name, 12*Sal AS “Annual Salary” FROM Emp;
  • 34. 1-34 Copyright  CSC India, 2001. All rights reserved. Defining a Column Alias
  • 35. 1-35 Copyright  CSC India, 2001. All rights reserved. Concatenation Operator • Concatenates columns or character strings to other columns • Operator is two vertical bars ( || ) • Creates a resultant column that is a character expression Example :
  • 36. 1-36 Copyright  CSC India, 2001. All rights reserved. Literal Character Strings  A character, a number, or a date included in the SELECT list  Date and character literal values must be enclosed within single quotation marks  Each character string is output once for each row returned  Literal strings included in the query are treated as a column in the SELECT list. Ex:
  • 37. 1-37 Copyright  CSC India, 2001. All rights reserved. Eliminating Duplicate Rows The default display is all rows, including duplicate rows To eliminate duplicate rows, use the DISTINCT keyword Note : The duplicate row are just not displayed but they remain in the database
  • 38. 1-38 Copyright  CSC India, 2001. All rights reserved. Interacting with Oracle Server We can interact with Oracle Server by two environments SQL*Plus : - Character based - Provides a line editor for modifying SQL statements iSQL*Plus : - GUI based - Provides online editing for modifying SQL statements - Accessed from browser
  • 39. Copyright  CSC India, 2001. All rights reserved. Restricting and Sorting Data
  • 40. 1-40 Copyright  CSC India, 2001. All rights reserved. Objective After completing this lesson, you should be able to do : • Limit the rows retrieved by a query • Sort the rows retrieved by a query
  • 41. 1-41 Copyright  CSC India, 2001. All rights reserved. Limiting the Rows Selected Use the WHERE clause SELECT * | { [DISTINCT] column/expression [alias],… } FROM table [ WHERE conditions(s) ]; The WHERE clause follows the FROM clause. The condition is composed of column names, expressions, constants and a comparison operator Ex : SELECT Empno, Ename, Job FROM Emp WHERE Deptno=10;
  • 42. 1-42 Copyright  CSC India, 2001. All rights reserved. Character Strings and Dates Are enclosed in single quotation marks Character values are case sensitive Date values are format sensitive The default date format is DD-MON-RR Ex:
  • 43. 1-43 Copyright  CSC India, 2001. All rights reserved. Comparison Operators They are used in the WHERE clause in the following Format. Syntax : ….. WHERE Expr operator value Operator Meaning = Equal to > Greater than >= Greater than or equal to < Less than <= Less than or equal to <> , != , ^= Not Equal to
  • 44. 1-44 Copyright  CSC India, 2001. All rights reserved. Other Comparison Operators Use the LIKE condition to perform wildcard searches of valid search string values - % denotes zero or many characters - _ denotes one character (underscore) Operator Meaning BETWEEN..AND… Between two values (inclusive) IN(Set) Match any of a list of values LIKE Match a character pattern IS NULL Is a null value
  • 45. 1-45 Copyright  CSC India, 2001. All rights reserved. Examples on using Comparison Operators SQL> SELECT * from Emp Where deptno IN (10,20); SQL> SELECT Empno,Ename,Job,Sal FROM Emp WHERE Job IN('MANAGER','CLERK'); SQL> SELECT * from Emp Where Ename LIKE ‘S%’; SQL> SELECT * from Emp Where Hiredate LIKE ‘%JAN%’; SQL> SELECT * from Emp Where Ename LIKE '_____' SQL> SELECT * from Emp Where Ename LIKE ‘S_I_H’ SQL> SELECT * from Emp Where Comm IS NULL; SQL> SELECT * from Emp Where NOT deptno=10; SQL> SELECT * from Emp Where EXISTS (select deptno from dept);
  • 46. 1-46 Copyright  CSC India, 2001. All rights reserved. Examples on using Comparison Operators
  • 47. 1-47 Copyright  CSC India, 2001. All rights reserved. Examples on using Comparison Operators
  • 48. 1-48 Copyright  CSC India, 2001. All rights reserved. Logical Operators Operator Meaning AND Returns TRUE if both component conditions are true OR Returns TRUE if either component condition is true NOT Returns TRUE if the following condition is false •Combines the result of two component conditions to produce a single result • With these operators we can use several conditions in one WHERE clause.
  • 49. 1-49 Copyright  CSC India, 2001. All rights reserved. Using the AND Operators AND requires both conditions to be true SELECT Empno, Ename, Job, Sal FROM Emp WHERE Sal >=2000 AND Job LIKE '%MAN%'; AND TRUE FALSE NULL TRUE TRUE FALSE NULL FALSE FALSE FALSE FALSE NULL NULL FALSE NULL
  • 50. 1-50 Copyright  CSC India, 2001. All rights reserved. Using the OR operator OR requires either condition to be true SELECT Empno, Ename, Job, Sal FROM Emp WHERE Sal >=2000 OR Job LIKE '%MAN%'; OR TRUE FALSE NULL TRUE TRUE TRUE TRUE FALSE TRUE FALSE NULL NULL TRUE NULL NULL
  • 51. 1-51 Copyright  CSC India, 2001. All rights reserved. Examples
  • 52. 1-52 Copyright  CSC India, 2001. All rights reserved. Using the NOT Operator To negate the result we use the NOT Operator SELECT Ename, Job, Sal FROM Emp WHERE Job NOT IN('MANAGER','CLERK');
  • 53. 1-53 Copyright  CSC India, 2001. All rights reserved. Rules of Precedence Order Evaluated Operator 1 Arithmetic operators 2 Concatenation operator 3 Comparison conditions 4 IS [NOT] NULL, LIKE, [NOT] IN 5 [NOT] BETWEEN 6 NOT logical condition 7 AND logical condition 8 OR logical condition Override rules of precedence by using parentheses. The same precedence operators work from left to right.
  • 54. 1-54 Copyright  CSC India, 2001. All rights reserved. ORDER BY Clause Sort rows with the ORDER BY clause - ASC : Ascending order, default - DESC : Descending order Syntax : SELECT expr,column(s) FROM table [WHERE condition(s)] [ORDER BY {column, expr} [ASC|DESC] ] ; Default Ordering of Data  Numeric values lowest values first 1 - 999  Date values earliest value first 1-jan-92 before 1-jan-95  Character values alphabetical order a first and z last  Null values last
  • 55. 1-55 Copyright  CSC India, 2001. All rights reserved. Sorting Examples SELECT Ename, Job, Deptno, Hire_date FROM Emp ORDER BY Hire_date ; SELECT Ename, Job, Deptno, Hire_date FROM Emp ORDER BY Hire_date DESC ;  Sort order can be specified by position value also SELECT Ename, Job, Deptno, Hire_date FROM Emp ORDER BY 3 DESC ;
  • 56. 1-56 Copyright  CSC India, 2001. All rights reserved. Some more sorting methods Sorting by Column Alias SELECT Empno, Ename, Sal*12 annual_sal FROM Emp ORDER BY annual_sal ; Sorting by Multiple Columns - we can use multiple columns in the ORDER BY clause - The order of ORDER BY list is the order of sort SELECT Ename , Deptno, Sal FROM Emp ORDER BY Deptno, Sal DESC;
  • 57. 1-57 Copyright  CSC India, 2001. All rights reserved. Examples
  • 58. 1-58 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you should have learned how to : Use the WHERE clause to restrict rows of output - use the comparison conditions - use the BETWEEN..AND.. , IN , LIKE , and NULL conditions - Apply the logical AND, OR, and NOT operators Use the ORDER BY clause to sort rows of output
  • 59. Copyright  CSC India, 2001. All rights reserved. Functions
  • 60. 1-60 Copyright  CSC India, 2001. All rights reserved. Objectives • After completing this lesson, you should be able to do the following : • Describe various types of functions available in SQL • Use character, number and date functions in SELECT statements • Describe the use of conversion functions
  • 61. 1-61 Copyright  CSC India, 2001. All rights reserved. SQL Functions Function Function performs action arg1 arg2 arg n Result value Input Output
  • 62. 1-62 Copyright  CSC India, 2001. All rights reserved. Two types of SQL Functions Single row functions : Operate on single rows only and return one result per row . Different Types of Single row functions : Character Number Date Conversion General Multiple row functions: Manipulates groups of rows to give one result per group of rows. Also called as group functions Functions Single-row functions Multiple-row functions
  • 63. 1-63 Copyright  CSC India, 2001. All rights reserved. Single Row Functions Single row functions : • Manipulate data items • Accept arguments and return one value • Act on each row returned • Return one result per row • May modify the data type • Can be nested • Accept arguments which can be a column or an expression function_name [ (arg1, arg2, …) ] • Can be used in SELECT, WHERE, and ORDER BY clauses
  • 64. 1-64 Copyright  CSC India, 2001. All rights reserved. Character Functions Character Functions Case-manipulation functions Character-manipulation functions LOWER UPPER INITCAP CONCAT SUBSTR LENGTH INSTR LPAD | RPAD TRIM REPLACE
  • 65. 1-65 Copyright  CSC India, 2001. All rights reserved. Case Manipulation Functions These functions convert case for character strings. - LOWER : converts character strings to lowercase - UPPER : converts character strings to uppercase - INITCAP: converts the first letter of each word to uppercase and remaining letters to lowercase Example : SELECT LOWER('SQL Course') , INITCAP('SQL Course') From Dual These functions are useful for String comparisons in WHERE clause Example I. SELECT * FROM Emp WHERE Ename = UPPER('scott');
  • 66. 1-66 Copyright  CSC India, 2001. All rights reserved. Character-Manipulation Functions These functions manipulate character strings : • CONCAT : Joins values together • SUBSTR : Extracts a string of determined length • LENGTH : Shows the length of a string as a numeric value • INSTR : Finds numeric position of a named character • LPAD : Pads the character value right-justified • RPAD : Pads the character value left-justified • TRIM : Trims heading or trailing characters( or both) from a character string
  • 67. 1-67 Copyright  CSC India, 2001. All rights reserved. Examples Query Output Select CONCAT('Hello', 'World') HelloWorld SUBSTR('HelloWorld',1,5) Hello LENGTH('HelloWorld'), 10 INSTR('HelloWorld', 'W'), 6 LPAD('Hello',10, '*'), *****Hello RPAD('Hello',10, '*'), Hello***** TRIM('H' FROM 'HelloWorld') elloWorld FROM dual;
  • 68. 1-68 Copyright  CSC India, 2001. All rights reserved. Character Functions: Character Functions Returning Character Values (CHR,LOWER,UPPER,LTRIM,RTRIM,INITCAP,REPLACE, SUBSTRING,INSTRING) CHR returns the character having the binary equivalent to n SELECT CHR(67)||CHR(65)||CHR(84) "Dog" FROM DUAL; Dog --- CAT LOWER returns char, with all letters lowercase SELECT LOWER('MR. SCOTT MCMILLAN') "Lowercase" FROM DUAL; UPPER returns char, with all letters uppercase. SELECT UPPER('Large') "Uppercase" FROM DUAL; Character-Manipulation Functions
  • 69. 1-69 Copyright  CSC India, 2001. All rights reserved. LTRIM removes characters from the left of char, with all the leftmost characters that appear in set removed SELECT LTRIM ( 'xyxXxyLAST WORD ','xy‘ ) "LTRIM example" FROM DUAL; Result: XxyLAST WORD RTRIM returns char, with all the rightmost characters that appear in set removed SELECT RTRIM ('BROWNINGyxXxy‘ ,'xy') "RTRIM example" FROM DUAL; Result: BROWNINGyxX INITCAP returns char, with the first letter of each word in uppercase, all other letters in lowercase SELECT INITCAP('the soap') "Capitals" FROM DUAL; Result: The Soap REPLACE returns char with every occurrence of search string replaced with replacement string. SELECT REPLACE('JACK and JUE','J','BL') "Changes" FROM DUAL; Result : BLACK and BLUE Character-Manipulation Functions
  • 70. 1-70 Copyright  CSC India, 2001. All rights reserved. SUBSTR return a portion of string, beginning at character position, substring length characters long. SELECT SUBSTR('ABCDEFG',3,4) "Substring" FROM DUAL; Result: CDEF Character Functions Returning Number Values: ASCII returns the decimal representation in the database character set of the first character of char. SELECT ASCII('Q') FROM DUAL; Result: 81 INSTR function returns an integer indicating the position of the character in string that is the first character of this occurrence. SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL; Result: 14 LENGTH function return the length of char SELECT LENGTH('CANDIDE') "Length in characters" FROM DUAL; Result:7 Character-Manipulation Functions
  • 71. 1-71 Copyright  CSC India, 2001. All rights reserved. Number Functions Numeric functions accept numeric input and return numeric values (ABS,CEIL,FLOOR, MOD,POWER,,ROUND,TRUNC) --ABS returns the absolute value of n. SQL> SELECT ABS(-15) "Absolute" FROM DUAL; Absolute ---------- 15 --CEIL returns smallest integer greater than or equal to n SELECT CEIL(15.7) "Ceiling" FROM DUAL; Ceiling ---------- 16
  • 72. 1-72 Copyright  CSC India, 2001. All rights reserved. Number Functions FLOOR returns largest integer equal to or less than n. SELECT FLOOR(15.7) "Floor" FROM DUAL; Floor ---------- 15 MOD returns the remainder of m divided by n. Returns m if n is 0. SELECT MOD(11,4) "Modulus" FROM DUAL; Modulus ---------- 3 POWER returns m raised to the nth power SELECT POWER(3,2) "Raised" FROM DUAL; Raised ---------- 9
  • 73. 1-73 Copyright  CSC India, 2001. All rights reserved. Number Functions ROUND returns number rounded to integer places right of the decimal point SELECT ROUND(15.193,1) "Round" FROM DUAL; Round ---------- 15.2 The TRUNC (number) function returns n truncated to m decimal places. SELECT TRUNC(15.79,1) "Truncate" FROM DUAL; Truncate ---------- 15.7 > SELECT ROUND(45.92,1),ROUND(45.92,0),ROUND(45.92,-1), TRUNC(45.92,1), TRUNC(45.92,0), TRUNC(45.92,-1), MOD(45 , 7 ), MOD(45,9) FROM DUAL; > O/p : 45.9 46 50 45.9 45 40 3 0
  • 74. 1-74 Copyright  CSC India, 2001. All rights reserved. Date Functions Function Description MONTHS_BETWEEN(date1, date2) Number of months between two dates ADD_MONTHS(date, n) Add calendar months to date NEXT_DAY(date, ‘char’) Next day of the date specified LAST_DAY(date) Last day of the month ROUND(date [, ‘fmt’] ) Round date TRUNC(date [,’fmt’]) Truncate date Datetime functions operate on values of the DATE datatype. All datetime functions return a datetime or interval value of DATE datatype, except the MONTHS_BETWEEN function, which returns a number.
  • 75. 1-75 Copyright  CSC India, 2001. All rights reserved. Using Date Functions SELECT MONTHS_BETWEEN(’01-sep-95’ , ’11-jan-94’) ADD_MONTHS(’11-JAN-94’ , 6) NEXT_DAY(’01-SEP-95’ , ‘FRIDAY’) LAST_DAY(’01-FEB-95’) ROUND(SYSDATE , ‘MONTH’) ROUND(SYSDATE , ‘YEAR’) TRUNC(SYSDATE, ‘MONTH’) TRUNC(SYSDATE, ‘YEAR’) SYSDATE FROM DUAL; 19.67741941 1-JUL-94 08-SEP-95 28-FEB-95 01-AUG-95 01-JAN-96 01-JUL-95 01-JAN-95 25-JUL-95 Output
  • 76. 1-76 Copyright  CSC India, 2001. All rights reserved. Date Functions Examples
  • 77. 1-77 Copyright  CSC India, 2001. All rights reserved. Date Functions Examples
  • 78. 1-78 Copyright  CSC India, 2001. All rights reserved. Conversion Functions Data type conversion Implicit data type conversion Explicit data type conversion
  • 79. 1-79 Copyright  CSC India, 2001. All rights reserved. Implicit Data Type Conversion If a different data type value comes for an expected data type value then Oracle server automatically converts the former to the later data type and uses it This can happen in assignments or expression evaluations The implicit conversion of string to number data type happens only when it is compatible Example : SELECT Ename, Job, Sal FROM Emp WHEREdeptno= '10'; ; Although implicit data type conversion is available, it is recommended to do explicit data type conversion to ensure reliability.
  • 80. 1-80 Copyright  CSC India, 2001. All rights reserved. Explicit Data Type Conversion Date or Number to Varchar2 string TO_CHAR(number/date , [fmt] ) Character to number TO_NUMBER(char , [fmt] ) Character to Date TO_DATE( char, [fmt] ) 5000 $5,000
  • 81. 1-81 Copyright  CSC India, 2001. All rights reserved. Explicit Conversion functions T0_CHAR Converts number and date values in to variable character format Sql> Select TO_CHAR (sysdate, ’dd/month/yyyy’ ) Today from dual; Result: 09/december /2008 Sql> Select TO_CHAR (258560,'$9,99,999') from Dual; Result: $2,58,560
  • 82. 1-82 Copyright  CSC India, 2001. All rights reserved. Explicit Conversion functions TO_DATE –> Converts variable date formats into default date formats Select TO_CHAR (TO_DATE('18-APR-06','DD-MON-YY'), 'dd/month/yyyy') Today from dual; Result: 18/april /2006 Select TO_CHAR (TO_DATE('18-APR-2006', 'DD-MON-YYYY'),'dd/month/yyyy') Today from dual; Result: 18/april /2006
  • 83. 1-83 Copyright  CSC India, 2001. All rights reserved. Explicit Conversion functions TO_NUMBER –>Converts Character datatype containing a number in the format to a value of NUMBER datatype Select TO_NUMBER('$5,46,350',’L9,99,999')from dual Result: 546350 Format Select TO_NUMBER('$2,555.760', 'L9,999.999')from dual Result: 2555.76
  • 84. 1-84 Copyright  CSC India, 2001. All rights reserved.
  • 85. 1-85 Copyright  CSC India, 2001. All rights reserved. Elements of the Date Format Model Format Model Description YYYY Full year in numbers YEAR Year spelled out MM Two-digit value for month MONTH Full name of the month MON Three-letter abbreviation of the month DY Three-letter abbreviation of day of the week DAY Full name of the day of the week DD Numeric day of the month
  • 86. 1-86 Copyright  CSC India, 2001. All rights reserved. Elements of the Date Format Model Format Model Description HH or HH12 or HH24 Hour of day, or hour(1-12), or hour(0-23) MI Minute (0-59) SS Second (0-59) SSSSS Seconds past midnight ( 0-86399 ) AM or PM Meridian indicator A.M. or P.M. Meridian indicator with periods
  • 87. 1-87 Copyright  CSC India, 2001. All rights reserved. RR Date Format Example : SELECT ename, hiredate FROM emp WHERE hiredate < TO_DATE(’01-JAN-60’ ,‘DD-MON- RR’); If the specified two-digit year is 0-49 50-99 If two digits of the current year are : 0-49 The return date is in current century The return date is in century before current one 50-99 The return date is in the century after current one The return date is in current century
  • 88. 1-88 Copyright  CSC India, 2001. All rights reserved. RR Date Format If the specified two-digit year is 0-49 50-99 If two digits of the current year are : 0-49 The return date is in current century The return date is in century before current one 50-99 The return date is in the century after current one The return date is in current century Current Year Given Date Interpreted( RR) Interpreted (YY) 1994 27-OCT-95 1995 1995 1994 27-OCT-17 2017 1917 2001 27-OCT-17 2017 2017
  • 89. 1-89 Copyright  CSC India, 2001. All rights reserved. YY Date Format Command is Run in 2009 Command is Run in 1999
  • 90. 1-90 Copyright  CSC India, 2001. All rights reserved. RR Date Format Command is Run in 2009 Command is Run in 1999
  • 91. 1-91 Copyright  CSC India, 2001. All rights reserved. Nesting Functions • Single – row functions can be nested to any level • Nested Functions are evaluated from deepest level to the least deep level Ex : SELECT TO_CHAR (TO_DATE('18-APR-06’), 'dd/month/yyyy') Today from dual; Result : 18/april /2006
  • 92. 1-92 Copyright  CSC India, 2001. All rights reserved. General Functions These functions work with any data type and pertain to using nulls. NVL( expr1, expr2) NVL2(expr1, expr2, expr3) NULLIF(expr1, expr2) COALESCE(expr1, expr2,…..,exprn) Note : The NVL2, NULLIF, COALESCE functions are introduced in Oracle 9i
  • 93. 1-93 Copyright  CSC India, 2001. All rights reserved. NVL Function • Converts a null to an actual value • Data types must match • Useful for expressions having null values as with this, null values converts to a meaningful value Syntax : NVL (expr1, expr2 ) If expr1 is null then expr2 is returned else expr1 is returned Example : SELECT NVL(10,20) FROM DUAL; SELECT NVL(null,20) FROM DUAL;
  • 94. 1-94 Copyright  CSC India, 2001. All rights reserved. Using NVL2 function NVL2 Function NVL2(expr1, expr2, expr3) If expr1 is not null then expr2 is returned else expr3 is returned Example : Output SELECT NVL2(10,20,30) FROM DUAL ; 20 SELECT NVL2(NULL,20,30) FROM DUAL ; 30
  • 95. 1-95 Copyright  CSC India, 2001. All rights reserved. Using NULLIF function NULLIF function NULLIF(expr1, expr2) If expr1 and expr2 are equal then null else expr1 is returned Example : SELECT NULLIF(4*3 , 3*2), NULLIF( 2*3, 3*2) FROM DUAL; O/p : 12 - Null is there but it will not appear
  • 96. 1-96 Copyright  CSC India, 2001. All rights reserved. Using the COALESCE Function The advantage of the COALESCE function over the NVL function is that this function can take multiple alternate values. COALESCE(expr1, expr2, expr3….,exprn) This checks sequentially from expr1 to exprn and returns first non-null value Example : SELECT COALESCE(NULL,NULL,NULL,2,NULL,10,20) FROM DUAL;
  • 97. 1-97 Copyright  CSC India, 2001. All rights reserved. DECODE Function Facilitates conditional inquiries by doing the work of a CASE or IF-THEN-ELSE statement DECODE (col /expression, search1, result1 [, search2, result2,...,] [, default])
  • 98. 1-98 Copyright  CSC India, 2001. All rights reserved. Using the DECODE Function SQL> SELECT job, sal, DECODE(job, 'ANALYST', SAL*1.1, 'CLERK', SAL*1.15, 'MANAGER', SAL*1.20, SAL) REVISED_SALARY FROM Emp; JOB SAL REVISED_SALARY --------- --------- -------------- PRESIDENT 5000 5000 MANAGER 2850 3420 MANAGER 2450 2940 ... 14 rows selected.
  • 99. 1-99 Copyright  CSC India, 2001. All rights reserved. Decode:
  • 100. 1-100 Copyright  CSC India, 2001. All rights reserved. Conditional Expressions To Provide the use of IF-THEN-ELSE logic within a SQL statement, use : - CASE expression - DECODE function CASE expression CASE expr WHEN comparison_expr1 THEN return_expr1 [WHEN comparison_expr2 THEN return_expr2 ELSE else_expr ] END DECODE function DECODE(col/expr, search1, result1 [, search2, result2,…] [, default] )
  • 101. 1-101 Copyright  CSC India, 2001. All rights reserved. Examples SELECT CASE ‘a’ WHEN ‘b’ THEN ‘hello b’ WHEN ‘a’ THEN ‘hello a’ ELSE ‘hello somebody’ END hello FROM DUAL; SELECT DECODE('A','B','HELLO B','A','HELLO A', 'HELLO X') HELLO FROM DUAL
  • 102. 1-102 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you should have learned how to : • Perform calculations on data using functions • Modify individual data items using functions • Manipulate output for groups of rows using functions • Alter date formats for display using functions • Convert column data types using functions • User NVL functions • Use IF-THEN-ELSE logic
  • 103. Copyright  CSC India, 2001. All rights reserved. Group Functions
  • 104. 1-104 Copyright  CSC India, 2001. All rights reserved. Objective After completing this lesson, you should be able to do the following : • Identify the available group functions • Describe the use of group functions • Group data using the GROUP BY clause • Include or exclude grouped rows by using the HAVING clause
  • 105. 1-105 Copyright  CSC India, 2001. All rights reserved. Group Functions Group Functions operate on sets of rows to give one result per group Syntax : SELECT [column, ] group_function(column), …. FROM table [WHERE condition] [GROUP BY column] [HAVING group_condition] [ORDER BY column] ; • All group functions ignore null values. To substitute a value for null values use NVL functions • The Oracle server implicitly sorts the result set in ascending order when using a GROUP BY clause.
  • 106. 1-106 Copyright  CSC India, 2001. All rights reserved. Types of Group Functions Function Description AVG([DISTINCT|ALL] n) Average value of n COUNT( { *| [DISTINCT|ALL] expr } ) Number of rows where expr evaluates to not null. For *, including duplicates and rows with nulls also MAX( [DISTINCT|ALL] expr ) Maximum value of expr MIN( [DISTINCT|ALL] expr) Minimum value of expr STDDEV( [DISTINCT|ALL] x) Standard deviation of n SUM ( [DISTINCT|ALL] n) Sum values of n VARIANCE( [DISTINCT|ALL]x) Variance of n
  • 107. 1-107 Copyright  CSC India, 2001. All rights reserved. Group functions Examples: Sql> select count(*),count (distinct(comm)) ,count(comm) from Emp; Sql> select max(sal) max_sal, min(sal) min_sal, avg(sal) avg_sal, sum(sal) sum_sal FROM Emp;
  • 108. 1-108 Copyright  CSC India, 2001. All rights reserved. Using the Group Functions The AVG and SUM are used with numeric data. The MIN and MAX functions used with any data type The COUNT returns the number of rows with non null values. Use DISTINCT clause not to consider duplicate values Group functions do not consider null values. To consider user NVL functions. Example : Select sum(sal), avg(comm), avg(nvl(comm,0)), min(hiredate), max(hiredate), count(*) strength FROM Emp;
  • 109. 1-109 Copyright  CSC India, 2001. All rights reserved. Group functions Examples: Select deptno ,max(sal) max_sal ,min(sal) min_sal ,avg(sal) avg_sal ,sum(sal) sum_sal from Emp group by deptno;
  • 110. 1-110 Copyright  CSC India, 2001. All rights reserved. Creating Groups of Data  Use GROUP BY clause to divide the table information into small groups  Use group functions to get summary information for each group  All individual columns other than group functions must be specified in the GROUP BY clause list, when using GROUP BY  Any column other than selected column can also be placed in GROUP BY clause  By default rows are sorted by ascending order of the column included in the GROUP BY list. Example : SELECT deptno, AVG(Sal) FROM Emp GROUP BY deptno;
  • 111. 1-111 Copyright  CSC India, 2001. All rights reserved. Excluding Group Results To restrict groups we have to use HAVING clause - Rows are grouped - The group function is applied - Groups matching the HAVING Clause are displayed. Example : SELECT Deptno, MAX(sal) FROM Emp GROUP BY Deptno HAVING MAX(sal) > 3000;
  • 112. 1-112 Copyright  CSC India, 2001. All rights reserved. Group functions Examples: Select deptno, count(deptno) From Emp Group by deptno Having count(*)>3;
  • 113. 1-113 Copyright  CSC India, 2001. All rights reserved. Group functions Examples: Sql> select deptno, count(deptno) From Emp Where deptno in(20,30) Group by deptno Having count(*)>3 Order by 1;
  • 114. 1-114 Copyright  CSC India, 2001. All rights reserved. Nesting of Group Functions Group functions can be nested to a depth of two. Example : SELECT MAX(AVG(salary)) FROM Emp GROUP BY Deptno ;
  • 115. 1-115 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you should have learned how to : • Use the group functions COUNT, MAX, MIN, AVG • Write queries that use the GROUP BY clause • Write queries that use the HAVING clause
  • 116. Copyright  CSC India, 2001. All rights reserved. Formatting Output Using SQL*Plus
  • 117. 1-117 Copyright  CSC India, 2001. All rights reserved. Objective After completing this lesson, you should be able to do : • Produce queries that require a substitution variables • Customize the iSQL*Plus environment • Produce more readable output • Create and execute script files
  • 118. 1-118 Copyright  CSC India, 2001. All rights reserved. Substitution Variables Some times, there is a need of user interaction to create interactive reports This can be achieved with the substitution variables Use substitution variables to : - To temporarily store values ~ Single ampersand (&) ~ Double ampersand (&&) ~ DEFINE command - Pass variable values between SQL statement - Dynamically after headers and footers
  • 119. 1-119 Copyright  CSC India, 2001. All rights reserved. Using the & substitution variable Use a variable prefixed with an ampersand (&) to prompt the user for a value Example : SELECT Empno ,Ename , Sal FROM Emp WHERE Deptno= &dno; Use single quotation marks for date and character values Example : SELECT Empno ,Ename , Sal FROM Emp WHERE Job= '&job_name';
  • 120. 1-120 Copyright  CSC India, 2001. All rights reserved. Defining Substitution Variables The DEFINE command predefines variables A defined variable is available for the current session only It remains defined until - it cleared using UNDEFINE command Or - Exit iSQL*Plus or SQL*Plus environment Command Description DEFINE variable = value Creates a user variable with the CHAR data and assigns a value to it DEFINE variable Displays the variable, its value, and its data type DEFINE Displays all user variables with their values and data types
  • 121. 1-121 Copyright  CSC India, 2001. All rights reserved. Using the DEFINE Command Create the substitution variable using the DEFINE command Use a variable prefixed with an ampersand (&) to substitute the value in the SQL statement. To change the value UNDEFINE the variable and recreate it.  DEFINE employee_num = 1  SELECT ‘hello world’ FROM DUAL WHERE &enum = &employee_num ; Here, enum variable is undefined and hence asks the user for input. Depending on the value and already defined employee_num value comparison is done and result is displayed UNDEFINE employee_num
  • 122. 1-122 Copyright  CSC India, 2001. All rights reserved. Use the && Substitution variable Use the double ampersand (&&) if you want to reuse the variable without prompting the user each time. Example : SELECT ‘welcome to ‘ || ‘&& name’ , ‘Hello ‘ ||’&name’ FROM DUAL ; The value supplied is stored to that variable using DEFINE command internally. Hence its value persists for this session. For any change in the value use UNDEFINE command
  • 123. 1-123 Copyright  CSC India, 2001. All rights reserved. Using the VERIFY Command Use the VERIFY command to toggle the display of the substitution variable, before and after iSQL*Plus replaces substitution variable with values. First set verify command using SET VERIFY ON This will show the text of command before and after it replaces the substitution variables with values
  • 124. 1-124 Copyright  CSC India, 2001. All rights reserved. Customizing the iSQL*Plus Environment Use SET commands to control current session SET system_variable value Verify what you have set by using the SHOW command - SET ECHO ON - SHOW ECHO O/p : echo ON Use SHOW ALL to see all SET variable values All format commands remain in effect until the end of iSQL*Plus session or the settings are overwritten or cleared If alias is present for a column, then reference the alias name, not the column name.
  • 125. 1-125 Copyright  CSC India, 2001. All rights reserved. SET Command Variables Examples : SET HEADING OFF SET FEEDBACK 4 SET Variable and Values Description ARRAY [SIZE] { 20 | n } Sets the database data fetch size FEED[BACK] {6|n|OFF|ON} Displays the number of records returned by a query when the query selects at least n records HEA[DING] {OFF|ON} Determines whether column headings are displayed in reports LONG {80 | n} Sets maximum width for displaying LONG values
  • 126. 1-126 Copyright  CSC India, 2001. All rights reserved. iSQL*Plus Format Commands Command Description COL[UMN][column option] Controls column formats TTI[TLE] [text | OFF | ON ] Specifies a header to appear at the top of each page of the report BTI[TLE] [text | OFF | ON] Specifies a footer to appear at the bottom of each page of the report BRE[AK][ON report_element] Suppresses duplicate values and divides rows of data into sections by using line breaks
  • 127. 1-127 Copyright  CSC India, 2001. All rights reserved. The COLUMN Command Controls display of a column : COL[UMN] [{column | alias} [OPTION] ] The various Column options are : - CLE[AR] clears any column formats - HEA[DING] text sets the column heading - FOR[MAT] format changes the display of the column using a format model - NOPRINT | PRINT not to display / display - NUL[L] text specifies text to be displayed for nulls Example :  COLUMN mgr NULL “no mgr”  SELECT * from emp;
  • 128. 1-128 Copyright  CSC India, 2001. All rights reserved. Using the Format Options Break : To suppress duplicates - BREAK ON job TTITLE : To Display headers - TTITLE ‘Salary/Report’ BTITLE : To display footers - BTITLE ‘Confidential’ CLEAR : To clear the settings - CLEAR COLUMN - CLEAR BREAK
  • 129. 1-129 Copyright  CSC India, 2001. All rights reserved. Sample Report  SET FEEDBACK OFF  TTITLE ‘Employee | Report’  BTITLE ‘Confidential’  BREAK ON job  COLUMN job HEADING ‘Job|Category’  COLUMN sal HEADING sal FORMAT $99,999.99  SELECT job, ename, sal FROM emp ;  CLEAR columns  CLEAR break
  • 130. 1-130 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you should have learned how to :  Use iSQL*Plus substitution variables to store values temporarily  Use SET commands to control the current iSQL*Plus environment  Use the COLUMN command to control the display of a column  Use the BREAK command to suppress duplicates and divide rows into sections  Use the TTITLE and BTITLE commands to display headers and footers.
  • 131. Copyright  CSC India, 2001. All rights reserved. Manipulating Data
  • 132. 1-132 Copyright  CSC India, 2001. All rights reserved. Objectives After completing this lesson, you should be able to do : • Describe each DML statement • Insert rows into a table • Update rows in a table • Delete rows from a table • Merge rows in a table • Control transactions
  • 133. 1-133 Copyright  CSC India, 2001. All rights reserved. Data Manipulation Language It is core part of SQL. A DML statement is executed when you : - Add new rows to a table - Modify existing rows in a table - Remove existing rows from a table A transaction consists of a collection of DML statements that form a logical unit of work. They are useful for the maintenance of Integrity of database
  • 134. 1-134 Copyright  CSC India, 2001. All rights reserved. The INSERT Statement Syntax Add new rows to a table by using the INSERT statement INSERT INTO table [ (column [, column…]) ] VALUES (value [, value … ] ) ; Example :  INSERT INTO dept VALUES ( 10, ’Sales’,’vizag’); Substitution variables can also be used  INSERT INTO departments VALUES ( 10, ’Sales’, ‘&location’ );
  • 135. 1-135 Copyright  CSC India, 2001. All rights reserved. INSERT Statement Examples • Syntax: – Insert into <table_name> values (val1,val2,val3……); SQL> INSERT into Emp values (1,’Allen’,5000,’20-jun-06’,10); • Inserting data into the specified columns • Syntax: – Insert into <table_name>(col1,col2,col3) values (val1,val2,val3); SQL> IINSERT into Emp (empno,ename,deptno) values (2,’Miller’,20); • Inserting data by using Substitution variables • Insert into <table_name> values (&val1,&val2,&val3….); SQL> INSERT into Emp values (&empno, ’&ename’ , &deptno); Note: Character and Date values should enclose within single quotes.
  • 136. 1-136 Copyright  CSC India, 2001. All rights reserved. Copying Row from Another Table Write INSERT statement with a sub query INSERT INTO copy_emp(id, name, salary,comm) SELECT empno, ename, sal, comm FROM emp WHERE job_id LIKE ‘%MAN%’ ; • Do not use the VALUES clause • Match the number of columns and their data types in the INSERT clause to those in the sub query
  • 137. 1-137 Copyright  CSC India, 2001. All rights reserved. Changing Data using UPDATE statement Modify existing rows with the UPDATE statement UPDATE table SET column = value [, column = value, … ] [WHERE condition ] ; • Update more than one row at a time, if required • If WHERE clause is omitted, then all rows are are modified • Subqueries can also be used for values Example : UPDATE Emp SET sal = 10000 WHERE deptno = 10 ;
  • 138. 1-138 Copyright  CSC India, 2001. All rights reserved. Removing rows using DELETE statement Syntax: DELETE [FROM] table [WHERE condition] ; If WHERE clause is omitted then all rows in table are deleted Example : DELETE FROM dept WHERE dname = ‘SALES’ ;
  • 139. 1-139 Copyright  CSC India, 2001. All rights reserved. Using WHERE Clause in DML Statements – To Restrict the rows affected by the Select, Insert, Update and Delete Statements – Should appear after ‘FROM’ clause – Where clause is Optional • Select with Where clause SQL> SELECT * from Emp WHERE Empno=10; SQL> SELECT * from Emp WHERE Ename=‘Miller’; SQL> SELECT * from Emp WHERE Hire_date=’20-jun-06’; SQL> SELECT * from Emp WHERE Empno=&Empno;
  • 140. 1-140 Copyright  CSC India, 2001. All rights reserved. Using WHERE Clause in DML Statements • Update with Where clause SQL> UPDATE Emp SET sal=30000 WHERE deptno=20; SQL> UPDATE Emp SET sal=&sal WHERE Empno=&Empno; • Delete with Where clause SQL> DELETE from Emp WHERE deptno=20; SQL> DELETE from Emp WHERE Ename=‘Allen’;
  • 141. 1-141 Copyright  CSC India, 2001. All rights reserved. Using a Sub query in an INSERT Statement Use a sub query in place of the table name in the INTO clause of the INSERT statement. The select list must have the same number of columns as the column list of the VALUES clause. Ex : INSERT INTO ( SELECT dname, deptno FROM dept) VALUES (’ODS’,100) ;
  • 142. 1-142 Copyright  CSC India, 2001. All rights reserved. Explicit Default Feature Oracle9i allows to use Default Keyword not only in DDL statements but also in DML statements too. DEFAULT can be used as a column value where its default value is desired Example :  INSERT INTO emp(empno ,ename ,sal , deptno) VALUES (416,’Srikanth’,5000,DEFAULT);  UPDATE emp SET sal=DEFAULT where deptno=10;
  • 143. 1-143 Copyright  CSC India, 2001. All rights reserved. Merge Statement • Facilitates the user to conditionally update or insert values into database table • Does an Update if the row exists; else inserts a new row into database table Syntax: MERGE INTO table_name table_alias USING (table|view|sub_query) alias ON (join condition) WHEN MATCHED THEN UPDATE SET col1=col_val1, col2=col_val2 … WHEN NOT MATCHED THEN INSERT (column_list) VALUES (column_values);
  • 144. 1-144 Copyright  CSC India, 2001. All rights reserved. Merge Statement merge into emp_copy c using emp e on( c.empno= e.empno) when matched then update set c.ename = e.ename, c.job = e.job, c.mgr=e.mgr, c.hiredate = e.hiredate, c.sal=e.sal, c.comm= e.comm ,c.deptno = e.deptno when not matched then insert values (e.empno, e.ename, e.job, e.mgr, e.hiredate , e.sal, e.comm , e.deptno);
  • 145. 1-145 Copyright  CSC India, 2001. All rights reserved. Database Transactions • Begin when the first executable SQL statement is executed • End with one of the following events: – COMMIT or ROLLBACK is issued – DDL or DCL statement executes (automatic commit) – User exits – System crashes
  • 146. 1-146 Copyright  CSC India, 2001. All rights reserved. Transaction Control Statements Statement Description COMMIT Ends the current transaction by making all pending data changes permanent SAVEPOINT name Marks a savepoint within the current transaction ROLLBACK Ends the current transaction by discarding all pending data changes ROLLBACK TO SAVEPOINT name Rolls back the current transaction to the specified savepoint, thereby discarding any changes and or savepoints created after the specified savepoint .
  • 147. 1-147 Copyright  CSC India, 2001. All rights reserved. DELETE Controlling Transactions Transaction Savepoint A ROLLBACK to Savepoint B DELETE Savepoint B COMMIT INSERT UPDATE ROLLBACK to Savepoint A INSERT UPDATE INSERT ROLLBACK INSERT
  • 148. 1-148 Copyright  CSC India, 2001. All rights reserved. Transaction Control Language (TCL) – COMMIT • Used to make the Transactions permanently in the database SQL> COMMIT; – ROLLBACK • Erase the Transactions to the latest committed statement SQL> ROLLBACK ; SQL> ROLLBACK to <Savepoint>; – SAVEPOINT • Used to mark the transaction in to suitable parts SQL> SAVEPOINT A; SQL> ROLLBACK to A;
  • 149. 1-149 Copyright  CSC India, 2001. All rights reserved. 100 SMITH 20000 101 ALLEN 25000 Commit 102 JAMES 20000 103 MILLER 30000 Savepoint A 105 BLAKE 35000 106 JONES 20000 Savepoint B 107 CLARK 25000 108 KING 40000 SQL> ROLLBACK; SQL> ROLLBACK to A;
  • 150. 1-150 Copyright  CSC India, 2001. All rights reserved. Implicit Transaction Processing • An automatic commit occurs under the following circumstances: – DDL statement is issued - Normal exit from SQL*Plus, without explicitly issuing COMMIT or ROLLBACK • An automatic Rollback occurs under an abnormal termination of SQL*Plus or a system failure.
  • 151. 1-151 Copyright  CSC India, 2001. All rights reserved. State of the Data Before COMMIT or ROLLBACK • The previous state of the data can be recovered. • The current user can review the results of the DML operations by using the SELECT statement. • Other users cannot view the results of the DML statements by the current user. • The affected rows are locked; other users cannot change the data within the affected rows.
  • 152. 1-152 Copyright  CSC India, 2001. All rights reserved. State of the Data After COMMIT • Data changes are made permanent in the database. • The previous state of the data is permanently lost. • All users can view the results. • Locks on the affected rows are released; those rows are available for other users to manipulate. • All savepoints are erased.
  • 153. 1-153 Copyright  CSC India, 2001. All rights reserved. State of the Data After ROLLBACK Discard all pending changes by using the ROLLBACK statement. • Data changes are undone. • Previous state of the data is restored. • Locks on the affected rows are released. SQL> DELETE FROM employee; 14 rows deleted. SQL> ROLLBACK; Rollback complete.
  • 154. 1-154 Copyright  CSC India, 2001. All rights reserved. Rolling Back Changes to a Marker • Create a marker in a current transaction by using the SAVEPOINT statement. • Roll back to that marker by using the ROLLBACK TO SAVEPOINT statement. SQL> UPDATE... SQL> SAVEPOINT update_done; Savepoint created. SQL> INSERT... SQL> ROLLBACK TO update_done; Rollback complete.
  • 155. 1-155 Copyright  CSC India, 2001. All rights reserved. Read Consistency • Read consistency guarantees a consistent view of the data at all times. • Changes made by one user do not conflict with changes made by another user. • Read consistency ensures that on the same data: – Readers do not wait for writers – Writers do not wait for readers
  • 156. 1-156 Copyright  CSC India, 2001. All rights reserved. Implementation of Read Consistency UPDATE emp SET sal = 2000 WHERE ename = 'SCOTT'; Data blocks Rollback segments changed and unchanged data before change “old” data User A User B Read consistent image SELECT * FROM emp;
  • 157. 1-157 Copyright  CSC India, 2001. All rights reserved. Data Control Language (DCL) – Used control the data among the multiple users – GRANT • To grant the privileges on specific object to the specific users – REVOKE • To Revoke the privileges on specific object from the specific users To Grant all privileges on table Emp to User SMITH SCOTT> Grant all on Emp to SMITH;
  • 158. 1-158 Copyright  CSC India, 2001. All rights reserved. To Update the Granted table SMITH> Update Scott.Emp set sal=35000 where Empno=7566; To Update the Granted table SMITH> Delete from Scott.emp where Ename=‘MILLER’; To Grant a Table to multiple Users with all privileges SCOTT> GRANT all on Emp to SMITH , JONES; To Grant a table with specified privileges SCOTT> Grant select, insert on Emp to SMITH ; To Revoke all Privileges from specified User SCOTT> Revoke all on emp from SMITH ;
  • 159. 1-159 Copyright  CSC India, 2001. All rights reserved. -To Revoke specified Privileges from specified Users SCOTT> Revoke update, delete on emp from SMITH , JONES; -To Grant all privileges to All users SCOTT > Grant all on Emp to PUBLIC; -To Revoke all privileges to All users SCOTT> Revoke all on Emp from PUBLIC;
  • 160. 1-160 Copyright  CSC India, 2001. All rights reserved. Summary Description Adds a new row to the table Modifies existing rows in the table Removes existing rows from the table Makes all pending changes permanent Allows a rollback to the savepoint marker Discards all pending data changes Statement INSERT UPDATE DELETE COMMIT SAVEPOINT ROLLBACK
  • 161. Copyright  CSC India, 2001. All rights reserved. Creating and Managing Tables
  • 162. 1-162 Copyright  CSC India, 2001. All rights reserved. Objectives After completing this lesson, you should be able to : • Describe the main database objects • Create tables • Describe the data types that can be used when specifying column definition • Alter table definitions • Drop, rename, and truncate tables
  • 163. 1-163 Copyright  CSC India, 2001. All rights reserved. Database Objects Object Description Table Basic unit of storage; composed of rows and columns View Logically represents subsets of data from one or more tables Sequence Generates primary key values Index Improves the performance of some queries Synonym Alternative name for an object
  • 164. 1-164 Copyright  CSC India, 2001. All rights reserved. Naming Rules  Table names and column names :  Must begin with a letter  Must be 1-30 characters long  Must contain only A-Z, a-z, 0-9, _ , $ , and #  Must not duplicate the name of another object owned by the same user  Must not be an Oracle server reserved word  Use descriptive names for tables and other database objects  Table names are case insensitive (not case sensitive)
  • 165. 1-165 Copyright  CSC India, 2001. All rights reserved. The CREATE TABLE Statement A user must have : - CREATE TABLE privilege - A storage area Syntax : CREATE TABLE [schema . ]table (column datatype [DEFAULT expr] [,….]) ; Specify - Table name - Column name, column data type, and column size - Specify a default value for a column during an insert.
  • 166. 1-166 Copyright  CSC India, 2001. All rights reserved. Data Types Data Type Description VARCAHR2(size) Variable length character data CHAR(size) Fixed-length character data NUMBER(p,s) Variable length numeric data DATE Date and Time values LONG Variable length character data up to 2 GB CLOB Character data up to 4 GB RAW & LONG RAW Raw binary data ROWID A 64 base number system representing unique address of a row in its table
  • 167. 1-167 Copyright  CSC India, 2001. All rights reserved. Examples Create the table CREATE TABLE dept ( dept_id NUMBER(2) , deptname varchar2(14) , location varchar2(13) ); Referencing Tables - If the table is in your schema only then SELECT * FROM employees; - If you want to use other user’s tables then You should use the owner’s name as a prefix SELECT * FROM user_b.employees;
  • 168. 1-168 Copyright  CSC India, 2001. All rights reserved. Tables in the Oracle Database User Tables : - Are a collection of tables created and maintained by the user - Contain user information Data Dictionary - Is a collection of tables created and maintained by Oracle Server - Contain database information Querying the Data Dictionary Views - USER_TABLES : gives tables owned by the user - USER_OBJECTS : gives distinct object types owned by user - USER_CATALOG : gives tables,views,synonyms and sequences owned by the user
  • 169. 1-169 Copyright  CSC India, 2001. All rights reserved. Creating a Table by Using a Subquery Syntax Create a table and insert rows by combining the CREATE TABLE statement and the select query with AS keyword CREATE TABLE table [ ( column, column, …) ] AS subquery ; Match the number of specified columns to the number of sub query columns Example : CREATE TABLE dept80AS SELECT empno, ename, sal*12 annsal,hiredate FROM emp WHERE deptno = 80 ;
  • 170. 1-170 Copyright  CSC India, 2001. All rights reserved. Create Table Examples: Syntax: Create Table <Table_name> ( <col_name1> <data_type> (size), <col_name2> <data_type> (size), <col_name3> …..); SQL> Create Table EMP (Empno Number (6) , Ename Varchar2(20) ,Sal Number (10, 2) , Hire_date Date , Deptno Number(4)); SQL> Desc EMP Name Null? Type ----------------------------------------- -------- -------------- EMPNO NUMBER(6) ENAME VARCHAR2(20) SAL NUMBER(10,2) HIRE_DATE DATE DEPTNO NUMBER(4)
  • 171. 1-171 Copyright  CSC India, 2001. All rights reserved. The ALTER TABLE Statement Use the ALTER TABLE statement to : • Add a new column • Modify an existing column and define a default value for the new column - ALTER TABLE table_name ADD | MODIFY (column datatype [DEFAULT expr] [,column datatype]…) ; Drop a column - ALTER TABLE table_name DROP (column) ;
  • 172. 1-172 Copyright  CSC India, 2001. All rights reserved. Adding a column ALTER TABLE dept80 ADD (job_id varcahr2(9) ); Modifying a column - we can change data type, size and default value ALTER TABLE dept80 MODIFY (last_name varchar2(30) ); Dropping a column ALTER TABLE dept80 DROP COLUMN job_id ; Examples
  • 173. 1-173 Copyright  CSC India, 2001. All rights reserved. ALTER Table Examples – Used to alter the structure of the schema objects. – Use ‘ADD’ keyword to add one or more columns to the table. – Use ‘MODIFY’ keyword to increase or decrease the size of columns. To add a new column Syntax: • Alter table <table_name> Add <col_name> <data_type>(size); SQL>Alter table Emp ADD comm number(7,2); To modify Existing Column SQL> Alter table Emp MODIFY Ename varchar2(30); To Drop a Column Syntax • Alter table <Table_name> DROP Column <Column_name>; SQL> Alter table Emp Drop Column Comm; SQL> Alter table emp set unused(comm); SQL> Alter table emp set unused(EMPNO,ENAME); SQL> Alter table emp drop unused columns;
  • 174. 1-174 Copyright  CSC India, 2001. All rights reserved. The SET UNUSED Option • Use the SET UNUSED option to mark one or more columns as unused. They are logically removed and can’t be viewed or used . • They can be dropped when the demand on system resources is lower • This is a fast process than using DROP clause - ALTER TABLE tablename SET UNUSED (column ) ; Example : - ALTER TABLE dept SET UNUSED (loc) ;
  • 175. 1-175 Copyright  CSC India, 2001. All rights reserved. The SET UNUSED Option View the unused columns in USER_UNUSED_COL_TABS Use DROP UNUSED COLUMNS option to remove the columns that are marked as unused - ALTER TABLE table DROP UNUSED COLUMNS ; Example : - ALTER TABLE dept DROP UNUSED COLUMNS;
  • 176. 1-176 Copyright  CSC India, 2001. All rights reserved. Dropping, Renaming, Truncating a Table Dropping - All data , structure in the table and indexes are dropped - Syntax : DROP TABLE table ; Renaming - We can change the name of a table, view, sequence - Syntax : RENAME oldname TO newname ; Truncating - Removes all rows from a table - Releases storage space used by that table - Syntax :TRUNCATE TABLE table ; Note : You can’t rollback these operations
  • 177. 1-177 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you should have learned how to use DDL statements to create, alter, drop and rename tables CREATE TABLE - Creates a table ALTER TABLE - Modifies table structures DROP TABLE - Removes the rows and table structure RENAME - Changes the name of the table, view, sequence, or synonym TRUNCATE - Removes all rows from table and releases storage space
  • 178. 1-178 Copyright  CSC India, 2001. All rights reserved.
  • 179. Copyright  CSC India, 2001. All rights reserved. SET Operators
  • 180. 1-180 Copyright  CSC India, 2001. All rights reserved. The SET Operators The SET Operators combine the results of two or more component queries into one result. Queries containing SET operators are called compound queries. Operator Returns UNION All distinct rows selected by either query UNION ALL All rows selected by either query,including duplicates INTERSECT All distinct rows selected by both queries MINUS All distinct rows that are selected by the first SELECT statement and not selected in the second SELECT statement.
  • 181. 1-181 Copyright  CSC India, 2001. All rights reserved. The UNION Operator The UNION operator returns all rows selected by either query from multiple tables after eliminating duplications Guidelines - UNION operates over all of the columns being selected - NULL values are not ignored during duplicate checking - By default, the output is sorted in ascending order of the first column of the SELECT clause
  • 182. 1-182 Copyright  CSC India, 2001. All rights reserved. Using the UNION Operator Example SQL> SELECT Deptno From Emp UNION SELECT Deptno From Dept; The UNION operator eliminates any duplicate records. If there are records that occur both in the EMP and the DEPT tables and are identical, the records will be displayed only once. To overcome this we have to use UNION ALL Operator
  • 183. 1-183 Copyright  CSC India, 2001. All rights reserved. The UNION ALL Operator The UNION ALL Operator returns all rows from multiple queries Guidelines : - Unlike UNION,duplicate rows are not eliminated - The output is not sorted by default. - The DISTINCT keyword cannot be used - apart from these, all the guidelines of UNION ALL and UNION are the same. Example : - SELECT Deptno FROM Emp UNION ALL SELECT Deptno FROM Dept;
  • 184. 1-184 Copyright  CSC India, 2001. All rights reserved. The INTERSECT Operator The INTERSECT Operator returns all rows common to multiple queries from multiple tables Guidelines : - INTERSECT result is same on reversing the order - INTERSECT does not ignore NULL values Example : SELECT Deptno FROM Emp INTERSECT SELECT Deptno FROM Dept;
  • 185. 1-185 Copyright  CSC India, 2001. All rights reserved. The MINUS Operator • The MINUS Operator returns rows returned by first query that are not present in the second query • - The result is not same by reversing the order Example : SELECT Deptno FROM Dept MINUS SELECT Deptno FROM Emp;
  • 186. 1-186 Copyright  CSC India, 2001. All rights reserved. SET Operator Guidelines • The expressions in the SELECT lists must match in number and data type • Parentheses can be used to alter the sequence of execution The ORDER BY clause : - can appear only at the very end of the statement - will accept the column name, aliases from the first SELECT statement, or the positional notation • SET operators can be used in subqueries
  • 187. 1-187 Copyright  CSC India, 2001. All rights reserved. The Oracle Server and SET Operators Duplicate rows are automatically eliminated excepted in UNION ALL Column names from the first query appear in the result The output is sorted in ascending order by default except in UNION ALL Operator. If component queries select character data, the data type of the return values are determined as follows : - If both queries select values of data type CHAR, the returned values have the data type CHAR. - If either or both of the queries select values of data type VARCHAR2 the returned values have data type VARCHAR2.
  • 188. 1-188 Copyright  CSC India, 2001. All rights reserved.
  • 189. 1-189 Copyright  CSC India, 2001. All rights reserved.
  • 190. 1-190 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you should have learned how to : - Use UNION to return all distinct rows - Use UNION ALL to return all rows, including duplicates - Use INTERSECT to return all rows shared by both queries - Use MINUS to return all distinct rows selected by the first query but not by the second - Use ORDER BY only at the very end of the statement
  • 191. Copyright  CSC India, 2001. All rights reserved. Including Constraints
  • 192. 1-192 Copyright  CSC India, 2001. All rights reserved. Objective After completing this lesson, you should be able to do : • Describe constraints • Create and maintain constraints
  • 193. 1-193 Copyright  CSC India, 2001. All rights reserved. What are constraints ? Constraints are the Business Rules which can be enforced to prevent invalid data The following constraint types are valid : NOT NULL : The column can’t contain a null value UNIQUE : Specifies column(s) whose values must be unique for all rows in the table. Null values are allowed PRIMARY KEY: Uniquely identifies each row of the table FOREIGN KEY: Establishes and enforces a foreign key relationship between the column and a column of referenced table CHECK : Specifies a condition that must be true
  • 194. 1-194 Copyright  CSC India, 2001. All rights reserved. Constraint Guidelines • Name a constraint or the Oracle Server will generate a name by using the SYS_Cn format. • Create a constraint: – At the same time as the table is created – After the table has been created • Define a constraint at the column or table level. • View a constraint in the data dictionary view User_Constraints
  • 195. 1-195 Copyright  CSC India, 2001. All rights reserved. Defining Constraints CREATE TABLE [schema.]table (column datatype [DEFAULT expr] [column_constraint], ... [table_constraint][,...]); CREATE TABLE emp( empno NUMBER(4), ename VARCHAR2(10), ... deptno NUMBER(7,2) NOT NULL, CONSTRAINT emp_empno_pk PRIMARY KEY (EMPNO));
  • 196. 1-196 Copyright  CSC India, 2001. All rights reserved. Defining Constraints • Column constraint level • Table constraint level column [CONSTRAINT constraint_name] constraint_type, column,... [CONSTRAINT constraint_name] constraint_type (column, ...),
  • 197. 1-197 Copyright  CSC India, 2001. All rights reserved. The NOT NULL Constraint Ensures that null values are not permitted for the column EMP EMPNO ENAME JOB ... COMM DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 7782 CLARK MANAGER 10 7566 JONES MANAGER 20 ... NOT NULL constraint (no row can contain a null value for this column) Absence of NOT NULL constraint (any row can contain null for this column) NOT NULL constraint
  • 198. 1-198 Copyright  CSC India, 2001. All rights reserved. The NOT NULL Constraint Defined at the column level SQL> CREATE TABLE emp( 2 empno NUMBER(4), 3 ename VARCHAR2(10) NOT NULL, 4 job VARCHAR2(9), 5 mgr NUMBER(4), 6 hiredate DATE, 7 sal NUMBER(7,2), 8 comm NUMBER(7,2), 9 deptno NUMBER(7,2) NOT NULL);
  • 199. 1-199 Copyright  CSC India, 2001. All rights reserved. The UNIQUE Key Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON UNIQUE key constraint 50 SALES DETROIT 60 BOSTON Insert into Not allowed (DNAME-SALES already exists) Allowed
  • 200. 1-200 Copyright  CSC India, 2001. All rights reserved. The UNIQUE Key Constraint – Maintains the Uniqueness in the values for the columns on which it is defined. – Allows the NULL values. SQL> CREATE TABLE dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE(dname));
  • 201. 1-201 Copyright  CSC India, 2001. All rights reserved. PRIMARY KEY – Combination of UNIQUE and NOT NULL – No two rows can have the same values – No single row can have the NULL value – Table can have only one primary key column
  • 202. 1-202 Copyright  CSC India, 2001. All rights reserved. The PRIMARY KEY Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON PRIMARY KEY Insert into 20 MARKETING DALLAS FINANCE NEW YORK Not allowed (DEPTNO-20 already exists) Not allowed (DEPTNO is null)
  • 203. 1-203 Copyright  CSC India, 2001. All rights reserved. The PRIMARY KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE dept( 2 deptno NUMBER(2), 3 dname VARCHAR2(14), 4 loc VARCHAR2(13), 5 CONSTRAINT dept_dname_uk UNIQUE (dname), 6 CONSTRAINT dept_deptno_pk PRIMARY KEY(deptno));
  • 204. 1-204 Copyright  CSC India, 2001. All rights reserved. FOREIGN KEY – Used to establish Master Detail relationship between the tables. – requires values in one table to match values in another table. – The table which contains primary key is called Master table. – The table which contains foreign key is called Detail table. – Before defining the foreign key in the Detail table primary key should be defined in the Master table.
  • 205. 1-205 Copyright  CSC India, 2001. All rights reserved. The FOREIGN KEY Constraint DEPT DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS ... PRIMARY KEY EMP EMPNO ENAME JOB ... COMM DEPTNO 7839 KING PRESIDENT 10 7698 BLAKE MANAGER 30 ... FOREIGN KEY 7571 FORD MANAGER ... 200 9 7571 FORD MANAGER ... 200 20 Insert into Not allowed (DEPTNO 9 does not exist in the DEPT table) Allowed
  • 206. 1-206 Copyright  CSC India, 2001. All rights reserved. The FOREIGN KEY Constraint Defined at either the table level or the column level SQL> CREATE TABLE emp( 2 empno NUMBER(4), 3 ename VARCHAR2(10) NOT NULL, 4 job VARCHAR2(9), 5 mgr NUMBER(4), 6 hiredate DATE, 7 sal NUMBER(7,2), 8 comm NUMBER(7,2), 9 deptno NUMBER(7,2) NOT NULL, 10 CONSTRAINT emp_deptno_fk FOREIGN KEY (deptno) 11 REFERENCES dept (deptno));
  • 207. 1-207 Copyright  CSC India, 2001. All rights reserved. FOREIGN KEY Constraint Keywords • FOREIGN KEY Defines the column in the child table at the table constraint level • REFERENCES Identifies the table and column in the parent table • ON DELETE CASCADE Allows deletion in the parent table and deletion of the dependent rows in the child table
  • 208. 1-208 Copyright  CSC India, 2001. All rights reserved. The CHECK Constraint • Defines a condition that each row must satisfy –To satisfy the constraint, each row in the table must make the condition either TRUE or unknown (due to a null). Expressions that are not allowed: – References to CURRVAL, NEXTVAL and ROWNUM pseudo columns – Calls to SYSDATE, UID, USER, and USERENV functions – Queries that refer to other values in other rows ..., deptno NUMBER(2), CONSTRAINT emp_deptno_ck CHECK (DEPTNO BETWEEN 10 AND 99),...
  • 209. 1-209 Copyright  CSC India, 2001. All rights reserved. Adding a Constraint • Add or drop, but not modify a constraint • Enable or disable constraints • Add a NOT NULL constraint by using the MODIFY clause ALTER TABLE table ADD [CONSTRAINT constraint] type (column);
  • 210. 1-210 Copyright  CSC India, 2001. All rights reserved. Adding a Constraint Add a FOREIGN KEY constraint to the EMP table indicating that a manager must already exist as a valid employee in the EMP table. SQL> ALTER TABLE emp 2 ADD CONSTRAINT emp_mgr_fk 3 FOREIGN KEY(mgr) REFERENCES emp(empno); Table altered.
  • 211. 1-211 Copyright  CSC India, 2001. All rights reserved. Dropping a Constraint • Remove the manager constraint from the EMP table. SQL> ALTER TABLE emp 2 DROP CONSTRAINT emp_mgr_fk; Table altered. • Remove the PRIMARY KEY constraint on the DEPT table and drop the associated FOREIGN KEY constraint on the EMP.DEPTNO column. SQL> ALTER TABLE dept 2 DROP PRIMARY KEY CASCADE; Table altered.
  • 212. 1-212 Copyright  CSC India, 2001. All rights reserved. Disabling Constraints • Execute the DISABLE clause of the ALTER TABLE statement to deactivate an integrity constraint. • Apply the CASCADE option to disable dependent integrity constraints. SQL> ALTER TABLE emp 2 DISABLE CONSTRAINT emp_empno_pk CASCADE; Table altered.
  • 213. 1-213 Copyright  CSC India, 2001. All rights reserved. Enabling Constraints • Activate an integrity constraint currently disabled in the table definition by using the ENABLE clause. • A UNIQUE or PRIMARY KEY index is automatically created if you enable a UNIQUE key or PRIMARY KEY constraint. SQL> ALTER TABLE emp 2 ENABLE CONSTRAINT emp_empno_pk; Table altered.
  • 214. 1-214 Copyright  CSC India, 2001. All rights reserved. Cascading Constraints The CASCADE CONSTRAINTS clause is used along with the DROP COLUMN clause The CASCADE CONSTRAINTS clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns. The CASCADE CONSTRAINTS clause also drops all multicolumn constraints defined on the dropped columns ALTER TABLE test1 DROP (pk) CASCADE CONSTRAINTS ;
  • 215. 1-215 Copyright  CSC India, 2001. All rights reserved. Viewing Constraints • Query the USER_CONSTRAINTS table to view all constraint definitions and names • View the columns associated with the constraint names in the USER_CONS_COLUMNS view. Example : SELECT constraint_name, constraint_type, search_condition FROM USER_CONSTRAINTS WHERE table_name = ‘EMP’ ;
  • 216. Copyright  CSC India, 2001. All rights reserved. Displaying Data from Multiple Tables
  • 217. 1-217 Copyright  CSC India, 2001. All rights reserved. EMPNO DEPTNO LOC ----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO ... 14 rows selected. Obtaining Data from Multiple Tables EMP DEPT EMPNO ENAME ... DEPTNO ------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10 DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
  • 218. 1-218 Copyright  CSC India, 2001. All rights reserved. What Is a Join? Use a join to query data from more than one table. • Write the join condition in the WHERE clause. • Prefix the column name with the table name when the same column name appears in more than one table. SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;
  • 219. 1-219 Copyright  CSC India, 2001. All rights reserved. Types of Joins Oracle proprietary Joins SQL:1999 Compliant Joins Cartesian product Cross joins Equijoin Natural joins Non-equijoin Using Clause Outer join Full or two sided outer joins Self join Arbitrary join conditions for outer joins
  • 220. 1-220 Copyright  CSC India, 2001. All rights reserved. Cartesian Product • A Cartesian product is formed when: – A join condition is omitted – A join condition is invalid – All rows in the first table are joined to all rows in the second table • To avoid a Cartesian product, always include a valid join condition in a WHERE clause. Example : SELECT Ename, Dname FROM Emp, Dept;
  • 221. 1-221 Copyright  CSC India, 2001. All rights reserved. Generating a Cartesian Product ENAME DNAME ------ ---------- KING ACCOUNTING BLAKE ACCOUNTING ... KING RESEARCH BLAKE RESEARCH ... 56 rows selected. EMP (14 rows) DEPT (4 rows) EMPNO ENAME ... DEPTNO ------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10 DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON “Cartesian product: 14*4=56 rows”
  • 222. 1-222 Copyright  CSC India, 2001. All rights reserved. Joining Tables • Use a join to query data from more than one table SELECT table1.column, table2.column FROM table1,table2 WHERE table1.column1 = table2.column2 ; • Write the join condition in the WHERE clause • Prefix the column name with the table name when the same column name appears in more than one table • Joining n tables need a minimum of n-1 join conditions
  • 223. 1-223 Copyright  CSC India, 2001. All rights reserved. Types of Joins Equijoin Non-equijoin Outer join Self join
  • 224. 1-224 Copyright  CSC India, 2001. All rights reserved. What Is an Equijoin? EMP DEPT EMPNO ENAME DEPTNO ------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20 ... 14 rows selected. DEPTNO DNAME LOC ------- ---------- -------- 10 ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 30 SALES CHICAGO 20 RESEARCH DALLAS 20 RESEARCH DALLAS ... 14 rows selected. Foreign key Primary key
  • 225. 1-225 Copyright  CSC India, 2001. All rights reserved. Retrieving Records with Equijoins SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno; EMPNO ENAME DEPTNO DEPTNO LOC ----- ------ ------ ------ --------- 7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS ... 14 rows selected.
  • 226. 1-226 Copyright  CSC India, 2001. All rights reserved. Qualifying Ambiguous Column Names • Use table prefixes to qualify column names that are in multiple tables. • Improve performance by using table prefixes. • Distinguish columns that have identical names but reside in different tables by using column aliases.
  • 227. 1-227 Copyright  CSC India, 2001. All rights reserved. Using Table Aliases Simplify queries by using table aliases. SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno =dept.deptno; SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno =d.deptno;
  • 228. 1-228 Copyright  CSC India, 2001. All rights reserved. Joining More Than Two Tables NAME CUSTID ----------- ------ JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS 107 ... ... 9 rows selected. CUSTOMER CUSTID ORDID ------- ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605 ... 21 rows selected. ORD ORDID ITEMID ------ ------- 610 3 611 1 612 1 601 1 602 1 ... 64 rows selected. ITEM
  • 229. 1-229 Copyright  CSC India, 2001. All rights reserved. Non-Equijoins EMP SALGRADE “salary in the EMP table is between low salary and high salary in the SALGRADE table” EMPNO ENAME SAL ------ ------- ------ 7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950 ... 14 rows selected. GRADE LOSAL HISAL ----- ----- ------ 1 700 1200 2 1201 1400 3 1401 2000 4 2001 3000 5 3001 9999
  • 230. 1-230 Copyright  CSC India, 2001. All rights reserved. Retrieving Records with Non-Equijoins ENAME SAL GRADE ---------- --------- --------- JAMES 950 1 SMITH 800 1 ADAMS 1100 1 ... 14 rows selected. SQL> SELECT e.ename, e.sal, s.grade 2 FROM emp e, salgrade s 3 WHERE e.sal 4 BETWEEN s.losal AND s.hisal;
  • 231. 1-231 Copyright  CSC India, 2001. All rights reserved. Outer Joins EMP DEPT No employee in the OPERATIONS department ENAME DEPTNO ----- ------ KING 10 BLAKE 30 CLARK 10 JONES 20 ... DEPTNO DNAME ------ ---------- 10 ACCOUNTING 30 SALES 10 ACCOUNTING 20 RESEARCH ... 40 OPERATIONS
  • 232. 1-232 Copyright  CSC India, 2001. All rights reserved. Outer Joins • You use an outer join to also see rows that do not usually meet the join condition. • Outer join operator is the plus sign (+). SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column(+) = table2.column; SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column = table2.column(+);
  • 233. 1-233 Copyright  CSC India, 2001. All rights reserved. Joining a Table to Itself WORKER.ENAME||'WORKSFOR'||MANAG ------------------------------- BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE ... 13 rows selected. SQL> SELECT worker.ename||' works for '||manager.ename 2 FROM emp worker, emp manager 3 WHERE worker.mgr = manager.empno;
  • 234. 1-234 Copyright  CSC India, 2001. All rights reserved. Summary Equijoin Non-equijoin Outer join Self join SELECT table1.column, table2.column FROM table1, table2 WHERE table1.column1 = table2.column2;
  • 235. 1-235 Copyright  CSC India, 2001. All rights reserved. Oracle 9i feature Oracle 9i introduced new features in compliance with SQL:1999 ANSI standard Syntax : SELECT table1.column, table2.column FROM table1 [CROSS JOIN table2] | [NATURAL JOIN table2] | [JOIN table2 USING (column_name) ] | [JOIN table2 ON (table1.column_name = table2.column_name) ] | [LEFT | RIGHT | FULL OUTER JOIN table2 ON (table1.column_name = table2.column_name) ] ;
  • 236. 1-236 Copyright  CSC India, 2001. All rights reserved. Cross Join Forms a Cartesian Product whenever Join condition is not specified SELECT Ename , Dname FROM Emp CROSS JOIN dept ;
  • 237. 1-237 Copyright  CSC India, 2001. All rights reserved. Natural Joins • Equivalent to Equi Join • Joins with all the common columns present in the tables • The column names as well as the data types should match E.g.: SELECT Empno , Ename , Dname FROM Emp NATURAL JOIN Dept;
  • 238. 1-238 Copyright  CSC India, 2001. All rights reserved. USING clause No matter how many common columns are available in the tables, NATURAL JOIN will join with all the common columns Use USING clause to join with specified columns Example : SELECT Empno , Ename ,Mgr ,Deptno , Dname FROM Emp JOIN Dept USING ( Deptno , Mgr);
  • 239. 1-239 Copyright  CSC India, 2001. All rights reserved. ON clause • Explicit join condition can be specified by using ON clause • Additional conditions as well as sub-queries can be used along with ON clause Example : SELECT e.empno , e.name, d.deptno , d.dname FROM Emp e JOIN Dept d ON (e.deptno = d.deptno) AND d.dname =‘SALES’ ;
  • 240. 1-240 Copyright  CSC India, 2001. All rights reserved. Left Outer Join SELECT e.ename,e.sal,d.deptno,d.dname FROM Emp e LEFT OUTER JOIN Dept d ON (e.deptno = d.deptno) ;
  • 241. 1-241 Copyright  CSC India, 2001. All rights reserved. Right Outer Join SELECT e.ename,e.sal,d.deptno,d.dname FROM Emp e RIGHT OUTER JOIN Dept d ON (e.deptno = d.deptno) ;
  • 242. 1-242 Copyright  CSC India, 2001. All rights reserved. FULL Outer Join SELECT e.ename, e.sal,d.deptno,d.dname FROM Emp e FULL OUTER JOIN Dept d ON (e.deptno = d.deptno ) ;
  • 243. 1-243 Copyright  CSC India, 2001. All rights reserved. Practice Overview • Joining tables using an equijoin • Performing outer and self joins • Adding conditions
  • 244. 1-244 Copyright  CSC India, 2001. All rights reserved. Summary In this lesson, you have learned : • Extracting data from multiple tables using joins • Oracle 8i proprietary joins • SQL:1999 ANSI standard joins ( oracle 9i feature)
  • 245. Copyright  CSC India, 2001. All rights reserved. Subqueries
  • 246. 1-246 Copyright  CSC India, 2001. All rights reserved. Objectives After completing this lesson, you should be able to do the following : • Describe the types of problem that subqueries can solve • Define subqueries • List the types of subqueries • Write single-row and multiple-row subqueries • Multiple column subqueries • Scalar subqueries • Correlated subqueries • Use of EXISTS and NOT EXISTS operator
  • 247. 1-247 Copyright  CSC India, 2001. All rights reserved. Using a Subquery to Solve a Problem “Who has a salary greater than Jones’?” “Which employees have a salary greater than Jones’ salary?” Main Query ? “What is Jones’ salary?” ? Subquery
  • 248. 1-248 Copyright  CSC India, 2001. All rights reserved. Subqueries • Sub queries are useful when a query is based on unknown values. • The subquery (inner query) executes once before the main query. • The result of the subquery is used by the main query (outer query). SELECT select_list FROM table WHERE expr operator (SELECT select_list FROM table);
  • 249. 1-249 Copyright  CSC India, 2001. All rights reserved. 2975 SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno=7566); Using a Subquery ENAME ---------- KING FORD SCOTT
  • 250. 1-250 Copyright  CSC India, 2001. All rights reserved. Guidelines for Using Subqueries • Enclose subqueries in parentheses • Place subqueries on the right side of the comparison condition • The ORDER BY clause in the sub query is not needed unless we are performing Top-N analysis. • Use single-row operators with single-row subqueries and use multiple-row operators with multiple-row subqueries. • For single-row subqueries, use single-row comparison operators like =, < , <= , > , >=, <> Or != • For multiple-row subqueries use multiple-row operators like IN , ANY , ALL
  • 251. 1-251 Copyright  CSC India, 2001. All rights reserved. Types of Subqueries • Single-row subquery Main query Subquery returns CLERK • Multiple-row subquery CLERK MANAGER Main query Subquery returns • Multiple-column subquery CLERK 7900 MANAGER 7698 Main query Subquery returns
  • 252. 1-252 Copyright  CSC India, 2001. All rights reserved. Single-Row Subqueries • Return only one row • Use single-row comparison operators Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to
  • 253. 1-253 Copyright  CSC India, 2001. All rights reserved. Executing Single-Row Subqueries CLERK 1100 ENAME JOB ---------- --------- MILLER CLERK SQL> SELECT ename, job 2 FROM emp 3 WHERE job = 4 (SELECT job 5 FROM emp 6 WHERE empno = 7369) 7 AND sal > 8 (SELECT sal 9 FROM emp 10 WHERE empno = 7876);
  • 254. 1-254 Copyright  CSC India, 2001. All rights reserved. Using Group Functions in a Subquery 800 ENAME JOB SAL ---------- --------- --------- SMITH CLERK 800 SQL> SELECT ename, job, sal 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp);
  • 255. 1-255 Copyright  CSC India, 2001. All rights reserved. HAVING Clause with Subqueries • The Oracle Server executes subqueries first. • The Oracle Server returns results into the HAVING clause of the main query. 800 SQL> SELECT deptno, MIN(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING MIN(sal) > 5 (SELECT MIN(sal) 6 FROM emp 7 WHERE deptno = 20);
  • 256. 1-256 Copyright  CSC India, 2001. All rights reserved. What Is Wrong with This Statement? ERROR: ORA-01427: single-row subquery returns more than one row no rows selected SQL> SELECT empno, ename 2 FROM emp 3 WHERE sal = 4 (SELECT MIN(sal) 5 FROM emp 6 GROUP BY deptno);
  • 257. 1-257 Copyright  CSC India, 2001. All rights reserved. Multiple-Row Subqueries • Return more than one row • Use multiple-row comparison operators Operator IN ANY ALL Meaning Equal to any member in the list Compare value to each value returned by the subquery Compare value to every value returned by the subquery
  • 258. 1-258 Copyright  CSC India, 2001. All rights reserved. Using ALL Operator in Multiple-Row Subqueries 2916.6667 2175 1566.6667 EMPNO ENAME JOB SAL --------- ---------- --------------- 7839 KING PRESIDENT 5000 7566 JONES MANAGER 2975 7902 FORD ANALYST 3000 7788 SCOTT ANALYST 3000 SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal > ALL 4 (SELECT avg(sal) 5 FROM emp 6 GROUP BY deptno);
  • 259. 1-259 Copyright  CSC India, 2001. All rights reserved. Using ALL Operator in Multiple-Row Subqueries SQL> SELECT empno, ename, job 2 FROM emp 3 WHERE sal > ANY 4 (SELECT avg(sal) 5 FROM emp 6 GROUP BY deptno); EMPNO ENAME JOB SAL ---------- ---------- --------- ---------- 7839 KING PRESIDENT 5000 7902 FORD ANALYST 3000 7788 SCOTT ANALYST 3000 7566 JONES MANAGER 2975 7698 BLAKE MANAGER 2850 7782 CLARK MANAGER 2450 7499 ALLEN SALESMAN 1600
  • 260. Copyright  CSC India, 2001. All rights reserved. Multiple-Column Subqueries
  • 261. 1-261 Copyright  CSC India, 2001. All rights reserved. Multiple-Column Subqueries Main query MANAGER 10 Subquery SALESMAN 30 MANAGER 10 CLERK 20 Main query compares MANAGER 10 Values from a multiple-row and multiple-column subquery SALESMAN 30 MANAGER 10 CLERK 20 to
  • 262. 1-262 Copyright  CSC India, 2001. All rights reserved. Using Multiple-Column Subqueries Display the order number, product number, and quantity of any item in which the product number and quantity match both the product number and quantity of an item in order 605. SQL> SELECT ordid, prodid, qty 2 FROM item 3 WHERE (prodid, qty) IN 4 (SELECT prodid, qty 5 FROM item 6 WHERE ordid = 605) 7 AND ordid <> 605;
  • 263. 1-264 Copyright  CSC India, 2001. All rights reserved. Using a Subquery in the FROM Clause ENAME SAL DEPTNO SALAVG ---------- --------- --------- ---------- KING 5000 10 2916.6667 JONES 2975 20 2175 SCOTT 3000 20 2175 ... 6 rows selected. SQL> SELECT a.ename, a.sal, a.deptno, b.salavg 2 FROM emp a, (SELECT deptno, avg(sal) salavg 3 FROM emp 4 GROUP BY deptno) b 5 WHERE a.deptno = b.deptno 6 AND a.sal > b.salavg;
  • 264. 1-265 Copyright  CSC India, 2001. All rights reserved. Sub query’s examples; SQL> Select Ename,sal from emp where sal=(select max(sal) from emp); SQL> Select Ename,deptno,sal from emp where (deptno,sal) in(select deptno,max(sal) from emp group by deptno); SQL> Create table emp1 as select * from emp; SQL> Create table emp2 as select * from emp where 1=2; SQL> Insert into emp2(select * from emp); SQL> Insert into emp2(empno,ename) (select empno,ename from emp); SQL> Update emp set sal=4000 where deptno=(select deptno from dept where dname=‘SALES’);
  • 265. 1-266 Copyright  CSC India, 2001. All rights reserved. • To find the employees getting maximum salary of any dept. Sql> Select ename, deptno,sal from emp WHERE sal> ANY (select max(sal) from emp group by deptno); • To find the employees getting maximum salary of every dept. Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select max(sal) from emp group by deptno); Sql> Select ename, deptno,sal from emp WHERE sal> ALL (select max(sal) from emp where deptno in(20,30) group by deptno); • To select Duplicate rows present in the table SQL> Select count(rowid), empno from emp group by empno having count(rowid)>1; SQL> select * from emp where rowid not in (select min(rowid) from emp group by empno);
  • 266. 1-267 Copyright  CSC India, 2001. All rights reserved. Updating with Multiple-Column Subquery Update employee 7698’s job and department to match that of employee 7499. SQL> UPDATE emp 2 SET (job, deptno) = 3 (SELECT job, deptno 4 FROM emp 5 WHERE empno = 7499) 6 WHERE empno = 7698; 1 row updated.
  • 267. 1-268 Copyright  CSC India, 2001. All rights reserved. Updating Rows Based on Another Table Use subqueries in UPDATE statements to update rows in a table based on values from another table. SQL> UPDATE employee 2 SET deptno = (SELECT deptno 3 FROM emp 4 WHERE empno = 7788) 5 WHERE job = (SELECT job 6 FROM emp 7 WHERE empno = 7788); 2 rows updated.
  • 268. 1-269 Copyright  CSC India, 2001. All rights reserved. Deleting Rows Based on Another Table Use subqueries in DELETE statements to remove rows from a table based on values from another table. SQL> DELETE FROM employee 2 WHERE deptno = 3 (SELECT deptno 4 FROM dept 5 WHERE dname ='SALES'); 6 rows deleted.
  • 269. 1-270 Copyright  CSC India, 2001. All rights reserved. Correlated Subqueries • A query is a Correlated Sub query when it references a column from a table referred to in the parent statement • They are executed once for every row of the outer query • They are used for row-by-row processing Example : SELECT ename, sal, deptno FROM emp e WHERE sal > (SELECT avg(sal) FROM emp d WHERE e.deptno = d.deptno ) ;
  • 270. 1-271 Copyright  CSC India, 2001. All rights reserved. Correlated UPDATE To update rows in one table based on rows from another table Syntax : UPDATE table1 alias1 SET column = ( SELECT expression FROM table2 alias2 WHERE alias1.column = alias2.column ) ; Example : UPDATE emp e SET deptname = (select dname FROM dept d WHERE e.deptno = d.deptno); Similarly Correlated Delete can be used
  • 271. 1-272 Copyright  CSC India, 2001. All rights reserved. Correlated query Example; • To find employee details who are getting salary greater than avg salary of their own department SQL> Select ename,sal,deptno from emp e where sal>(select avg(sal) from emp m where m.deptno =e.deptno); • To find N th max sal SQL> select * from emp x where &no=(select count (distinct sal) from Emp y where y.sal>=x.sal); • To find N th least sal SQL> select * from emp x where &no=(select count (distinct sal) from Emp y where y.sal<=x.sal)
  • 272. 1-273 Copyright  CSC India, 2001. All rights reserved. EXISTS Operator • Tests for existence of rows in the results set of the sub query • Returns TRUE if sub query returns at least one row else FALSE is returned • IN operator can replace EXISTS operator • NOT EXISTS operator is opposite of EXISTS operator Example : SELECT empno, ename FROM emp e WHERE empno IN (SELECT mgr FROM emp ) ; SELECT empno, ename FROM emp e WHERE EXISTS ( SELECT 1 FROM emp WHERE mgr = e.empno );
  • 273. Copyright  CSC India, 2001. All rights reserved. Schema Objects
  • 274. 1-275 Copyright  CSC India, 2001. All rights reserved. Schema Objects Description Basic unit of storage; composed of rows and columns Logically represents subsets of data from one or more tables Generates primary key values Improves the performance of some queries Alternative name for an object Object Table View Sequence Index Synonym
  • 275. 1-276 Copyright  CSC India, 2001. All rights reserved. TABLE • In a RDBMS, the data is logically perceived as tables. – Tables are logical data structures that we assume hold the data that the database intends to represent. – Tables are not physical structures. – Each table has a unique name. – In general, when tables are defined, the number of columns remain fixed for the duration of the table, however, the number of rows present in the table is bound to vary – Tables are required to have at least one column.
  • 276. Copyright  CSC India, 2001. All rights reserved. Creating Views
  • 277. 1-278 Copyright  CSC India, 2001. All rights reserved. Views Objectives  Describe a view  Create, alter the definition of, and drop a view  Retrieve data through a view  Insert, update, and delete data through a view  Create and use an inline view  Perform “Top-N” analysis In this part you learn how to