The IN
serves to verify that the expression is equal to any of the given values (see the documentation).
For example, supposing we have these tables:
customers
| id | country |
|----|-----------|
| 1 | Brasil |
| 2 | Argentina |
| 3 | Paraguai |
| 4 | Uruguai |
| 5 | Peru |
suppliers
| id | country |
|----|-----------|
| 6 | Peru |
| 7 | Chile |
| 8 | Brasil |
If I do so:
select * from customers where country in ('Brasil', 'Chile', 'Peru');
He’ll check on the table customers
all records where the column country
has one of the values indicated ("Brazil", "Chile" or "Peru"). As "Brazil" and "Peru" have, but "Chile" does not, the query returns:
| id | country |
|----|---------|
| 1 | Brasil |
| 5 | Peru |
But instead of fixed values, we can also place a subquery inside the IN
. Thus, the values returned by subquery will be used.
That is, the query below:
select country from suppliers;
Returns this data:
| country |
|---------|
| Peru |
| Chile |
| Brasil |
So if I do:
select * from customers
where country in (select country from suppliers);
It would be the same as doing the first query above (select * from customers where country in ('Brasil', 'Chile', 'Peru')
). The difference, of course, is that the first, with fixed values, will always use those specific values. Already the one that uses the subquery can bring different results, according to the table suppliers
is modified (since it always uses the values the table has at the time the query is executed).
Without more context, we can not explain much about what it would mean, but by the names of the tables and columns, what we can infer is: the query is looking for clients (customers) countries where there are also suppliers (Suppliers). If the customer is in a country where there is no registered supplier (for example, the customer
with id
equal to 2, whose country is Argentina, and which has no record in the table suppliers
), he is not returned.
To find out if this consultation makes sense or not, just having more context on the system.
Finally, the same result would be obtained with INNER JOIN
:
select c.* from customers c inner join suppliers s on c.country = s.country;
Read more on the subject here, here and here.
To try to understand why you say, "It didn’t make any sense to me." show an example of input data the result obtained and the expected result. Apparently what you report as a return is the expected behavior of the clause
IN
, but I may not have understood your question.– anonimo