I need to merge two query results as in union, but I want to only keep the difference between the two results. Is this possible?
I am basically selecting ALL resources in Query 1, and NOT-ALLOWED resources in Query 2, I obviously need the ALLOWED resources in my last result.
In pseodo-code:
Query1 - Query2
Queryresult 1:
+-------+
| id |
+-------+
| 1 |
+-------+
| 2 |
+-------+
| 3 |
+-------+
| 4 |
+-------+
| 5 |
+-------+
| 6 |
+-------+
Queryresult 2:
+-------+
| id |
+-------+
| 2 |
+-------+
| 5 |
+-------+
Needed:
+-------+
| id |
+-------+
| 1 |
+-------+
| 3 |
+-------+
| 4 |
+-------+
| 6 |
+-------+
The MINUS operator is one of three set operators in the SQL standard that includes UNION , INTERSECT , and MINUS . The MINUS compares the results of two queries and returns distinct rows from the result set of the first query that does not appear in the result set of the second query.
The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.
We can compare the execution plan of the already saved query execution plan as well. To do so, just open the query execution plan in SQL Server Management Studio 2016. Once opened, right click on the execution plan, and click on the Showplan compare.
Answer: To find the difference between two numbers, subtract the number with the smallest value from the number with the largest value. The product of this sum is the difference between the two numbers.
Like this, using NOT IN
:
SELECT id FROM queryOneTable
WHERE id NOT IN (
SELECT id FROM queryTwoTable
)
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