E
E
estry2022-04-13 16:57:51
PostgreSQL
estry, 2022-04-13 16:57:51

How to compose an SQL query to return missing values?

I have a table in a PostgreSQL database. It has simple columns - id, name, age.
You need to create a query that will return non-existent values.

For example, I have 10 records in the table, in the id column, I have numbers from 1 to 10. I make a request indicating the numbers 1,3,6,12,17. And since there are no 12 and 17 in the table, the numbers 12.17 are returned to me . It

was not difficult to make a SELECT query:

SELECT id FROM test WHERE id=1 OR id=3 OR id=6, OR id=12 OR id=17

But how to get the opposite, those values ​​that do not exist?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
nApoBo3, 2022-04-13
@nApoBo3

The idea is not very good, you are doing something wrong.
But if you really need it, you can for example like this.
select a,b
from (
values ​​(1), (2), (3)
) s(a)
left join
(
values ​​(1), (4), (3)
) f(b)
on a = b
instead of f( b) substitute any table you want.

S
Slava Rozhnev, 2022-04-13
@rozhnev

select n from unnest(array[1, 3, 5, 7]) n
left join test on n = id
where id is null;

postgres sandbox

A
Alexeytur, 2022-04-14
@Alexeytur

SELECT id FROM test WHERE id NOT IN (<список цифр>)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question