Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking whether an item does not exist in another table

My tables are set up something like this:

table name: process
fields: name, id_string

table name: value_seach
fields: id_string, value

I want to construct a select statement that will display all of the process names (with it's respective id_string) that do not have an entry in value_search.

The id_string in the process table can be null, and still have a name, but those need to be excluded if possible. The id_string in value_search can never be null

How do I do this?

like image 467
user906153 Avatar asked Feb 20 '12 17:02

user906153


People also ask

How do you check if data not exists in a table SQL?

To test whether a row exists in a MySQL table or not, use exists condition. The exists condition can be used with subquery. It returns true when row exists in the table, otherwise false is returned. True is represented in the form of 1 and false is represented as 0.

How do I select data from one table is not in another table?

We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


4 Answers

In general if you want rows that don't exist in another table, then LEFT JOIN the other table and WHERE ... IS NULL to a column on the second table. Also you mentioned that you don't want rows where process.id_string is NULL.

SELECT p.name, p.id_string
FROM
    process p
    LEFT JOIN value_search v
        ON v.id_string = p.id_string
WHERE
    v.id_string IS NULL
    AND p.id_string IS NOT NULL

This is known as an anti-join.

like image 87
zgpmax Avatar answered Oct 19 '22 09:10

zgpmax


I believe using Not Exists would be your best option here.

SELECT p.name, p.id_string
FROM process p
WHERE 
   NOT p.id_string IS NULL AND
   NOT EXISTS(
          SELECT NULL
          FROM value_search v
          WHERE p.id_string = v.id_string)
like image 20
Magnus Avatar answered Oct 19 '22 08:10

Magnus


The query you want should look something like this. Note that a JOIN will be significantly faster than a subquery in the WHERE clause.

SELECT p.name, p.id_string
FROM process p
LEFT OUTER JOIN value_search v
   ON p.id_string = v.id_string
   AND p.id_string IS NOT NULL
   AND v.id_string IS NULL

An equally valid variant of the query above would be:

SELECT p.name, p.id_string
FROM process p
LEFT OUTER JOIN value_search v
   ON p.id_string = v.id_string
WHERE
   p.id_string IS NOT NULL
   AND v.id_string IS NULL
like image 25
Brian Driscoll Avatar answered Oct 19 '22 08:10

Brian Driscoll


SELECT 
  name,
  id_string
FROM process
WHERE id_string IS NOT NULL AND id_string NOT IN SELECT id_string FROM value_seach
like image 2
alexsuslin Avatar answered Oct 19 '22 08:10

alexsuslin