I am currently working on a homework assignment that requires a selection to occur that pulls out an element containing a specific attribute of maximum value compared to all other records. I've read a number of sources online that reference an "aggregate" relational algebra function called maximum, but they don't describe how it works using the basic operators. How does one select the attribute containing a maximum value?
SQL Aggregate Functions. SQL aggregation function is used to perform the calculations on multiple rows of a single column of a table. It returns a single value. It is also used to summarize the data.
The usual technique for such queries is to first use either sorting or hashing on the grouping attributes to partition the file into the appropriate groups. Then the algorithm computes the aggregate function for the tuples in each group, which have the same grouping attribute(s) value.
Such count & group are not actually relational operators, they are non-terminals in so-called relational algebras that are really query languages, designed by SQL apologists, suggesting it is easy to map SQL to relational algebra, but begging the question of how we aggregate in an algebra.
You can very well express aggregate functions with only basic operators. It's a pretty neat thing.
Suppose we have a table T, and we'd like to find the maximum of its "value" field. First, we should take the cartesian product of T with itself -- or rather with a copy of itself, T2. Then we select the rows where T.value is smaller than T2.value: this nets us all the unwanted rows, whose value is less than the value of some other row. To get the maximal values, we should subtract these unwanted rows from the set of all rows. And that's it. At least that's the basic idea, we also need to use projections to get the dimensions right.
Unfortunately I have no idea how to insert Latex here, but using relational algebra notation, it'd be something like this:
π(T.a1...Tan, T.value)(T) - π(T.a1...Tan, T.value)( σ(T.value<T2.value)( ρ(T, T2) x T ) )
where π is the projection operator, - is the set difference, σ is the selection operator and ρ is the rename operator.
SQLishly:
SELECT T.* FROM T MINUS SELECT T.* FROM T, T as T2 WHERE T.value<T2.value
And more practically:
SELECT T.* FROM T LEFT JOIN T as T2 ON T.value<T2.value WHERE T2.value IS NULL
Of course, all this is mostly only of academic interest, i.e. that it shows that the relational algebra works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With