Question : Need help understranding 'WHERE EXISTS' and 'WHERE NOT EXISTS'

Hi all

Finally have come up against an SQL command that I can;t seem to make work.  I'm sure it's just that I am thick, but I really want to know how this works as I can see it being quite useful in a number of instances...  here's the example:

I have two tables.  One is a list of services.  The other is a list of services used by each client.  I want to build a list of services NOT already assigned to a client.  I was using the following command:

SELECT serviceid
FROM services
WHERE NOT EXISTS (
   SELECT serviceid
   FROM insp_client_services
   WHERE clientid=2 )

The services table has the follwoing data:

(`serviceid`, `description`)
(1, '10% (outside area 2)'),
(3, 'Digital photos'),
(101, 'new service for test');

The clientservices table has the following data:

(`clientserviceid`, `serviceid`, `clientid`)
(727, 1, 2),
(729, 3, 2),
(910, 1, 3),
(912, 3, 3);

What I would expect from the above is one record for serviceid 101 to be the result.  The result I get is empty.  I know this one will be humbling, but can anyone see where I have gone wrong?  I definitely have been staring at it too long to see something that is most assuredly quite obvious...

TIA
Owen
Code Snippet:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
CREATE TABLE IF NOT EXISTS `services` (
  `serviceid` int(11) NOT NULL auto_increment,
  `description` varchar(50) NOT NULL,
  PRIMARY KEY  (`serviceid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=102 ;
 
-- 
-- Dumping data for table `services`
-- 
 
INSERT INTO `services` (`serviceid`, `description`) VALUES 
(1, '10% (outside area 2)'),
(3, 'Digital photos');
 
-- 
-- Table structure for table `clientservices`
-- 
 
CREATE TABLE IF NOT EXISTS `clientservices` (
  `clientserviceid` int(11) NOT NULL auto_increment,
  `serviceid` int(11) NOT NULL default '0',
  `clientid` int(11) NOT NULL default '0',
  PRIMARY KEY  (`clientserviceid`),
  KEY `services_list` (`clientid`,`serviceid`,`clientserviceid`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=971 ;
 
-- 
-- Dumping data for table `clientservices`
-- 
 
INSERT INTO `clientservices` (`clientserviceid`, `serviceid`, `clientid`) VALUES 
(727, 1, 2),
(729, 3, 2),
(910, 1, 3),
(912, 3, 3);

Answer : Need help understranding 'WHERE EXISTS' and 'WHERE NOT EXISTS'

hi,

SELECT serviceid
FROM services
WHERE NOT EXISTS (
   SELECT serviceid
   FROM insp_client_services
   WHERE clientid=2 and services.serviceid = insp_client_services.serviceid  )
Random Solutions  
 
programming4us programming4us