Forum Moderators: open

Message Too Old, No Replies

SQL Except

Syntax for SQL2K

         

aspdaddy

12:01 pm on Aug 6, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Does anyone know the syntax for this function, it is supported but I cant find an example.

I want to do a set difference to select the people who enquire but diddnt buy - something like

(SELECT Name FROM Enquiries)
EXCEPT
(SELECT Name FROM Sales)

This gives error - Incorrect syntax

Any ideas?

Thanks.
ASPDaddy

asmith_2048

12:44 pm on Aug 6, 2003 (gmt 0)

10+ Year Member



I wasn't aware you could embed subqueries in the Except function ... and I've never been able to get it to work either. I _think_ it's an Analysis Services-specific thingy.

This should do what you want:


SELECT Name
FROM Enquiries WITH (NOLOCK)
WHERE Name NOT IN (SELECT Name FROM Sales WITH (NOLOCK))

(the "WITH (NOLOCK)" stuff is just a common SQL Server optimisation for read-only queries and has no direct relevance to your question)

aspdaddy

12:52 pm on Aug 6, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Nice one.

I was set on using except and totally forgot about WHERE NOT IN, does exactly the same.
Thanks.

markus007

10:37 pm on Aug 9, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



the "where not in" will give you MAJOR problems if the table gets big as your doing a table scan, the following will do a index seek instead. If you have lots of records in the table, the with nolock will allow you to read uncommited data.

SELECT Name
FROM Enquiries WITH (NOLOCK)
where not exists (select 1 from sales with (nolock) where sales.name =enquiries.name)

aspdaddy

11:11 pm on Aug 10, 2003 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks for the tip.

asmith_2048

12:13 am on Aug 11, 2003 (gmt 0)

10+ Year Member



Yeah markus007 has the more efficient query.