Is it possible to filter an SQL base based on a list of values?

Asked

Viewed 49 times

2

On pandas, when I want to filter one DataFrame based on a list of values, I:

valores=[15,17,22]
df=df[[k in valores for k in df.mpg]]

In SQL I know I can get the same result with the following code:

SELECT * FROM 'dataset.table1'
WHERE mpg=15
OR mpg=17
OR mpg=22

The problem with this method is that if the list of values is too large I need to write OR hundreds or even thousands of times.

There is a more succinct way to do this query in SQL using a list as in pandas?

P.S.: In the example of pandas I used the example dataset auto.csv

1 answer

2


The operator IN tests multiple values in a list of elements in parentheses.

Your example would be:

SELECT * FROM 'dataset.table1' WHERE mpg IN (15, 17, 22)

It is also possible to use the result of a SELECT as a value:

SELECT * FROM numeros WHERE num IN (SELECT num FROM pares)

Example in Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.