Passing a list of column names to a query in psycopg2
<p>I have the following query:</p>

<pre><code>select distinct * from my_table where %s is NULL;
</code></pre>

<p>I would like to be able to pass in more than one column name to this query, but I do not know how many columns I will want to be checking for nulls every time.</p>

<p>How can I use query parameter techniques like the above to make both the below queries from the same statement?:</p>

<pre><code>select distinct * from my_table where "col1" is NULL or "col2" is NULL;
select distinct * from my_table where "col1" is NULL or "col2" is NULL or "col3" is NULL;
</code></pre>

<p>I would appreciate an answer that includes being able to get the below as well, but it is not necessary in this case:</p>

<pre><code>select distinct * from my_table where "col1" is NULL;
</code></pre>

<p>(I am using Amazon Redshift, in case that removes an postgresql-related possibilities)</p>

<pre><code>query = '''
    select distinct *
    from my_table
    where
        %s or
        "col1" is NULL and %s or
        "col2" is NULL and %s or
        "col3" is NULL and %s
'''
</code></pre>

<p>Pass <code>True</code> to the conditions which you want to be evaluated. Say you want rows where any of <code>col1</code> and <code>col2</code> are <code>null</code>:</p>

<pre><code>cursor.execute(query, (False, True, True, False))
</code></pre>

<p>If you want all rows regardless:</p>

<pre><code>cursor.execute(query, (True, False, False, False))
</code></pre>

<p>BTW double quoting identifiers is a bad idea.</p>

python postgresql amazon-redshift psycopg2