Select values from a table that are not in a list SQL

I usually use SELECT 'FOO' AS COL UNION SELECT 'BAR' etc and then use the standard idiom of left joining and checking for NULL to find missing elements.

CREATE TABLE #YourTable(
name nvarchar(50)
)

insert into #YourTable (name) values ('Test1'), ('Test3')

-- ALL
select * from #YourTable

--MISSING
select t1.* from (
  select 'Test1' testName
  union select 'Test2'
  union select 'Test3') as t1
  left outer join #YourTable yt on t1.testName = yt.name
  where yt.name is null

DROP TABLE #YourTable

Gives output

name
--------------------------------------------------
Test1
Test3

(2 row(s) affected)

testName
--------
Test2

(1 row(s) affected)

Depending on how many values you have, you could do a few unions.

See: http://www.sqlfiddle.com/#!5/0e42f/1

select * from (
  select 'Test 1' thename union
  select 'Test 2' union 
  select 'Test 3'
)
where thename not in (select name from foo)

Select a.value from (
SELECT 'testvalue' value UNION
SELECT 'testvalue2' value UNION
SELECT 'testvalue3' value UNION
SELECT 'testvalue4' value UNION
) a
left outer join othertable b
on a.value=b.value
where b.value is null

This is perfect for my problem without temp table#

Tags:

Sql