You are on page 1of 27

Chapter7: Multiple-Column Subquery

SELECT [column, column]


FROM
table1
WHERE (column, column, ...) IN
(SELECT column, column, ... from table2 WHERE ...);

Combine duplicate WHERE conditions into a single WHERE


clause
Perform Pairwise comparison. Each candidate row in the
SELECT statement must have ALL the multiple columns match
the multiple columns returned by the subquery.

Chapter 7

Chapter7: Multiple-Column Subquery


--Find the empno,ename,job,deptno which has the same
--job,deptno as empno 7369 or 7698.
--Exclude empno 7369 and 7698 from result
SQL> select empno,ename,job,deptno from emp
where (job, deptno) in (select job, deptno from emp where
empno in (7369,7698) ) and empno not in (7369,7698);
EMPNO ENAME
JOB
DEPTNO
---------- ---------- --------- ---------7876 ADAMS
CLERK
20
--Not the same as above. Using 2 single-column subqueries.
--Doing non-pairwise comparision then cross product.
SQL> select empno,ename,job,deptno from emp
where job in (select job from emp where empno in (7369,7698))
and deptno in (select deptno from emp where empno in (7369,7698))
and empno not in (7369,7698);

EMPNO
---------7876
7566
7900

ENAME
---------ADAMS
JONES
JAMES

Chapter 7

JOB
DEPTNO
--------- ---------CLERK
20
MANAGER
20
CLERK
30

Chapter7: NULL in Subquery


--Using IN operator, even NULL is present, the other
--values are compared. IN is equivalent to =ANY
--Find the ename/job of the managers
SQL> select ename, job from emp where empno IN (select mgr
from emp);
ENAME
JOB
---------- --------JONES
MANAGER
BLAKE
MANAGER
CLARK
MANAGER
SCOTT
ANALYST
KING
PRESIDENT
FORD
ANALYST
--Find the ename/job of non-managers. NOT IN is equivalent
--to !=ALL. When empno compared with NULL, its not true
SQL> select ename, job from emp where empno NOT IN (select
mgr from emp);
no rows selected

Chapter 7

Chapter7: INLINE View


--Subquery in the FROM clause is also called Inline View
--This can help build very complicated queries.
--Find the average students in each course. Average is on
--the total students registered the course each trimester
SQL> select b.course_number, avg(a.reg_count) avg_reg
FROM
(select course_id, trimester, count(*) reg_count from
registered_students
group by course_id, trimester
) a
,courses b
where a.course_id=b.course_id
group by b.course_number
order by 2 desc;
COURSE_NUMBER
AVG_REG
------------------------------ ---------cs537
68
cs503a
44.5
cs528
44

Chapter 7

Chapter7: Correlated Subquery


SELECT select_list
FROM table1 t_alias1
WHERE expr operator
(SELECT column_list
FROM table2 t_alias2
WHERE t_alias1.column operator t_alias2.column);

A correlated subquery answers a multiple-part question whose


answer depends on the value in each row processed by the parent
statement.

Chapter 7

Chapter7: Correlated Subquery


--Subquery in the FROM clause is also called Inline View
--This can help build very complicated queries.
--e.g. find emp with sal > his/her own depts avg(sal)
SQL> SELECT ename, sal, deptno
FROM emp a
WHERE sal > (SELECT AVG(sal)
FROM emp b
WHERE a.deptno = b.deptno)
ORDER BY deptno, sal;
ENAME
SAL
DEPTNO
---------- ---------- ---------KING
5000
10
JONES
2975
20
--What if we display the avg(sal) for each deptno as well
select a.ename, a.sal,a.deptno,round(b.dept_avg_sal) dept_avg_sal
from emp a, (select deptno, avg(sal) dept_avg_sal
from emp b group by deptno) b
where a.deptno=b.deptno and a.sal>b.dept_avg_sal
order by a.deptno, a.sal;

Chapter 7

Chapter7: Data Manipulation Language


DML (Data Manipulation Language) consists of
INSERT
UPDATE
DELETE
SELECT
One transaction consists of a collection of DML statements,
which form a logical unit of work. Transaction Control
commands are:
COMMIT
ROLLBACK
SAVEPOINT
Chapter 7

Chapter7: INSERT (one row)


INSERT INTO table [(column [, column ...]) ]
VALUES (value [, value ...] );

Insert one row into at a time to the table.


The column list should correspond to the value list.
If the column list is missing, then the order should be the one in
the table definition. (when doing a desc table_name).
Usually all the NOT NULL columns in the table need to have
a corresponding non-NULL value in the value clause, unless
the column has a default value in the table definition.
If the column is missing from the column list/value clause, then
it will have NULL values, unless it has default value in the
table definition.
Chapter 7

Chapter7: INSERT (one row)


--Insert without the column list. All column values
--need to be in the value clause. The column order is the
--same in the table definition. (desc table_name).
SQL> insert into courses values (721,'cs601', 2, 83, 'Data
Mining', 'Data Mining', '', '', '', 'A', sysdate, 'admin',
sysdate, user);
1 row created.
--If missing one value in the value clause.
SQL> insert into courses values (722,'cs602', 2, 83, 'Data
Mining II', 'Data Mining II', '', '', '', 'A', sysdate,
'admin', sysdate);
ERROR at line 1:
ORA-00947: not enough values
--Switching the last 2 columns in the value clause.
SQL> insert into courses values (722,'cs602', 2, 83, 'Data
Mining II', 'Data Mining II', '', '', '', 'A', sysdate,
'admin', user, sysdate);
ORA-01858:
Chapter 7a non-numeric character was found where a
9

Chapter7: INSERT (one row)


--Insert with the column list. All columns are speicified
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date, modified_by) values (722,'cs602', 2, 83,
'Data Mining II', 'Data Mining II', '', '', '', 'A',
sysdate, 'admin', sysdate, user);
1 row created.
--Switching the last 2 columns in the column list AND the
--value clause. It still works.
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_by, modified_date) values (723,'cs603', 2, 83,
'Data Mining III', 'Data Mining III', '', '', '', 'A',
sysdate, 'admin', user, sysdate);

Chapter 7

10

Chapter7: INSERT NULL value


--If the column is not in the column list. And it doesnt
--have a default value in table definition. E.g
--modified_by
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date) values (723,'cs603', 2, 83, 'Data Mining
II', 'Data Mining II', '', '', '', 'A', sysdate, 'admin',
sysdate);
1 row created.
--If the column is in the column list. Explicitly specify
--NULL in the value clause.
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date, modified_by) values (724,'cs604', 2, 83,
'Data Mining III', 'Data Mining III', '', '', '', 'A',
sysdate, 'admin', sysdate, NULL);

Chapter 7

11

Chapter7: INSERT NULL


--If the column is defined as NOT NULL (Mandatory), it has
--to have a value. The following is missing major_id.
SQL> insert into courses (course_id, course_number,
instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date) values (723,'cs603', 83, 'Data Mining II',
'Data Mining II', '', '', '', 'A', sysdate, 'admin',
sysdate);
ERROR at line 1:
ORA-01400: cannot insert NULL into
("CS457"."COURSES"."MAJOR_ID")
--If the following is perform, then the above will succeed
--This is going to be covered in Chapter9
SQL> alter table courses modify major_id number default 2;

Chapter 7

12

Chapter7: INSERT Date value


--If the dates are included in single quote like a
--character string. Its implicitly converted to DATE
--using NLS_DATE_FORMAT parameter. Its recommended to use
--the to_date() function to explicitly convert to DATE
--data type, so the code is more portable/robust.
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date) values (725,'cs604', 2, 83, 'Data Mining
II', 'Data Mining II', '', '', '', 'A', sysdate, 'admin',
to_date('06/23/2003', 'mm/dd/yyyy'));
1 row created.

Chapter 7

13

Chapter7: Using Substitution Variable


--In SQL*PLUS, the variable with & in front can be
--replaced with a value during runtime.
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date) values (&course_id,'&course_number', 2, 83,
'&course_description', '', '', '', '', 'A', sysdate,
'admin', sysdate);
Enter value for course_id: 725
Enter value for course_number: cs605
Enter value for course_description: Data Mining V
1 row created.
--If the character string itself contains & inside. Use
--SQL*PLUS command set scan off to ignore
--the interpretation of & as substitution variable
--e.g. course_short_description as 'Data Mining I & II'

Chapter 7

14

Chapter7: Using Substitution Variable


--In SQL*PLUS, Use ACCEPT to store the value in a variable
--Use PROMPT to display customized text. E.g. the
--following is in a SQL script.
accept course_id prompt 'Please enter the course_id
(max(course_id_+ 1): '
accept course_number prompt 'Please enter the Course
Number: '
accept course_description prompt 'Please enter the course
short description: '
insert into courses (course_id, course_number, major_id,
instructor_user_id, course_short_description,
course_long_description, handout_main_url, syllabus_url,
instructor_url, status, created_date, created_by,
modified_date) values (&course_id,'&course_number', 2, 83,
'&course_description', '', '', '', '', 'A', sysdate,
'admin', sysdate);
SQL> @7th_week_1.sql
Please enter the course_id (max(course_id_+ 1): 725
Please enter the Course Number: cs605
Please
enter
Chapter
7 the course short description: Data Mining V15

Chapter7: INSERT (Multiple Rows)


INSERT INTO table [(column [, column ...]) ]
SELECT (value [, value ...] ) from table2;

Replace the value clause with a subquery


The number of rows inserted will be dependent on the returned
rows of the SELECT clause.
Match the number of columns, column data type in the
INSERTs column list with those in the subquery.
--The following inserts 3 rows in courses table
SQL> insert into courses (course_id, course_number,
major_id, instructor_user_id, course_short_description)
select 725+rownum, decode(rownum, 1, 'cs606a', 2,
'cs606b', 3, 'cs606c'), 2, 83, 'Data Mining '||rownum
from courses where course_number like 'cs457%';
3 rows created.

Chapter 7

16

Chapter7: UPDATE
UPDATE table
SET column=value [,column=value, ...]
[WHERE condition];

Update one or more rows at a time.


If the WHERE clause is missing, all the rows in the table will
be affected. Be careful.
If the WHERE clause is specified, the rows affected are those
who meet the WHERE condition.
--Update modified_by to inst_wuy and modified_date to
--current date for course cs540b
SQL> update courses set modified_by='inst_wuy',
modified_date=trunc(sysdate) where course_number='cs540b';
1 row updated.

Chapter 7

17

Chapter7: UPDATE
--If where clause is missing, then all the rows in courses
--table will be updated.
SQL> update courses set modified_by='inst_wuy',
modified_date=trunc(sysdate);
190 rows updated.
--Updated value need to satisfy the constraints of the
--table. This will be covered in Chapter 10.
SQL> update courses set course_number='cs540a' where
course_number='cs540b';
update courses set course_number='cs540a' where
course_number='cs540b'
*
ERROR at line 1:
ORA-00001: unique constraint (IT310.COURSES_UK1) violated

Chapter 7

18

Chapter7: UPDATE with Subquery


UPDATE table1
SET
(column, column, ...) =
(SELECT column, column, ...
FROM table2
WHERE condition )
WHERE condition;

--Change the instructor_user_id & course_short_description


--of course cs457b to be the same as cs457as
SQL> update courses
set (instructor_user_id, course_short_description) =
(select instructor_user_id, course_short_description
from courses
where course_number='cs457a')
where course_number='cs457b';
1 row updated.

Chapter 7

19

Chapter7: DELETE
DELETE [FROM] table
WHERE condition;

--delete all ESL courses.


--of course cs457b to be the same as cs457as
SQL> delete courses where course_number like 'esl%';
2 rows deleted.
--If the where clause is missing, then all the rows in the
--table is deleted. Also the following will violate the
--integrity constraints. So the statement fails.
SQL> delete courses;
delete courses
*
ERROR at line 1:
ORA-02292: integrity constraint (CS457.COURSE_TAS_FK1)
violated - child record found

Chapter 7

20

Chapter7: Database Transactions


Oracle Server guarantees data consistency based on transactions.
Transactions give the user more flexibility and control when
changing data and ensures data consistency in the event of user
process failure or system failure.
A database transaction consitsts of one of the following
statements:
DML statements that make up on consistent change to the data.
one DDL (Data Definition Language) statement, e.g. create
table, alter table.
one DCL (Data Control Language) statement, e.g. grant, revoke

Chapter 7

21

Chapter7: Database Transactions


Begin when the first executable SQL statement is executed
End with one of the following events:
COMMIT or ROLLBACK is issued
DDL or DCL statement executes (auto-commit)
User exits (auto-commit on/off)
System crashes (auto-rollback)
Dead-Lock (rollback)
After one transaction ends, the next executable SQL statement
automatically starts the next transaction.
A DDL/DCL statement automatically commits and implicitly
ends a transaction.
Chapter 7

22

Chapter7: Controlling Transactions


Statement

Description

COMMIT

Ends the current transaction by making


all pending data changes permanent

SAVEPOINT name

Marks a savepoint within the current


transaction. Not ANSI standard SQL.

ROLLBACK [TO
SAVEPOINT name]

ROLLBACK ends the current


transaction by discarding/reverting all
pending data changes; TO SAVEPOINT
name discards the savepoint and all
subsequent changes.

Chapter 7

23

Chapter7: Before COMMIT


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 can not view the results of the DML statements by
the current user.
The affected rows are locked. Other users can not change the
data of the affect rows.

Chapter 7

24

Chapter7: After COMMIT


Data changes are made permanent in the database.
The previous state of the data is permanently lost.
All users can view the results.
Locks on the affected rows are released. If the other users were
executing statements which hangs waiting for the affected
rows, those statements can proceed.
All savepoints are erased.

Chapter 7

25

Chapter7: After ROLLBACK


Data changes are undone or reverted.
The previous state of the data is restored.
All users can still view the data before the change.
Locks on the affected rows are released. If the other users were
executing statements which hangs waiting for the affected
rows, those statements can proceed.

Chapter 7

26

Chapter7: SAVEPOINT
Create a marker in a current transaction by using SAVEPOINT
statement.
rollback to that marker by using ROLLBACK TO
SAVEPOINT statement.
--The following will make the permanent changes for the
--first statement.
savepoint a;
insert into majors(major_id,name) values (6, 'Chemistry');
select major_id, name from majors;
savepoint b;
update majors set name='Comp Science' where major_id=2;
savepoint c;
delete majors where major_id=5;
select major_id, name from majors;
rollback to savepoint b;
select major_id, name from majors;

Chapter 7

27

You might also like