Download presentation
Presentation is loading. Please wait.
Published bySamson Oliver Modified over 6 years ago
1
Lecture 3 SQL Relational Algebra Aggregate Operators
GROUP BY and HAVING Arithmetic, AS in SELECT DDL Set theory operators in SQL Subqueries Relational Algebra Join queries Set queries Rename operator Divide operator 12/7/2018
2
Learning Objectives LO2.1 Write SQL queries involving GROUP BY and HAVING. LO2.2 Write an SQL query involving set operators. LO2.3 Write an SQL query involving a subquery. LO2.4 Tell whether an SQL subquery is correlated. LO2.5 Write join queries in relational algebra LO2.6 Write set operator queries in relational algebra 12/7/2018
3
Aggregate Operators Let's return to the cl tables in your handout.
Find the number of donations, the largest, the smallest and the average donation. SELECT COUNT(*), MAX(amount), MIN(amount), AVG(amount) FROM indivcl; round(AVG(amount),2) will get rid of all those significant digits. count max min avg 12/7/2018
4
Aggregates with DISTINCT*
What is the difference between SELECT COUNT(street1) FROM commcl; and SELECT COUNT(DISTINCT street1) FROM commcl; The difference is that the first query will retrieve the number of street1 addresses, which is the same as the number of committees. The second will retrieve the number of distinct addresses, which, as you can see, is much less. 12/7/2018
5
Bad SQL* What are the occupations of donors who gave the highest donations? This SQL doesn't make sense because the query processor has no way to know which values of occup to list with the MAX value of amount. What if the aggregate function were AVG? So if one aggregate operator appears in the SELECT clause, then ALL of the entries in the select clause must be aggregate operators (unless the query includes a GROUP BY clause - covered next). SELECT occup, MAX(amount) FROM indivcl; AVG has the same problem – there may be no one, or more than one donor, who gave the average donation. 12/7/2018
6
French Fries Warmup-1* What is the largest donation for each month?
Month MAX(amount) STRATEGY: First GROUP the rows by month, then SELECT the month and MAX size NOTE: “each month” GROUP BY month 12/7/2018
7
GROUP BY Here is the SQL for that query: SELECT month, MAX(amount)
3 For each month, compute the values in the SELECT clause FROM indivcl 1 Gather rows from indivgb GROUP BY month 2 Create groups, one for each GROUP BY value 12/7/2018
8
French Fries Warmup-2* For each committee that has less than five donations of over $200, what is the total number of donations for that committee? committeeid SUM(amount) C C STRATEGY: First keep donations > $500, then GROUP BY commitee, then keep the groups HAVING < 5 distinct donations, then SELECT the committeeid and total donations. NOTE: Did you include the committeeid in the answer? 12/7/2018
9
SQL for this query: HAVING
SELECT commid, SUM(amount) 5 For each committee, compute the values in the SELECT clause FROM indivgb 1 Gather rows from indivgb WHERE amount > 200 2 Keep rows satisfying the WHERE condition GROUP BY commid 3 Create groups, one for each GROUP BY value HAVING COUNT(*) > 5; 4 Keep groups satisfying the HAVING condition 12/7/2018
10
Practice Group By/Having*
Back to the indivcl on your handout. What is the SQL for: For commitees that received at least three donations in March, how many donations did they receive? SELECT commid, COUNT(*) FROM indivcl WHERE month = 3 GROUP BY commid HAVING COUNT(*) > 2; Notice that the WHERE clause, keeps rows, whereas the HAVING clause, keeps groups. It is easy to confuse these two clauses, so keep in mind that one keeps rows, the other keeps groups. 12/7/2018
11
12/7/2018
12
LO2.1: GROUP BY/HAVING Consider only donations in February and March. For each committee that had at least $2500 in donations, display that committee's range* of donations. *range = highest - lowest 12/7/2018
13
Arithmetic and AS in SELECT
SELECT commcl.commid, commname, MAX(amount) - MIN(amount) AS Range Arbitrary arithmetic is possible in the SELECT clause. AS is used to label output columns. FROM commcl JOIN indivcl USING (commid) WHERE month = 2 OR month = 3 donations in February and March GROUP BY commcl.commid, commcl.commname commname must be here to be in the SELECT clause HAVING(SUM(amount)>=2500); any group condition can be in the HAVING clause 12/7/2018
14
NULLs and Aggregates The value NULL is ignored by all aggregate functions. COUNT, SUM, AVG all ignore it, and it cannot be the MIN or MAX. COUNT(*) is the number of rows but COUNT(att) is the number of rows with non-null att values. However, if you GROUP BY an attribute, a separate group is created for NULL values of the attribute. So you don't like NULL and vow never to insert NULL values in your database? Sorry. If you aggregate (except count) over an empty table, you get NULL. There's no way to avoid it. 12/7/2018
15
Return to DDL: Populating a Database
Recall that SQL consists of DDL and DML. We've been learning DML. Let's digress for a bit and learn some more DDL, by reviewing the code for populating the PostgreSQL database we're using. Related to ETL in data warehousing Populating a database consists of these steps (my files) 0. Format and clean the data (u2uc) Create the schema (Tables.sql) Copy the data into the database (cs) Create structures and other tables (DDL.sql) 12/7/2018
16
0. Format and clean the data (u2uc)
The first step does not involve DDL The shell script u2uc prepares files for copying into PostgreSQL. unzip: decompress FEC compresses the data for faster data transfer and cheaper storage dos2unix: remove carriage return The parameter -437 suppresses an error message pit: C program to insert delimiter | between fields split : writes a file into line pieces (xaa,xab,…) so it can be edited u2uc Document in 12/7/2018
17
1. Create the schema (Tables.sql)
The next step is to create schemas for all the FEC tables. This is done in Tables.sql . Note these DDL statements: DROP TABLE [IF EXISTS] tablename; CREATE TABLE tablename ( [ attributename domain [ [NOT] NULL], ….] ) For domains see CREATE TABLE has many other options, see documentation. As we have discussed, for efficiency reasons, we don't use any of those other options until after the copy step. Tables.sql Document in 12/7/2018
18
Sidebar on DROP DROP TABLE tablename; is not the same as
DELETE FROM tablename; The former deletes the table's rows and all its structure – it no longer exists. The latter just deletes the rows. There is a shorter way to delete the rows: TRUNCATE tablename; DROP applies to many objects: databases, schemas, constraints, views, etc, and these depend on each other. So SQL3 requires that you specify either CASCADE or RESTRICT, though no DBMS does. CASCADE: drop everything that depends on it. For example, a foreign key dependency RESTRICT: if anything depends on it, do not execute the command (typically the default). 12/7/2018
19
2. Copy the data into the database (cs)
There are two COPY commands in PostgreSQL, one in SQL and another in psql. psql executes in the address space of the DBMS We use the psql version because CAT's databases are on a remote server. The COPY commands are invoked from a shell script, cs, which takes as a parameter part of the name of the database, e.g., $ cs 386 Note that blank princomm or assoccand values are changed to NULL. cs Document in 12/7/2018
20
3. Create structures and other tables (DDL.sql): INTO, IN
Now that we have copied data into the database, we use ALTER TABLE to change the database schema, and SELECT … INTO to create new tables. First we ALTER TABLE tablename DROP column; to get rid of filler columns. We will discuss the stored procedure next week; Skip to Oregon versions. Notice INTO…. , which can appear after any SELECT clause. INTO creates a new table with attributes from the SELECT clause. An error is raised if a table with that name exists. Results are not returned to the user. DDL.sql Document in 12/7/2018
21
DDL.sql, Ctd. In the in class versions, notice the use of IN. It can be used in any WHERE clause IN is true when the left side is contained in the right side Notice how a primary key constraint is declared Recall that those columns were declared NOT NULL in the CREATE TABLE statements. Why do we give a name to the constraints? Can easily DROP them or ALTER them later. Notice the foreign key constraints, which we have discussed. 12/7/2018
22
Set Operators in SQL We now turn to set operators in SQL: UNION, INTERSECT, Difference (in SQL this is called EXCEPT or MINUS). Suppose A, B are sets. What is the definition of A UNION B, A∪B? A INTERSECT B, AB? A MINUS B, A – B? You've seen these operators in CS250, but here they operate on multisets. So they come in two versions. UNION, INTERSECT and EXCEPT/MINUS eliminate duplicates. Each of them with ALL preserve duplicates. Let's see how they work. 12/7/2018
23
UNION Let’s consider the entire FEC data: cand, comm, indiv, pas.
Suppose I have a table indivlast, leftover from the last time I taught the course, representing donations from the 2006 election. I want to combine it with indiv and display all the results. The proper SQL to do that is: SELECT * FROM indiv UNION SELECT * FROM indivlast The UNION appears between any two SQL statements. The output of the SQL statements must be UNION-Compatible: Domains of corresponding attributes must be the same Names don't need to be the same. The names of the first table are used in the output. SELECT * from indivcl UNION SELECT * FROM commcl is illegal. 12/7/2018
24
Surprise! (UNION ALL) Suppose we want to simplify the result by omitting the date: SELECT fecid,commid,occup,month,amount FROM indivlast UNION SELECT fecid,commid,occup,month,amount FROM indiv We'll be surprised to learn that this time we have fewer donations! UNION eliminates duplicates. To avoid duplicate elimination, use UNION ALL. 12/7/2018
25
Subquery in FROM Clause
The previous UNION statements have displayed results on the screen. Suppose I want to place results in indivnew. SELECT * INTO indivnew FROM ( (SELECT * FROM indiv) UNION (SELECT * FROM indivlast) ) AS indiv_union; Note the "subquery" in the FROM clause, enclosed in parens. Any expression, whose result is a table, is legal as a term (comma-separated) in the FROM clause. SQL requires a range variable after a FROM subquery. Subquery 12/7/2018
26
INTERSECTION* Is this query legal?
SELECT princomm FROM candcl WHERE party = 'REP' INTERSECT SELECT commid FROM indivcl where month = 1; Identify one row in the answer to this query. Describe, in nontechnical English, what this query produces: INTERSECT eliminates duplicates, but INTERSECT ALL will retain them. It is legal because the SQL statements are union-compatible. Each outputs committee-ids, with the same domains. The answer to the query is: princomm C The principal committees of Republican candidates that received donations in January 12/7/2018
27
EXCEPT (or MINUS)* Identify one row in the answer to this query.
In nontechnical English, what does this query retrieve? SELECT commid FROM commcl EXCEPT SELECT commid FROM indivcl WHERE month=2; EXCEPT eliminates duplicates, but EXCEPT ALL will retain them The answer to this query is: Commid C C C C C C C C C C C C C C The query retrieves committees that did not receive a donation in February 12/7/2018
28
Example* In indivcl, which unique committees received donations in January OR in February? Write the answer in three different ways, one with and two without a set operator. Order the results by commid. SELECT DISTINCT commid FROM indivcl WHERE month = 1 OR month = 2 order by commid; WHERE month IN {1,2} SELECT commid FROM indivcl WHERE month = 1 UNION SELECT commid FROM indivcl WHERE month = 2 12/7/2018
29
LO2.2: Example* In indivcl, which unique committees received donations in January AND in February? Write the answer in two different ways, with and without a set operator. SELECT DISTINCT i1.commid FROM indivcl i1, indivcl i2 WHERE i1.commid = i2.commid AND I1.month = 1 AND i2.month = 2 ; SELECT commid FROM indivcl WHERE month = 1 INTERSECT SELECT commid FROM indivcl WHERE month = 2; 12/7/2018
30
SUBQUERIES (in the WHERE Clause)*
The circled expression, a complete SELECT..FROM..WHERE query, is called an inner block or subquery. The rest is the outer block. Describe what this query retrieves. Hint: First figure out what the subquery retrieves. Note that the scope of the range variable in the subquery overrides that of the outer query. SELECT occup FROM indivcl WHERE amount = (SELECT MAX(amount) FROM indivcl) How would you execute this query? English: What are the occupations of the donors who gave the highest donations? Execute: replace subquery with constant, then execute result query. 12/7/2018
31
LO2.3:Practice Subqueries*
Write the SQL to return the occupations of donors who gave donations (at any time) of at least $500 more than the minimum donation given during March. SELECT occup FROM indivcl WHERE amount >= 500 + (SELECT MIN(amount) FROM indivcl where month = 3); 12/7/2018
32
IN and subqueries You've seen IN, in the definition of the cl tables, e.g.: SELECT candid, candname, party, street1, princomm INTO candcl FROM cand WHERE candid IN ('P ', 'P ' , 'S6OR00094' , 'S8OR00207') ; IN can also precede a subquery: SELECT commname FROM commcl m WHERE m.commid IN ( SELECT i.commid FROM indivcl i WHERE amount > 1000); What does this query return? How would you execute this query? NOT IN is also legal in a query Query returns names of committees that received a donation over $1000. Execute it by replacing the subquery with a set of commids, then executing the resulting query, which will look like the previous one. 12/7/2018
33
LO2.4:Unnesting/Flattening a Query*
Queries with subqueries are called nested queries. Often they can be rewritten as flat queries. This typically makes them much faster to execute Can you write a flat version of the previous query? SELECT commname FROM commcl m WHERE m.commid IN ( SELECT i.commid FROM indivcl I WHERE amount > 1000); Hint: Think of what it returns, then write that query. Why do you need DISTINCT in the flat version? Often the nested version is easier to write. names of committees that received a donation over $1000 SELECT DISTINCT commname FROM commcl JOIN indivcl USING(commid) WHERE amount > 1000; 12/7/2018
34
EXISTS* What does this query return? SELECT N.candname FROM candcl N
WHERE EXISTS ( SELECT * FROM commcl M WHERE M.assoccand = N.candid AND M.street1 LIKE '228 S WASHINGTON ST%'); How would you execute this query? Because of N.candid, you cannot substitute a constant for the subquery Such a query is called correlated. Returns names of candidates that have at least one associated committee whose address begins 228 S WASHINGTON ST You can execute this query using what it called tuple-at-a-time semantics: For each row N in candcl, execute the subquery, which will return a single value. Then execute the entire query. 12/7/2018
35
Review, Preview We are working with structured data, modeled with the relational model. Databasics Anonymous 7-step method: Organizing structured data into an ER Diagram, Ch. 2 Transforming an ER diagram into a Schema of Tables, Ch. 3 Eliminating anomalies from those tables (normalization), Ch. 21 Structuring those tables efficiently (physical design), Ch. 22 Managing those tables using the intergalactic standard language (SQL), Ch. 5 The DBMS manages the tables internally using Relational Algebra, Ch. 4 Protecting those tables during concurrent use (ACID properties), Ch. 16 Accessing those tables through a web-based interface (some scripting language) Now we continue step 5 and study Relational Algebra. Done Done Next 12/7/2018
36
(R)DBMS Architecture Security Parser Catalog Optimizer Concurrency
Web Form Applic. Front end SQL interface SQL Security Parser Catalog Relational Algebra(RA) Optimizer Executable Plan (RA+Algorithms) Concurrency Plan Executor Files, Indexes & Access Methods Crash Recovery Database, Indexes 12/7/2018
37
Relational Algebra: 5 Basic Operations
Select() Selects a subset of rows from a table (horizontal) Project() Selects a subset of columns from a table (vertical) Cross-product() Computes all combinations from two tables Set-difference () Rows in table1, not in table2 Union () Rows in table1 and/or in table2 12/7/2018
38
Algebra Relational Algebra is an algebra of operators on tables
Input is (a) table(s), output is a table Just as plus, minus, multiply, divide are an algebra of operators on numbers Since each relational algebra operation produces a table, the relational algebra is closed. 12/7/2018
39
Select () Consider the indivcl table in the handout. Suppose we want to find donations of more than $2000. We construct the answer with the query amount > 2000 indivcl, whose output is fecid commid occup month amount C PACIFIC CREST/PRINCIPLE C SELF-EMPLOYED 12/7/2018
40
Examples using the Select Operator*
How many rows are in the output of each query? amount <= 225 indivcl (amount > 2000) (commid=‘C ’) indivcl (commid=‘C ’) (amount > 1000) indivcl Is there a simple way to calculate this? (amount > 1000) ( (commid=‘C431445’) indivcl ) The predicate amount <= 225 indivcl [3] (amount > 2000) (commid=‘C ’) indivcl [6] (commid=‘C ’) (amount > 1000) indivcl [0] Is there a simple way to calculate this? (amount > 1000) ( (commid=‘C431445’) indivcl ) [0] An algebraic expression 12/7/2018
41
Project operator () in relational algebra
Which committees received donations from in the period January-April 2008? commid(indivcl) This query will produce 21 rows, with many CommIDs repeated – like the Recipient table we saw previously. 12/7/2018
42
The Project operator in the the Relational Model and in DBMSs
The project operator in the relational model operates on relations (sets), so the project operator in the relational algebra eliminates duplicates. But the project operator in DBMSs, operating on tables/multisets, does not eliminate duplicates. In this class we will study relational algebra on tables, so project does not eliminate duplicates. 12/7/2018
43
Smart question At this point some smart person in class will ask: in DBMSs, how do you eliminate duplicates from a multiset of data items? There is a duplicate elimination operator. It is a terribly important, and expensive, operator, like sorting, but it changes only the presentation properties of the data. We will introduce these two operators later, when we talk about algorithms for RA operators. 12/7/2018
44
Practice with , * Show the IDs of our 4 candidates and their principal committees Show the occupations of donors who donated at least $500 Show the committees that received donations of more than $200. Show the IDs of our 4 candidates and their principal committees candid,princommcandcl Show the occupations of donors who donated at least $500 occup(amount>=500indivcl) Show the committees that received donations of more than $200. commid(amount>200indivcl) 12/7/2018
45
occup(amount < 1000indivcl)
Equivalent Queries* Describe in English the output of this query occup(amount < 1000indivcl) Which of these queries is equivalent to the above query, i.e. gives the same output for all table instances? amount < 1000( occup, amountindivcl) amount < 1000( occupindivcl) occup(amount < 1000( occup, amountindivcl)) Describe in English the output of this query occup(amount < 1000indivcl) Occupations of of donors who donated less than $1,000 to some committee. Which of these queries is equivalent to the first query, i.e. gives the same output for all table instances? amount < 1000( occup, amountindivcl) Not equivalent. Has an extra attribute amount < 1000( occupindivcl) Not equivalent. Not well formed occup(amount < 1000( occup, amountindivcl)) Equivalent 12/7/2018
46
The Cross Product Operator,
All our previous operators are unary operators, they operate on one table. The cross product operator is our first binary operator and is fundamental to most other binary operators. T1 T2 is every possible combination of rows from T1 and T2. For example T1 T2 candid candname P MCCAIN, JOHN S. P OBAMA, BARACK S6OR SMITH, GORDON S8OR MERKLEY, JEFFREY commid commname C REPUBLICAN NATIONAL COMMITTEE C DEMOCRATIC NATIONAL COMMITTEE T1T2 candid candname commid commname P MCCAIN, JOHN S. C REPUBLICAN NATIONAL COMMITTEE P OBAMA, BARACK C REPUBLICAN NATIONAL COMMITTEE S6OR00094 SMITH, GORDON C REPUBLICAN NATIONAL COMMITTEE S8OR00207 MERKLEY, JEFFREY C REPUBLICAN NATIONAL COMMITTEE P MCCAIN, JOHN S. C DEMOCRATIC NATIONAL COMMITTEE P OBAMA, BARACK C DEMOCRATIC NATIONAL COMMITTEE S6OR00094 SMITH, GORDON C DEMOCRATIC NATIONAL COMMITTEE S8OR00207 MERKLEY, JEFFREY C DEMOCRATIC NATIONAL COMMITTEE 12/7/2018
47
The Join Operator, ⋈ Joining condition
Suppose we want to list each candidate’s name along with his/her principal committee’s name. We want to combine a candidate row n in candcl with a committee row m in commcl if n.princomm = m.commid Try it on a few row pairs (n,m). The notation for the required query is: candname, commname( candcl ⋈ princomm=commid commcl ) And its output is: Joining condition candname commname MCCAIN, JOHN S. JOHN MCCAIN 2008 INC. OBAMA, BARACK OBAMA FOR AMERICA SMITH, GORDON FRIENDS OF GORDON SMITH MERKLEY, JEFFREY JEFF MERKLEY FOR OREGON 12/7/2018
48
commname, candname(commcl ⋈ assoccand=candidcandcl)
LO2.5 Practice with Join* Describe in English what this computes: commname, candname(commcl ⋈ assoccand=candidcandcl) Write a query describing, for each donor, the occupation of the donor and the name of the candidate to whom he/she donated. The query computes: The name of each committee with its associated candidate’s name The requested query is: occup, candname((indivcl ⋈commid=commidcommcl) ⋈ assoccand=candidcandcl) 12/7/2018
49
Join as a derived operator
Is it possible to derive the join operator from other operators that we have seen? That is, could you express every join query in terms of previous operators we have seen? T1 ⋈joincondT2 joincond ( T1 T2) Note that this is valid for every table T1 and T2 and every join condition “joincond”. Thus the join operator is not one of the original five operators in the relational algebra. 12/7/2018
50
Foreign Key Joins Almost every join used in the real world is a foreign key join, in which the join condition is "a foreign key equals the key it refers to". That is the main reason it helps to draw a picture of a schema with arrows pointing from foreign keys to the keys they refer to; many software tools will do this automatically. Such a diagram (which looks like but is not the same as an ER diagram) can be very helpful in formulating join queries. That's why I gave you the file to help you in homework 2. 12/7/2018
51
Seldom used Flavors of Join
The join operators we use are called equijoins since the join conditions are equalities between attributes, typically a foreign key to the key that it references. There are 2 other kinds of joins that are seldom used. One is inequalities between attributes, called theta-join or θ-join. Those of you who have used databases: have you ever seen one? Here’s an example. What does it compute? commid, commid(indivcl ⋈ amount<amountindivcl) 12/7/2018
52
Natural Join Another seldom used flavor of join (in practice, though it is important in theory) is the join operator ⋈ without any subscript, called a natural join. To make this work, you give foreign keys the same name as the key they refer to. Here’s an example, with the foreign keys in italics: newcandcl( candid, candname, party, street1, commid) newcommcl( commid, commname, address, candid) newindivcl( fecid, commid, occup, month, amount) The natural join newindivcl ⋈ newcommcl will combine each donation with the committee donated to. There are four reasons the use of natural join is discouraged : It does not permit the use of meaningful attribute names like candcl(princomm) or commcl(assoccand) . If you add a new attribute, it may break existing code. Sometimes a natural join does not give what is intended. For example, what will the query newcandcl ⋈ newcommcl produce? 4. It's hard to distinguish between a natural join and a join without conditions. 12/7/2018
53
Set Operators in Relational Algebra
Set Operators (Union, difference, intersect) in relational algebra are very similar to SQL's set operators. Their operands must be union-compatible, that is, have the same domains in corresponding attributes, though not necessarily the same names. 12/7/2018
54
The Union Operator Suppose indivlast represents donations from 2006, and we want to form the table of 2006 and 2008 donations. The natural operator is Union: indivcl indivlast The Union operator, in the relational model and in DBMSs, eliminates duplicates. 12/7/2018
55
The Difference Operator *
Write the RA expression that lists the committees that did not receive donations. commidcommcl commidindivcl 12/7/2018
56
The Intersect Operator *
R intersect S, RS, is the rows that are in R and S. Like join, intersect adds no computational power to the five basic relational algebra operators, because R S = R (R S) What is the meaning of this query? princommcandcl commid(amount>500 indivcl) Which principal committees have received at least one donation of more than $500? 12/7/2018
57
LO2.6 Practice* What are the occupations of donors who have given at least one donation of > 500 and at least one donation of <500? What are the IDs of Committees who have received at least one donation > 1000 and at least one donation < 250 but whose street1 is not ‘228 S WASHINGTON ST’? occup(amount>500 indivcl) occup(amount<500 indivcl) --This is not quite right. Do you see why? The difficulty arises because occupation is not a key. So it is possible that there are two different donors with the same occupation. One gives a large donation, the other gives a small donation. But their common occupation still ends up in the answer. ( Commid(amount>1000 indivcl commid(amount<250 indivcl)) – commid (street1=‘228 S WASHINGTON ST’ commcl) 12/7/2018
58
ρ(temp, commID (street1=‘228 S WASHINGTON ST’ commcl))
The Rename Operator ρ Our relational algebraic expressions will soon get too complex to put on one line, or to formulate in one step. The rename operator ρ allows us to form temporary tables. ρ(temp, commID (street1=‘228 S WASHINGTON ST’ commcl)) This places the result of the query into the table named temp. 12/7/2018
59
ρ( B, princomm (party='DEM' candcl))
The Divide Operator A(x,y) B(y) is all values of x such that (x,y) is in A for every value of y in B. What are the occupations of donors who have given to the principal committee of every democratic candidate? First form the principal committee of every DEM candidate: ρ( B, princomm (party='DEM' candcl)) Now form the occupations and committees of donors: ρ( A, commid,occup (indivcl)) and calculate the results A B princomm C C 12/7/2018
60
Divide as a derived operator
Division is another operator that can be derived from the five basic operators, but is useful for logic applications. Idea: For R(x,y) S(y), compute all x values that are not “disqualified” by some y value in S. x value is disqualified if for some y value in S, (x,y) is not in X Disqualified x values: x((x(R) S) R) R S = x (R) disqualified x values 12/7/2018
61
Division in SQL Find account owners who own all types of accounts
SELECT A1. Owner FROM Account-owner A1 WHERE NOT EXISTS ( SELECT T.Type FROM Account-types T SELECT A2.* FROM Account-owner A2 WHERE A2.Type=T.Type AND A2.Owner=A1.Owner)) Find owners A1 such that There is no account type T That A1 does not possess 12/7/2018
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.