I have a question that I think that is a better fit here than a programming SE as SQL is founded on set theory and my question is more about set theory than about a programming question.
Assuming I have the following question: "Retrieve all the students who take exactly 2 courses" which should be formed as a SQL query, the solutions I have seen, essentially re-phrase the question as follows: "Retrieve all the students who take at least 2 courses and do not take a third course" or "Retrieve all the students who take at least 2 courses and do not take at least 3 courses"
The results of these queries are correct and the formulation of the SQL queries are relatively straightforward (at least when the query is presented it is easily understood).
Now my question is, why does the original query need to be rephrased to be expressed in an SQL dialect?
Is it not possible to express the "exactly 2 courses" within Set theory?
Can we express "exactly X" with set theory?
94 Views Asked by Bumbble Comm https://math.techqa.club/user/bumbble-comm/detail AtThere are 2 best solutions below
On
The word "exactly" means "no more and no less". Mathematics, and set theory, is wonderful because its "core dictionary" is so small. We define more and more terms, and abbreviate and so on, but when we want to write something formally we have very little to write it with.
So when we want to write that there are exactly two courses, we write that there are two (so at least two), but not three (at most two).
This is exactly what those SQL queries do. And essentially, that is what you do when someone tells you that they want "exactly five oranges": you give them at least five oranges, but not more.
To the question whether or not these queries can be written otherwise, in a more direct way, that is definitely not a question for this website.
It depends on what you meanby "express". There are no students and no courses in set theory (and it takes a while till you have a $2$).
To match your SQL situation, let's assume a set $S$ of students, a set $C$ of courses and a relation $R\subseteq S\times C$. The students with exactly two course could then be described as $$ \{\,s\in S\mid\exists a,b\in C\colon sRa\land sRb\land a\ne b\land (\forall c\in C\colon sRc\to c=a\lor c=b)\,\}$$ but also as $$ \{\,s\in S\mid|(\{s\}\times C)\cap R|=2\,\}.$$ The first would somewhat correspond to "at least two but not at least three", maybe the second is something you ask for.
Since you can get a list of all students and their course counts from someting like
SELECT student,count(course) FROM studentcourserelation GROUP BY studentI guess that adding some suitableHAVINGclause should work in SQL