3

How to write SQL query in Python to select elements LIKE IN Python list?

For example, I have Python list of strings

Names=['name_1','name_2',..., 'name_n']

and SQLite_table.

My task is to find shortest way to

SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_1%'
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_2%'
...
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_n%'
3
  • duplicate of stackoverflow.com/q/15041534/2266261 ? Commented Jan 5, 2014 at 23:05
  • No. The problem is LIKE. Commented Jan 5, 2014 at 23:23
  • 2
    SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_1%' OR element_name LIKE '%name_2%' OR element_name LIKE '%name_n%' ?? Commented Jan 6, 2014 at 0:42

2 Answers 2

5

You would need a regular expression of the form name_1|name_2|name_3|…, which you can generate using '|'.join(Names):

SELECT elements FROM SQLite_table WHERE element_name REGEXP 'name_1|name_2|name_3|…|name_n'

Check How do I use regex in a SQLite query? for instructions on how to use regular expressions in SQLite.

Sign up to request clarification or add additional context in comments.

2 Comments

There is no REGEX operator, and the linked answers say that REGEXP is not available by default.
Sorry about the typo. However, the linked answers give enough information to install and use the REGEXP operator. For example, this answer installs the operator in 5 lines of Python.
3

Mmhh

Names=['name_1','name_2','name_n']
for i in Names:
    sql = "SELECT elements FROM SQLite_table WHERE element_name LIKE '%" + i + "%'" 
    print sql

SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_1%'
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_2%'
SELECT elements FROM SQLite_table WHERE element_name LIKE '%name_n%'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.