You are on page 1of 231

SQL Statements

•SELECT Data Retrieval

•INSERT
•UPDATE Data manipulation language (DML)
•DELETE

•CREATE
•ALTER
•DROP Data definition language (DDL)
•RENAME
•TRUNCATE

•COMMIT Transaction Control Language


•ROLLBACK (TCL)
•SAVEPOINT
Data Retrieval
SELECT
SELECT STATEMENT

Syntax :

SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ]


FROM table [ alias ] , ...
[ WHERE [ join condition ] ... ]
[ AND [ row condition ] ... ]
[ OR [ another row condition ] ]
[ GROUP BY [ expr | column ]]
[ HAVING [ group condition ]]
[ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;
Consider two tables:
• stud_name, containing the id and names of all
students
• stud_reg, having the registration details for the
courses that the students opt for.

Consider this query:


Select the most recent registration data of
students. All the students must be listed even if
they do not have any registration details.
Approach 1:
SELECT n.id ID,
n.name Name,
r1.seq Sequence,
r1.sponsor Sponsor,
r1.fee Fee,
r1.regdate "REG DATE"
FROM stud_name n,
stud_reg r1
WHERE r1.stud_id(+) = n.id
AND (r1.rowid IS NULL
OR r1.seq = (SELECT MAX(r2.seq)
FROM stud_reg r2
WHERE r2.stud_id = n.id))
ORDER BY 1;
Approach 2:
SELECT n.id ID,
n.name Name,
TO_NUMBER('') Sequence,
'' Sponsor,
TO_NUMBER('') Fee,
'' "REG DATE"
FROM stud_name n
WHERE NOT EXISTS (SELECT 'x'
FROM stud_reg r
WHERE r.stud_id = n.id)
UNION
(Approach 2
SELECT n.id ID,
contd.)
n.name Name,
r1.seq Sequence,
r1.sponsor Sponsor,
r1.fee Fee,
TO_CHAR(r1.regdate) "REG
DATE"
FROM stud_name n,
stud_reg r1
WHERE r1.stud_id = n.id
AND r1.seq = (SELECT MAX(r2.seq)
FROM stud_reg r2
WHERE r2.stud_id = n.id);
SELECT STATEMENT

Syntax :

SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ]


FROM table [ alias ] , ...
[ WHERE [ join condition ] ... ]
[ AND [ row condition ] ... ]
[ OR [ another row condition ] ]
[ GROUP BY [ expr | column ]]
[ HAVING [ group condition ]]
[ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;
Capabilities of SQL SELECT
Statements
Restriction Projection

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

7839 KING PRESIDENT 10


7782 CLARK MANAGER 10
7934 MILLER CLERK 10
Creating a Projection on a
DEPT
Table
DEPTNO DNAME LOC “…Retrieve
DEPTNO and LOC
10 ACCOUNTING NEW YORK columns from the
20 RESEARCH DALLAS
30 SALES CHICAGO
DEPT table”
40 OPERATIONS BOSTON

DEPT
DEPTNO LOC

10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON

only two columns are displayed


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.
Generating a Cartesian
Product
EMP (14 rows) DEPT (4 rows)
EMPNO
EMPNO ENAME
ENAME ...
... DEPTNO
DEPTNO DEPTNO
DEPTNO DNAME
DNAME LOC
LOC
------
------ -----
----- ...
... ------
------ ------ ---------- --------
------ ---------- --------
7839 KING
7839 KING ...
... 10
10 10
10 ACCOUNTING
ACCOUNTING NEW
NEW YORK
YORK
7698
7698 BLAKE
BLAKE ...
... 30
30 20 RESEARCH
20 RESEARCH DALLAS
DALLAS
...
... 30
30 SALES
SALES CHICAGO
CHICAGO
7934
7934 MILLER
MILLER ...
... 10
10 40
40 OPERATIONS
OPERATIONS BOSTON
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;

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

Syntax :

SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ]


FROM table [ alias ] , ...
[ WHERE [ join condition ] ... ]
[ AND [ row condition ] ... ]
[ OR [ another row condition ] ]
[ GROUP BY [ expr | column ]]
[ HAVING [ group condition ]]
[ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;
Obtaining Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON

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

ENAME JOB DEPTNO


---------- --------- ---------
JAMES CLERK 30
SMITH CLERK 20
ADAMS CLERK 20
MILLER CLERK 10
Types of Joins

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

Links rows that satisfy a specified condition

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.

Foreign key Primary key


Retrieving Records
with an Equijoin
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.
Qualifying Ambiguous
Column Names
– Use table prefixes to qualify column names
that are in multiple tables.
– Use table prefixes to improve performance.
Defining a Column Alias
•A column alias:
– Renames a column heading
– Is useful with calculations
– Immediately follows a column name;
optional AS keyword may fall between a
column name and an alias
– Requires double quotation marks if it
contains spaces, special characters, or is
case sensitive
Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;

NAME SALARY
------------- ---------
...

SQL> SELECT ename "Name",


2 sal * 12 "Annual Salary"
3 FROM emp;

Name Annual Salary


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

… can be written as ...


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;
Using Table Aliases
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;

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
7654 MARTIN 30 30 CHICAGO
7499 ALLEN 30 30 CHICAGO
...

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;

ENAME SAL GRADE


---------- --------- ---------
JAMES 950 1
SMITH 800 1
ADAMS 1100 1
...
14 rows selected.
Joining More Than Two
EMP Tables DEPT
ENAME SAL DEPTNO DEPTNO DNAME
---------- --------- --------- --------- ----------
JAMES 950 30 10 ACCOUNTING
SMITH 800 20 20 RESEARCH
ADAMS 1100 20 30 SALES
MARTIN 1250 30 40 OPERATIONS
WARD 1250 30
MILLER 1300 10
… SALGRADE
14 rows selected. LOSAL HISAL GRADE
--------- --------- ---------
700 1200 1
WHERE emp.sal BETWEEN 1201 1400 2
salgrade.losal AND 1401 2000 3
salgrade.hisal 2001 3000 4
AND emp.deptno = dept.deptno 3001 9999 5
Using Multiple Joins
SQL> SELECT e.ename, e.deptno, d.dname, e.sal, s.grade
2 FROM emp e, dept d, salgrade s
3 WHERE e.deptno=d.deptno
4 AND e.sal BETWEEN s.losal and s.hisal;

ENAME DEPTNO DNAME SAL GRADE


---------- --------- -------------- --------- ---------
JAMES 30 SALES 950 1
SMITH 20 RESEARCH 800 1
ADAMS 20 RESEARCH 1100 1
MARTIN 30 SALES 1250 2
WARD 30 SALES 1250 2
MILLER 10 ACCOUNTING 1300 2
ALLEN 30 SALES 1600 3
...
14 rows selected.
Selfjoins
EMP (WORKER) EMP (MANAGER)
EMPNO ENAME MGR EMPNO ENAME
----- ------ ---- ----- --------
7839 KING
7698 BLAKE 7839 7839 KING
7782 CLARK 7839 7839 KING
7566 JONES 7839 7839 KING
7654 MARTIN 7698 7698 BLAKE
7499 ALLEN 7698 7698 BLAKE

“MGR in the WORKER table is equal to EMPNO in the


MANAGER table.”
Joining a Table to Itself
SQL> SELECT worker.ename||' works for '||manager.ename
2 AS WHO_WORKS_FOR_WHOM
3 FROM emp worker, emp manager
4 WHERE worker.mgr = manager.empno;

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;

ENAME DEPTNO DNAME


---------- --------- -------------
MARTIN 30 SALES
ALLEN 30 SALES
TURNER 30 SALES
JAMES 30 SALES
WARD 30 SALES
40 OPERATIONS
15 rows selected.
Additional Search Conditions
Using the AND Operator
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
... ...
14 rows selected. 14 rows selected.

WHERE emp.deptno=dept.deptno AND emp.ename=´KING´


Using Additional Search
Conditions with a Join
SQL> SELECT emp.empno, emp.ename, emp.deptno, dept.loc
2 FROM emp, dept;
3 WHERE emp.deptno = dept.deptno
4 AND INITCAP(emp.ename) = 'King';

EMPNO ENAME DEPTNO LOC


--------- ---------- --------- -------------
7839 KING 10 NEW YORK
Using Additional Search
Conditions with a Join
SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname
2 FROM emp, dept
3 WHERE emp.deptno=dept.deptno
4 AND emp.job IN ('MANAGER','PRESIDENT');

ENAME JOB DEPTNO DNAME


---------- --------- --------- --------------
KING PRESIDENT 10 ACCOUNTING
BLAKE MANAGER 30 SALES
CLARK MANAGER 10 ACCOUNTING
JONES MANAGER 20 RESEARCH
SELECT STATEMENT

Syntax :

SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ]


FROM table [ alias ] , ...
[ WHERE [ join condition ] ... ]
[ AND [ row condition ] ... ]
[ OR [ another row condition ] ]
[ GROUP BY [ expr | column ]]
[ HAVING [ group condition ]]
[ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;
Using the GROUP BY Clause
– Any column or expression in the SELECT
list which is not an aggregate function must
be in the GROUP BY clause.

SQL> SELECT deptno, COUNT(*) emps


2 FROM emp
3 GROUP BY deptno
4 HAVING COUNT(*) > 3;

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

•Divide rows in a table into smaller


groups by using the GROUP BY clause.
Using AVG and SUM
Functions
•You can use AVG and SUM for numeric data.
SQL> SELECT AVG(sal), MAX(sal),
2 MIN(sal), SUM(sal)
3 FROM emp
4 WHERE job LIKE 'SALES%';

AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)


-------- --------- --------- ---------
1400 1600 1250 5600
Using MIN and MAX
Functions
•You can use MIN and MAX for any
datatype.
SQL> SELECT MIN(hiredate), MAX(hiredate)
2 FROM emp;

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;

DEPTNO JOB SUM(SAL)


--------- --------- ---------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
...
9 rows selected.
Illegal Queries
Using Group Functions
•Any column or expression in the
SELECT list that is not an aggregate s ee
s
function must be in the GROUP ccBY llaauu
BYY
clause. P B
SQL>
SQL> SELECT
SELECT deptno,
22 FROM
deptno, COUNT(ename) UP
COUNT(ename) U
emp; OO
FROM emp;
G R
R
ee G
tthh
SELECT
SELECT deptno,
deptno, COUNT(ename) iinn
COUNT(ename)
nngg
** ssii
ERROR
ERROR at
at line
line 1: 1: m
s
iis
m
ORA-00937:
ORA-00937: notnot aannsingle-group
single-group group group function
function
uumm
o ll
CCo
Illegal Queries
Using Group Functions
––You
You cannot
cannot use
use the
the WHERE
WHERE clause
clause toto restrict
restrict
groups.
groups.
––You
You use
use the
the HAVING
HAVING clause
clause to
to restrict
restrict groups.
groups.
SQL>
SQL> SELECT
SELECT deptno,
deptno, AVG(sal)
AVG(sal) ssee
22 FROM
FROM emp
emp l aauu
33 WHERE AVG(sal) cc l
WHERE AVG(sal) >> 2000
2000 EE
RR s
HHEE ouupps
44 GROUP
GROUP BY
BY deptno;
deptno;

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.

SQL> SELECT max(avg(sal))


2 FROM emp
3 GROUP BY deptno;

MAX(AVG(SAL))
-------------
2916.6667
SELECT STATEMENT

Syntax :

SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ]


FROM table [ alias ] , ...
[ WHERE [ join condition ] ... ]
[ AND [ row condition ] ... ]
[ OR [ another row condition ] ]
[ GROUP BY [ expr | column ]]
[ HAVING [ group condition ]]
[ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;
ORDER BY Clause
– Sort rows with the ORDER BY clause
• ASC: ascending order (default)
• DESC: descending order
– The ORDER BY clause comes last in the
SELECT statement.
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate;

ENAME JOB DEPTNO HIREDATE


---------- --------- --------- ---------
SMITH CLERK 20 17-DEC-80
ALLEN SALESMAN 30 20-FEB-81
...
14 rows selected.
Sorting in Descending Order
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 ORDER BY hiredate DESC;

ENAME JOB DEPTNO HIREDATE


---------- --------- --------- ---------
ADAMS CLERK 20 12-JAN-83
SCOTT ANALYST 20 09-DEC-82
MILLER CLERK 10 23-JAN-82
JAMES CLERK 30 03-DEC-81
FORD ANALYST 20 03-DEC-81
KING PRESIDENT 10 17-NOV-81
MARTIN SALESMAN 30 28-SEP-81
...
14 rows selected.
Sorting by Column Alias
SQL> SELECT empno, ename, sal * 12 annsal
2 FROM emp
3 ORDER BY annsal;

EMPNO ENAME ANNSAL


--------- ---------- ---------
7369 SMITH 9600
7900 JAMES 11400
7876 ADAMS 13200
7654 MARTIN 15000
7521 WARD 15000
7934 MILLER 15600
7844 TURNER 18000
...
14 rows selected.
Sorting by Multiple Columns
– The order of the columns in the ORDER BY
clause is the order of the sort.
SQL> SELECT ename, deptno, sal
2 FROM emp
3 ORDER BY deptno, sal DESC;

ENAME DEPTNO SAL


---------- --------- ---------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
FORD 20 3000
...
14 rows selected.

• You can sort by a column that is not in


the SELECT clause.
SELECT STATEMENT

Syntax :

SELECT [ DISTINCT ] ( [ table ] . * | expr [alias ], ... ]


FROM table [ alias ] , ...
[ WHERE [ join condition ] ... ]
[ AND [ row condition ] ... ]
[ OR [ another row condition ] ]
[ GROUP BY [ expr | column ]]
[ HAVING [ group condition ]]
[ ORDER BY [ expr | column ] [ ASC |DESC ] ] ;
Combining queries

• Subqueries
• Set operators
SUBQUERIES

Single Row SubQuery

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

“Which employees have a salary greater


? than Jones’s salary?”

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

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

<> Not equal to


Executing Single-Row
Subqueries
SQL> SELECT ename, job
2 FROM emp
3 WHERE job = CLERK
4 (SELECT job
5 FROM emp
6 WHERE empno = 7369)
7 AND sal > 1100
8 (SELECT sal
9 FROM emp
10 WHERE empno = 7876);

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

IN Equal to any member in the list

ANY Compare value to each value returned by


the subquery

Compare value to every value returned by


ALL
the subquery
Using ANY Operator
in Multiple-Row Subqueries
SQL> SELECT empno, ename, job 1300
2 FROM emp 1100
800
3 WHERE sal < ANY 950
4 (SELECT sal
5 FROM emp
6 WHERE job = 'CLERK')
7 AND job <> 'CLERK';

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

Main query Values from a multiple-row and


compares to
multiple-column subquery

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

ENAME DEPTNO SAL COMM


---------- --------- --------- ---------
JAMES 30 950
BLAKE 30 2850
TURNER 30 1500 0
CLARK 10 1500 300
...
7 rows selected.
Summary
––A
A multiple-column
multiple-column subquery
subquery returns
returns more
more
than
than one
one column.
column.
––Column
Column comparisons
comparisons in
in aa multiple-
multiple- column
column
comparisons
comparisons cancan be
be pairwise
pairwise or or
nonpairwise.
nonpairwise.
––A
A multiple-column
multiple-column subquery
subquery can can also
also be
be
used
used in
in the
the FROM
FROM clause
clause ofof aa SELECT
SELECT
statement.
statement.
Using a Correlated Subquery
to Solve a Problem
•“Which employees earn more than the
average salary for each department?”
Main Query

“Which employees earn more than the


? average salary for their individual
department?”
Correlated Subquery

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

Find all departments that do not have any


employees.
SQL>
SQL> SELECT
SELECT deptno,
deptno, dname
dname
22 FROM
FROM dept
dept dd
33 WHERE
WHERE NOT
NOT EXISTS
EXISTS (SELECT
(SELECT '1'
'1'
44 FROM
FROM emp
emp ee
55 WHERE
WHERE d.deptno
d.deptno == e.deptno);
e.deptno);

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

Union / Union All

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


---------- --------- ---------
ADAMS CLERK 30
ALLEN SALESMAN 30
ALLEN SALESMAN 20
BALFORD CLERK 20
BLAKE MANAGER 30
...
20 rows selected.
UNION ALL
A B
Using the UNION ALL
Operator
•Display the names, employee numbers,
and job titles of all employees.
SQL> SELECT ename, empno, job
2 FROM emp
3 UNION ALL
4 SELECT name, empid, title
5 FROM emp_history;

ENAME EMPNO JOB


---------- --------- ---------
KING 7839 PRESIDENT
BLAKE 7698 MANAGER
CLARK 7782 MANAGER
CLARK 7782 MANAGER
MARTIN 7654 SALESMAN
...
23 rows selected.
INTERSECT
A B
Using the INTERSECT
Operator
•Display the distinct names, employee
numbers, and job titles of employees
found in both the EMP and
EMP_HISTORY tables.
SQL> SELECT ename, empno, job
2 FROM emp
3 INTERSECT
4 SELECT name, empid, title
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

•COMMIT Transaction Control Language


•ROLLBACK (TCL)
•SAVEPOINT
Manipulating Data
DML
Data Manipulation Language
– A DML statement is executed when you:
• Add new rows to a table (INSERT)
• Modify existing rows in a table (UPDATE)
• Remove existing rows from a table (DELETE)
– A transaction consists of a collection of
DML statements that form a logical unit of
work.
Adding a New Row to a Table
50 DEVELOPMENT DETROIT
New row
“…insert a new row
DEPT
into DEPT table…”
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS DEPT
30 SALES CHICAGO DEPTNO DNAME LOC
40 OPERATIONS BOSTON ------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
50 DEVELOPMENT DETROIT
The INSERT Statement
––Add
Add new
new rows
rows to
to aa table
table by
by using
using the
the
INSERT
INSERT statement.
statement.
INSERT
INSERT INTO
INTO table
table [(column
[(column [,
[, column...])]
column...])]
VALUES
VALUES (value
(value [,
[, value...]);
value...]);

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

Enter value for department_id: 80


Enter value for department_name: EDUCATION
Enter value for location: ATLANTA

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

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 20
10
7566 JONES MANAGER 20
...
The UPDATE Statement
––Modify
Modify existing
existing rows
rows with
with the
the UPDATE
UPDATE
statement.
statement.
UPDATE
UPDATE table
table
SET
SET column
column == value
value [,
[, column
column == value]
value]
[WHERE
[WHERE condition];
condition];

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

•You can remove existing rows from a


table by using 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);

•Use a correlated subquery to update


rows in one table based on rows from
another table.
Correlated DELETE

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

•COMMIT Transaction Control Language


•ROLLBACK (TCL)
•SAVEPOINT
Creating and Managing
Tables
DDL
• These statements are used to create, modify or remove
Oracle database structures, including tables.
• have an immediate effect on the database ,and record
information in the Data dictionary.

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

CREATE TABLE [schema.]table


(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint]);

– You specify the table name, column name,


column datatype, column size, and the table
and/or column constraint.
Creating Tables
– Create the table.
SQL> CREATE TABLE dept
2 (deptno NUMBER(2),
3 dname VARCHAR2(14),
4 loc VARCHAR2(13));
Table created.

• Confirm table creation.


SQL> DESCRIBE dept

Name Null? Type


--------------------------- -------- ---------
DEPTNO NOT NULL NUMBER(2)
DNAME VARCHAR2(14)
LOC VARCHAR2(13)
The DEFAULT Option
•You can specify a default value for a
column during an insert:
... hiredate DATE DEFAULT SYSDATE, ...

• Legal values are a literal value, an


expression, or a SQL function.
• Illegal values are another column’s name or
pseudocolumn.
• The default datatype must match the
column datatype.
What Are Constraints?
– Constraints enforce rules at the table level.
– Constraints prevent the deletion of a table if
there are dependencies.
– The following constraint types are valid in the
Oracle Server:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
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.
Defining Constraints
CREATE TABLE [schema.]table
(column datatype [DEFAULT expr]
[column_constraint],
...
[table_constraint]);

– 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

7839 KING PRESIDENT 10


7698 BLAKE MANAGER 30
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...

NOT NULL constraint Absence of NOT NULL NOT NULL constraint


(no row may contain constraint
a null value for (any row can contain
this column) null for this column)
The UNIQUE Key Constraint
UNIQUE key constraint
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into
Not allowed
50 SALES DETROIT (DNAMESALES
already exists)
60 BOSTON Allowed
The UNIQUE Key Constraint

•You can define the UNIQUE key constraint


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));
The PRIMARY KEY
Constraint
PRIMARY key
DEPT
DEPTNO DNAME LOC
------ ---------- --------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON

Insert into
Not allowed
20 MARKETING DALLAS (DEPTNO20 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
(DEPTNO9
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;

– Match the number of specified columns to


the number of subquery columns.
– Define columns with column names and
default values.
Creating a Table by Using a
Subquery
SQL> CREATE TABLE scott.dept30
2 AS
3 SELECT empno, ename, sal * 12 ANNSAL, hiredate
4 FROM emp
5 WHERE deptno = 30;
Table created.

SQL> DESCRIBE dept30

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

ALTER TABLE table


MODIFY (column datatype [DEFAULT expr] [NOT NULL]
[, column datatype]...);
Adding a Column “…add a
DEPT30 New column
new
EMPNO ENAME ANNSAL HIREDATE JOB column
------ ---------- -------- into
7698 BLAKE 34200 01-MAY-81 DEPT30
7654 MARTIN 15000 28-SEP-81 table…”
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
DEPT30
EMPNO ENAME ANNSAL HIREDATE JOB

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


7698 BLAKE 34200 01-MAY-81
7654 MARTIN 15000 28-SEP-81
7499 ALLEN 19200 20-FEB-81
7844 TURNER 18000 08-SEP-81
...
Modifying a Column
•Modify a column definition by using the
ALTER TABLE statement with the
MODIFY clause.
– You can change a column’s datatype, size,
default value, and NOT NULL column
constraint.
SQL> ALTER TABLE emp
2 MODIFY (job VARCHAR2(50));
Table altered.

– A change to the default value affects only


subsequent insertions to the table.
Adding a Constraint
•Add constraints to a table or column by
using the ALTER TABLE statement
with the ADD clause:
ALTER
ALTER TABLE
TABLE table
table
ADD
ADD [CONSTRAINT
[CONSTRAINT constraint]
constraint] type
type (column);
(column);

– You can add or drop but not modify the


structure of a constraint.
– You can enable or disable constraints.
– You can add a NOT NULL constraint by
using the MODIFY clause.
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.
Dropping a Constraint
– Remove the manager constraint from the
EMP table.
SQL>
SQL> ALTER
ALTER TABLE
TABLE emp
emp
22 DROP
DROP CONSTRAINT
CONSTRAINT emp_mgr_fk;
emp_mgr_fk;
Table
Table altered.
altered.
• Remove the PRIMARY KEY constraint on
the DEPT table and drop the associated
FOREIGN KEY constraint on the
EMP.DEPTNO column.

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.

– A UNIQUE or PRIMARY KEY index is


automatically created if you enable a
UNIQUE or PRIMARY KEY constraint.
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


What Is a Sequence?
––Automatically
Automatically generates
generates unique
unique numbers
numbers
––Is
Is aa sharable
sharable object
object
––Is
Is typically
typically used
used to
to create
create aa primary
primary key
key
value
value
––Replaces
Replaces application
application code
code
––Speeds
Speeds up up the
the efficiency
efficiency of
of accessing
accessing
sequence
sequence values
values when
when cached
cached inin memory
memory
The CREATE SEQUENCE
Statement
•Define a sequence to generate
sequential numbers automatically
CREATE
CREATE SEQUENCE
SEQUENCE sequence
sequence
[INCREMENT
[INCREMENT BYBY n]
n]
[START
[START WITH
WITH n]
n]
[{MAXVALUE
[{MAXVALUE nn || NOMAXVALUE}]
NOMAXVALUE}]
[{MINVALUE
[{MINVALUE nn || NOMINVALUE}]
NOMINVALUE}]
[{CYCLE
[{CYCLE || NOCYCLE}]
NOCYCLE}]
[{CACHE
[{CACHE nn || NOCACHE}];
NOCACHE}];
Creating a Sequence
––Create
Create aa sequence
sequence named
named DEPT_DEPTNO
DEPT_DEPTNO to
to be
be used
used for
for the
the primary
primary key
key of
of the
the
DEPT
DEPT table.
table.
––Do
Do not
not use
use the
the CYCLE
CYCLE option.
option.

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.

•You cannot roll back this statement.


Changing the Name of an
Object
– To change the name of a table, view,
sequence, or synonym, execute the
RENAME statement.

SQL> RENAME dept TO department;


Table renamed.

– You must be the owner of the object.


Truncating a Table
– The TRUNCATE TABLE statement:
• Removes all rows from a table
• Releases the storage space used by that table

SQL> TRUNCATE TABLE department;


Table truncated.

– You cannot roll back row removal when


using TRUNCATE.
– Alternatively, you can remove rows by
using the DELETE statement.
Adding Comments to a Table
– You can add comments to a table or column by
using the COMMENT statement.
SQL> COMMENT ON TABLE emp
2 IS 'Employee Information';
Comment created.

– Comments can be viewed through the following


data dictionary views:
• ALL_COL_COMMENTS
• USER_COL_COMMENTS
• ALL_TAB_COMMENTS
• USER_TAB_COMMENTS
Summary
– Types of constraints:
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
– Use data dictionary views to retrieve table,
column, and constraint information.
Summary
Create
Create and
and maintain
maintain tables
tables using
using the
the
following
following statements:
statements:
Statement Description
CREATE TABLE Creates a table
ALTER TABLE Modifies table structures
DROP TABLE Removes the rows and table structure
RENAME Changes the name of a table, view,
sequence, or synonym
TRUNCATE Removes all rows from a table and
releases the storage space
COMMENT Adds comments to a table or view
SQL Statements
•SELECT Data Retrieval

•INSERT
•UPDATE Data manipulation language (DML)
•DELETE

•CREATE
•ALTER
•DROP Data definition language (DDL)
•RENAME
•TRUNCATE

•COMMIT Transaction Control Language


•ROLLBACK (TCL)
•SAVEPOINT
Contolling Transactions
TCL
Database Transactions
Database transactions can consist of:
– DML statements that make up one
consistent change to the data
Example: UPDATE
– One DDL statement
Example: CREATE
– One DCL statement
Example: GRANT and REVOKE
Database Transactions

•Begin when the first executable SQL


statement is executed
•End with one of the following events:
• COMMIT or ROLLBACK
• DDL or DCL statement executes (automatic
commit)
• User exits
• System crashes
Advantages of COMMIT
and ROLLBACK

– COMMIT and ROLLBACK ensure data


consistency.
– Users can preview data changes before
making changes permanent.
– Users can group logically related
operations.
Controlling Transactions
Transaction

INSERT UPDATE INSERT DELETE

COMMIT Savepoint A Savepoint B

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.

• Commit the changes.


SQL> COMMIT;
Commit complete.
State of the Data After
ROLLBACK
Discard all pending changes by using
the ROLLBACK statement. Following a
ROLLBACK:
– Data changes are undone.
– The 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.
Rolling Back Changes
to a Marker
– Create a marker within 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.
Statement-Level Rollback
– If a single DML statement fails during
execution, only that statement is rolled
back.
– Oracle implements an implicit savepoint.
– All other changes are retained.
– The user should terminate transactions
explicitly by executing a COMMIT or
ROLLBACK statement.
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 or other readers
• Writers do not wait for readers
Implementation of Read
Consistency
UPDATE emp Data
SET sal = 2000 blocks
WHERE ename = 'SCOTT';

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

Exclusive lock Prevents a resource from being shared.

The first transaction to lock a resource


exclusively is the only transaction that can
alter the resource until the exclusive lock is
released.

Share Allows the resource to be shared.

Multiple users reading data can share the


data, holding share locks to prevent
concurrent access by a writer (who needs an
exclusive lock).

Several transactions can acquire share locks


on the same resource.
Implicit Locking
User Action Row-Level Lock Table-Level Lock

SELECT ... FROM table ... None None

INSERT INTO table ... X RX

UPDATE table ... X RX

DELETE FROM table ... X RX

DDL Operation None X


Explicit Locking
User Action Row-Level lock Table-Level lock

SELECT FOR UPDATE X RS [NOWAIT]

LOCK TABLE IN option None Depends on the MODE


restrictiveness used

Override the default lock mechanism:


– For a consistent view of data when reading
across multiple tables
– When a transaction may change data
based on other data that must not change
until the whole transaction is complete
Summary
– A transaction is a logical unit of work.
– Transaction control statements:
Statement Description

COMMIT Makes all pending changes permanent.

SAVEPOINT Allows a rollback to the savepoint marker.

ROLLBACK Discards all pending data changes.

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

ENAME JOB COMM


---------- --------- ---------
KING PRESIDENT
BLAKE MANAGER
...
TURNER SALESMAN 0
...
14 rows selected.
Null Values in a Subquery

SQL> SELECT employee.ename


2 FROM emp employee
3 WHERE employee.empno NOT IN
4 (SELECT manager.mgr
5 FROM emp manager);
no rows selected.
NVL Function
•Converts null to an actual value
––Datatypes
Datatypes that
that can
can be
be used
used are
are date,
date,
character,
character, and
and number.
number.
––Datatypes
Datatypes must
must match
match
•• NVL(comm,0)
NVL(comm,0)
•• NVL(hiredate,'01-JAN-97')
NVL(hiredate,'01-JAN-97')
•• NVL(job,'No
NVL(job,'No Job
Job Yet')
Yet')
Using the NVL Function
SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)
2 FROM emp;

ENAME SAL COMM (SAL*12)+NVL(COMM,0)


---------- --------- --------- --------------------
KING 5000 60000
BLAKE 2850 34200
CLARK 2450 29400
JONES 2975 35700
MARTIN 1250 1400 16400
ALLEN 1600 300 19500
...
14 rows selected.
Null Values in Arithmetic
Expressions
•Use the NVL function to convert a null
value to an actual value.
SQL> SELECT ename NAME, 12 * sal + NVL(comm, 0)
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

•Facilitates conditional inquiries by doing


the work of a CASE or IF-THEN-ELSE
statement
DECODE(col/expression,
DECODE(col/expression, search1,
search1, result1
result1
[,
[, search2,
search2, result2,...,]
result2,...,]
[,
[, default])
default])
Using the DECODE Function
SQL> SELECT job, sal,
2 DECODE(job, 'ANALYST', SAL*1.1,
3 'CLERK', SAL*1.15,
4 'MANAGER', SAL*1.20,
5 SAL)
6 REVISED_SALARY
7 FROM emp;

JOB SAL REVISED_SALARY


--------- --------- --------------
PRESIDENT 5000 5000
MANAGER 2850 3420
MANAGER 2450 2940
...
14 rows selected.
Example 1 :
SELECT ename
, job
, DECODE ( job, ‘CLERK’, ‘WORKER’
, ‘MANAGER’, ‘SUPERVISOR’
, ‘PRESIDENT’, ‘BOSS’
, ‘OTHERS’) Decoded_Job
FROM emp;
Example 2 :
UPDATE emp
SET comm = DECODE(sign(sal - 1000), -1, sal*0.1
, DECODE(sign(sal - 2000), -1, sal*0.2
, DECODE(sign(sal - 3000), -1, sal*0.25,
0, sal*0.3,
sal*0.4)))
Example 3 :
DELETE
FROM emp
WHERE sal < DECODE(SIGN(NVL(comm,0) - 1000),
-1, 999, 0, 1000, 1, 1500);
Nesting Functions
––Single-row
Single-row functions
functions can
can be
be nested
nested to
to any
any
level.
level.
––Nested
Nested functions
functions are
are evaluated
evaluated from
from deepest
deepest
level
level to
to the
the least
least deep
deep level.
level.

F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
Nesting Functions

SQL> SELECT ename,


2 NVL(TO_CHAR(mgr),'No Manager')
3 FROM emp
4 WHERE mgr IS NULL;

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;

This statement uses ROWNUM to limit


the number of rows shown by the query.
EMPNO
EMPNO ENAME
ENAME JOB
JOB MGR
MGR HIREDATE
HIREDATE

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

- has its own command language for controlling


the behaviour of the product, and for formatting
the output from SQL queries.
SQL Statements Versus
SQL*Plus Commands
SQL SQL*Plus
• Is a language • Is an environment
• Is ANSI standard • Is Oracle proprietary
• Keywords cannot be • Keywords can be
abbreviated abbreviated
• Statements manipulate • Commands do not
data and table allow manipulation of
definitions in the values in the database
database

SQL SQL SQL*Plus SQL*Plus


statements buffer commands buffer
Overview of SQL*Plus
With SQL*Plus you can:
– Describe the table structure.
– Edit your SQL statement.
– Execute SQL from SQL*Plus.
– Save SQL statements to files and append
SQL statements to files.
– Execute saved files.
– Load commands from file to buffer for editing.
– Format columns.
Displaying Table Structure
Use the SQL*Plus DESCRIBE command
to display the structure of a table.
DESC[RIBE]
DESC[RIBE] tablename
tablename

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

You might also like