-1

I have a list of string as follow:

['a', 'b', 'c']

and I need to create a SQL query from it. I am writing this kind of query because I am using the python client for BigQuery and this is the way to do. The query will look like this:

WHERE data IN ('a', 'b', 'c')

I tried to do this:

WHERE data IN ({", ".join(myList)})

but the result is:

WHERE data IN (a, b, c)

How should I do this?

EDIT FOR PRECISION

Actually my problem was that I was already in a f string and couldn't use a backslash into it to escape my quotes. I did like so:

quote = "'"
f'WHERE gcloud_id IN ({", ".join(f"{quote}{ g_id }{quote}" for g_id in gcloud_id)}) '

Thanks

Kimor
  • 532
  • 4
  • 17
  • 5
    Read the docs for whatever DB engine you're using, you should not be building SQL queries manually with strings. – jonrsharpe Aug 17 '21 at 10:59
  • They need to be quoted, `", ".join(myList.map(lambda x: f"\"{x}\""))`, also this is a bad idea. – castis Aug 17 '21 at 10:59
  • Take a look at this at SQLalchemy https://pypi.org/project/SQLAlchemy/ it provides a system of constructing SQL expressions – dejanualex Aug 17 '21 at 11:02
  • 1
    @Kimor, do try to search SO for existing answers as 9 out of 10 times you will find the solutions you are looking for if the problem is trivial or commonly faced by others. – Akshay Sehgal Aug 17 '21 at 11:06
  • I am using big query and this is the way to build SQL Queries. – Kimor Aug 17 '21 at 12:09
  • I did not found any answers fot it, if so I wouldn't have ask :) – Kimor Aug 17 '21 at 12:10

1 Answers1

1
words = ['a', 'b', 'c']

', '.join(f"'{ word }'" for word in words)

This should do the work. But again, like the comment said, this is a bad idea as you should not be querying this way. Cheers!

Owenn
  • 638
  • 1
  • 6
  • 23
  • Hi, Owenn, this is a duplicate question. Do try to guide people to existing answers rather than copying an answer from another SO page and adding it, as it helps keep the site clean and reduce redundancy. – Akshay Sehgal Aug 17 '21 at 11:04
  • 1
    @AkshaySehgal Right, my bad, didn't even know there was an existing answer. But thanks for the advice though! – Owenn Aug 17 '21 at 11:07
  • Thanks @Owenn once again, I am using BigQuery and this is the way to build query. – Kimor Aug 17 '21 at 12:11