0

I'm trying to write a SQL query to find the lowest available/unused ID from a column named internal that exists in two separate tables:

  1. machines
  2. machines_ignore

Data is processed from an external source, and we want to fetch data from all machines that are not in the machines_ignore table. The ignore table is just a manual table set up by us when we identify machines we don't want to analyze.

I've found scripts that work on a single table (like only the machines table), but as soon as I try to get it working when combining two tables.

Example

Table 1 (machines)

id internal
1 1
2 2
3 3
4 5
5 6

Table 2 (machines_ignore)

internal
4
7
8
9
12

Expected result

Based on the example above, this query should output 10, 11, 13 etc.

Any ideas?

Mad Marvin
  • 3,309
  • 3
  • 18
  • 18

1 Answers1

2

One solution is to combine the values from both tables then check if each value has next value in both tables using EXISTS:

SELECT x.internal + 1
FROM (
    SELECT internal FROM machines
    UNION
    SELECT internal FROM machines_ignore
) AS x
WHERE NOT EXISTS (
    SELECT 1 FROM machines WHERE internal = x.internal + 1
) AND NOT EXISTS (
    SELECT 1 FROM machines_ignore WHERE internal = x.internal + 1
)
LIMIT 1
Salman A
  • 262,204
  • 82
  • 430
  • 521