Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: ... WHERE X IN (SELECT Y FROM ...)

Tags:

sql

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?

like image 535
CJ7 Avatar asked Jun 02 '10 08:06

CJ7


People also ask

Can I use select in WHERE clause in SQL?

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.

What is select from WHERE in SQL?

The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.

What does select * from mean SQL?

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.

What is select X in SQL?

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.


3 Answers

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.

like image 187
Matti Virkkunen Avatar answered Sep 19 '22 13:09

Matti Virkkunen


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 NULLs 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

like image 37
Martin Smith Avatar answered Sep 17 '22 13:09

Martin Smith


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
like image 30
codingbadger Avatar answered Sep 20 '22 13:09

codingbadger