Download presentation
Presentation is loading. Please wait.
Published byRalf Anderson Modified over 9 years ago
1
1 3. Relational Algebra and SQL Example: Let the following relations describe point sets: A(x, y), B(x, y), J(x, y) 2D points in the plane H(x, y, z), I(x, y, z) 3D points in space F(z) line on the z-axis K(y,z) 2D points in (y, z) plane
2
2 3.1 Relation algebra operators A B A B A \ B A and B
3
3 A F J K
4
4 x,y H y,z H 2x+z = 0 I
5
5 Example: Find the SSN and tax for each person. π SSN,Tax σ wages+interest+capital_gain = income Taxrecord × Taxtable Example: Find the area of Lincoln reached by a radio station. ( π X,Y ( σ Name=“Lincoln” Town ) ) ( π X,Y Broadcast )
6
6 3.2 SQL SELECT a 1,..., a n FROM R 1, R 2, …, R m WHERE Con 1, …,Con k This means: π a 1,..., a n ( σ Con 1 ( … (σ Con k ( R 1 × R 2 × … × R m ))…))
7
7 Example: Find the SSN and tax for each person. SELECT SSN, Tax FROM Taxrecord, Taxtable WHERE wages + interest + capital_gain = income
8
8 AS – keyword used to rename relations Two SQL expressions can be combined by: INTERSECT UNION MINUS – set difference
9
9 Example: Find the names of the streets that intersect. SELECT S.NAME, T.NAME FROM Streets AS S, Streets AS T WHERE S.X = T.X and S.Y = T.Y
10
10 Example: Assume we have the relations: Broadcast ( Radio, X, Y ) Town ( Name, X, Y ) Find the parts of Lincoln, NE that can be reached by at least one Radio station. (SELECT X, Y FROM Town WHERE Name = “Lincoln”) INTERSECT (SELECT X, Y FROM Broadcast)
11
11 Another way of connecting SQL expressions is using the IN keyword. SELECT …….. FROM …….. WHERE a IN ( SELECT b FROM ….. WHERE ….. )
12
12 SQL with aggregation – SELECT aggregate_function FROM ……. WHERE …… aggregate_function – Max (c 1 a 1 + ……..+ c n a n ) where a i are attributes Min (c 1 a 1 + ……..+ c n a n ) and c i are constants Sum(a) where a is an attribute that is Avg(a) constant in each constraint tuple Count(a)
13
13 Example: Package(Serial_No, From, Destination, Weight) Postage (Weight, Fee) Find the total postage of all packages sent from Omaha. SELECT Sum(Fee) FROM Package, Postage WHERE Package.Weight = Postage.Weight AND Package.From = “ Omaha “
14
14 GROUP BY – SELECT a 1, …, a n, aggregate_function FROM ….. WHERE …… GROUP BY a 1,..., a k Evaluates basic SQL query Groups the tuples according to different values of a 1,..,a k Applies the aggregate function to each group separately {a 1, …, a k } {a 1, …, a n }
15
15 Example: Find the total postage sent out from each city. SELECT Package.From, Sum(Postage.Fee) FROM Package, Postage WHERE Package.Weight = Postage.Weight GROUP BY Package.From
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.