Search code examples
c#npgsql

How to use IN() to search for existence?


I am using Npgsql to connect to a Postgres database, and I want to run a query like this one:

 SELECT column IN('foo', 'bar') FROM table;

to check if the column is in a list.

I have this C# code now:

var list = new string[] { "foo", "bar" };
var cmd = new NpgsqlCommand("SELECT column IN(:list) FROM table", myConnection);
cmd.Parameters.AddWithValue("list", list);

But that doesn't work, as Npgsql makes an ARRAY from list, where it should be something else, ... but what?


Solution

  • I fixed it by using the ANY operator, as that takes an array:

    var list = new string[] { "foo", "bar" };
    var cmd = new NpgsqlCommand("SELECT column = ANY(:list) FROM table", myConnection);
    cmd.Parameters.AddWithValue("list", list);