0

I have got 2 tables:

users (user-id, user-name)  
devices (device-id, user-id, device-name)

Both tables are linked via the foreign key user-id in the table devices.
One user can have n devices or NO device.

I am looking for those users who do NOT have a device.
In other words, users for whom there is NO user-id in the devices table.

What is the SQL statement?

The opposide works fine:

SELECT users.user-name, devices.device-name 
FROM users,devices WHERE users.user-id=devices.user-id;
jarlh
  • 42,561
  • 8
  • 45
  • 63
derTobi
  • 13
  • 1
  • 1
    Try using JOIN not comma to separate tables. Then do a join on the field and you can add a where column (you want to show up in 2nd table) is NULL. – Brad Aug 15 '22 at 17:02
  • 1
    @Brad, don't forget to mention it has to be an outer join. – jarlh Aug 15 '22 at 17:11
  • Which DBMS product are you using? "SQL" is just a query language, not the name of a specific database product. Please add a [tag](https://stackoverflow.com/help/tagging) for the database product you are using. [Why should I tag my DBMS](https://meta.stackoverflow.com/questions/388759/) – Igor Aug 15 '22 at 17:12

3 Answers3

1
SELECT U.USER_ID,U.USER_NAME
FROM USERS U
WHERE NOT EXISTS
(
   SELECT 1 FROM DEVICES D WHERE U.USER_ID=D.USER_ID
)
Sergey
  • 4,719
  • 1
  • 6
  • 11
1

You can use a LEFT JOIN to get user that have no device, they would have a deviceid NULL

SELECT users.user-name
FROM users LEFT JOIN devices ON users.user-id=devices.user-id
WHERE device-id IS NULL;
nbk
  • 45,398
  • 8
  • 30
  • 47
0

This will list out all users that does not have devices.

SELECT users.user-name 
FROM users
WHERE users.user-id NOT in 
  (SELECT devices.user-id
    FROM  devices)
jose_bacoy
  • 12,227
  • 1
  • 20
  • 38