Given a query like this:
select customerId
from customer
where customerId in (
1, 2, 3
)
I have hundreds of IDs in the where
clause's list; how would I return the IDs from the list in the where
clause that are not in the table?
This is a production table that I can only run select
queries against. I can only run select
queries; I don't have permissions to create any tables.
One easy way is to use a tally table, let's say it's called numbers with column number - of all numbers (this code may not be the best, but it should be clear what the intent is):
Another possibility is to write the ids you are looking for into an actual table or table variable.
I'd put those IDs into a table structure and left join that against your customer table.
You can use the VALUES statement to fake up a table in your SELECT:
References
There is a much easier way to do this on DB2, using VALUES to construct a table on the fly:
Note that you need to put parenthesis around each value to ensure that each value is a "row" in the table construct.
For this example, if your
customers
table has customerIDs 1, 2, 3 and 4, this query will return the value 4.This should work on DB2 UDB for z/OS Version 8 and newer. It will aslo work on DB2 for Linux/UNIX/Windows.
The really, really brutal approach, for most DBMS, this will work (except Oracle where you need to
select..from dual
). This should work on DB2 even if you have no access to create/update tables and can onlySELECT
Expand the subqueries as required to cover your full number range.
If you could create tables (or had one handy), create a "numbers" table instead with the digits 0 to 9 (10 records), and keep joining to itself, i.e.
A
numbers
table is always useful for various queries.For reference for SQL Server, assuming the numbers are within the range 0-2047, you can use
If you need a larger range, keep joining to master..spt_values again to get a larger range