How do I represent a subquery in relation algebra? Do I put the new select under the previous select condition?
SELECT number
FROM collection
WHERE number = (SELECT anotherNumber FROM anotherStack);
How do I represent a subquery in relation algebra? Do I put the new select under the previous select condition?
SELECT number
FROM collection
WHERE number = (SELECT anotherNumber FROM anotherStack);
You would just rewrite that as a
join
.I'm not sure how widely used the syntax I learned for Relational Algebra is so in words.
anotherNumber
fromanotherStack
anotherNumber
from the result of step 1 asnumber
collection
number
from the result of step 3According to this pdf, you can convert a sub-query easily to a relational algebric expression.
Firstly, you have to convert the whole query from the form
to
Then you have to convert the sub-query first into relational algebra. To do this for the sub-query given above:
Here
R1, R2...
are the contextual relations, andr1, r2...
are sub-query relations.As the syntax is pretty disaster in stack overflow, please head over to that pdf to get a broad overview of how to convert sub query to relational algebra.
The answer depends on which operators your algebra comprises. A semi-join operator would be most useful here.
If the common attribute was named
number
in both relations then it would be a semi-join followed by projection ofnumber
. Assuming a sem-join operator namedMATCHING
, as per Tutorial D:As posted, the attribute needs to be renamed first:
If Standard SQL's (SQL-92)
JOIN
can be considered, loosely speaking, a relational operator then it is true that SQL has no no semi-join. However, it has several comparison predicates that may be used to write a semi-join operator e.g.MATCH
:However,
MATCH
is not widely supported in real life SQL products, hence why a semi-join is commonly written usingIN (subquery)
orEXISTS (subquery)
(and I suspect that's why you name-checked "subquery" in your question i.e. the term semi-join is not well known among SQL practitioners).Another approach would be to use an intersect operator if available.
Something like (pseudocode):
In SQL:
This is quite well supported in real life (SQL Server, Oracle, PostgreSQL, etc but notably not MySQL).