SQL Statements: - Select - Insert - Update - Delete - Create - Alter - Drop - Rename - Truncate - Commit - Rollback - Savepoint
SQL Statements: - Select - Insert - Update - Delete - Create - Alter - Drop - Rename - Truncate - Commit - Rollback - Savepoint
•INSERT
•UPDATE Data manipulation language (DML)
•DELETE
•CREATE
•ALTER
•DROP Data definition language (DDL)
•RENAME
•TRUNCATE
Syntax :
Syntax :
Table 1 Table 1
Product / Join
Table 1 Table 2
Limiting Rows Using a
EMP
Restriction
EMPNO ENAME JOB ... DEPTNO
“Retrieve all
7839 KING PRESIDENT 10 employees
7698 BLAKE MANAGER 30 in department 10.”
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
EMP
EMPNO ENAME JOB ... DEPTNO
DEPT
DEPTNO LOC
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
ENAME
ENAME DNAME
DNAME
------
------ ----------
----------
KING
KING ACCOUNTING
ACCOUNTING
“Cartesian BLAKE
BLAKE ACCOUNTING
ACCOUNTING
product: ...
...
KING
KING RESEARCH
RESEARCH
14*4=56 rows” BLAKE RESEARCH
BLAKE RESEARCH
...
...
56
56 rows
rows selected.
selected.
What Is a Join?
Use a join to query data from more than
one table:
SELECT
SELECT table1.column,
table1.column, table2.column
table2.column
FROM
FROM table1,
table1, table2
table2
WHERE
WHERE table1.column1
table1.column1 == table2.column2;
table2.column2;
Syntax :
EMPNO
EMPNO DEPTNO
DEPTNO LOC
LOC
----- ------- --------
----- ------- --------
7839
7839 10
10 NEW
NEW YORK
YORK
7698
7698 30 CHICAGO
30 CHICAGO
7782
7782 10
10 NEW
NEW YORK
YORK
7566
7566 20 DALLAS
20 DALLAS
7654
7654 30
30 CHICAGO
CHICAGO
7499
7499 30 CHICAGO
30 CHICAGO
...
...
14
14 rows
rows selected.
selected.
Using the WHERE Clause
– Character strings and date values are
enclosed in single quotation marks.
– Character values are case sensitive and
date values are format sensitive.
SQL> SELECT ename, job, deptno
2 FROM emp
3 WHERE job = 'CLERK';
Equijoin
Equijoin
Nonequijoin
Nonequijoin
Selfjoin
Selfjoin
What is an Equijoin?
EMP
EMPNO ENAME DEPTNO
------ ------- -------
... DEPT
7782 CLARK 10
DEPTNO DNAME LOC
------- ---------- --------
...
10 ACCOUNTING NEW YORK
...
WHERE emp.deptno=dept.deptno
What is An Equijoin?
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------- ---------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.
NAME SALARY
------------- ---------
...
14 rows selected.
Nonequijoins
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
------ ------- ------ ----- ----- ------
7839 KING 5000 1 700 1200
7698 BLAKE 2850 2 1201 1400
7782 CLARK 2450 3 1401 2000
7566 JONES 2975 4 2001 3000
7654 MARTIN 1250 5 3001 9999
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
... “Salary in the EMP
14 rows selected. table is between
low salary and high
salary in the SALGRADE
table.”
Retrieving Records
with Nonequijoins
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;
WHO_WORKS_FOR_WHOM
WHO_WORKS_FOR_WHOM
-------------------------------
-------------------------------
BLAKE
BLAKE works
works for
for KING
KING
CLARK
CLARK works
works for
for KING
KING
JONES
JONES works
works for
for KING
KING
MARTIN
MARTIN works
works for
for BLAKE
BLAKE
...
...
13
13 rows
rows selected.
selected.
Outer Joins
EMP DEPT
ENAME DEPTNO DEPTNO DNAME
----- ------ ------ ----------
KING 10 10 ACCOUNTING
BLAKE 30 30 SALES
CLARK 10 10 ACCOUNTING
JONES 20 20 RESEARCH
... ...
40 OPERATIONS
No employee in the
OPERATIONS department
Outer Joins
– You use an outer join to see rows that do
not usually meet the join condition.
– The outer join operator is the plus sign (+).
SELECT
SELECT table.column,
table.column, table.column
table.column
FROM
FROM table1,
table1, table2
table2
WHERE
WHERE table1.column(+)
table1.column(+) == table2.column;
table2.column;
SELECT
SELECT table.column,
table.column, table.column
table.column
FROM
FROM table1,
table1, table2
table2
WHERE
WHERE table1.column
table1.column == table2.column(+);
table2.column(+);
Using Outer Joins
SQL> SELECT e.ename, d.deptno, d.dname
2 FROM emp e, dept d
3 WHERE e.deptno(+) = d.deptno;
Syntax :
DEPTNO EMPS
---------- ----------
20 5
30 6
SQL Functions
Input Output
Function
arg 1 Function
performs action
arg 2
Result
value
arg n
Two Types of SQL Functions
Functions
Single-row Multiple-row
functions functions
Single-Row Functions
––Manipulate
Manipulate data
data items
items
––Accept
Accept arguments
arguments and
and return
return one
one value
value
––Act
Act on
on each
each row
row returned
returned
––Return
Return one
one result
result per
per row
row
––May
May modify
modify the
the datatype
datatype
––Can
Can be
be nested
nested
function_name
function_name (column|expression,
(column|expression, [arg1,
[arg1, arg2,...])
arg2,...])
Single-Row Functions
Character
General Number
Single-row
functions
Conversion Date
What Are Group Functions?
••Group
Group functions
functions operate
operate on
on sets
sets of
of rows
rows to
to
give
give one
one result
result per
per group.
group.
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000 “maximum MAX(SAL)
20 3000 salary in ---------
20 2975 the EMP table” 5000
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
Creating Groups of Data
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 2916.6667
10 1300
20 800 “average DEPTNO AVG(SAL)
20 1100 salary
------- ---------
20 3000 2175 in EMP
20 3000 table 10 2916.6667
20 2975 for each 20 2175
30 1600 department” 30 1566.6667
30 2850
30 1250 1566.6667
30 950
30 1500
30 1250
Creating Groups of Data:
GROUP BY Clause
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
MIN(HIRED MAX(HIRED
--------- ---------
17-DEC-80 12-JAN-83
Using the GROUP BY Clause
•All columns in the SELECT list that are
not in group functions must be in the
GROUP BY clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667
Using the GROUP BY Clause
•The GROUP BY column does not have
to be in the SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;
AVG(SAL)
---------
2916.6667
2175
1566.6667
Grouping by More
EMP
Than One Column
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
DEPTNO JOB SUM(SAL)
10 PRESIDENT 5000
-------- --------- ---------
10 CLERK 1300
10 CLERK 1300
20 CLERK 800 “sum salaries in 10 MANAGER 2450
20 CLERK 1100 the EMP table
10 PRESIDENT 5000
20 ANALYST 3000 for each job,
20 ANALYST 6000
20 ANALYST 3000 grouped by
20 CLERK 1900
20 MANAGER 2975 department”
20 MANAGER 2975
30 SALESMAN 1600
30 CLERK 950
30 MANAGER 2850
30 MANAGER 2850
30 SALESMAN 1250
30 SALESMAN 5600
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
Using the GROUP BY Clause
on Multiple Columns
SQL> SELECT
SQL> SELECT deptno,
deptno, job,
job, sum(sal)
sum(sal)
22 FROM
FROM emp
emp
33 GROUP
GROUP BY
BY deptno,
deptno, job;
job;
e WW grro
WHERE
WHERE AVG(sal)
AVG(sal) >> 2000 t h
h e tt g
2000
ee t riicc
**
uss s
s ttr
tt u rree
ERROR
ERROR at
at line
line 3:
3:
n
n o
o ttoo
ORA-00934: groupaan
ORA-00934: group n
function
function is
is notnot allowed
allowed here here
CC
Excluding Group Results
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 5000
10 1300
20 800
20 1100 “maximum DEPTNO MAX(SAL)
20 3000 salary --------- ---------
3000
20 3000 per department 10 5000
20 2975 greater than 20 3000
30 1600 $2900”
30 2850
30 1250
30 950
2850
30 1500
30 1250
Excluding Group Results:
HAVING Clause
•Use the HAVING clause to restrict
groups
•• Rows
Rows are
are grouped.
grouped.
•• The
The group
group function
function is
is applied.
applied.
•• Groups
Groups matching
matching the
the HAVING
HAVING clause
clause are
are
displayed.
displayed.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Using the HAVING Clause
SQL> SELECT deptno, max(sal)
2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
Using the HAVING Clause
SQL> SELECT job, SUM(sal) PAYROLL
2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
Nesting Group Functions
•Display the maximum average salary.
MAX(AVG(SAL))
-------------
2916.6667
SELECT STATEMENT
Syntax :
Syntax :
• Subqueries
• Set operators
SUBQUERIES
Multirow Subquery
Nested Subqueries
Correlated Subqueries
Subqueries
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
– The subquery (inner query) executes once before the main query.
– The result of the subquery is used by the main query (outer query).
Using a Subquery
to Solve a Problem
••“Who
“Who has
has aa salary
salary greater
greater than
than Jones’s?”
Jones’s?”
Main Query
Subquery
?
“What is Jones’s salary?”
Using a Subquery
SQL> SELECT ename
2 FROM emp 2975
3 WHERE sal >
4 (SELECT sal
5 FROM emp
6 WHERE empno=7566);
ENAME
ENAME
----------
----------
KING
KING
FORD
FORD
SCOTT
SCOTT
Guidelines for Using
Subqueries
––Enclose
Enclose subqueries
subqueries in
in parentheses.
parentheses.
––Place
Place subqueries
subqueries on
on the
the right
right side
side of
of the
the
comparison
comparison operator.
operator.
––Do
Do not
not add
add an
an ORDER
ORDER BY BY clause
clause to
to aa
subquery.
subquery.
––Use
Use single-row
single-row operators
operators with
with single-row
single-row
subqueries.
subqueries.
––Use
Use multiple-row
multiple-row operators
operators with
with multiple-
multiple-
row
row subqueries.
subqueries.
Types of Subqueries
–– Single-row
Single-row subquery
subquery
Main query
returns
Subquery CLERK
•• Multiple-row
Multiple-row subquery
subquery
Main query
Subquery
returns CLERK
MANAGER
•• Multiple-column
Multiple-column subquery
subquery
Main query
returns
Subquery CLERK 7900
MANAGER 7698
Single-Row Subqueries
––Return
Return only
only one
one row
row
––Use
Use single-row
single-row comparison
comparison operators
operators
Operator Meaning
= Equal to
ENAME
ENAME JOB
JOB
----------
---------- ---------
---------
MILLER
MILLER CLERK
CLERK
Using Group Functions
in a Subquery
SQL> SELECT ename, job, sal
800
2 FROM emp
3 WHERE sal =
4 (SELECT MIN(sal)
5 FROM emp);
ENAME
ENAME JOB
JOB SAL
SAL
----------
---------- ---------
--------- ---------
---------
SMITH
SMITH CLERK
CLERK 800
800
HAVING Clause with
Subqueries
––The
The Oracle
Oracle Server
Server executes
executes subqueries
subqueries
first.
first.
––The
The Oracle
Oracle Server
Server returns
returns results
results into
into the
the
main
main query’s
query’s HAVING
HAVING clause.
clause.
SQL> SELECT deptno, MIN(sal)
2 FROM emp
3 GROUP BY deptno
800
4 HAVING MIN(sal) >
5 (SELECT MIN(sal)
6 FROM emp
7 WHERE deptno = 20);
What Is Wrong
with This Statement? y
e r
qu
SQL> SELECT empno, ename
ub
2 FROM emp s
3 WHERE sal = ow
4 (SELECT -
MIN(sal)r
l e
5 FROM
t i p
emp
6 GROUP BYul deptno);
m
ith
r w
ERROR:
ERROR: to
ORA-01427:
ORA-01427: single-row
single-row a
r subquery
subquery returns
returns more
more than
than
e
one
one row
row op
ow
no rows selected
no rows selected - r
gle
i n
S
Will This Statement Work?
SQL> SELECT ename, job
2 FROM emp
3 WHERE job =
4 (SELECT job e s s
5 FROM emp a lu
v
6 WHERE o
ename='SMYTHE');
n
ns
ur
no
no rows
rows selected et
selected r
ry
ue
bq
Su
Multiple-Row Subqueries
––Return
Return more
more than
than one
one row
row
––Use
Use multiple-row
multiple-row comparison
comparison operators
operators
Operator Meaning
EMPNO
EMPNO ENAME
ENAME JOB
JOB
---------
--------- ----------
---------- ---------
---------
7654
7654 MARTIN
MARTIN SALESMAN
SALESMAN
7521
7521 WARD
WARD SALESMAN
SALESMAN
Using ALL Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job 1566.6667
2 FROM emp 2175
2916.6667
3 WHERE sal > ALL
4 (SELECT avg(sal)
5 FROM emp
6 GROUP BY deptno);
EMPNO
EMPNO ENAME
ENAME JOB
JOB
---------
--------- ----------
---------- ---------
---------
7839
7839 KING
KING PRESIDENT
PRESIDENT
7566
7566 JONES
JONES MANAGER
MANAGER
7902
7902 FORD
FORD ANALYST
ANALYST
7788
7788 SCOTT
SCOTT ANALYST
ANALYST
Summary
•Subqueries are useful when a query is
based on unknown values.
SELECT select_list
FROM table
WHERE expr operator
(SELECT select_list
FROM table);
Multiple-Column Subqueries
Main query
MANAGER 10
Subquery
SALESMAN 30
MANAGER 10
CLERK 20
SALESMAN 30
MANAGER 10
MANAGER 10
CLERK 20
Using Multiple-Column
Subqueries
•Display
Display the
the name, department
department number,
salary, and commission of any employee
whose salary and commission matches both
both
the commission and
and salary
salary of any employee
in department 30.
SQL> SELECT ename, deptno, sal, comm
2 FROM emp
3 WHERE (sal, NVL(comm,-1)) IN
4 (SELECT sal, NVL(comm,-1)
5 FROM emp
6 WHERE deptno = 30);
Column Comparisons
Pairwise Nonpairwise
SAL COMM SAL COMM
1600 300 1600 300
1250 500 1250 500
1250 1400 1250 1400
2850 2850
1500 0 1500 0
950 950
Nonpairwise Comparison
Subquery
••Display
Display the
the name,
name, department
department number,
number,
salary,
salary, and
and commission
commission of of any
any employee
employee
whose
whose salary
salary and
and commission matches the
commission
commission and
and salary
salary of
of any
any employee
employee in
in
department
department 30.
30.
SQL> SELECT ename, deptno, sal, comm
2 FROM emp
3 WHERE sal IN (SELECT sal
4 FROM emp
5 WHERE deptno = 30)
6 AND
7 NVL(comm,-1) IN (SELECT NVL(comm,-1)
8 FROM emp
9 WHERE deptno = 30);
Modifying the EMP Table
––Assume
Assume that
that salary
salary and
and commission
commission for
for Clark
Clark are
are
modified.
modified.
•• Salary
Salary is
is changed
changed to to $1500
$1500 and
and commission
commission to to
$300.
$300.
ENAME SAL COMM
---------- --------- ---------
...
CLARK 1500 300
...
ALLEN 1600 300
TURNER 1500 0
...
14 rows selected.
Pairwise Subquery
SQL> SELECT ename, deptno, sal, comm
2 FROM emp
3 WHERE (sal, NVL(comm,-1)) IN
4 (SELECT sal, NVL(comm,-1)
5 FROM emp
6 WHERE deptno = 30);
ENAME
ENAME DEPTNO
DEPTNO SAL
SAL COMM
COMM
----------
---------- ---------
--------- ---------
--------- ---------
---------
JAMES
JAMES 30
30 950
950
WARD
WARD 30
30 1250
1250 500
500
MARTIN
MARTIN 30
30 1250
1250 1400
1400
TURNER
TURNER 30
30 1500
1500 00
ALLEN
ALLEN 30
30 1600
1600 300
300
BLAKE
BLAKE 30
30 2850
2850
66 rows
rows selected.
selected.
Nonpairwise Subquery
SQL> SELECT ename,deptno, sal, comm
2 FROM emp
3 WHERE sal IN (SELECT sal
4 FROM emp
5 WHERE deptno = 30)
6 AND
7 NVL(comm,-1) IN (SELECT NVL(comm,-1)
8 FROM emp
9 WHERE deptno = 30);
?
“What is the average salary
for the employee’s
department?”
Using Correlated Subqueries
•Find all employees who make more
than the average salary in their
department.
SQL> SELECT empno, sal, deptno Each time the outer query
2 FROM emp outer is processed, the
3 WHERE sal > (SELECT AVG(sal) inner query is
4 FROM emp inner evaluated.
5 WHERE outer.deptno = inner.deptno);
EMPNO
EMPNO SAL
SAL DEPTNO
DEPTNO
--------
-------- ---------
--------- ---------
---------
7839
7839 5000
5000 10
10
7698
7698 2850
2850 30
30
7566
7566 2975
2975 20
20
...
...
66 rows
rows selected.
selected.
Using the EXISTS Operator
––IfIf aa subquery
subquery row
row value
value is
is found:
found:
•• The
The search
search will
will not
not continue
continue in
in the
the inner
inner query
query
•• The
The condition
condition is
is flagged
flagged TRUE
TRUE
––IfIf aa subquery
subquery row
row value
value is
is not
not found:
found:
•• The
The condition
condition is
is flagged
flagged FALSE
FALSE
•• The
The search
search will
will continue
continue in
in the
the inner
inner query
query
Using the NOT EXISTS Operator
DEPTNO
DEPTNO DNAME
DNAME
---------
--------- --------------
--------------
40
40 OPERATIONS
OPERATIONS
Summary
––Subqueries
Subqueries areare useful
useful when
when aa query
query is
is based
based
on
on unknown
unknown values.
values.
––A
A nested
nested subquery
subquery is
is executed
executed once.
once.
––A
A correlated
correlated subquery
subquery is is executed
executed once
once for
for
each
each parent
parent candidate
candidate row.
row.
––Nested
Nested subqueries
subqueries can
can be be used
used for
for multi-
multi-
column
column comparison.
comparison.
––The
The EXISTS
EXISTS operator
operator is
is aa Boolean
Boolean operator,
operator,
testing
testing the
the presence
presence ofof aa value.
value.
––Caution
Caution isis necessary
necessary with
with NULL
NULL values
values and
and
NOT
NOT IN.
IN.
Combining queries
• Subqueries
• Set operators
The Set Operators
A B
Intersect
A B A B
A B
Minus
UNION
A B
Using the UNION Operator
•Display the name, job title, and
department of all employees.
SQL> SELECT ename, job, deptno
2 FROM emp
3 UNION
4 SELECT name, title, deptid
5 FROM emp_history;
ENAME
ENAME EMPNO
EMPNO JOB
JOB
----------
---------- ---------
--------- ---------
---------
ALLEN
ALLEN 7499
7499 SALESMAN
SALESMAN
CLARK
CLARK 7782
7782 MANAGER
MANAGER
SCOTT
SCOTT 7788
7788 ANALYST
ANALYST
MINUS
A B
MINUS
Display
Display the
the names,
names, employee
employee numbers,
numbers, and
and
job
job titles
titles for
for all
all employees
employees who
who have
have left
left the
the
company.
company.
SQL> SELECT name, empid, title
2 FROM emp_history
3 MINUS
4 SELECT ename, empno, job
5 FROM emp;
NAME
NAME EMPID
EMPID TITLE
TITLE
----------
---------- ---------
--------- ---------
---------
BALFORD
BALFORD 6235
6235 CLERK
CLERK
BRIGGS
BRIGGS 7225
7225 PAY
PAY CLERK
CLERK
JEWELL
JEWELL 7001
7001 ANALYST
ANALYST
SPENCER
SPENCER 6087
6087 OPERATOR
OPERATOR
...
...
66 rows
rows selected.
selected.
SET Operator Rules
––The
The expressions
expressions in in the
the SELECT
SELECT lists lists must
must
match
match inin number
number andand datatype.
datatype.
––Duplicate
Duplicate rows
rows are
are automatically
automatically eliminated
eliminated
except
except inin UNION
UNION ALL.ALL.
––Column
Column names
names from
from the
the first
first query
query appear
appear
in
in the
the result.
result.
––The
The output
output isis sorted
sorted in
in ascending
ascending orderorder by
by
default
default except
except inin UNION
UNION ALL.ALL.
––Parentheses
Parentheses can can be
be used
used toto alter
alter the
the
sequence
sequence of of execution.
execution.
Matching the SELECT
Statement
Display
Display the
the department
department number,
number, location,
location,
and
and hiredate
hiredate for
for all
all employees.
employees.
SQL>
SQL> SELECT
SELECT deptno,
deptno, TO_CHAR(null)
TO_CHAR(null) location,
location, hiredate
hiredate
22 FROM
FROM emp
emp
33 UNION
UNION
44 SELECT
SELECT deptno,
deptno, loc,
loc, TO_DATE(null)
TO_DATE(null)
55 FROM
FROM dept;
dept;
Controlling the Order of
Rows
Produce an English sentence using two
Produce
Produce an
an English
English sentence
sentence using
using two
two
UNION
UNION operators.
operators.
SQL>
SQL> COLUMN
COLUMN a_dummy
a_dummy NOPRINT
NOPRINT
SQL>
SQL> SELECT
SELECT 'to
'to sing'
sing' "My
"My dream",
dream", 33 a_dummy
a_dummy
22 FROM
FROM dual
dual
33 UNION
UNION
44 SELECT
SELECT 'I''d
'I''d like
like to
to teach',
teach', 11
55 FROM
FROM dual
dual
66 UNION
UNION
77 SELECT
SELECT 'the
'the world',
world', 22
88 FROM
FROM dual
dual
99 ORDER
ORDER BY
BY 2;
2;
My
My dream
dream
-------------------------
-------------------------
I'd
I'd like
like to
to teach
teach
the world
the world
to
to sing
sing
Summary
––UNION
UNION returns
returns all
all distinct
distinct rows.
rows.
––UNION
UNION ALL ALL returns
returns all
all rows
rows including
including
duplicates.
duplicates.
––INTERSECT
INTERSECT returns
returns all
all rows
rows that
that both
both
queries
queries share.
share.
––MINUS
MINUS returns
returns all
all distinct
distinct rows
rows selected
selected by
by
the
the first
first query
query but
but not
not the
the second.
second.
––ORDER
ORDER BY BY can
can only
only appear
appear atat the
the very
very
end
end of
of the
the statement.
statement.
SQL Statements
•SELECT Data Retrieval
•INSERT
•UPDATE Data manipulation language (DML)
•DELETE
•CREATE
•ALTER
•DROP Data definition language (DDL)
•RENAME
•TRUNCATE
––Only
Only one
one row
row is
is inserted
inserted at
at aa time
time with
with this
this
syntax.
syntax.
Inserting New Rows
––Insert
Insert aa new
new rowrow containing
containing values
values for
for each
each
column.
column.
––List
List values
values inin the
the default
default order
order of
of the
the
columns
columns in in the
the table.
table.
––Optionally
Optionally list
list the
the columns
columns inin the
the INSERT
INSERT
clause.
clause.
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (50, 'DEVELOPMENT', 'DETROIT');
1 row created.
––Enclose
Enclose character
character and
and date
date values
values within
within
single
single quotation
quotation marks.
marks.
Inserting Rows with Null
Values
––Implicit
Implicit method:
method: Omit
Omit the
the column
column from
from the
the
column
column list.
list.
SQL> INSERT INTO dept (deptno, dname )
2 VALUES (60, 'MIS');
1 row created.
•• Explicit
Explicit method:
method: Specify
Specify the
the NULL
NULL
keyword.
keyword.
SQL> INSERT INTO dept
2 VALUES (70, 'FINANCE', NULL);
1 row created.
Inserting Special Values
•The SYSDATE function records the
current date and time.
SQL> INSERT INTO emp (empno, ename, job,
2 mgr, hiredate, sal, comm,
3 deptno)
4 VALUES (7196, 'GREEN', 'SALESMAN',
5 7782, SYSDATE, 2000, NULL,
6 10);
1 row created.
Inserting Specific Date Values
––Add
Add aa new
new employee.
employee.
SQL> INSERT INTO emp
2 VALUES (2296,'AROMANO','SALESMAN',7782,
3 TO_DATE('FEB 3,97', 'MON DD, YY'),
4 1300, NULL, 10);
1 row created.
•• Verify
Verify your
your addition.
addition.
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- -------- ---- --------- ---- ---- ------
2296 AROMANO SALESMAN 7782 03-FEB-97 1300 10
Inserting Values by Using
Substitution Variables
•Create an interactive script by using
SQL*Plus substitution parameters.
SQL> INSERT INTO dept (deptno, dname, loc)
2 VALUES (&department_id,
3 '&department_name', '&location');
1 row created.
Creating a Script
with Customized Prompts
––ACCEPT
ACCEPT stores
stores the
the value
value into
into aa variable.
variable.
––PROMPT
PROMPT displays
displays your
your customized
customized text.
text.
ACCEPT department_id PROMPT 'Please enter the -
department number:'
ACCEPT department_name PROMPT 'Please enter -
the department name:'
ACCEPT location PROMPT 'Please enter the -
location:'
INSERT INTO dept (deptno, dname, loc)
VALUES (&department_id, '&department_name',
'&location');
Copying Rows
from Another Table
––Write
Write your
your INSERT
INSERT statement
statement with
with aa
subquery.
subquery.
SQL> INSERT INTO managers(id, name, salary, hiredate)
2 SELECT empno, ename, sal, hiredate
3 FROM emp
4 WHERE job = 'MANAGER';
3 rows created.
Do
Do not
not use
use the
the VALUES
VALUES clause.
clause.
––Match
Match the
the number
number of of columns
columns in in the
the
INSERT
INSERT clause
clause to
to those
those inin the
the subquery.
subquery.
EMP
Changing Data in a Table
EMPNO ENAME JOB ... DEPTNO
“…update a row
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30 in EMP table…”
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
EMP
EMPNO ENAME JOB ... DEPTNO
––Update
Update more
more than
than one
one row
row at
at aa time,
time, ifif
required.
required.
Updating Rows in a Table
––Specific
Specific row
row or
or rows
rows are
are modified
modified when
when
you
you specify
specify the
the WHERE
WHERE clause.
clause.
SQL> UPDATE emp
2 SET deptno = 20
3 WHERE empno = 7782;
1 row updated.
––All
All rows
rows in
in the
the table
table are
are modified
modified ifif you
you
omit
omit the
the WHERE
WHERE clause.
clause.
SQL>
SQL> UPDATE
UPDATE employee
employee
22 SET
SET deptno
deptno == 20;
20;
14
14 rows
rows updated.
updated.
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.
Updating Rows Based
on Another Table
•Use subqueries in UPDATE statements
to update rows in a table based on values
from another table.
SQL>
SQL> UPDATE
UPDATE employee
employee
22 SET
SET deptno
deptno == (SELECT
(SELECT deptno
deptno
33 FROM
FROM emp
emp
44 WHERE
WHERE empno
empno == 7788)
7788)
55 WHERE
WHERE job
job == (SELECT
(SELECT job
job
66 FROM
FROM emp
emp
77 WHERE
WHERE empno
empno == 7788);
7788);
22 rows
rows updated.
updated.
Removing a Row from a Table
DEPT
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS “…delete a row
30 SALES CHICAGO
40 OPERATIONS BOSTON from DEPT table…”
50 DEVELOPMENT DETROIT
60 MIS DEPT
...
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
60 MIS
...
The DELETE Statement
DELETE
DELETE [FROM]
[FROM] table
table
[WHERE
[WHERE condition];
condition];
Deleting Rows from a Table
––Specific
Specific row
row or
or rows
rows are
are deleted
deleted when
when you
you
specify
specify the
the WHERE
WHERE clause.
clause.
SQL>
SQL> DELETE
DELETE FROM
FROM department
department
22 WHERE
WHERE dname
dname == 'DEVELOPMENT';
'DEVELOPMENT';
11 row
row deleted.
deleted.
––All
All rows
rows in
in the
the table
table are
are deleted
deleted ifif you
you omit
omit
the
the WHERE
WHERE clause.
clause.
SQL>
SQL> DELETE
DELETE FROM
FROM department;
department;
44 rows
rows deleted.
deleted.
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.
Correlated UPDATE
UPDATE
UPDATE table1
table1 alias1
alias1
SET
SET column
column == (SELECT
(SELECT expression
expression
FROM
FROM table2
table2 alias2
alias2
WHERE
WHERE alias1.column
alias1.column == alias2.column);
alias2.column);
DELETE
DELETE FROM
FROM table1
table1 alias1
alias1
WHERE
WHERE column
column operator
operator
(SELECT
(SELECT expression
expression
FROM
FROM table2
table2 alias2
alias2
WHERE
WHERE alias1.column
alias1.column == alias2.column);
alias2.column);
Use
Use aa correlated
correlated subquery
subquery toto delete
delete only
only
those
those rows
rows that
that also
also exist
exist in
in another
another
table.
table.
Summary
• INSERT Statement
• UPDATE Statement
• DELETE Statement
SQL Statements
•SELECT Data Retrieval
•INSERT
•UPDATE Data manipulation language (DML)
•DELETE
•CREATE
•ALTER
•DROP Data definition language (DDL)
•RENAME
•TRUNCATE
DDL Statements in
SQL :
• CREATE
• ALTER
• DROP
• RENAME
• TRUNCATE
Naming Conventions
Table and column names:
– Must begin with a letter
– Can 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 Oracle Server reserved words
Datatypes
Datatype Description
VARCHAR2(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 gigabytes
RAW and Raw binary data
LONG RAW
CLOB Single-byte character data up to 4 gigabytes
BLOB Binary data up to 4 gigabytes
BFILE Binary data up to 4 gigabytes stored in an
external file
ROWID Hexadecimal string representing the unique
address of a row in its table
The CREATE TABLE
Statement
– You must have:
• The CREATE TABLE privilege
• A storage area
– Column-level constraint
column
column [CONSTRAINT
[CONSTRAINT constraint_name]
constraint_name] constraint_type,
constraint_type,
– Table-level constraint
column,...
column,...
[CONSTRAINT
[CONSTRAINT constraint_name]
constraint_name] constraint_type
constraint_type
(column,
(column, ...),
...),
The NOT NULL Constraint
•The NOT NULL constraint ensures that
null values are not permitted for the
column.
EMP
EMPNO ENAME JOB ... COMM DEPTNO
Insert into
Not allowed
50 SALES DETROIT (DNAMESALES
already exists)
60 BOSTON Allowed
The UNIQUE Key Constraint
Insert into
Not allowed
20 MARKETING DALLAS (DEPTNO20 already
exists)
FINANCE NEW YORK Not allowed
(DEPTNO is null)
The FOREIGN KEY
Constraint
DEPT
PRIMARY DEPTNO DNAME LOC
key ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
...
EMP
EMPNO ENAME JOB ... COMM DEPTNO FOREIGN
key
7839 KING PRESIDENT 10
7698 BLAKE MANAGER 30
... Not allowed
(DEPTNO9
Insert into does not exist
in the DEPT
7571 FORD MANAGER ... 200 9 table)
7571 FORD MANAGER ... 200 Allowed
The FOREIGN KEY
Constraint
•You can define the FOREIGN KEY
constraint 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));
The CHECK Constraint
•You can define a condition that each row
must satisfy.
•The following expressions are not
allowed:
– References to pseudocolumns CURRVAL,
NEXTVAL, LEVEL, and ROWNUM
– Calls to SYSDATE, UID, USER, and
USERENV functions
– Queries
...,
that refer to other values in other
deptno NUMBER(2),
CONSTRAINT emp_deptno_ck
rows CHECK (DEPTNO BETWEEN 10 AND 99),...
Example
CREATE TABLE new_emp
(empno NUMBER(4) CONSTRAINT pk_emp_empno
PRIMARY KEY,
ename VARCHAR2(10) CONSTRAINT chk_upp_ename
CHECK(ENAME= UPPER(ENAME)),
job VARCHAR2(9),
mgr NUMBER(4) CONSTRAINT fk_emp_mgr
REFERENCES new_emp(empno),
hiredate DATE DEFAULT SYSDATE,
sal NUMBER(7, 2) CONSTRAINT nn_sal
NOT NULL,
comm NUMBER(7, 2),
deptno NUMBER(2) CONSTRAINT nn_deptno
NOT NULL,
CONSTRAINT fk_emp_deptno
FOREIGN KEY(deptno)
REFERENCES new_dept(deptno)
ON DELETE CASCADE ) ;
Updating Rows:
Integrity Constraint Error
is t
SQL> UPDATE emp ex
SQL>
22
UPDATE
SET
emp
deptno == 55 o t
33
SET
WHERE
deptno
deptno ==
55
10; s n
WHERE deptno 10;
o e
5 d
r 5
be
um
UPDATE
UPDATE emp
emp n t
**
e n
ERROR
ERROR at
at linet
line
r m 1:
1:
ORA-02291:
p
ORA-02291: a integrity
integrity constraint
constraint (USR.EMP_DEPTNO_FK)
(USR.EMP_DEPTNO_FK)
e -- parent
violated
D
violated parent key
key not
not found
found
Deleting Rows:
Integrity Constraint Error
s a n
i n y i
SQL>
SQL> DELETE
DELETE FROM
FROM dept
dept n ta ke
22 WHERE
WHERE deptno
deptno == 10; 10; t co ign
ha o re
t f
ow sa
DELETE
DELETE FROM
FROM dept a r a
dept
t e se d
**
l e u
ERROR
ERROR atat line
line 1:1: de is
ORA-02292: o t
integrity a t
constraint (USR.EMP_DEPTNO_FK)
n
ORA-02292: integrity
n recordt h constraint (USR.EMP_DEPTNO_FK)
violated
c a
violated -- child
child
e y
record found
. found
o u ry k ble
• Y ma r ta
pri othe
an
Querying the Data Dictionary
– Describe tables owned by the user.
SQL> SELECT *
2 FROM user_tables;
•• View
View distinct
distinct object
object types
types owned
owned by
by the
the
user.
user.
SQL> SELECT DISTINCT object_type
2 FROM user_objects;
•• View
View tables,
tables, views,
views, synonyms,
synonyms, and
and
sequences
sequences owned
owned byby the
the user.
user.
SQL> SELECT *
2 FROM user_catalog;
Viewing Constraints
•Query the USER_CONSTRAINTS
table to view all constraint definitions
and names.
SQL> SELECT constraint_name, constraint_type,
2 search_condition
3 FROM user_constraints
4 WHERE table_name = 'EMP';
View
View the
the columns
columns associated
associated with
with the
the
constraint
constraint names
names in
in the
the
USER_CONS_COLUMNS
USER_CONS_COLUMNS view. view.
SQL>
SQL> SELECT
SELECT constraint_name,
constraint_name, column_name
column_name
22 FROM
FROM user_cons_columns
user_cons_columns
33 WHERE
WHERE table_name
table_name == 'EMP';
'EMP';
Commonly used Data
Dictionary Views
USER_OBJECTS
USER_TABLES
USER_CONSTRAINTS
USER_CONS_COLUMNS
USER_SOURCE
USER_VIEWS
USER_TRIGGERS
USER_INDEXES
Creating a Table by Using a
Subquery
– Create a table and insert rows by combining
the CREATE TABLE statement and AS
subquery option.
CREATE TABLE table
[column(, column...)]
AS subquery;
Name
Name Null?
Null? Type
Type
----------------------------
---------------------------- --------
-------- -----
-----
EMPNO
EMPNO NOT
NOT NULL
NULL NUMBER(4)
NUMBER(4)
ENAME
ENAME VARCHAR2(10)
VARCHAR2(10)
ANNSAL
ANNSAL NUMBER
NUMBER
HIREDATE
HIREDATE DATE
DATE
The ALTER TABLE Statement
•Use the ALTER TABLE statement to:
– Add and modify columns
– Add or remove constraints
– Enable or disable constraints
– Define a default value for the new column
ALTER TABLE table
ADD (column datatype [DEFAULT expr] [NOT NULL]
[, column datatype]...);
SQL>
SQL> ALTER
ALTER TABLE
TABLE dept
dept
22 DROP
DROP PRIMARY
PRIMARY KEY
KEY CASCADE;
CASCADE;
Table
Table altered.
altered.
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>
SQL> ALTER
ALTER TABLE
TABLE emp
emp
22 DISABLE
DISABLE CONSTRAINT
CONSTRAINT emp_empno_pk
emp_empno_pk CASCADE;
CASCADE;
Table
Table altered.
altered.
Enabling Constraints
– Activate an integrity constraint currently
disabled in the table definition by using the
ENABLE clause.
SQL>
SQL> ALTER
ALTER TABLE
TABLE emp
emp
22 ENABLE
ENABLE CONSTRAINT
CONSTRAINT emp_empno_pk;
emp_empno_pk;
Table
Table altered.
altered.
SQL>
SQL> CREATE
CREATE SEQUENCE
SEQUENCE dept_deptno
dept_deptno
22 INCREMENT
INCREMENT BY
BY 11
33 START
START WITH
WITH 91
91
44 MAXVALUE
MAXVALUE 100
100
55 NOCACHE
NOCACHE
66 NOCYCLE;
NOCYCLE;
Sequence
Sequence created.
created.
Confirming Sequences
––Verify
Verify your
your sequence
sequence values
values in
in the
the
USER_SEQUENCES
USER_SEQUENCES data data dictionary
dictionary table.
table.
SQL>
SQL> SELECT
SELECT sequence_name,
sequence_name, min_value,
min_value, max_value,
max_value,
22 increment_by,
increment_by, last_number
last_number
33 FROM
FROM user_sequences;
user_sequences;
––The
The LAST_NUMBER
LAST_NUMBER column
column displays
displays the
the
next
next available
available sequence
sequence number.
number.
NEXTVAL and CURRVAL
Pseudocolumns
– NEXTVAL returns the next available
– NEXTVAL returns the next available
sequence
sequence value.
value.
ItIt returns
returns aa unique
unique value
value every
every time
time itit is
is
referenced,
referenced, eveneven for
for different
different users.
users.
––CURRVAL
CURRVAL obtainsobtains the
the current
current sequence
sequence
value.
value.
NEXTVAL
NEXTVAL must must be
be issued
issued for
for that
that
sequence
sequence before
before CURRVAL
CURRVAL contains
contains aa
value.
value.
Using a Sequence
––Insert
Insert aa new
new department
department named
named
“MARKETING”
“MARKETING” in in San
San Diego.
Diego.
SQL>
SQL> INSERT
INSERT INTO
INTO dept(deptno,
dept(deptno, dname,
dname, loc)
loc)
22 VALUES
VALUES (dept_deptno.NEXTVAL,
(dept_deptno.NEXTVAL,
33 'MARKETING',
'MARKETING', 'SAN
'SAN DIEGO');
DIEGO');
11 row
row created.
created.
––View
View the
the current
current value
value for
for the
the
DEPT_DEPTNO
DEPT_DEPTNO sequence.
sequence.
SQL>
SQL> SELECT
SELECT dept_deptno.CURRVAL
dept_deptno.CURRVAL
22 FROM
FROM dual;
dual;
Using a Sequence
––Caching
Caching sequence
sequence values
values in
in memory
memory allows
allows
faster
faster access
access to
to those
those values.
values.
––Gaps
Gaps inin sequence
sequence values
values can
can occur
occur when:
when:
•• A
A rollback
rollback occurs
occurs
•• The
The system
system crashes
crashes
•• A
A sequence
sequence isis used
used in
in another
another table
table
––View
View the
the next
next available
available sequence,
sequence, ifif itit was
was
created
created with
with NOCACHE,
NOCACHE, by by querying
querying the the
USER_SEQUENCES
USER_SEQUENCES table. table.
Modifying a Sequence
•Change the increment value, maximum
value, minimum value, cycle option, or
cache option.
SQL>
SQL> ALTER
ALTER SEQUENCE
SEQUENCE dept_deptno
dept_deptno
22 INCREMENT
INCREMENT BY
BY 11
33 MAXVALUE
MAXVALUE 999999
999999
44 NOCACHE
NOCACHE
55 NOCYCLE;
NOCYCLE;
Sequence
Sequence altered.
altered.
Guidelines for Modifying
a Sequence
––You
You must
must be
be the
the owner
owner or
or have
have the
the ALTER
ALTER
privilege
privilege for
for the
the sequence.
sequence.
––Only
Only future
future sequence
sequence numbers
numbers are
are
affected.
affected.
––The
The sequence
sequence must
must bebe dropped
dropped and
and re-re-
created
created toto restart
restart the
the sequence
sequence at
at aa
different
different number.
number.
––Some
Some validation
validation is
is performed.
performed.
Removing a Sequence
––Remove
Remove aa sequence
sequence from
from the
the data
data
dictionary
dictionary by
by using
using the
the DROP
DROP SEQUENCE
SEQUENCE
statement.
statement.
––Once
Once removed,
removed, the
the sequence
sequence can
can no
no
longer
longer be
be referenced.
referenced.
SQL>
SQL> DROP
DROP SEQUENCE
SEQUENCE dept_deptno;
dept_deptno;
Sequence
Sequence dropped.
dropped.
Dropping a Table
•The DROP TABLE statement:
– Deletes all data and the table structure
– Commits any pending transactions
– Drops all indexes
SQL> DROP TABLE dept30;
Table dropped.
•INSERT
•UPDATE Data manipulation language (DML)
•DELETE
•CREATE
•ALTER
•DROP Data definition language (DDL)
•RENAME
•TRUNCATE
ROLLBACK to Savepoint B
ROLLBACK to Savepoint A
ROLLBACK
Implicit Transaction
Processing
– An automatic commit occurs under the
following circumstances:
• A DDL statement is issued, such as CREATE
• A DCL statement is issued, such as GRANT
• A normal exit from SQL*Plus occurs without an
explicitly issued COMMIT or ROLLBACK
statement
– An automatic rollback occurs under an
abnormal termination of SQL*Plus or a
system failure.
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.
Committing Data
•Change the department number of an
employee (Clark) identified by a
employee number.
– Make the changes.
SQL>
SQL> UPDATE
UPDATE emp
emp
22 SET
SET deptno
deptno == 10
10
33 WHERE
WHERE empno
empno == 7782;
7782;
11 row
row updated.
updated.
Rollback
segments
User A
Changed
and
SELECT * unchanged
Read
FROM emp; data
consistent
image Before
change
“old” data
User B
Locking
The Oracle Server locks:
– Prevent destructive interaction between
concurrent transactions
– Require no user action
– Automatically use the lowest level of
restrictiveness
– Are held for the duration of the transaction
– Have two basic modes:
• Exclusive
• Share
Locking Modes
Lock Mode Description
•• The
The Oracle
Oracle Server
Server guarantees
guarantees aa read-
read-
consistent
consistent view.
view.
•• Locking
Locking is
is automatic.
automatic.
•• Locking
Locking can
can be
be implicit
implicit or
or explicit.
explicit.
Power / Pitfalls & Tips
Defining a Null Value
– A null is a value that is unavailable, unassigned,
unknown, or inapplicable.
– A null is not the same as zero or a blank space.
– takes up one byte of internal ‘storage’ overhead
– any column or expression contains Null, the result
will be Null.
SQL> SELECT ename, job, comm
2 FROM emp;
NAME 12*SAL+NVL(COMM,0)
---------- ------------------
KING 60000
...
14 rows selected.
Group Functions and Null
Values
•Group functions ignore null values in
the column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
Using the NVL Function
with Group Functions
•The NVL function forces group functions
to include null values.
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp;
AVG(NVL(COMM,0))
----------------
157.14286
DECODE Function
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
Nesting Functions
ENAME NVL(TO_CHAR(MGR),'NOMANAGER')
---------- -----------------------------
KING No Manager
Using the COUNT Function
•COUNT(*) returns the number of rows in
a table.
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;
COUNT(*)
---------
6
Using the COUNT Function
•COUNT(expr) returns the number of
nonnull rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)
-----------
4
Using Pseudocolumns
•A pseudocolumn behaves like a table
column, but is not stored in a table.
•ROWID returns a row’s address.
SQL>
SQL> SELECT
SELECT ROWID,
ROWID, ename
ename
22 FROM
FROM emp
emp
33 WHERE
WHERE deptno
deptno == 20;
20;
ROWID
ROWID ENAME
ENAME
-------------------
------------------- -------------
-------------
AAAAdNAAEAAAAEbAAD
AAAAdNAAEAAAAEbAAD SMITH
SMITH
AAAAdNAAEAAAAEbAAJ
AAAAdNAAEAAAAEbAAJ JONES
JONES
...
...
Using Pseudocolumns
ROWNUM returns a number indicating
the order in which the row is selected.
SQL>
SQL> SELECT
SELECT empno,
empno, ename,
ename, job,
job, mgr,
mgr, hiredate
hiredate
22 FROM
FROM emp
emp
33 WHERE
WHERE ROWNUM
ROWNUM << 5;
5;
---------
--------- ----------
---------- ---------
--------- ---------
--------- ---------
---------
7839
7839 KING
KING PRESIDENT
PRESIDENT 17-NOV-81
17-NOV-81
7698
7698 BLAKE
BLAKE MANAGER
MANAGER 7839
7839 01-MAY-81
01-MAY-81
Summary
– NVL
– DECODE
– COUNT
– PSEUDOCOLUMNS
SQL*Plus
What is SQL*Plus ?
- An Oracle Product with which SQL and certain other
commands may be used
SQL>
SQL> DESCRIBE
DESCRIBE dept
dept
Name
Name Null?
Null? Type
Type
-----------------
----------------- --------
-------- ----
----
DEPTNO
DEPTNO NOT
NOT NULL
NULL NUMBER(2)
NUMBER(2)
DNAME
DNAME VARCHAR2(14)
VARCHAR2(14)
LOC
LOC VARCHAR2(13)
VARCHAR2(13)
SQL*Plus Editing Commands
– A[PPEND] text
– C[HANGE] / old / new
– C[HANGE] / text /
– CL[EAR] BUFF[ER]
– DEL
– DEL n
– DEL m n
SQL*Plus Editing Commands
– I[NPUT]
– I[NPUT] text
– L[IST]
– L[IST] n
– L[IST] m n
– R[UN]
–n
– n text
– 0 text
SQL*Plus File Commands
– SAVE filename
– GET filename
– START filename
– @ filename
– EDIT filename
– SPOOL filename
– EXIT
Summary of SQL*Plus
• Displaying table structure
• Editing Commands
• File Commands