Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python & Psycopg2 | Dynamic Query with varying WHERE clauses

I am trying to create a function that executes a query based on the arguments that are passed to it.

def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table 
        WHERE filter1 = %s AND filter2 =%s AND filter3 = %s;'''
        cursor.fetchall()

But whenever either of the filters is None, then I do not want that parameter to be part of the SQL query.

For example, if ONLY filter 1 is used then I would want the query to become:

def sql_query(filter1, filter2, filter3):
    with ConnectionPool() as cursor:
        cursor.execute('''SELECT * FROM table 
        WHERE filter1 = %s;'''
        cursor.fetchall()

How to do this such that the query is generated dynamically?

like image 276
Teacher Mik Avatar asked Mar 03 '23 22:03

Teacher Mik


1 Answers

Consider COALESCE as Python's None translates to SQL's NULL. Below method now uses optional args that default to None:

def sql_query(filter1=None, filter2=None, filter3=None):
    with ConnectionPool() as cursor:
        sql = '''SELECT * FROM table 
                 WHERE filter1 = COALESCE(%s, filter1) 
                   AND filter2 = COALESCE(%s, filter2) 
                   AND filter3 = COALESCE(%s, filter3);
              '''
        cursor.execute(sql, (filter1, filter2, filter3))
        cursor.fetchall()
like image 147
Parfait Avatar answered Mar 06 '23 12:03

Parfait