Question

Kinda stack and can't figure out. Wondering if you can help... I want to exclude Accounts start with 100...

SELECT * 
  FROM Inventory   --returns 300 records
SELECT * 
  FROM Inventory 
 WHERE AccNum LIKE '100%'    --returns 50 records

But this one returns schema and NO records. Why? I should get 250 records...

SELECT * 
  FROM Inventory 
 WHERE NOT EXISTS(SELECT * 
                    FROM Inventory 
                   WHERE AccNum LIKE '100%')

No correct solution

OTHER TIPS

Let me explain why your query fails first, then show how to fix it.

This is the query that doesn't work as expected:

SELECT *
FROM Inventory
WHERE NOT EXISTS(SELECT * FROM Inventory WHERE AccNum LIKE '100%');

The reason it doesn't return any rows is because of the where clause. The subquery returns 50 rows. Hence, it exists. In other words, this version of the query will return either all rows in the table or none of the rows. Nothing changes from row to row.

One way to fix this is by using in:

SELECT *
FROM Inventory i
WHERE AccNum NOT IN (SELECT AccNum FROM Inventory i2 WHERE AccNum LIKE '100%');

This will work so long as AccNum is never NULL.

Of course, an easier way is just to use a simple where clause:

SELECT *
FROM inventory
WHERE AccNum NOT LIKE '100%' OR AccNum IS NULL;

I think you mean:

SELECT * FROM Inventory 
WHERE AccNum not in (SELECT AccNum FROM Inventory WHERE AccNum LIKE '100%')

In your original 'SELECT * FROM Inventory WHERE AccNum LIKE '100%'' will always return records and so the NOT EXISTS will always fail

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top