1

I want to add another condition to this WHERE clause:

stmt = 'SELECT account_id FROM asmithe.data_hash WHERE percent < {};'.format(threshold)

I have the variable juris which is a list. The value of account_id and juris are related in that when an account_id is created, it contains the substring of a juris.

I want to add to the query the condition that it needs to match anyone of the juris elements. Normally I would just add ...AND account_id LIKE '{}%'".format(juris) but this doesn't work because juris is a list.

How do I add all elements of a list to the WHERE clause?

Michael Currie
  • 13,721
  • 9
  • 42
  • 58
Celeritas
  • 14,489
  • 36
  • 113
  • 194

3 Answers3

1

Use Regex with operator ~:

 juris = ['2','7','8','3']

'select * from tbl where id ~ \'^({})\''.format('|'.join(juris))

which leads to this query:

select * from tbl where id ~ '^(2|7|8|3)'

This brings the rows which their id start with any of 2,7,8 or 3. Here is a fiddle for it.

If you want the id start with 2783 use:

select * from tbl where id ~ '^2783'

and if id contains any of 2,7,8 or 3

select * from t where id ~ '.*(2|7|8|3).*'
Taher Rahgooy
  • 6,528
  • 3
  • 19
  • 30
0

I am hoping juris is a list of strings? If so, this might help:

myquery = ("SELECT accountid FROM asmithe.data_hash "
           "WHERE percent in (%s)" % ",".join(map(str,juris)))

See these links:

  1. python list in sql query as parameter

  2. How to select item matching Only IN List in sql server

  3. String formatting operations

Community
  • 1
  • 1
0

Stop using string formatting with SQL. Right now. Understand?

OK now. There's a construct, ANY in SQL, that lets you take an operator and apply it to an array. psycopg2 supports passing a Python list as an SQL ARRAY[]. So in this case you can just

curs.execute('SELECT account_id FROM asmithe.data_hash WHERE percent LIKE ANY (%s)', (thelist,))

Note here that %s is the psycopg2 query-parameter placeholder. It's not actually a format specifier. The second argument is a tuple, the query parameters. The first (and only) parameter is the list.

There's also ALL, which works like ANY but is true only if all the matches are true, not just if one or more is true.

Craig Ringer
  • 307,061
  • 76
  • 688
  • 778