Is the following the most efficient in SQL to achieve its result:
SELECT *
FROM Customers
WHERE Customer_ID NOT IN (SELECT Cust_ID FROM SUBSCRIBERS)
Could some use of joins be better and achieve the same result?
You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.
An asterisk (" * ") can be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause, which indicates the table(s) to retrieve data from.
SELECT 'x' from table returns the constant value x for all rows. It's often used in EXISTS because the EXISTS predicate doesn't care about values, it's only concerned about whether or not there's a row. SELECT x from table returns the column named x from the table, or an error if there is no column named x.
Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN
. Use whatever is more readable to you.
One reason why you might prefer to use a JOIN
rather than NOT IN
is that if the Values in the NOT IN
clause contain any NULL
s you will always get back no results. If you do use NOT IN
remember to always consider whether the sub query might bring back a NULL value!
RE: Question in Comments
'x' NOT IN (NULL,'a','b')
≡ 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'
≡ Unknown and True and True
≡ Unknown
Maybe try this
Select cust.*
From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null
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