I have been tasked with returning a negative selection from our sql database. I'll define the criteria as best i can. Thus far I haven't crafted a query that has worked.
[Bus Name] [Bus ID]
[Activity ID] [Bus ID]
[Ext ID] [Activity ID] [Bus ID]
I need the Business names for all businesses that do not have a record with that businesses id # in the associated tables. Simply put, all businesses without activities. The Business ID can be present in one or both of the associated tables.
This has caused me trouble for a few hours while trying to craft queries with joins and not exists or not in statements. No success.
Any ideas?
In SQL Server, the T-SQL SIGN() function returns the sign of a number. In other words, it indicates whether or not the value is a positive number, a negative number, or zero.
What is a Minus Query? A Minus Query is a query that uses the MINUS operator in SQL to subtract one result set from another result set to evaluate the result set difference. If there is no difference, there is no remaining result set. If there is a difference, the resulting rows will be displayed.
To exclude multiple values to be fetched from a table we can use multiple OR statements but when we want to exclude a lot of values it becomes lengthy to write multiple AND statements, To avoid this we can use the NOT IN clause with the array of values that need to be excluded with the WHERE statement.
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.
NOT IN
SELECT b.*
FROM BUSINESS b
WHERE b.business_id NOT IN (SELECT a.business_id
FROM ACTIVITY a)
AND b.business_id NOT IN (SELECT ae.business_id
FROM ACTIVITY_EXTENSION ae)
NOT EXISTS
SELECT b.*
FROM BUSINESS b
WHERE NOT EXISTS (SELECT NULL
FROM ACTIVITY a
WHERE a.business_id = b.business_id)
AND NOT EXISTS (SELECT NULL
FROM ACTIVITY_EXTENSION ae
WHERE ae.business_id = b.business_id)
LEFT JOIN/IS NULL
SELECT b.*
FROM BUSINESS b
LEFT JOIN ACTIVITY a ON a.business_id = b.business_id
LEFT JOIN ACTIVITY_EXTENSION ae ON ae.business_id = b.business_id
WHERE a.business_id IS NULL
AND ae.business_id IS NULL
Because the relationship is a foreign key (business_id), it's safe to assume none of them to be null. In which case, NOT IN
and NOT EXISTS
are the best means of looking for missing values in SQL Server. LEFT JOIN/IS NULL is less efficient - you can read more about it in this article.
SELECT * FROM businesses WHERE business.id NOT IN (SELECT DISTINCT business_id FROM activities)
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