Docsity

SQL-Database Management using Database Principles, Programming and Performance-Lecture 02 Notes-Computer Science, Study notes of Database Management Systems (DBMS)

Toggle sidebar
bg1
-1-
Lecture Notes for
Database Management, using
Database Principles, Programming and Performance
Notes by Patrick E. O'Neil
Chapter 3 Idea of SQL. Computerized query language.
IBM developed SQL, and it became standard. Most queries (including updates,
inserts, deletes) are very standard across relational products.
We will only use ORACLE in class to begin with, but will also talk about others.
Try to keep to basic standard for now (called Basic SQL in the text). Will
show some more advanced features of SQL-99 a bit later.
In Appendix A.2, to enter Oracle, tells you to login to UNIX, give command:
%sqlplus
Any problems, contact DBA for course.
You will need to start creating tables. Follow directions in assignment and in
Appendix A.2.
Create table. Result is empty table.
create table customers (cid char(4) not null, cname varchar(13),
city varchar(20), discnt real, primary key(cid));
Names and gives types to each of columns: Explain char(4), varchar(20).
Primary key clause means can't duplicate in table, foreign keys will refer to
this column by default.
Note "not null" is an integrity constraint: must specify value on insert, can't
leave null. More integrity constraints in Chapter 7, on DBA stuff.
Next, load from OS file into table. (Called sqlldr in ORACLE) No-one wants to
type in one line at a time: everything is moved around on tape or disk (say
from one DBMS to another). Note expected format:
c001,TipTop,Duluth,10.00 <-- comma separated, no spaces
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28

Partial preview of the text

Download SQL-Database Management using Database Principles, Programming and Performance-Lecture 02 Notes-Computer Science and more Study notes Database Management Systems (DBMS) in PDF only on Docsity!

Lecture Notes for

Database Management, using

Database Principles, Programming and Performance

Notes by Patrick E. O'Neil

Chapter 3 Idea of SQL. Computerized query language.

IBM developed SQL, and it became standard. Most queries (including updates, inserts, deletes) are very standard across relational products.

We will only use ORACLE in class to begin with, but will also talk about others. Try to keep to basic standard for now (called Basic SQL in the text). Will show some more advanced features of SQL-99 a bit later.

In Appendix A.2, to enter Oracle, tells you to login to UNIX, give command:

%sqlplus

Any problems, contact DBA for course.

You will need to start creating tables. Follow directions in assignment and in Appendix A.2.

Create table. Result is empty table.

create table customers (cid char(4) not null, cname varchar(13), city varchar(20), discnt real, primary key(cid));

Names and gives types to each of columns: Explain char(4), varchar(20).

Primary key clause means can't duplicate in table, foreign keys will refer to this column by default.

Note "not null" is an integrity constraint: must specify value on insert, can't leave null. More integrity constraints in Chapter 7, on DBA stuff.

Next, load from OS file into table. (Called sqlldr in ORACLE) No-one wants to type in one line at a time: everything is moved around on tape or disk (say from one DBMS to another). Note expected format:

c001,TipTop,Duluth,10.00 <-- comma separated, no spaces

c002,Basics,Dallas,12.

You have to create a .ctl table for each table, custs.ctl,... Then use "sql- ldr" command (or sqlload in Oracle version 7) from the UNIX prompt (not from within SQL*PLUS).

After think have table loaded, use the sqlplus command and within that environment type:

select * from customers;\g

Should print out whole table. (* means all columns.)

Chapter 3.3. Simple Select Statements (Basically same as examples in the text, although starts somewhat different.)

Example 3.3.1. Find (JUST) names of agents based in New York.

rel. alg.: (AGENTS where city = 'New York')[aname]

SQL: select aname from agents where city = 'New York';

Keywords: SELECT, FROM (clause), WHERE (clause), end with semi-colon (;).

After SELECT have select list , resulting variables to report: project on.

The FROM clause names tables to take Cartesian product.

The WHERE clause connects and limits rows in Cartesian product. No join. (SQL-92 now allows join operation: Cover later.)

Note duplicate aname values ARE possible. SQL statement above WILL re- port duplicate names (Relational rule broken) unless write:

select distinct aname from agents where city = 'New York';

If want to emphasize that duplicates can arise, give name to default:

select all aname from agents where city = 'New York';

Recall we did: select * from customers; at end of table load.

Conceptual process in Select. (1) Take product of tables in from clause, (2) apply selection in where clause, (3) project on attributes in select-list and report.

But this in not necessarily (usually not) the actual order of events. Query optimization is applied. If customers has 1000 rows, orders 100,000, and products 1000, then Cartesian product has 100 billion rows. But eventual answer will have at most 100,000 rows.

Can make this much more efficient: index customers by cid and products by pid; now go through orders one row at a time and put out cname, pname into temporary file. Finally, sort cname, pname pairs and cast out duplicates.

This is what the query optimizer might do in its query plan. Basically, a query plan is like a program that retrieves the data you want. You don't have to worry about it. Only type SQL, query optimizer makes the program.

Can perform calculations in select.

Example 3.3.5. retrieve a table based on orders, with columns ordno, cid, aid, pid, and profit on order.

select ordno, x.cid, x.aid, x.pid, 0.40(x.qtyp.price)

  • 0.01(c.discnt + a.percent)(x.qty*p.price) as profit from orders x, customers c, agents a, products p where c.cid = x.cid and a.aid = x.aid and p.pid = x.pid;

(Profit is quantity * price, where subtract off 60% of cost, discnt for customer, and percent commission for agent. Expressions allow: +, -, *, / **, and functions: upper( ) or ceil( ) (Oracle, smalles integer greater than float -- functions with numeric arguments are not part of standard).

Without the "as profit" clause, Oracle will head the column with the ex- pression. After clause put in, heading will be "profit" In ORACLE, this is called a column alias, comparable to the way table aliases are created.

In INFORMIX, it is called a "Display Label".

Table alias is also called correlation name (in DB2) and range variable. Sometimes not just shorthand, but necessary, as when join table with itself (need different qualifying names).

Example 3.3.6. List all pairs of customer cids based in the same city.

We have seen this kind of thing before in Rel Alg. Need to report distinct pairs of cid only once.

select [distinct?] c1.cid, c2.cid from customers c1, customers c where c1.city = c2.city and c1.cid < c2.cid;

Note, could be upper case C1 and C2 column aliases; lower case is our general rule, but not crucial; just need to be consistent (case counts).

Do we need to say distinct above, class? (No. Because (c1, c2) is a set of unique pairs. Waste to use distinct when not necessary.)

Alias idea is to make two copies of all content of customers table as c1 and c2; then take Cartesian product, perform selection, and finally report out project onto c1, c2.

But what system really does is (draw customers table, show c1 and c2 as variables ranging over rows, perform nested loop — RANGE VARIABLES):

FOR c1 FROM ROWS 1 TO LAST OF customers FOR c2 FROM ROWS 1 TO LAST OF customers IF (c1.city = c2.city and c1.cid < c2.cid) PRINT OUT SELECT-LIST VALUES: c1.cid, c2.cid END FOR c END FOR c

Once again c1 and c2 do not represent copied tables, but variables taking on row values in the same table! Trick here is to NOT MATERIALIZE THE PRODUCT. And now see why aliases are sometimes called range variables: we can picture them as variables that range over the rows of a table.

select [distinct?] x.pid from orders x where x.aid = 'a06';

Would need distinct if wanted unique x.pid values. Next, customers who order those products:

select distinct y.cid from orders x, orders y NESTED LOOP OF where x.aid = 'a06' and y.pid = x.pid; (SLOW) RANGE VARIABLES

x.pid reports back the first cloud above, and set y.pid = x.pid to get second cloud y.cid.

But an even MORE straightforward way to do that is to use a subquery (Section 3.4):

select distinct y.cid from orders y where y.pid in (select x.pid from orders x where x.aid = 'a06');

The "subquery" retrieves the first cloud, and then the outer select retrieves all y.cid where y.pid is "in" the first cloud.

The condition "in" is an operator expecting a variable on the left and a "set" of values on the right (from a subquery); it is true when the variable on the left is equal to any of the elements retrieved by the subquery.

Of course the outer Select retrieves all rows for which the condition is true.

For the first time, we are using some recursion based on the idea that a select retrieves a table. Now we can operate on that table as a set of rows (or in the case just covered, a set of values).

NOTE : For any type of query we have learned so far, if we can do it with join we can do with subquery and vice-versa. Subqueries are supposed to give a slightly more natural approach to some queries. BUT I will insist that you be able to translate Subqueries to joins in most cases.

Example 3.4.1. Retrieve cids of customers who place orders with agents in Los Angeles or Dallas. First find all agents in LA or Dallas, and make that a subquery:

select cid from orders where aid in (select aid from agents where city = 'Los Angeles' or city = 'Dallas');

Note don't need to qualify aid in subquery use or outside subquery: in each case there is only one table that is natural.

Conceptually, innermost subquery operates first, returns a set of values, then outer select runs through customer rows and tests whether cid is in this set. In fact that might NOT be the way it is done by the system (after query optimization). Equivalent to:

select [distinct?] x.cid from orders x, agents a where x.aid = a.aid and (a.city = 'Los Angeles' or a.city = 'Dallas');

Why ( )s? Because of order of operations: p and q or r is (p and q) or r, but that isn't what we want; want p and (q or r).

Otherwise, if r were true for any p, q, whole statement true; then if agents has some agent in Dallas, will get all cids reported (won't need x.aid = a.aid).

Skip a few simple examples. In particular, can construct your own set using a condition such as:... where... city in ('Duluth', 'Dallas'). Of course we could also do this using or,

All these variant ways of doing things don't necessarily help — just make user uncomfortable about having a complete grasp of the SQL syntax.

OK, now idea of correlated subquery. Recall in 3.4.1 didn't need qualified names because rows had natural home. But can refer to OUTER range vari- able from INNER subquery.

Example 3.4.4. (Variant) Find names of customers with discnt >= 10 who order product p05. To illustrate a point, using subquery:

select cname from customers where discnt >= 10 and 'p05' in (select pid from orders where cid = customers.cid);

Yes, unusual to say where in subquery (looks like a typo), but per- fectly valid and as long as condition is true will retrieve cname.

Note that in subquery, the cid without a qualifier has home qualifier of or- ders, while customers.cid harks back to outer select. As if we wrote:

FOR c FROM ROW 1 TO LAST OF customers discard c if c.discnt < 10

select cid from customers where cid not in (select cid from orders where orders.aid = 'a03'); /* example of minus operator */

Example 3.4.6. In older products, IN predicate only works for single values. Can't have condition "... where (cid, aid) in (select cid, aid from orders"...

This is part of the full SQL-92 standard (Note need (,)), and Oracle permits i t.

Quantified Comparison Predicates. List:

= s o m e < > s o m e < = s o m e > s o m e < s o m e > = s o m e = a n y < > a n y < = a n y > a n y < a n y > = a n y = a l l < > a l l < = a l l > a l l < a l l > = a l l

If comparison operator ∝ stands for operator in the set {<, <=. =, <>, >,

=},

v ∝some (subquery) is TRUE iff v ∝ s for some s in the subquery v ∝any (subquery) is TRUE iff v ∝ s for some s in the subquery v ∝all (subquery) is TRUE iff v ∝ s is true for all s in the subquery.

∝some and ∝any mean same thing: ∝some is easier to remember.

Example 3.4.7. Find aid values of agents with a minimum percent com- mission. This was HARD in relational algebra. Now easy.

select aid from agents where percent <= (select percent from agents);

Class 8.

Exam 1 on Class 13 Responsible for most of Chapter 3.

OK, last time talking about Quantified Comparison Predicates Some, Any, or All. (You are responsible for this nomenclature, here and as in book.)

Example 3.4.8. Find all cids of customers who have the same discount as any customer in Dallas or Boston.

select cid from customers where discnt =some (select discnt from customers where city = 'Dallas' or city = 'Boston');

OK, =some same as =any or in. Could do away with in. But <some, etc. new.

New Example. Find cids of customers who do not place any order through agent 'a03'. Used not in, above:

select cid from customers where cid not in (select cid from orders where orders.aid = 'a03');

Since =any is same as in, is it true that <>any is same as not in?

select cid from customers where cid <>any (select cid from orders where orders.aid = 'a03');

NO! Doesn't work! <>any is true if cid = 'c001' and subquery is {'c001', 'c003'}. There IS ONE value it is not equal to. Really mean <>all. The re- verse of =any is <>all. Exercise on this.

By the way, what do you think happens if you write:

select cid from customers where cid <> (select cid from orders where orders.aid = 'a03');

Just <>, not <>any or <>all? Does it even make sense if single value on left, set on right? Answer is, perfectly legal if set on right contains exactly one element. Otherwise, runtime error.

By the way, what happens if cid >= subquery, and subquery is an empty set? Is the result TRUE or FALSE? The answer is, result is UNKNOWN: almost like false, but not quite. More later.

This basically means that to use the form "Exists" is unnecessary. Don't use Exists if don't need it.

not exists, on the other hand, is a different matter.

Example 3.4.12. Retrieve all customer names where the customer does not place an order through 'a05'. Recall that this doesn't work:

select c.cname from customers c, orders x where not (c.cid = x.cid and x.aid = 'a05'); ***** WRONG EFFECT *****

Because customers c where c.cid = 'c001' and orders x where x.cid = 'c001' and x.aid = 'a01', so condition is false, not is true, and 'c001' is retrieved. But c001 does order through a05.

THERE IS NO WAY TO DO THIS WITHOUT A SUBQUERY! Want:

select c.cname from customers c where not exists (select * from orders x where c.cid = x.cid and x.aid = 'a05');

Recall we did something like this above also, with not in:

select cname from customers where cid not in (select cid from orders where aid = 'a05');

Is not exists more powerful than not in?

Example. Find all cid, aid pairs where the customer does not place an order through the agent:

select cid, aid from customers c, agents a where not exists (select * from orders x where x.cid = c.cid and x.aid = a.aid);

Note not in USED TO assume a simple value, so couldn't write:

select cid, aid from customers c, agents a where (cid, aid) not in (select cid, aid from orders x);

As a result, not exists was able to do things not in wasn't. But this is no longer true (SQL-92, Oracle V7.1,.. .)

Section 3.5. How to do FOR ALL (Very Hard) and Union (easy)

Example 3.5.2. Find cids of customers who place orders with ALL agents based in New York. In rel alg:

ORDERS[cid, aid] DIVIDEBY (AGENTS where city = 'New York')[aid]

Harder in SQL. Formulate as follows.

Want to retrieve cid such that FOR ALL agents based in New York, there EXISTS an order connecting cid to agent.

But we don't have a FORALL predicate. If we did, we'd like to write in SQL:

select cid from customers c where FORALL(select aid from agents a where city = 'New York', EXISTS(select * from orders x where x.aid = a.aid and c.cid = x.cid));

Where FORALL(subquery, condition) is true iff for all elements in the sub- query, the condition is true. (Being explicit about EXISTS here for a reason.)

OK, no FORALL predicate, so instead have to use a trick. FORALL (x, p) is equivalent to NOT EXISTS (x, NOT p) (there is no counterexample which would cause FORALL to fail).

In our case, we have FORALL(x, EXISTS (y, p)) is equivalent to NOT EXISTS (x, NOT EXISTS (y, p)). So statement above becomes:

select cid from customers c where not exists (select aid from agents a where city = 'New York' and not exists (select * from orders x where x.aid = a.aid and c.cid = x.cid));

Look at form above again for FORALL. In general, queries which obey a FORALL condition, have this form:

select... where not exists( select... where not exists( select... );

Hardest query you will be asked to pose. Last hard trick need to finish homework.

(2) Select all counter examples. Start you off:

select pid from orders x where x.cid = 'c006' and -- products ordered by 'c006' and (Class?) not exists (select * from orders y where x.pid= y.pid and y.cid= ?.cid);

(3) OK, now say no counter-example exists: not exists (subquery above)

(4) Let the row we want to retrieve be range variable in outer select with no counter-examples. (Usually choose range variable in smallest table.)

select c.cid from customers c where not exists (select pid from orders x where x.cid = 'c006' and not exists (select * from orders y where x.pid = y.pid and y.cid = c.cid));

OK, subtraction and union in Section 3.5 are very easy. Next time I will go on to 3.6.

Class 9.

Next hw, all undotted exercises through end of Chapter 3. Due class 13.

Exam 1, Class 14. Responsible for ALL of Chapter 2 and 3 (except no detail on Chapters 3.10 and 3.11 — Responsible for all homework and concepts covered in class).

Section 3.

Start with Union, Difference, Intersect: how to do in SQL. We intend to add new operators to perform these operations in this Section. Already covered Union in Section 3.5.

These operators are NOT uniformly available in the different products.

New Example. List all cities that contain the products costing less than $1.00 or that contain agents who have made no sales.

It is easy to get cities associated with products or cities associated with agents. But you should see that no simple query of the form:

retrieve x.city from table1 x, table2 y,...

Is going to work, since x.city comes from one table only. Might conceivably do this by retrieving:

retrieve x.city, y.city from table1 x, table2 y,...

But then will be retrieving pairs, and that messes us up. What will we retrieve if there are NO cities of the second kind? (Class?) Nothing.

This is easy using UNION of relational algebra, and it turns out that standard SQL has a union form THAT ALL VENDORS HAVE IMPLEMENTED. Answer

select city from products where price < 1. union select city from agents where aid not in (select aid from orders);

Now consider the Subquery form. Two forms only, Subquery and Select statement. Subquery is a select sql syntax that will go in (subquery).

Recall, idea of too many equivalent forms. This makes it worse. ALL is a new capability, but is it ever wanted?

How would we implement "intersect"? Get list of cities that contain products AND agents.

select city from products where city in (select city from agents);

With use of INTERSECT, this becomes:

select city from products intersect select city from agents;

The CORRESPONDING clause is used to select a set of equivalently named columns on which to perform intersection (lazy about select_list).

OK, now expanded definition of FROM Clause. SQL-89 Definition was:

from tablename [[AS] corr_name] {, tablename [[AS] corr_name]...}

Implementation of these operators.

ORACLE Release 8 provides UNION, UNION ALL, INTERSECT and MINUS (variant of EXCEPT), but not INTERESECT ALL or MINUS ALL and provides no CORRESPONDING Clause.

DB2 Universal Database, Version 5, implements {UNION | INTERSECT | EXCEPT} [ALL], but no CORRESPONDING Clause.

INFORMIX basically implements only UNION [ALL] and recommends workarounds for the other operators.

To define SQL-92 FROM Clause general form, start with def of tableref:


tableref::= tablename [[AS] corr_name] [(colname {, colname ...})]] | (subquery) [[AS] corr_name] [(colname {, colname ...})] | tableref1 [INNER | {LEFT | RIGHT | FULL} OUTER ] JOIN tableref [ON search_condition | USING (colname {, colname.. .})]

FROM clause ::= FROM tableref {, tableref.. .}

Figure 3.11 SQL-99 Recursive tableref Definition

Note that tableref is recursive: tableref can be any kind of join of two tablerefs.

Let's start with the fact that one can Select FROM a Subquery.

Example 3.6.3. Retrieve all customer names where the customer places at least two orders for the same product. Here's a new way:

select cname from (select o.cid as spcid from orders o, orders x where o.cid = x.cid and o.pid = x.pid and o.ordno <> x.ordno) as y, customers c where y.spcid = c.cid;

Note alias y for Subquery, alias spcid for column o.cid.

Foreshadowing in this query form of something called Views.

Next, talk about the various Join operators on lines 3 & 4 (and 5)

Can say: tableref1 CROSS JOIN tableref

select cname from customers c cross join orders o where...

Same effect as

select cname from customers c, orders o where...

OK, now if we only use the JOIN keyword in the general form above, we can use one of the forms on line 5, either the ON search_condition or USING.

We call it a condition join when two different named columns are to be compared in an ON clause. E.g. if had cities table with columns named cityname, latitude and longitude, could write:

select city, latitude, longitude from customers c join cities x on (c.city = x.cityname);

OK, next is NATURAL JOIN.