Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax Error in SQL Query( select ) when an empty list is passed

I'm running SQL Query using python-Django RAW Query..!!

I'm using IN() function to pass my tuple in the query.

My code looks like this...

Here I am getting the list of dnc_domains and dnc_company from a json/function

dnc_domain_names = list(map(lambda x: get_domain_name(x), dnc_websites))
dnc_company_names = list(map(lambda l: l.lower(), list(filter(None, list(map(lambda x: x['company_name'], dnc_info))))))

QUERY:

select_query = """
                   select c.id
                   from (
                         select id, lower(company_name) as c_name,substring(website from '(?:.*://)?(?:www\.)?([^/]*)') as website_domain, 
                         from contacts 
                         where campaign_id = %s
                         ) c
                   where
                    c.c_name IN %s 
                    OR c.website_domain IN %s
                 """

Executing Query:

with connection.cursor() as cursor:
     cursor.execute(select_query, (campaign.id,tuple(dnc_company_names),tuple(dnc_domain_names))
     matching_contact_ids = cursor.fetchall()

But, there is a case when any dnc_company_names or dnc_domain_name is empty [] then my Query throws an Error otherwise if there at least 1 element in any of them then it works fine.

SQL Error:

syntax error at or near ")"
LINE 5:                                 WHERE id IN ()
                                                     ^

So, help me to tackle this error. SQL should handle both empty or non empty tuples.

like image 636
Shubham Srivastava Avatar asked Jun 10 '26 20:06

Shubham Srivastava


1 Answers

This is solved by providing NULL values in list

if not dnc_company_name:
    dnc_company_name = [None]

finally, in my question, I am converting dnc_company_name into tuple.

and it solved my problem.

like image 129
Shubham Srivastava Avatar answered Jun 12 '26 10:06

Shubham Srivastava