Introduction! Select-From-Where Statements! Queries Over Several Relations! Subqueries!
Introduction! Select-From-Where Statements! Queries Over Several Relations! Subqueries!
Expresses what to do rather than how to do it.! Avoid a lot of data-manipulation details needed in procedural languages like C++ or Java.! Called query optimization. !
database.!
But SQL also includes a data-denition component for describing database schemas!
varying feature sets from later standards and special proprietary features. !
Allows the specication of not only a set of relations but also information about each relation, including:!
The schema for each relation.! The domain of values associated with each attribute.! Integrity constraints!
! ! ! !
To delete a relation:!
Most basic element: an attribute and its type.! The most common types are:!
INT or INTEGER (synonyms).! REAL or FLOAT (synonyms).! CHAR(n ) = xed-length string of n characters.! VARCHAR(n ) = variable-length string of up to n characters.!
UNIQUE.!
Either says that no two tuples of the relation may agree in all the
Can also place PRIMARY KEY or UNIQUE after the type in the
!create table branch " " (branch_name ! ! branch_city " ! ! assets "
The bar and beer together are the key for Sells:!
! ! ! ! ! !
!CREATE TABLE Sells (! ! ! ! ! !);! !bar !beer !price ! ! ! !CHAR(20),! !VARCHAR(20),! !REAL,!
!create table r (A1 D1, A2 D2, ..., An Dn, " " "(integrity-constraint1), ! ! !..., ! ! !(integrity-constraintk))!
r is the name of the relation! each Ai is an attribute name in the schema of relation r" Di is the data type of values in the domain of attribute Ai"
Example:!
!create table branch ! !(branch_name "char(15) not null, ! !branch_city !char(30), ! !assets " "integer)!
not null! primary key (A1, ..., An ) the attributes form a primary key! unique (A1, ..., An ) the attributes together form a
candidate key! Example: Declare branch_name as the primary key for branch" .! !create table branch " " (branch_name "char(15), ! ! branch_city "char(30), ! ! assets " "integer, ! ! primary key (branch_name))!
The drop table command deletes all information about the dropped
relation: !
All tuples in the relation are assigned null as the value for the new attribute. !
relation:! !
"
where A is the name of an attribute of relation r" Dropping of attributes not supported by many databases!
SELECT desired attributes! FROM one or more tables! WHERE condition about tuples of the tables!
! ! ! ! ! !
Underline indicates key attributes.! ! !Beers(name, manf)! ! ! ! ! ! !Bars(name, addr, license)! !Customers(name, addr, phone)! !Likes(customer, beer)! !Sells(bar, beer, price)! !Frequents(customer, bar)!
! ! !
! ! ! ! !
The answer is a relation with a single attribute, name, and tuples with the name of each beer by Molson, such as Export.!
Begin with the relation in the FROM clause.! Apply the selection indicated by the WHERE clause.! Apply the extended projection indicated by the SELECT clause.!
E.g.:
name
manf
Export Molson
Check if! Molson!
FROM.!
Check if the current tuple satises the WHERE clause.! If so, compute the attributes or expressions of the SELECT clause using
When there is one relation in the FROM clause, * in the SELECT clause
! ! ! ! !
!name
! ! ! ! !
If you want the result to have different attribute names, use AS <new name>
to rename an attribute.!
Example: Using Beers(name, manf):!
! ! !
! ! ! ! !
!beer
! ! ! ! !
clause.!
Example: Using Sells(bar, beer, price):!
! ! ! !
! ! ! !
!beer
!Export ! Sleeman ! !
!SELECT customer,! ! ! !likes Export AS whoLikesExport! !FROM Likes! !WHERE beer = Export;!
! ! ! !
We often build data warehouses from the data at many sources.! Suppose each bar has its own relation Menu(beer, price) .! To contribute to Sells(bar, beer, price) we need to query each bar and
Boolean operators AND, OR, NOT.! Comparisons =, <>, <, >, <=, >=.!
Using Sells(bar, beer, price), nd the price Joes Bar charges for Export:!
! ! !
!SELECT price! !FROM Sells! !WHERE bar = Joes Bar AND beer = Export;!
<Attribute> LIKE <pattern> or ! <Attribute> NOT LIKE <pattern>! % = any string; ! _ = any character.!
555:! SELECT name! FROM Customers! WHERE phone LIKE %555-_ _ _ _;!
Tuples in SQL relations can have NULL as a value for one or more
components.!
Meaning depends on context. ! Two common cases:!
Missing value : e.g., we know Joes Bar has some address, but we dont know what it is.! Inapplicable : e.g., the value of attribute spouse for an unmarried person.!
UNKNOWN.!
Comparing any value (including NULL itself) with NULL yields UNKNOWN.! A tuple is in a query answer iff the WHERE clause is TRUE (not FALSE or
UNKNOWN).!
To understand how AND, OR, and NOT work in 3-valued logic, think of
TRUE AND (FALSE OR NOT(UNKNOWN)) = ! MIN(1, MAX(0, (1 - ))) =! !MIN(1, MAX(0, )) = ! MIN(1, ) = .!
! !
! !
!bar
!beer
!price! !NULL!
!Joes Bar
!Export !
!SELECT bar! !FROM Sells! !WHERE price < 2.00 OR price >= 2.00;! The WHERE clause evaluates to UNKNOWN.! So Joes Bar isnt SELECTed..!
Some common laws, like commutativity of AND, hold in 3-valued logic. ! But not others, e.g., the law of the excluded middle : !
p OR NOT p = TRUE in classical logic.! When p = UNKNOWN, the left side is ! MAX( , (1 )) = != 1.!
Interesting queries often combine data from more than one relation.! We can address several relations in one query by listing them all in
!<relation>.<attribute> .!
beers liked by at least one person who frequents Joes Bar.! !SELECT beer! !FROM Likes, Frequents! !WHERE bar = Joes Bar AND Frequents.customer = Likes.customer;!
Start with the product of all the relations in the FROM clause.! Apply the selection condition from the WHERE clause.! Project onto the list of attributes and expressions in the SELECT clause.!
These tuple-variables visit each combination of tuples, one from each relation.!
bar
customer Sally
Joes check for Joe check these are equal Likes to output
Frequents
Sometimes, a query needs to use two copies of the same relation.! Distinguish copies by following the relation name by the name of a
essential.!
manufacturer.!
! ! !
Do not produce pairs like (Export, Export).! Produce pairs in alphabetic order, e.g. (Export, Sleeman), not (Sleeman, Export).! SELECT b1.name, b2.name! FROM Beers b1, Beers b2! WHERE b1.manf = b2.manf AND b1.name < b2.name;!
Find the beers liked by at least one person who frequents Joes Bar.!
Usually, the tuple has one component.! A run-time error occurs if there is no tuple or more than one tuple.!
Using Sells(bar, beer, price), nd the bars that serve Sleeman for the same price Joe charges for Export.! Two queries would certainly work:!
1. 2.
Find the price Joe charges for Export.! Find the bars that serve Sleeman at that price.!
!SELECT bar! !FROM Sells! !WHERE beer = Sleeman AND! ! ! !price = (SELECT price! ! ! ! ! FROM Sells! WHERE bar = Joes Bar! !AND beer = Export);!
manufacturer of each beer that Fred likes.! ! SELECT *! ! FROM Beers! ! WHERE name IN (SELECT beer! ! ! The set! of! ! beers Fred! likes! ! ! FROM Likes! WHERE customer = Fred);!
a b 1 2 3 4 R
b c 2 5 2 6 S
(1,2) with (2,5) and (1,2) with (2,6) both satisfy! the condition;! 1 is output twice.!
Two 2s! SELECT FROM ! WHERE !a! !R! !b IN (SELECT b FROM S);!
a b 1 2 3 4 R
b c 2 5 2 6 S
empty.!
Example: From Beers(name, manf) , nd those beers that are the
Notice scope rule: manf refers! to closest nested FROM with! a relation having that attribute.
!SELECT *! !FROM Beers! !WHERE manf = b1.manf AND! ! !name <> b1.name);!
<> can be any comparison operator.! Example: x >= ALL(<subquery>) means there is no tuple larger than x
From Sells(bar, beer, price), nd the beer(s) sold for the highest price.!
! ! ! ! !
!SELECT beer! !FROM Sells! !WHERE price >= ALL(! ! ! !SELECT price! !FROM Sells);!
price from the outer! Sells must not be! less than any price.!
Using Likes(customer, beer), Sells(bar, beer, price), and Frequents (customer, bar), nd the Customers and beers such that:!
1. 2.
The customer likes the beer, and! The customer frequents at least one bar that sells the beer.!
Notice trick:! subquery is! really a stored! table.! The customer frequents! a bar that sells the! beer.!
(SELECT * FROM Likes)! !INTERSECT! (SELECT customer, beer! FROM Sells, Frequents! WHERE Frequents.bar = Sells.bar! );!
Aside: This is an example of a query that departs from the outer SELECTFROM-WHERE template!
rst.!
SELECT DISTINCT . . .!
as in
. . . UNION ALL . . .!
From Sells(bar, beer, price), nd all the different prices charged for
! ! !
!(SELECT customer FROM Frequents)! ! !EXCEPT ALL! !(SELECT customer FROM Likes);!
Lists Customers who frequent more bars than they like beers, and does
SQL provides several versions of (bag) joins.! These expressions can be stand-alone queries or used in place of
Natural join:!
! !
!R NATURAL JOIN S;! !R CROSS JOIN S;! Likes NATURAL JOIN Sells;!
! !
!gives us all (d, a, d, b) quadruples such that customer d lives at address a and frequents bar b.!