0

I am working with a correlated and a non-correlated subquery in SQL and I am trying to get the same results with both types of queries. My issue is with my non-correlated subquery. The query runs but does not return any results. My correlated subquery does return results, like it should. I need help trying to figure out if my simple non-correlated subquery is written incorrectly. Any help is greatly appreciated. My queries are as follows:

--non-correlated subquery

SELECT *
FROM hr.bc_products p
WHERE p.sku NOT IN (SELECT ol.sku FROM hr.bc_orderlines ol);

--correlated subquery

SELECT * 
FROM hr.bc_products p
WHERE NOT EXISTS (SELECT ol.sku FROM hr.bc_orderlines ol WHERE ol.sku = p.sku);
2
  • 1
    fwiw, I'd tend to write this with an exclusion join: SELECT p.* FROM hr.bc_products p LEFT JOIN hr.bc_orderlines ol ON p.sku = ol.sku WHERE ol.sku IS NULL Commented Mar 25, 2014 at 2:37
  • That makes sense. Let me give that a try. Commented Mar 25, 2014 at 14:03

1 Answer 1

1

I finally figured out what the issue was. After looking through the results of each query I realized that nulls were affecting the outcome. I updated my non-correlated subquery by excluding nulls. My updated non-correlated subquery works and looks like this:

--non-correlated subquery

SELECT *
FROM hr.bc_products p
WHERE p.sku NOT IN (SELECT ol.sku FROM hr.bc_orderlines ol WHERE ol.sku IS NOT NULL);

Hopefully this will help someone avoid the problem in the future.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.