0% found this document useful (0 votes)
17 views62 pages

DBDev 03C

Uploaded by

T O K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views62 pages

DBDev 03C

Uploaded by

T O K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Guide to Oracle 10g

Chapter 3c
Using SQL Queries to Insert, Update, Delete, and View
Data

By Ahmed M. Zeki for ITBIS373


Introduction
! Retrieving data from a single table, so far.

! In this chapter:
◦ Create SQL queries that join multiple tables
◦ Create nested SQL queries
● The output form query 1 serves as a search condition in
query 2.
◦ Combine query results using set operators
◦ Create and use database views
◦ Create DB indexes.

2 / 61
Joining Multiple Tables
! Strength of SQL
! Joins or combines tables using foreign key
references. To qualify a column name, specify the
name of the table that contains the
column, followed by a period , then
specify the column name.
! General Syntax
SELECT column1, column2, …
FROM table1, table2
WHERE table1.joincolumn = table2.joincolumn
AND search_condition(s);
Join condition: specifies the table names
to be joined and col names on which to
join the tables. It contains foreign key ref
in one table and primary key in the other.

3 / 61
Join Queries: Inner Joins
! The simplest type

! Also called:
◦ equality join
◦ Equijoin
◦ natural join

! Join 2 tables based on values in table 1 being


equal to values in table 2

4 / 61
Join Queries: Inner Joins

F_ID is the primary key in


FACULTY and foreign key in
STUDENT

Because F_ID exists in both


tables, you must qualify

5 / 61
Join Queries: Inner Joins The pri key & foreig
key col on which you
join the tables are
called join colm

In case where the tables have a


single commonly named and defined
column, you can use NATURAL
JOIN keyword to join the tables in
the FROM clause of the SELECT
statement. 6 / 61
Join Queries: Inner Joins
! You can join any number of tables.

! When join tables, the name of each table in the


query must appear in the FROM clause.

! This includes tables whose columns are display


columns, which are columns that appear in the
SELECT clause, and whose columns are search
columns, which appear in search condition.

7 / 61
Join Queries: Inner Joins
! When you join multiple tables, sometimes you
must join the tables using an intermediary table
whose columns are not display or search columns,
but whose columns are join columns that serve to
join the two tables.

8 / 61
Join Queries: Inner Joins

A query lists the last


names of all faculty
members who teach
in Summer’07

9 / 61
Join Queries: Inner Joins
! A linking table does not contribute as display
columns or search condition columns, but contains
join columns that link the other tables through
shared foreign key values.

10 / 61
Join Queries: Inner Joins
Even though the query does not display cols from the
COURSE_SECTION or include them in search conditions, this table
must be included in the FROM clause, and include join conditions to not
only specify the links between FACULTY and COURSE_SECTION, but
also the links between the COURSE_SECTION and TERM.

NATURAL JOIN cannot be used to join the 3


table, because FACULTY & COURSE_SECTION
have 2 commonly named and defined columns:
11 / 61
F_ID and TERM_ID
Join Queries: Inner Joins
! Sometimes queries that join multiple tables can
become complex.

! For example, a query to display the COURSE_NAME


and GRADE values for each of student ‘Tammy Jones’
courses. This query requires you to join four table:
◦ STUDENT (to search for S_FIRST and S_LAST),
◦ ENROLLMENT (to display GRADE),
◦ COURSE to display COURSE_NO), and
◦ COURSE_SECTION (to join ENROLLMENT to COURSE
using the C_SEC_ID join column).

12 / 61
Join Queries: Inner Joins
! A query design diagram shows the display and
search columns in a SQL query that joins multiple
tables, as well as the required join columns and
their links.

Total # of tables = Number of join conditions + 1

13 / 61
Join Queries: Inner Joins
! Deriving the SQL query from the query design
diagram

14 / 61
Join Queries: Inner Joins

15 / 61
Join Queries: Inner Joins
! If you accidentally omit a join condition in a
multiple-table query, the output retrieves more
rows than you expect.

! When you omit a join condition, the query creates


a Cartesian product, whereby every row in one
table is joined with every row in the other table. For
example , 6 rows in STUDENT and 5 rows in
FACULTY, the result is 6*5 = 30 rows.

16 / 61
Join Queries: Inner Joins

17 / 61
Join Queries: Outer Joins
! An inner join returns rows only if values exist in all tables
that are joined. If no values exist for a row in one of the
joined tables, the inner join does not retrieve the row.

! Example: retrieve the different locations of the courses


included in the COURSE_SECTION table.

! This query requires joining rows in the LOCATION and


COURSE_SECTION tables. Not every location in the
LOCATION table has an associated COURSE_SECTION
row, so the query retrieves rows only for locations that
have associated COURSE_SECTION rows.

18 / 61
Join Queries: Outer Joins

19 / 61
Join Queries: Outer Joins
! To retrieve information for all locations, regardless
of whether they have associated course sections
or not, Outer Joins must be used.

! An outer join returns all rows from one table, which


is called the inner table. Also retrieves matching
rows from a second table, which is called the outer
table.

Inner Table Outer Table


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

All Rows Matching


Rows 20 / 61
Join Queries: Outer Joins
! If inner join is used:
SQL> SELECT c_sec_id, location.loc_id
2 FROM course_section, location
3 WHERE course_section.loc.id = location.loc_id;
C_SEC_ID LOC_ID
---------- ----------
1 1
11 1
3 2
8 3
6 5
7 5
10 5
13 5
9 5
4 6
12 6
5 6
2 7

21 / 61
Join Queries: Outer Joins
! How to specify which table is the inner table and which table is
the outer table?

◦ In this case, because you want to retrieve all of the rows in the
LOCATION table, you specify LOCATION as the inner table.

◦ Because you want to display the course section rows if they exist, you
specify COURSE_SECTION as the outer table.

! Syntax
inner_table.join_column = outer_table.join_column(+)

◦ The outer join operator (+) signals the DBMS to insert a NULL
value for the columns in the outer table that do not have matching
rows in the inner table.

22 / 61
Join Queries: Outer Joins

In Oracle 10g, NULL


(undefined) values appear
as blank spaces rather than
as the word NULL.

23 / 61
Join Queries: Self-Joins
! Sometimes a relational DB table contains a foreign
key that references a column in the same table.

! For example, at Northwood's University each


assistant and associate professor is assigned to
full professor who serves as the junior professor’s
supervisor.

24 / 61
Join Queries: Self-Joins
! The ID stored in the F_SUPER col can be linked
back to the F_ID col in the table to identify the
name of the individual’s supervisor.

F_SUPER col is a foreign


key in the FACULTY table
that references that same
table’s primary key. 25 / 61
Join Queries: Self-Joins
! To create a query that lists the names of each
junior faculty member and the names of their
supervisor, you must join the FACULTY table to
itself.

! When you create a query that joins a table to it


self, you create a self-join.

! To create a self-join, you must create a table alias


and structure the query as if you are joining the
table to a copy of itself.

26 / 61
Join Queries: Self-Joins
! The syntax to create a table alias in the FROM clause is:
FROM table1 alias1,……

! When you create a table alias, you must then use the
table alias, rather than the table name, to qualify column
names in the SELECT clause and in join condition.

! To make the process easier to understand, you create


two table aliases
◦ FAC for faculty version of the table
◦ SUPER for the supervisor version of the same table

27 / 61
Join Queries: Self-Joins

28 / 61
Nested Queries
! Query that is based on the results of another
query.

! Example: retrieve the first and last names of all


students who have the same S_CLASS value as
student Jorge Perez.

◦ Create a query that retrieves Jorge’s S_CLASS value.


◦ Create a second query to retrieve the names of the
students with the same S_CLASS value.

29 / 61
Nested Queries
! The other alternative way is to use a single nested
query:

! The nested query consists of main query and one


or more subqueries.

◦ Main query: First query that appears in the SELECT


command.

◦ Subquery: Retrieves values that main query’s search


condition must match.

30 / 61
Nested Queries
! In a nested query, the DBMS executes the
subquery first, and the main query second.

! Hence, you create nested queries to retrieve


intermediate results that are then used within the
main query’s search conditions.

31 / 61
Nested Queries
Subqueries that return a single value
! General Syntax

! The search column in the main query


(search_field1) must reference the same column
as the SELECT column (fieldname1) in the
subquery.

32 / 61
Nested Queries
Subqueries that return a single value
! If the subquery retrieves no rows or multiple rows,
an error message appears.

! Subqueries can also be used in search conditions


in UPDATE and DELETE commands.

33 / 61
Nested Queries
Subqueries that return a single value
! Example: Retrieve first and last of all students who
have the same S_CLASS value as student Jorg
Perez. The main query retrieves
the student first and last
names

The subquery retrieves


a single value, which is
Jorge’s S_CLASS value

34 / 61
Nested Queries
Subqueries that return a single value
! To make the query easier to read and understand,
indent the subquery .

! To debug a nested query, run the subquery


separately to ensure that it is retrieving the correct
results before you combine it with the main query.

35 / 61
Nested Queries
Subqueries that return multiple values
! The subquery returns multiple results each of
which satisfies the search condition.

! Example: retrieve the names of all students who


have ever been enrolled in the same course
section as Perez.

! To structure this query, you must use the IN


comparison operator instead of the ‘equal to’
comparison operator (=).

36 / 61
Nested Queries
Subqueries that return multiple values
You use the DISTINCT qualifier in the
main query’s SELECT clause to suppress
duplicate names.

You can use NOT IN to


specify that the main query
should retrieve all rows except
those that satisfy the search
condition.

37 / 61
Nested Queries Retrieve the names of all students who have
Multiple Subqueries the same S_CLASS value as Jorge Perez
and have also been enrolled in a course
section with him.

Use AND and OR operators to


specify multiple subqueries to join
the search conditions associated
with the subqueries.

38 / 61
Nested Queries
Nested Subqueries
! Subquery that contains second subquery that specifies
its search expression.
! Example: Create a query to retrieve the names of
students who have taken courses with Jorge Perez in the
CR building.
! The innermost subquery retrieves the course section ID
values for all course sections located in the CR building.
! The outermost main query retrieves the names of all
students who enrolled in the course sections that satisfy
both of these conditions.

39 / 61
! SELECT distinct s_first, s_last
! from student,enrollment
! where student.s_id = enrollment.s_id
! and c_sec_id in ( select c_sec_id
! from student,enrollment
! where student.s_id = enrollment.s_id
! and s_first like 'Jorge'
! and c_sec_id in ( select c_sec_id
! from course_section, location
! where course_section.loc_id = location.loc_id
! and location.bldg_code = 'CR'
! )
! )
! ;

40 / 61
Nested Queries
Nested Subqueries
! Nested queries execute slower than queries that
join multiple tables, so you should probably not use
nested queries unless you cannot retrieve the
desired result using a non-nested query.
◦ See Figure 3-57

41 / 61
Using Set Operators to Combine Query
Results
! Combine results of 2 separate queries not specified by
foreign key relationships.

! Example: Telephone directory that shows the names and


telephone numbers of all students and faculty members
(One single query can’t retrieve data from 2 unrelated
queries you must use a UNION set operator)

! Example: Retrieve the first and last names of faculty


members who have offices at BUS building and have
taught a class at BUS.

42 / 61
Using Set Operators to Combine Query
Results
! These rows don’t have any foreign key
relationships, so the only way to retrieve them is to
create multiple queries.

! Alternatively, you can use common set operators to


combine the results of separate queries into a
single result.

43 / 61
UNION and UNION ALL
! Joins the output of two unrelated queries into
single output result. Create a telephone directory of every student
and faculty member.

! General syntax
query1 UNION query2; Both queries must have the
same number of display
columns in their SELECT
clauses, and each display
column in the first query must
have the same data type as the
corresponding column in the
second query.

The default output column titles


are the column names in the
first query’s SELECT
statement.
44 / 61
UNION and UNION ALL
! UNION suppresses duplicates, and shows
duplicate row only once, while UNION ALL displays
all duplicate rows. (See Figure 3-59 and 3-60)

45 / 61
INTERSECT
! Returns only rows returned by both queries

! Requires that both queries have the same number


of display columns in the SELECT statement and
that each column in the first query has the same
data type as the corresponding column in the
second query.

! Automatically suppresses duplicate rows.

46 / 61
INTERSECT
! Example: create a query that retrieves the courses
taken only by students who were not seniors, in
addition to courses that were offered in term 6.
(See Figure 3-61)

47 / 61
MINUS
! Finds the difference between two unrelated query
result lists.

! Both queries have the same number of display


columns in the SELECT statement. Each column in
the first query has the same data type as the
corresponding column in the second query.

! MINUS automatically suppressed duplicate rows.

48 / 61
MINUS
! Example: retrieve the courses that were taken by
freshmen, sophomores, and juniors, but were not
offered in term 6.
◦ You can use the previous statement MINUS any courses
offered in term 6.
◦ (See Figure 3-62)

49 / 61
Database Views
! Presents data in a different format than the one
stored in tables.

! Similar to storing results of a query in the DB.

! To create a view, use a SQL query called the


source query which can specify a subset of a
single table’s column or rows, or can join multiple
tables.

50 / 61
Database Views
! You can then retrieve data from the view the same
way you retrieve data from a table.

! You can use special views called updatable views


(or simple views) to insert, update, and delete
data in the underlying tables.

! A view derives its data from tables called source


tables (or underlying base tables).

51 / 61
Database Views
! When users insert, update, or delete data values in
view’s source tables, the view reflects the updates
as well.

! If a DBA alters the structure of a view’s source


table, or if a DBA drops view’s source table, then
the view becomes invalid and can no longer be
used.

52 / 61
Database Views
! Once you create a view, you can use it to retrieve
rows just as with a table.
◦ This saves you from having to reenter complex query
commands.
● e.g. no need to retype the join or search conditions.

! DBAs use views to enforce DB security by allowing


certain users to view only selected table columns
or rows.
◦ e.g. a specific user might be given privileges to
manipulate few columns only.

53 / 61
Database Views
! Syntax:
CREATE VIEW view_name
AS source_query;

! View_name can’t already exist in the user


DB schema. If there is a possibility that you
have already created a view using a specific
name, use:
CREATE OR REPLACE VIEW view_name
AS source_query;

54 / 61
Database Views
! Once created, you can grant or revoke privileges
to other users to perform operations such as
SELECT, INSERT, or UPDATE.

! When you replace an existing view, you replace


only the view column definitions. All of the existing
object privileges that you granted on the view
remain intact.

55 / 61
Database Views
! When creating an updatable view, the SQL query
has specific restrictions:

◦ The SELECT clause can contain only column names, and


it can’t specify arithmetic calculations or single_row
functions.

◦ The query can’t contain the ORDER BY, DISTINCT, or


GROUP BY clauses, group functions, or set operations.

◦ The query’s search condition can’t contain nested query.

56 / 61
Database Views
! This view contains all of the FACULTY columns
except F_PIN and F_IMAGE

57 / 61
Database Views
! You can use a complex source query to create a
view that contains a listing of the courses being
taught by faculty members for term 6.

! Figure 3-64 (Next Slide)

! This source query contains columns from multiple


tables so it restricts the DMS operations.

58 / 61
Database Views
CREATE OR REPLACE VIEW faculty_teaching AS

SELECT f_last, f_first, course_name


FROM faculty, course, course_section

WHERE faculty.f_id = course_section.f_id


AND course_section.course_no = course.course_no
AND term_id=6
ORDER BY f_last

View created.
____________
Figure 3-64

59 / 61
Database Views
! After creating an updatable view you can use the view to
execute action queries that insert, update, or delete data
in the source tables, as far as you don’t violate any
constraints that exist for the source table. And provided
that you have sufficient object privileges for updating or
deleting rows in the view.

! Example: use FACULTY_VIEW to insert/delete a row into


the FACULTY source table:
INSERT INTO faculty_view VALUES
(6, ‘May’, ‘Lis’, ‘I’, 11, ‘7155552508’,
‘INST’);
DELETE FROM faculty_view WHERE f_last =‘May’;

60 / 61
Example: create a query that joins
FACULTY_VIEW with the LOCATION table

Database Views to list the names of each faculty member,


along with the building code and room
number of the faculty member’s office.

Note that the query to retrieve data from the


view is much simpler than the query to
retrieve the data from the underlying table.

61 / 61
Database Views
! To remove a view from your user schema:
DROP VIEW view_name;

! Dropping a view does not delete the data


values that appear in the view, you drop only
the view definition.

62 / 61

You might also like