Can we do a switch case with an in clause

Question:

Can we do use an in clause with case

sql_query=f"""SELECT * FROM table1
where column1 in ('{list_of_values}')
order by CASE
WHEN column2 like'a%' THEN 1
WHEN column2 like'b%' THEN 2
WHEN column2 like'c%' THEN 3
ELSE 99 END;
"""

I am not getting any value in return but when I try

sql_query=f"""SELECT * FROM table1
where column1 = '{value1}'
order by CASE
WHEN column2 like'a%' THEN 1
WHEN column2 like'b%' THEN 2
WHEN column2 like'c%' THEN 3
ELSE 99 END;
"""

I get a value in return. What am I doing wrong in the first query. Thanks.

Asked By: Tanu

||

Answers:

where column1 in ('{list_of_values}')

your '{list_of_values}' isn’t going to work, it needs to be each individual item comma separated and within individual quotes e.g. where column1 in ('a','b','c','etc')

Answered By: isamu

It seems like the issue with your first SQL query is related to the format of the list_of_values variable that you are using in the IN clause.

When you are using a list of values in the IN clause, you need to make sure that the values are separated by commas and enclosed in parentheses. So your SQL query should be modified to something like this:

sql_query=f"""SELECT * FROM table1
where column1 in ({','.join(list_of_values)})
order by CASE
WHEN column2 like'a%' THEN 1
WHEN column2 like'b%' THEN 2
WHEN column2 like'c%' THEN 3
ELSE 99 END;
"""

Assuming that the list_of_values variable is a Python list of values that you want to include in the IN clause.

Additionally, when you’re constructing an SQL query using input from an external source, like a user, it’s important to sanitize the inputs to prevent SQL injection attacks. One way to do this is to use parameterized queries instead of string interpolation. Parameterized queries can help prevent SQL injection attacks by separating the SQL code from the user input values. You can modify your code to use parameterized queries like this:

sql_query = """SELECT * FROM table1
               WHERE column1 IN %(list_of_values)s
               ORDER BY CASE
               WHEN column2 LIKE 'a%' THEN 1
               WHEN column2 LIKE 'b%' THEN 2
               WHEN column2 LIKE 'c%' THEN 3
               ELSE 99 END;"""

params = {'list_of_values': list_of_values}

cursor.execute(sql_query, params)

This way, you can pass the list_of_values parameter as a dictionary to the execute() method and the psycopg2 library will handle the parameterization and the escaping of the values.

Answered By: jar-r
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.